1 import { OpenAPI } from "types"
2 import { parseDocument } from "yaml"
3 import { workerCompatibleFetch } from "docs-utils"
4 import { readSpecFromBinding } from "./read-spec-from-binding"
5
6 export default async function readSpecDocument(filePath: string) {
7 const fileContent =
8 (await readSpecFromBinding(filePath)) ??
9 (await workerCompatibleFetch<string>({
10 url: filePath,
11 responseTransformer: async (res) => {
12 if (!res.ok) {
13 throw new Error(`Failed to fetch spec: ${filePath} (${res.status})`)
14 }
15 return await res.text()
16 },
17 fallbackAction: async () => {
18 // In local development, we can read the spec directly from the filesystem
19 const { readFileSync, existsSync } = await import("fs")
20
21 if (!existsSync(filePath)) {
22 throw new Error(`Spec file not found: ${filePath}`)
23 }
24 return readFileSync(filePath, "utf-8")
25 },
26 }))
27 return parseDocument(fileContent).toJS() as OpenAPI.OpenAPIV3.PathItemObject
28 }