|
1
|
import { parseDocument } from "yaml" |
|
2
|
import { OpenAPI } from "types" |
|
3
|
import dereference from "./dereference" |
|
4
|
import { unstable_cache } from "next/cache" |
|
5
|
import { workerCompatibleFetch } from "docs-utils" |
|
6
|
import { readSpecFromBinding } from "./read-spec-from-binding" |
|
7
|
|
|
8
|
async function getSchemaContent_(schemaUrl: string, baseSchemasUrl: string) { |
|
9
|
const schemaContent = |
|
10
|
(await readSpecFromBinding(schemaUrl)) ?? |
|
11
|
(await workerCompatibleFetch<string>({ |
|
12
|
url: schemaUrl, |
|
13
|
responseTransformer: async (res) => { |
|
14
|
if (!res.ok) { |
|
15
|
throw new Error( |
|
16
|
`Failed to fetch schema: ${schemaUrl} (${res.status})` |
|
17
|
) |
|
18
|
} |
|
19
|
return await res.text() |
|
20
|
}, |
|
21
|
fallbackAction: async () => { |
|
22
|
// In local development, we can read the schema directly from the filesystem |
|
23
|
const { readFileSync, existsSync } = await import("fs") |
|
24
|
|
|
25
|
if (!existsSync(schemaUrl)) { |
|
26
|
throw new Error(`Schema file not found: ${schemaUrl}`) |
|
27
|
} |
|
28
|
return readFileSync(schemaUrl, "utf-8") |
|
29
|
}, |
|
30
|
})) |
|
31
|
const schema = parseDocument(schemaContent).toJS() as OpenAPI.SchemaObject |
|
32
|
|
|
33
|
// resolve references in schema |
|
34
|
const dereferencedDocument = await dereference({ |
|
35
|
basePath: baseSchemasUrl, |
|
36
|
schemas: [schema], |
|
37
|
}) |
|
38
|
|
|
39
|
return { |
|
40
|
dereferencedDocument, |
|
41
|
originalSchema: schema, |
|
42
|
} |
|
43
|
} |
|
44
|
|
|
45
|
const getSchemaContent = unstable_cache( |
|
46
|
async (schemaUrl: string, baseSchemasUrl: string) => |
|
47
|
getSchemaContent_(schemaUrl, baseSchemasUrl), |
|
48
|
["tag-schema"] |
|
49
|
) |
|
50
|
|
|
51
|
export default getSchemaContent |