1 import { addExtraToMd, docPageToMarkdown, getCleanMd } from "docs-utils"
2 import { unstable_cache } from "next/cache"
3 import { notFound } from "next/navigation"
4 import { NextRequest, NextResponse } from "next/server"
5 import {
6 addUrlToRelativeLink,
7 crossProjectLinksPlugin,
8 localLinksRehypePlugin,
9 } from "remark-rehype-plugins"
10 import type { Plugin } from "unified"
11 import { filesMap } from "../../../generated/files-map.mjs"
12 import { slugChanges } from "../../../generated/slug-changes.mjs"
13 import { PostHog } from "posthog-node"
14 import { fetchMdxContent } from "../../../utils/fetch-mdx-content"
15 import { getSidebarForPath } from "../../../utils/get-sidebar-for-path"
16
17 type Params = {
18 params: Promise<{ slug?: string[] }>
19 }
20
21 export async function GET(req: NextRequest, { params }: Params) {
22 const { slug: rawSlug } = await params
23 const slug = rawSlug?.filter(Boolean) ?? []
24 const origin = process.env.NEXT_PUBLIC_BASE_URL || new URL(req.url).origin
25 const basePath = process.env.NEXT_PUBLIC_BASE_PATH || ""
26
27 const filePathFromMap = await getFileFromMaps(`/${slug.join("/")}`)
28
29 if (!filePathFromMap) {
30 return notFound()
31 }
32
33 // An `_md-content.mdx` file next to the page overrides it for this route,
34 // so a page can serve agents different content than it renders.
35 const overrideContent = filePathFromMap.endsWith("page.mdx")
36 ? await fetchMdxContent(
37 `${origin}${basePath}`,
38 filePathFromMap.replace(/page\.mdx$/, "_md-content.mdx")
39 )
40 : null
41
42 const fileContent =
43 overrideContent ??
44 (await fetchMdxContent(`${origin}${basePath}`, filePathFromMap))
45 if (!fileContent) {
46 return notFound()
47 }
48
49 const isOverride = !!overrideContent
50
51 // Reference pages are the JSON doc-model (page.json) — convert the DocPage to
52 // Markdown directly rather than running the MDX cleaner over it.
53 // the app directory that holds the source MDX pages, used to resolve
54 // relative `page.mdx` links against the current page's path
55 const appDir = filePathFromMap.replace(/\/app\/.*$/, "/app")
56
57 const cleanMdContent = filePathFromMap.endsWith("page.json")
58 ? await docPageToMarkdown_(fileContent)
59 : await getCleanMd_(fileContent, `/${slug.join("/")}`, {
60 before: [
61 [
62 crossProjectLinksPlugin,
63 {
64 baseUrl: process.env.NEXT_PUBLIC_BASE_URL,
65 projectUrls: {
66 docs: {
67 url: process.env.NEXT_PUBLIC_DOCS_URL,
68 path: "",
69 },
70 "user-guide": {
71 url: process.env.NEXT_PUBLIC_USER_GUIDE_URL,
72 },
73 ui: {
74 url: process.env.NEXT_PUBLIC_UI_URL,
75 },
76 api: {
77 url: process.env.NEXT_PUBLIC_API_URL,
78 },
79 },
80 useBaseUrl:
81 process.env.NODE_ENV === "production" ||
82 process.env.VERCEL_ENV === "production" ||
83 !!process.env.CLOUDFLARE_ENV,
84 },
85 ],
86 // in "content" mode there is no vfile path, so pass the current
87 // page's file path explicitly to resolve relative `page.mdx` links
88 [
89 localLinksRehypePlugin,
90 { filePath: filePathFromMap, basePath: appDir },
91 ],
92 ] as unknown as Plugin[],
93 after: [
94 // links in the doc are app-relative (without the base path), so
95 // prepend both the base URL and the base path to make them absolute
96 [
97 addUrlToRelativeLink,
98 { url: `${process.env.NEXT_PUBLIC_BASE_URL || ""}${basePath}` },
99 ],
100 ] as unknown as Plugin[],
101 })
102
103 const acceptHeader = req.headers.get("accept") || ""
104 if (
105 acceptHeader.includes("text/plain") ||
106 acceptHeader.includes("text/markdown")
107 ) {
108 const client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
109 host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
110 })
111
112 const urlObj = new URL(req.url)
113 const url = `${process.env.NEXT_PUBLIC_BASE_URL || ""}${process.env.NEXT_PUBLIC_BASE_PATH || ""}${urlObj.pathname}`
114
115 client.capture({
116 distinctId: "anonymous",
117 event: "md_content_requested_agents",
118 properties: {
119 $current_url: url,
120 $raw_user_agent: req.headers.get("user-agent") || undefined,
121 $ip:
122 req.headers.get("cf-connecting-ip") ||
123 req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
124 undefined,
125 },
126 })
127
128 await client.shutdown()
129 }
130
131 return new NextResponse(
132 isOverride
133 ? cleanMdContent
134 : addExtraToMd(cleanMdContent, {
135 baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "",
136 basePath: process.env.NEXT_PUBLIC_BASE_PATH || "",
137 }),
138 {
139 headers: {
140 "Content-Type": "text/markdown",
141 "Cache-Control": "public, max-age=3600, must-revalidate",
142 },
143 status: 200,
144 }
145 )
146 }
147
148 const getCleanMd_ = unstable_cache(
149 async (
150 content: string,
151 currentPath: string,
152 plugins?: { before?: Plugin[]; after?: Plugin[] }
153 ) => {
154 // `ChildDocs` renders the child items of the current sidebar, so resolve
155 // the sidebar for this path and pass it (along with the path and base path)
156 // to the parser that reproduces the component's output as Markdown.
157 const sidebar = await getSidebarForPath(currentPath)
158 return getCleanMd({
159 file: content,
160 type: "content",
161 plugins,
162 parserOptions: {
163 ChildDocs: {
164 sidebar,
165 activePath: currentPath,
166 },
167 },
168 })
169 },
170 ["clean-md"],
171 {
172 revalidate: 3600,
173 }
174 )
175
176 /** Converts a reference DocPage JSON string to Markdown. */
177 const docPageToMarkdown_ = unstable_cache(
178 async (content: string): Promise<string> => {
179 try {
180 return docPageToMarkdown(JSON.parse(content), {
181 baseUrl: process.env.NEXT_PUBLIC_BASE_URL,
182 })
183 } catch {
184 return ""
185 }
186 },
187 ["doc-page-md"],
188 {
189 revalidate: 3600,
190 }
191 )
192
193 const getFileFromMaps = unstable_cache(
194 async (path: string) => {
195 return (
196 slugChanges.find((slugChange) => slugChange.newSlug === path)?.filePath ||
197 filesMap.find((file) => file.pathname === path)?.filePath
198 )
199 },
200 ["file-map"],
201 {
202 revalidate: 3600,
203 }
204 )