1 import { addExtraToMd, 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 path from "path"
6 import { PostHog } from "posthog-node"
7 import {
8 addUrlToRelativeLink,
9 crossProjectLinksPlugin,
10 localLinksRehypePlugin,
11 } from "remark-rehype-plugins"
12 import type { Plugin } from "unified"
13 import { fetchRawMdx } from "../../../utils/fetch-raw-mdx"
14 import { getChangelogMarkdown } from "../../../utils/changelog"
15 import { getPricingMarkdown } from "../../../utils/pricing"
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 const isCloudflare = !!process.env.CLOUDFLARE_ENV
27
28 const result = await fetchRawMdx(origin, basePath, slug)
29
30 if (!result) {
31 return notFound()
32 }
33
34 const { content: fileContent, isOverride } = result
35
36 // The changelog and pricing pages render their content from generated files
37 // and Sanity, so their Markdown must be built here rather than read from the
38 // MDX file.
39 const parserOptions = await getParserOptions(
40 slug,
41 process.env.NEXT_PUBLIC_BASE_URL || origin
42 )
43
44 const cleanMdContent = await getCleanMd_(fileContent, parserOptions, {
45 before: [
46 [
47 crossProjectLinksPlugin,
48 {
49 baseUrl: process.env.NEXT_PUBLIC_BASE_URL,
50 projectUrls: {
51 docs: {
52 url: process.env.NEXT_PUBLIC_DOCS_URL,
53 path: "",
54 },
55 resources: {
56 url: process.env.NEXT_PUBLIC_RESOURCES_URL,
57 },
58 ui: {
59 url: process.env.NEXT_PUBLIC_UI_URL,
60 },
61 api: {
62 url: process.env.NEXT_PUBLIC_API_URL,
63 },
64 "user-guide": {
65 projectPath: path.resolve("..", "user-guide"),
66 },
67 },
68 useBaseUrl:
69 process.env.NODE_ENV === "production" ||
70 process.env.VERCEL_ENV === "production" ||
71 isCloudflare,
72 },
73 ],
74 [localLinksRehypePlugin],
75 ] as unknown as Plugin[],
76 after: [
77 [addUrlToRelativeLink, { url: process.env.NEXT_PUBLIC_BASE_URL }],
78 ] as unknown as Plugin[],
79 })
80
81 const acceptHeader = req.headers.get("accept") || ""
82 if (
83 acceptHeader.includes("text/plain") ||
84 acceptHeader.includes("text/markdown")
85 ) {
86 const client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
87 host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
88 })
89
90 const urlObj = new URL(req.url)
91 const url = `${process.env.NEXT_PUBLIC_BASE_URL || ""}${process.env.NEXT_PUBLIC_BASE_PATH || ""}${urlObj.pathname}`
92
93 client.capture({
94 distinctId: "anonymous",
95 event: "md_content_requested_agents",
96 properties: {
97 $current_url: url,
98 $raw_user_agent: req.headers.get("user-agent") || undefined,
99 $ip:
100 req.headers.get("cf-connecting-ip") ||
101 req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
102 undefined,
103 },
104 })
105
106 await client.shutdown()
107 }
108
109 return new NextResponse(
110 isOverride
111 ? cleanMdContent
112 : addExtraToMd(cleanMdContent, {
113 baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "",
114 basePath: process.env.NEXT_PUBLIC_BASE_PATH || "",
115 }),
116 {
117 headers: {
118 "Content-Type": "text/markdown",
119 "Cache-Control": "public, max-age=3600, must-revalidate",
120 },
121 status: 200,
122 }
123 )
124 }
125
126 const getParserOptions = async (
127 slug: string[],
128 baseUrl: string
129 ): Promise<Record<string, unknown> | undefined> => {
130 if (slug.length !== 1) {
131 return
132 }
133
134 switch (slug[0]) {
135 case "changelog":
136 return {
137 ChangelogList: { content: await getChangelogMarkdown(baseUrl) },
138 }
139 case "pricing":
140 return {
141 PricingContent: { content: await getPricingMarkdown(baseUrl) },
142 }
143 }
144 }
145
146 const getCleanMd_ = unstable_cache(
147 async (
148 content: string,
149 parserOptions?: Record<string, unknown>,
150 plugins?: { before?: Plugin[]; after?: Plugin[] }
151 ) => getCleanMd({ file: content, type: "content", parserOptions, plugins }),
152 ["clean-md"],
153 {
154 revalidate: 3600,
155 }
156 )