1 import path from "path"
2 import {
3 throwErrorResponse,
4 withRouteErrorHandling,
5 workerCompatibleFetch,
6 } from "docs-utils"
7 import { getPathForEnv } from "../../../utils/get-path-for-env"
8 import { readSpecFromBinding } from "../../../utils/read-spec-from-binding"
9
10 type DownloadParams = {
11 params: Promise<{
12 area: string
13 }>
14 }
15
16 export const GET = withRouteErrorHandling(
17 async (request: Request, props: DownloadParams) => {
18 const params = await props.params
19 const { area } = params
20 const { searchParams } = new URL(request.url)
21 const version = searchParams.get("version")
22
23 const r2Base = process.env.SPECS_R2_BASE_URL
24 const basePath = r2Base
25 ? `${r2Base}/specs`
26 : path.join(process.cwd(), "specs")
27
28 // A requested version resolves to its own spec only — falling back to the
29 // default spec would return the wrong document for an unknown version.
30 const specUrl = version
31 ? getPathForEnv(basePath, "versions", version, area, "openapi.full.yaml")
32 : getPathForEnv(basePath, area, "openapi.full.yaml")
33
34 let fileContent: string | null = await readSpecFromBinding(specUrl)
35
36 fileContent ??= await workerCompatibleFetch<string | null>({
37 url: specUrl,
38 responseTransformer: async (res) => {
39 if (res.status === 404) {
40 return null
41 }
42 if (!res.ok) {
43 throw new Error(`Failed to fetch spec: ${res.status}`)
44 }
45 return await res.text()
46 },
47 fallbackAction: async () => {
48 // In local development, we can read the spec directly from the filesystem
49 const { readFileSync, existsSync } = await import("fs")
50
51 if (!existsSync(specUrl)) {
52 return null
53 }
54 return readFileSync(specUrl, "utf-8")
55 },
56 })
57
58 if (!fileContent) {
59 throwErrorResponse(
60 404,
61 version
62 ? `No OpenAPI spec found for area "${area}" and version "${version}"`
63 : `No OpenAPI spec found for area "${area}"`
64 )
65 }
66
67 return new Response(fileContent, {
68 headers: {
69 "Content-Type": "application/x-yaml",
70 "Content-Disposition": `attachment; filename="openapi.yaml"`,
71 },
72 })
73 }
74 )