1 import { addExtraToMd, workerCompatibleFetch } from "docs-utils"
2 import { notFound } from "next/navigation"
3 import { NextRequest, NextResponse } from "next/server"
4 import path from "path"
5 import { PostHog } from "posthog-node"
6 import { getCleanMdCached } from "../../../utils/get-clean-md-cached"
7 import { fetchRawMdx } from "../../../utils/fetch-raw-mdx"
8 import { fetchFromAssetsBinding } from "../../../utils/fetch-from-assets-binding"
9
10 type Params = {
11 params: Promise<{ slug?: string[] }>
12 }
13
14 export async function GET(req: NextRequest, { params }: Params) {
15 const { slug: rawSlug } = await params
16 const slug = rawSlug?.filter(Boolean) ?? []
17 const origin = process.env.NEXT_PUBLIC_BASE_URL || new URL(req.url).origin
18
19 if (slug.length === 0) {
20 const homepageUrl = `${origin}/homepage.md`
21 const homepageContent =
22 (await fetchFromAssetsBinding(homepageUrl)) ??
23 (await workerCompatibleFetch<string | null>({
24 url: homepageUrl,
25 responseTransformer: async (res) => {
26 return res.ok ? res.text() : null
27 },
28 fallbackAction: async () => {
29 try {
30 const { promises: fs } = await import("fs")
31 return await fs.readFile(
32 path.join(process.cwd(), "public", "homepage.md"),
33 "utf-8"
34 )
35 } catch {
36 return null
37 }
38 },
39 }))
40
41 if (!homepageContent) {
42 return notFound()
43 }
44
45 return new NextResponse(
46 addExtraToMd(homepageContent, {
47 baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "",
48 }),
49 {
50 headers: {
51 "content-type": "text/markdown",
52 "cache-control": "public, max-age=3600, must-revalidate",
53 },
54 status: 200,
55 }
56 )
57 }
58
59 const result = await fetchRawMdx(origin, slug)
60 if (!result) {
61 return notFound()
62 }
63
64 const { content, isOverride } = result
65
66 const cleanMdContent = await getCleanMdCached(content, {
67 removeExtra: isOverride,
68 })
69
70 const acceptHeader = req.headers.get("accept") || ""
71 if (
72 acceptHeader.includes("text/plain") ||
73 acceptHeader.includes("text/markdown")
74 ) {
75 const client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
76 host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
77 })
78
79 const urlObj = new URL(req.url)
80 const url = `${process.env.NEXT_PUBLIC_BASE_URL || ""}${process.env.NEXT_PUBLIC_BASE_PATH || ""}${urlObj.pathname}`
81
82 client.capture({
83 distinctId: "anonymous",
84 event: "md_content_requested_agents",
85 properties: {
86 $current_url: url,
87 $raw_user_agent: req.headers.get("user-agent") || undefined,
88 $ip:
89 req.headers.get("cf-connecting-ip") ||
90 req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
91 undefined,
92 },
93 })
94
95 await client.shutdown()
96 }
97
98 return new NextResponse(cleanMdContent, {
99 headers: {
100 "content-type": "text/markdown",
101 "cache-control": "public, max-age=3600, must-revalidate",
102 },
103 status: 200,
104 })
105 }