1 import { workerCompatibleFetch } from "docs-utils"
2 import path from "path"
3 import { fetchFromAssetsBinding } from "./fetch-from-assets-binding"
4
5 async function fetchRawMdxFile(
6 origin: string,
7 slug: string[],
8 fileName: string
9 ): Promise<string | null> {
10 const isCloudflare = !!process.env.CLOUDFLARE_ENV
11 const url = `${origin}/raw-mdx/${[...slug, fileName].join("/")}`
12
13 return (
14 (await fetchFromAssetsBinding(url)) ??
15 (await workerCompatibleFetch<string | null>({
16 url,
17 responseTransformer: async (res) => {
18 return res.ok ? res.text() : null
19 },
20 fallbackAction: async () => {
21 try {
22 const { promises: fs } = await import("fs")
23 return await fs.readFile(
24 path.join(process.cwd(), "app", ...slug, fileName),
25 "utf-8"
26 )
27 } catch {
28 return null
29 }
30 },
31 useRemote: isCloudflare,
32 }))
33 )
34 }
35
36 export async function fetchRawMdx(
37 origin: string,
38 slug: string[]
39 ): Promise<{ content: string; isOverride: boolean } | null> {
40 // An `_md-content.mdx` file overrides `page.mdx` if it exists.
41 const overrideContent = await fetchRawMdxFile(origin, slug, "_md-content.mdx")
42
43 if (overrideContent) {
44 return { content: overrideContent, isOverride: true }
45 }
46
47 const pageContent = await fetchRawMdxFile(origin, slug, "page.mdx")
48
49 return pageContent ? { content: pageContent, isOverride: false } : null
50 }