@stacksjs/components 0.2.991 → 0.2.997
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ApiOperation-369y1zgt.stx +114 -0
- package/dist/ApiReference-ww45jj32.stx +92 -0
- package/dist/ApiSchema-dsx4tsv4.stx +47 -0
- package/dist/AreaChart-8fy34adp.stx +77 -0
- package/dist/BarChart-4xdrjhhn.stx +77 -0
- package/dist/{Combobox-9n04ec5w.stx → Combobox-fgbpxbty.stx} +174 -5
- package/dist/ComboboxOptions-sfkc98a9.stx +36 -0
- package/dist/{CommandPalette-cj6pe5ph.stx → CommandPalette-sf03s7b2.stx} +3 -1
- package/dist/LineChart-ctebkkm8.stx +77 -0
- package/dist/{Notification-ke5vw4k8.stx → Notification-1pvt347q.stx} +11 -3
- package/dist/{Popover-jjt7p7sn.stx → Popover-gntg33xd.stx} +1 -1
- package/dist/PricingPlan-h7jt2696.stx +67 -0
- package/dist/PricingTable-v3vdn6av.stx +149 -0
- package/dist/SecretField-q2xgth94.stx +219 -0
- package/dist/{Select-36s22z6d.stx → Select-yhmtvqcx.stx} +7 -4
- package/dist/Sparkline-gp859n4h.stx +29 -0
- package/dist/StatCard-gff0yx6b.stx +93 -0
- package/dist/StatGroup-e0d5dmt7.stx +17 -0
- package/dist/components/CodeBlock.d.ts +4 -1
- package/dist/components/CodeGroup.d.ts +34 -0
- package/dist/components/code-group.d.ts +19 -0
- package/dist/components/index.d.ts +2 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +25 -22
- package/dist/ui/api-reference/ApiOperation.d.ts +17 -0
- package/dist/ui/api-reference/ApiReference.d.ts +28 -0
- package/dist/ui/api-reference/ApiSchema.d.ts +17 -0
- package/dist/ui/api-reference/index.d.ts +30 -0
- package/dist/ui/api-reference/openapi.d.ts +137 -0
- package/dist/ui/chart/AreaChart.d.ts +33 -0
- package/dist/ui/chart/BarChart.d.ts +33 -0
- package/dist/ui/chart/LineChart.d.ts +33 -0
- package/dist/ui/chart/Sparkline.d.ts +19 -0
- package/dist/ui/chart/core.d.ts +111 -0
- package/dist/ui/chart/index.d.ts +51 -0
- package/dist/ui/chart/interaction.d.ts +11 -0
- package/dist/ui/combobox/Combobox.d.ts +10 -1
- package/dist/ui/combobox/ComboboxOptions.d.ts +6 -0
- package/dist/ui/combobox/index.d.ts +7 -0
- package/dist/ui/command-palette/CommandPalette.d.ts +2 -0
- package/dist/ui/input/SecretField.d.ts +56 -0
- package/dist/ui/input/index.d.ts +21 -0
- package/dist/ui/notification/Notification.d.ts +2 -0
- package/dist/ui/pricing/PricingPlan.d.ts +21 -0
- package/dist/ui/pricing/PricingTable.d.ts +50 -0
- package/dist/ui/pricing/index.d.ts +38 -0
- package/dist/ui/pricing/pricing.d.ts +64 -0
- package/dist/ui/select/Select.d.ts +2 -0
- package/dist/ui/stat/StatCard.d.ts +42 -0
- package/dist/ui/stat/StatGroup.d.ts +12 -0
- package/dist/ui/stat/format.d.ts +37 -0
- package/dist/ui/stat/index.d.ts +23 -0
- package/package.json +3 -3
- package/src/components/CodeBlock.stx +4 -1
- package/src/components/CodeGroup.stx +217 -0
- package/src/components/code-group.ts +57 -0
- package/src/components/index.ts +2 -0
- package/src/index.ts +18 -0
- package/src/ui/api-reference/ApiOperation.stx +114 -0
- package/src/ui/api-reference/ApiReference.stx +92 -0
- package/src/ui/api-reference/ApiSchema.stx +47 -0
- package/src/ui/api-reference/README.md +44 -0
- package/src/ui/api-reference/index.ts +35 -0
- package/src/ui/api-reference/openapi.ts +825 -0
- package/src/ui/chart/AreaChart.stx +77 -0
- package/src/ui/chart/BarChart.stx +77 -0
- package/src/ui/chart/LineChart.stx +77 -0
- package/src/ui/chart/README.md +97 -0
- package/src/ui/chart/Sparkline.stx +29 -0
- package/src/ui/chart/core.ts +730 -0
- package/src/ui/chart/index.ts +71 -0
- package/src/ui/chart/interaction.ts +175 -0
- package/src/ui/combobox/Combobox.stx +174 -5
- package/src/ui/combobox/ComboboxOptions.stx +20 -0
- package/src/ui/combobox/README.md +41 -0
- package/src/ui/combobox/index.ts +13 -0
- package/src/ui/command-palette/CommandPalette.stx +3 -1
- package/src/ui/input/SecretField.stx +219 -0
- package/src/ui/input/index.ts +32 -0
- package/src/ui/notification/Notification.stx +11 -3
- package/src/ui/popover/Popover.stx +1 -1
- package/src/ui/pricing/PricingPlan.stx +67 -0
- package/src/ui/pricing/PricingTable.stx +149 -0
- package/src/ui/pricing/README.md +74 -0
- package/src/ui/pricing/index.ts +49 -0
- package/src/ui/pricing/pricing.ts +177 -0
- package/src/ui/select/Select.stx +7 -4
- package/src/ui/stat/README.md +60 -0
- package/src/ui/stat/StatCard.stx +93 -0
- package/src/ui/stat/StatGroup.stx +17 -0
- package/src/ui/stat/format.ts +147 -0
- package/src/ui/stat/index.ts +38 -0
- package/dist/ComboboxOptions-zhr9b6rx.stx +0 -16
|
@@ -0,0 +1,825 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAPI 3.0 / 3.1 to an API reference model (stacksjs/stx#2324).
|
|
3
|
+
*
|
|
4
|
+
* `loadOpenApi` reads a document (an object, a path to JSON or YAML, or a URL)
|
|
5
|
+
* and validates it, failing with a message that names the offending path.
|
|
6
|
+
* `buildApiReference` turns it into a model a template renders without any
|
|
7
|
+
* logic of its own: operations grouped by tag, parameters and bodies and
|
|
8
|
+
* responses with `$ref` resolved, schemas flattened to rows, the security each
|
|
9
|
+
* operation needs, request examples in curl, JavaScript and Python, stable
|
|
10
|
+
* anchors, a table of contents and search index entries.
|
|
11
|
+
*
|
|
12
|
+
* No dependency: YAML goes through Bun's own parser.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export type JsonObject = Record<string, any>
|
|
16
|
+
|
|
17
|
+
export class OpenApiError extends Error {
|
|
18
|
+
/** Where in the document, as a JSON pointer-ish path: `paths./keys.get.responses`. */
|
|
19
|
+
readonly path: string
|
|
20
|
+
/** Thrown from a server script, it fails the build that renders the page (stx reads this flag). */
|
|
21
|
+
readonly stxBuildFailure = true
|
|
22
|
+
constructor(path: string, message: string) {
|
|
23
|
+
super(`Invalid OpenAPI document at ${path || '(root)'}: ${message}`)
|
|
24
|
+
this.name = 'OpenApiError'
|
|
25
|
+
this.path = path
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const
|
|
30
|
+
type Method = typeof METHODS[number]
|
|
31
|
+
|
|
32
|
+
/** Parse JSON or YAML text. */
|
|
33
|
+
export function parseOpenApiText(text: string, source = 'document'): JsonObject {
|
|
34
|
+
const trimmed = text.trim()
|
|
35
|
+
if (trimmed.startsWith('{')) {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(trimmed)
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw new OpenApiError('', `${source} is not valid JSON (${(error as Error).message})`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const yaml = (globalThis as { Bun?: { YAML?: { parse: (s: string) => unknown } } }).Bun?.YAML
|
|
44
|
+
if (!yaml)
|
|
45
|
+
throw new OpenApiError('', `${source} looks like YAML, which needs Bun's YAML parser; give the document as JSON`)
|
|
46
|
+
try {
|
|
47
|
+
return yaml.parse(trimmed) as JsonObject
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
throw new OpenApiError('', `${source} is not valid YAML (${(error as Error).message})`)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function readText(location: string): Promise<string> {
|
|
55
|
+
if (/^https?:\/\//i.test(location)) {
|
|
56
|
+
const response = await fetch(location)
|
|
57
|
+
if (!response.ok)
|
|
58
|
+
throw new OpenApiError('', `could not fetch ${location} (${response.status})`)
|
|
59
|
+
return response.text()
|
|
60
|
+
}
|
|
61
|
+
const file = (globalThis as { Bun?: { file: (p: string) => { exists: () => Promise<boolean>, text: () => Promise<string> } } }).Bun?.file(location)
|
|
62
|
+
if (!file || !(await file.exists()))
|
|
63
|
+
throw new OpenApiError('', `no OpenAPI document at ${location}`)
|
|
64
|
+
return file.text()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function resolveLocation(base: string, relative: string): string {
|
|
68
|
+
if (/^https?:\/\//i.test(relative) || relative.startsWith('/'))
|
|
69
|
+
return relative
|
|
70
|
+
if (/^https?:\/\//i.test(base))
|
|
71
|
+
return new URL(relative, base).href
|
|
72
|
+
const dir = base.includes('/') ? base.slice(0, base.lastIndexOf('/') + 1) : ''
|
|
73
|
+
return dir + relative
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function pointerInto(doc: unknown, pointer: string, at: string): unknown {
|
|
77
|
+
let target: any = doc
|
|
78
|
+
for (const part of pointer.replace(/^#?\/?/, '').split('/').filter(Boolean).map(p => p.replace(/~1/g, '/').replace(/~0/g, '~'))) {
|
|
79
|
+
target = target?.[part]
|
|
80
|
+
if (target === undefined)
|
|
81
|
+
throw new OpenApiError(at, `#/${pointer.replace(/^#?\/?/, '')} does not exist`)
|
|
82
|
+
}
|
|
83
|
+
return target
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Inline every `$ref` to another file (`./schemas/key.yaml#/Key`), relative
|
|
88
|
+
* to the document that holds it, so the rest of the renderer only ever meets
|
|
89
|
+
* local references. A file is read once; a cycle through files keeps its
|
|
90
|
+
* reference rather than recursing.
|
|
91
|
+
*/
|
|
92
|
+
export async function bundleExternalRefs(doc: JsonObject, location: string): Promise<JsonObject> {
|
|
93
|
+
const files = new Map<string, Promise<unknown>>()
|
|
94
|
+
const load = (where: string): Promise<unknown> => {
|
|
95
|
+
if (!files.has(where))
|
|
96
|
+
files.set(where, readText(where).then(text => parseOpenApiText(text, where)))
|
|
97
|
+
return files.get(where)!
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function visit(node: unknown, base: string, at: string, active: Set<string>): Promise<unknown> {
|
|
101
|
+
if (Array.isArray(node))
|
|
102
|
+
return Promise.all(node.map((item, i) => visit(item, base, `${at}[${i}]`, active)))
|
|
103
|
+
if (!node || typeof node !== 'object')
|
|
104
|
+
return node
|
|
105
|
+
const ref = (node as JsonObject).$ref
|
|
106
|
+
// Another file's ref, or a `#/...` ref inside another file (local to THAT file).
|
|
107
|
+
if (typeof ref === 'string' && (!ref.startsWith('#') || base !== location)) {
|
|
108
|
+
const [file, pointer = ''] = ref.split('#')
|
|
109
|
+
const where = file ? resolveLocation(base, file) : base
|
|
110
|
+
const key = `${where}#${pointer}`
|
|
111
|
+
if (active.has(key))
|
|
112
|
+
return node
|
|
113
|
+
const target = pointerInto(await load(where), pointer, at)
|
|
114
|
+
return visit(target, where, at, new Set(active).add(key))
|
|
115
|
+
}
|
|
116
|
+
const out: JsonObject = {}
|
|
117
|
+
for (const [k, v] of Object.entries(node as JsonObject))
|
|
118
|
+
out[k] = await visit(v, base, at ? `${at}.${k}` : k, active)
|
|
119
|
+
return out
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return await visit(doc, location, '', new Set()) as JsonObject
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Read a document from an object, a file path or a URL, at build time, and validate it. */
|
|
126
|
+
export async function loadOpenApi(input: unknown): Promise<JsonObject> {
|
|
127
|
+
let doc: unknown = input
|
|
128
|
+
let location = ''
|
|
129
|
+
if (typeof input === 'string') {
|
|
130
|
+
if (input.trim().startsWith('{') || /^\s*openapi\s*:/m.test(input)) {
|
|
131
|
+
doc = parseOpenApiText(input)
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
location = input
|
|
135
|
+
doc = parseOpenApiText(await readText(input), input)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (location && doc && typeof doc === 'object')
|
|
139
|
+
doc = await bundleExternalRefs(doc as JsonObject, location)
|
|
140
|
+
validateOpenApi(doc)
|
|
141
|
+
return doc as JsonObject
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The checks a renderer depends on. Throws `OpenApiError` naming the first offending path. */
|
|
145
|
+
export function validateOpenApi(doc: unknown): asserts doc is JsonObject {
|
|
146
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc))
|
|
147
|
+
throw new OpenApiError('', 'the document must be an object')
|
|
148
|
+
const d = doc as JsonObject
|
|
149
|
+
if (typeof d.openapi !== 'string' || !/^3\.[01]\./.test(d.openapi))
|
|
150
|
+
throw new OpenApiError('openapi', `expected a 3.0.x or 3.1.x version string, found ${JSON.stringify(d.openapi)}`)
|
|
151
|
+
if (!d.info || typeof d.info !== 'object')
|
|
152
|
+
throw new OpenApiError('info', 'is required')
|
|
153
|
+
if (typeof d.info.title !== 'string')
|
|
154
|
+
throw new OpenApiError('info.title', 'is required')
|
|
155
|
+
if (d.paths !== undefined && (typeof d.paths !== 'object' || Array.isArray(d.paths)))
|
|
156
|
+
throw new OpenApiError('paths', 'must be an object')
|
|
157
|
+
if (d.webhooks !== undefined && (typeof d.webhooks !== 'object' || Array.isArray(d.webhooks)))
|
|
158
|
+
throw new OpenApiError('webhooks', 'must be an object')
|
|
159
|
+
for (const [route, item] of Object.entries<JsonObject>(d.paths || {}))
|
|
160
|
+
checkPathItem(d, `paths.${route}`, item, route)
|
|
161
|
+
for (const [name, item] of Object.entries<JsonObject>(d.webhooks || {}))
|
|
162
|
+
checkPathItem(d, `webhooks.${name}`, item, null)
|
|
163
|
+
// Every $ref must point at something.
|
|
164
|
+
walkRefs(d, d, '')
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function checkPathItem(d: JsonObject, base: string, rawItem: unknown, route: string | null): void {
|
|
168
|
+
if (route !== null && !route.startsWith('/'))
|
|
169
|
+
throw new OpenApiError(base, 'a path must start with "/"')
|
|
170
|
+
const item = resolveRef(d, rawItem, base)
|
|
171
|
+
if (!item || typeof item !== 'object')
|
|
172
|
+
throw new OpenApiError(base, 'must be a path item object')
|
|
173
|
+
for (const method of METHODS) {
|
|
174
|
+
const op = item[method]
|
|
175
|
+
if (op === undefined)
|
|
176
|
+
continue
|
|
177
|
+
const at = `${base}.${method}`
|
|
178
|
+
if (!op || typeof op !== 'object')
|
|
179
|
+
throw new OpenApiError(at, 'must be an operation object')
|
|
180
|
+
if (!op.responses || typeof op.responses !== 'object' || !Object.keys(op.responses).length)
|
|
181
|
+
throw new OpenApiError(`${at}.responses`, 'an operation needs at least one response')
|
|
182
|
+
for (const [i, p] of (op.parameters || []).entries())
|
|
183
|
+
checkParameter(d, p, `${at}.parameters[${i}]`)
|
|
184
|
+
}
|
|
185
|
+
for (const [i, p] of (item.parameters || []).entries())
|
|
186
|
+
checkParameter(d, p, `${base}.parameters[${i}]`)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function checkParameter(doc: JsonObject, raw: unknown, at: string): void {
|
|
190
|
+
const p = resolveRef(doc, raw, at)
|
|
191
|
+
if (!p || typeof p !== 'object')
|
|
192
|
+
throw new OpenApiError(at, 'must be a parameter object')
|
|
193
|
+
if (typeof p.name !== 'string' || !p.name)
|
|
194
|
+
throw new OpenApiError(`${at}.name`, 'is required')
|
|
195
|
+
if (!['query', 'header', 'path', 'cookie'].includes(p.in))
|
|
196
|
+
throw new OpenApiError(`${at}.in`, `must be query, header, path or cookie, found ${JSON.stringify(p.in)}`)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function walkRefs(doc: JsonObject, node: unknown, at: string, seen = new Set<unknown>()): void {
|
|
200
|
+
if (!node || typeof node !== 'object' || seen.has(node))
|
|
201
|
+
return
|
|
202
|
+
seen.add(node)
|
|
203
|
+
if (typeof (node as JsonObject).$ref === 'string')
|
|
204
|
+
resolveRef(doc, node, at)
|
|
205
|
+
for (const [key, value] of Object.entries(node as JsonObject))
|
|
206
|
+
walkRefs(doc, value, at ? `${at}.${key}` : key, seen)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Follow a local `$ref` (`#/components/schemas/Key`). */
|
|
210
|
+
export function resolveRef(doc: JsonObject, node: unknown, at = ''): any {
|
|
211
|
+
let current: any = node
|
|
212
|
+
const chain = new Set<string>()
|
|
213
|
+
while (current && typeof current === 'object' && typeof current.$ref === 'string') {
|
|
214
|
+
const ref: string = current.$ref
|
|
215
|
+
if (chain.has(ref))
|
|
216
|
+
return current
|
|
217
|
+
chain.add(ref)
|
|
218
|
+
if (!ref.startsWith('#/'))
|
|
219
|
+
throw new OpenApiError(at, `${ref} is in another file, which is resolved only when the document is loaded from a path or URL`)
|
|
220
|
+
let target: any = doc
|
|
221
|
+
for (const part of ref.slice(2).split('/').map(p => p.replace(/~1/g, '/').replace(/~0/g, '~'))) {
|
|
222
|
+
target = target?.[part]
|
|
223
|
+
if (target === undefined)
|
|
224
|
+
throw new OpenApiError(at, `${ref} does not exist`)
|
|
225
|
+
}
|
|
226
|
+
current = target
|
|
227
|
+
}
|
|
228
|
+
return current
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function slugify(value: string): string {
|
|
232
|
+
return value.toLowerCase().replace(/\{([^}]+)\}/g, '$1').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'item'
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export interface SchemaRow {
|
|
236
|
+
/** Dotted from the top: `data.items[].name`. */
|
|
237
|
+
name: string
|
|
238
|
+
depth: number
|
|
239
|
+
type: string
|
|
240
|
+
required: boolean
|
|
241
|
+
description: string
|
|
242
|
+
/** Enum, format, default, constraints, in words. */
|
|
243
|
+
notes: string[]
|
|
244
|
+
/** The named schema this row is, for a link: `schema-key`. */
|
|
245
|
+
ref?: string
|
|
246
|
+
/** `oneOf`, `anyOf` or `allOf` heading this row's alternatives. */
|
|
247
|
+
combinator?: 'oneOf' | 'anyOf' | 'allOf'
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export interface ApiParameter {
|
|
251
|
+
name: string
|
|
252
|
+
in: 'query' | 'header' | 'path' | 'cookie'
|
|
253
|
+
required: boolean
|
|
254
|
+
type: string
|
|
255
|
+
description: string
|
|
256
|
+
deprecated: boolean
|
|
257
|
+
example?: unknown
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export interface ApiBody {
|
|
261
|
+
mediaType: string
|
|
262
|
+
required: boolean
|
|
263
|
+
description: string
|
|
264
|
+
rows: SchemaRow[]
|
|
265
|
+
ref?: string
|
|
266
|
+
/** The named schema the body is, when it is one. */
|
|
267
|
+
schema?: string
|
|
268
|
+
example: string
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export interface ApiResponse {
|
|
272
|
+
status: string
|
|
273
|
+
description: string
|
|
274
|
+
mediaType: string
|
|
275
|
+
rows: SchemaRow[]
|
|
276
|
+
ref?: string
|
|
277
|
+
schema?: string
|
|
278
|
+
example: string
|
|
279
|
+
/** Response headers: name, type and description. */
|
|
280
|
+
headers: Array<{ name: string, type: string, description: string, required: boolean }>
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export interface ApiSecurityScheme {
|
|
284
|
+
name: string
|
|
285
|
+
anchor: string
|
|
286
|
+
type: string
|
|
287
|
+
/** `Header X-Api-Key`, `Bearer (JWT)`, `OAuth 2 (authorizationCode)`. */
|
|
288
|
+
summary: string
|
|
289
|
+
description: string
|
|
290
|
+
/** For an apiKey scheme. */
|
|
291
|
+
in?: string
|
|
292
|
+
paramName?: string
|
|
293
|
+
scheme?: string
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export interface ApiOperation {
|
|
297
|
+
id: string
|
|
298
|
+
anchor: string
|
|
299
|
+
method: string
|
|
300
|
+
path: string
|
|
301
|
+
summary: string
|
|
302
|
+
description: string
|
|
303
|
+
deprecated: boolean
|
|
304
|
+
tag: string
|
|
305
|
+
parameters: ApiParameter[]
|
|
306
|
+
body: ApiBody | null
|
|
307
|
+
responses: ApiResponse[]
|
|
308
|
+
/** Each alternative is a set of schemes that must all be present. Empty: no auth. */
|
|
309
|
+
security: Array<Array<{ name: string, anchor: string, scopes: string[] }>>
|
|
310
|
+
/** Request examples; null for a webhook, which the API sends rather than receives. */
|
|
311
|
+
examples: { curl: string, javascript: string, python: string } | null
|
|
312
|
+
/** A 3.1 `webhooks` entry: a request the API makes to the subscriber. */
|
|
313
|
+
webhook: boolean
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export interface ApiTag {
|
|
317
|
+
name: string
|
|
318
|
+
anchor: string
|
|
319
|
+
description: string
|
|
320
|
+
operations: ApiOperation[]
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export interface ApiSchema {
|
|
324
|
+
name: string
|
|
325
|
+
anchor: string
|
|
326
|
+
description: string
|
|
327
|
+
type: string
|
|
328
|
+
rows: SchemaRow[]
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export interface ApiReferenceModel {
|
|
332
|
+
title: string
|
|
333
|
+
version: string
|
|
334
|
+
description: string
|
|
335
|
+
baseUrl: string
|
|
336
|
+
tags: ApiTag[]
|
|
337
|
+
schemas: ApiSchema[]
|
|
338
|
+
securitySchemes: ApiSecurityScheme[]
|
|
339
|
+
toc: Array<{ text: string, anchor: string, children: Array<{ text: string, anchor: string, method?: string }> }>
|
|
340
|
+
search: Array<{ title: string, anchor: string, text: string, kind: 'operation' | 'schema' | 'tag' }>
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function schemaName(node: unknown): string | undefined {
|
|
344
|
+
const ref = node && typeof node === 'object' ? (node as JsonObject).$ref : undefined
|
|
345
|
+
if (typeof ref === 'string' && ref.startsWith('#/components/schemas/'))
|
|
346
|
+
return ref.slice('#/components/schemas/'.length)
|
|
347
|
+
return undefined
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function typeOf(doc: JsonObject, raw: unknown): string {
|
|
351
|
+
const name = schemaName(raw)
|
|
352
|
+
const s = resolveRef(doc, raw)
|
|
353
|
+
if (!s || typeof s !== 'object')
|
|
354
|
+
return 'any'
|
|
355
|
+
if (name)
|
|
356
|
+
return name
|
|
357
|
+
if (s.oneOf)
|
|
358
|
+
return 'one of'
|
|
359
|
+
if (s.anyOf)
|
|
360
|
+
return 'any of'
|
|
361
|
+
if (s.allOf)
|
|
362
|
+
return 'all of'
|
|
363
|
+
let type = Array.isArray(s.type) ? s.type.filter((t: string) => t !== 'null').join(' | ') : s.type
|
|
364
|
+
if (!type)
|
|
365
|
+
type = s.properties ? 'object' : s.items ? 'array' : 'any'
|
|
366
|
+
if (type === 'array')
|
|
367
|
+
return `${typeOf(doc, s.items)}[]`
|
|
368
|
+
const nullable = s.nullable === true || (Array.isArray(s.type) && s.type.includes('null'))
|
|
369
|
+
return nullable ? `${type} | null` : type
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function notesOf(s: JsonObject): string[] {
|
|
373
|
+
const notes: string[] = []
|
|
374
|
+
if (s.format)
|
|
375
|
+
notes.push(`format: ${s.format}`)
|
|
376
|
+
if (Array.isArray(s.enum))
|
|
377
|
+
notes.push(`one of: ${s.enum.map((v: unknown) => JSON.stringify(v)).join(', ')}`)
|
|
378
|
+
if (s.default !== undefined)
|
|
379
|
+
notes.push(`default: ${JSON.stringify(s.default)}`)
|
|
380
|
+
if (s.minimum !== undefined)
|
|
381
|
+
notes.push(`min: ${s.minimum}`)
|
|
382
|
+
if (s.maximum !== undefined)
|
|
383
|
+
notes.push(`max: ${s.maximum}`)
|
|
384
|
+
if (s.minLength !== undefined)
|
|
385
|
+
notes.push(`min length: ${s.minLength}`)
|
|
386
|
+
if (s.maxLength !== undefined)
|
|
387
|
+
notes.push(`max length: ${s.maxLength}`)
|
|
388
|
+
if (s.pattern)
|
|
389
|
+
notes.push(`pattern: ${s.pattern}`)
|
|
390
|
+
if (s.readOnly)
|
|
391
|
+
notes.push('read only')
|
|
392
|
+
if (s.writeOnly)
|
|
393
|
+
notes.push('write only')
|
|
394
|
+
if (s.deprecated)
|
|
395
|
+
notes.push('deprecated')
|
|
396
|
+
return notes
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* A schema as rows, depth-first. A named schema met below the top is one row
|
|
401
|
+
* linking to its own section, so a recursive or shared schema is never
|
|
402
|
+
* expanded twice; `maxDepth` bounds an anonymous one.
|
|
403
|
+
*/
|
|
404
|
+
export function schemaRows(doc: JsonObject, raw: unknown, options: { expandTopRef?: boolean, maxDepth?: number } = {}): SchemaRow[] {
|
|
405
|
+
const rows: SchemaRow[] = []
|
|
406
|
+
const maxDepth = options.maxDepth ?? 6
|
|
407
|
+
|
|
408
|
+
function walk(node: unknown, prefix: string, depth: number, required: Set<string>, expand: boolean): void {
|
|
409
|
+
const s = resolveRef(doc, node)
|
|
410
|
+
if (!s || typeof s !== 'object' || depth > maxDepth)
|
|
411
|
+
return
|
|
412
|
+
const name = schemaName(node)
|
|
413
|
+
if (name && !expand)
|
|
414
|
+
return
|
|
415
|
+
for (const combinator of ['allOf', 'oneOf', 'anyOf'] as const) {
|
|
416
|
+
if (!Array.isArray(s[combinator]))
|
|
417
|
+
continue
|
|
418
|
+
if (combinator === 'allOf') {
|
|
419
|
+
// allOf merges: its members' properties are this object's.
|
|
420
|
+
for (const member of s[combinator])
|
|
421
|
+
walk(member, prefix, depth, new Set([...required, ...(resolveRef(doc, member)?.required || [])]), true)
|
|
422
|
+
continue
|
|
423
|
+
}
|
|
424
|
+
s[combinator].forEach((member: unknown, i: number) => {
|
|
425
|
+
const memberName = schemaName(member)
|
|
426
|
+
rows.push({
|
|
427
|
+
name: `${prefix || 'value'} (option ${i + 1})`,
|
|
428
|
+
depth,
|
|
429
|
+
type: typeOf(doc, member),
|
|
430
|
+
required: false,
|
|
431
|
+
description: resolveRef(doc, member)?.description || '',
|
|
432
|
+
notes: [],
|
|
433
|
+
ref: memberName ? `schema-${slugify(memberName)}` : undefined,
|
|
434
|
+
combinator,
|
|
435
|
+
})
|
|
436
|
+
if (!memberName)
|
|
437
|
+
walk(member, prefix, depth + 1, new Set(resolveRef(doc, member)?.required || []), true)
|
|
438
|
+
})
|
|
439
|
+
}
|
|
440
|
+
const props = s.properties && typeof s.properties === 'object' ? s.properties : null
|
|
441
|
+
if (props) {
|
|
442
|
+
const req = new Set<string>([...(s.required || []), ...required])
|
|
443
|
+
for (const [key, value] of Object.entries<JsonObject>(props)) {
|
|
444
|
+
const child = resolveRef(doc, value) || {}
|
|
445
|
+
const childName = schemaName(value)
|
|
446
|
+
// An array of a named schema links to that schema, as the schema itself would.
|
|
447
|
+
const linked = childName || (child.items ? schemaName(child.items) : undefined)
|
|
448
|
+
const full = prefix ? `${prefix}.${key}` : key
|
|
449
|
+
rows.push({
|
|
450
|
+
name: full,
|
|
451
|
+
depth,
|
|
452
|
+
type: typeOf(doc, value),
|
|
453
|
+
required: req.has(key),
|
|
454
|
+
description: child.description || '',
|
|
455
|
+
notes: notesOf(child),
|
|
456
|
+
ref: linked ? `schema-${slugify(linked)}` : undefined,
|
|
457
|
+
})
|
|
458
|
+
if (childName)
|
|
459
|
+
continue
|
|
460
|
+
if (child.properties || child.allOf || child.oneOf || child.anyOf)
|
|
461
|
+
walk(value, full, depth + 1, new Set(child.required || []), true)
|
|
462
|
+
else if (child.items) {
|
|
463
|
+
const items = resolveRef(doc, child.items)
|
|
464
|
+
if (!schemaName(child.items) && items && (items.properties || items.allOf))
|
|
465
|
+
walk(child.items, `${full}[]`, depth + 1, new Set(items.required || []), true)
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
else if (s.items && depth === 0 && !prefix) {
|
|
470
|
+
const itemsName = schemaName(s.items)
|
|
471
|
+
rows.push({ name: '[]', depth, type: typeOf(doc, s.items), required: true, description: resolveRef(doc, s.items)?.description || '', notes: [], ref: itemsName ? `schema-${slugify(itemsName)}` : undefined })
|
|
472
|
+
if (!itemsName)
|
|
473
|
+
walk(s.items, '[]', depth + 1, new Set(resolveRef(doc, s.items)?.required || []), true)
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
walk(raw, '', 0, new Set(), options.expandTopRef !== false)
|
|
478
|
+
return rows
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** An example value for a schema: its own example, else one made from its shape. */
|
|
482
|
+
export function exampleFor(doc: JsonObject, raw: unknown, depth = 0, seen = new Set<string>()): unknown {
|
|
483
|
+
const name = schemaName(raw)
|
|
484
|
+
if (name) {
|
|
485
|
+
if (seen.has(name) || depth > 6)
|
|
486
|
+
return {}
|
|
487
|
+
seen = new Set(seen).add(name)
|
|
488
|
+
}
|
|
489
|
+
const s = resolveRef(doc, raw)
|
|
490
|
+
if (!s || typeof s !== 'object')
|
|
491
|
+
return null
|
|
492
|
+
if (s.example !== undefined)
|
|
493
|
+
return s.example
|
|
494
|
+
if (Array.isArray(s.examples) && s.examples.length)
|
|
495
|
+
return s.examples[0]
|
|
496
|
+
if (s.default !== undefined)
|
|
497
|
+
return s.default
|
|
498
|
+
if (Array.isArray(s.enum) && s.enum.length)
|
|
499
|
+
return s.enum[0]
|
|
500
|
+
if (s.allOf)
|
|
501
|
+
return Object.assign({}, ...s.allOf.map((m: unknown) => exampleFor(doc, m, depth + 1, seen)).filter((v: unknown) => v && typeof v === 'object'))
|
|
502
|
+
if (s.oneOf || s.anyOf)
|
|
503
|
+
return exampleFor(doc, (s.oneOf || s.anyOf)[0], depth + 1, seen)
|
|
504
|
+
const type = Array.isArray(s.type) ? s.type.find((t: string) => t !== 'null') : s.type
|
|
505
|
+
if (type === 'object' || s.properties) {
|
|
506
|
+
const out: JsonObject = {}
|
|
507
|
+
for (const [key, value] of Object.entries<unknown>(s.properties || {}))
|
|
508
|
+
out[key] = exampleFor(doc, value, depth + 1, seen)
|
|
509
|
+
return out
|
|
510
|
+
}
|
|
511
|
+
if (type === 'array')
|
|
512
|
+
return [exampleFor(doc, s.items, depth + 1, seen)]
|
|
513
|
+
if (type === 'integer' || type === 'number')
|
|
514
|
+
return s.minimum ?? 0
|
|
515
|
+
if (type === 'boolean')
|
|
516
|
+
return true
|
|
517
|
+
if (type === 'string') {
|
|
518
|
+
if (s.format === 'date-time')
|
|
519
|
+
return '2026-01-01T00:00:00Z'
|
|
520
|
+
if (s.format === 'date')
|
|
521
|
+
return '2026-01-01'
|
|
522
|
+
if (s.format === 'email')
|
|
523
|
+
return 'user@example.com'
|
|
524
|
+
if (s.format === 'uuid')
|
|
525
|
+
return '00000000-0000-0000-0000-000000000000'
|
|
526
|
+
if (s.format === 'uri' || s.format === 'url')
|
|
527
|
+
return 'https://example.com'
|
|
528
|
+
return 'string'
|
|
529
|
+
}
|
|
530
|
+
return null
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function pickMedia(content: JsonObject | undefined): [string, JsonObject] | null {
|
|
534
|
+
if (!content || typeof content !== 'object')
|
|
535
|
+
return null
|
|
536
|
+
const entries = Object.entries<JsonObject>(content)
|
|
537
|
+
return entries.find(([type]) => type.includes('json')) || entries[0] || null
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function mediaExample(doc: JsonObject, media: JsonObject): unknown {
|
|
541
|
+
if (media.example !== undefined)
|
|
542
|
+
return media.example
|
|
543
|
+
const first = media.examples && Object.values<JsonObject>(media.examples)[0]
|
|
544
|
+
if (first) {
|
|
545
|
+
const resolved = resolveRef(doc, first)
|
|
546
|
+
if (resolved && resolved.value !== undefined)
|
|
547
|
+
return resolved.value
|
|
548
|
+
}
|
|
549
|
+
return exampleFor(doc, media.schema)
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function securitySummary(s: JsonObject): string {
|
|
553
|
+
if (s.type === 'apiKey')
|
|
554
|
+
return `${String(s.in).charAt(0).toUpperCase()}${String(s.in).slice(1)} ${s.name}`
|
|
555
|
+
if (s.type === 'http')
|
|
556
|
+
return s.scheme === 'bearer' ? `Bearer token${s.bearerFormat ? ` (${s.bearerFormat})` : ''}` : `HTTP ${s.scheme}`
|
|
557
|
+
if (s.type === 'oauth2')
|
|
558
|
+
return `OAuth 2 (${Object.keys(s.flows || {}).join(', ') || 'flows'})`
|
|
559
|
+
if (s.type === 'openIdConnect')
|
|
560
|
+
return 'OpenID Connect'
|
|
561
|
+
if (s.type === 'mutualTLS')
|
|
562
|
+
return 'Mutual TLS'
|
|
563
|
+
return String(s.type || 'unknown')
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const shellQuote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
|
|
567
|
+
|
|
568
|
+
function placeholder(param: ApiParameter): string {
|
|
569
|
+
if (param.example !== undefined)
|
|
570
|
+
return String(param.example)
|
|
571
|
+
return param.in === 'path' ? `{${param.name}}` : `<${param.name}>`
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Request examples that include every required parameter and the auth the operation needs. */
|
|
575
|
+
export function requestExamples(op: Omit<ApiOperation, 'examples' | 'webhook'>, baseUrl: string, schemes: ApiSecurityScheme[]): NonNullable<ApiOperation['examples']> {
|
|
576
|
+
let path = op.path
|
|
577
|
+
for (const p of op.parameters.filter(p => p.in === 'path'))
|
|
578
|
+
path = path.replace(`{${p.name}}`, encodeURIComponent(placeholder(p)).replace(/%7B/g, '{').replace(/%7D/g, '}'))
|
|
579
|
+
const query = op.parameters.filter(p => p.in === 'query' && p.required)
|
|
580
|
+
const qs = query.length ? `?${query.map(p => `${encodeURIComponent(p.name)}=${encodeURIComponent(placeholder(p))}`).join('&')}` : ''
|
|
581
|
+
const url = `${baseUrl.replace(/\/+$/, '')}${path}${qs}`
|
|
582
|
+
|
|
583
|
+
const headers: Array<[string, string]> = []
|
|
584
|
+
const auth = op.security[0] || []
|
|
585
|
+
for (const requirement of auth) {
|
|
586
|
+
const scheme = schemes.find(s => s.name === requirement.name)
|
|
587
|
+
if (!scheme)
|
|
588
|
+
continue
|
|
589
|
+
if (scheme.type === 'apiKey' && scheme.in === 'header')
|
|
590
|
+
headers.push([scheme.paramName!, '$API_KEY'])
|
|
591
|
+
else if (scheme.type === 'http' && scheme.scheme === 'bearer')
|
|
592
|
+
headers.push(['Authorization', 'Bearer $TOKEN'])
|
|
593
|
+
else if (scheme.type === 'http' && scheme.scheme === 'basic')
|
|
594
|
+
headers.push(['Authorization', 'Basic $CREDENTIALS'])
|
|
595
|
+
else if (scheme.type === 'oauth2' || scheme.type === 'openIdConnect')
|
|
596
|
+
headers.push(['Authorization', 'Bearer $ACCESS_TOKEN'])
|
|
597
|
+
}
|
|
598
|
+
for (const p of op.parameters.filter(p => p.in === 'header' && p.required))
|
|
599
|
+
headers.push([p.name, placeholder(p)])
|
|
600
|
+
const apiKeyQuery = auth.map(r => schemes.find(s => s.name === r.name)).find(s => s?.type === 'apiKey' && s.in === 'query')
|
|
601
|
+
const fullUrl = apiKeyQuery ? `${url}${url.includes('?') ? '&' : '?'}${encodeURIComponent(apiKeyQuery.paramName!)}=$API_KEY` : url
|
|
602
|
+
const bodyJson = op.body ? op.body.example : ''
|
|
603
|
+
if (op.body)
|
|
604
|
+
headers.push(['Content-Type', op.body.mediaType])
|
|
605
|
+
|
|
606
|
+
const method = op.method.toUpperCase()
|
|
607
|
+
// Double quotes where a shell variable must expand, single quotes otherwise.
|
|
608
|
+
const sh = (v: string): string => v.includes('$') ? `"${v.replace(/(["\\`])/g, '\\$1')}"` : shellQuote(v)
|
|
609
|
+
const curl = [`curl -X ${method} ${sh(fullUrl)}`]
|
|
610
|
+
.concat(headers.map(([k, v]) => ` -H ${sh(`${k}: ${v}`)}`))
|
|
611
|
+
.concat(op.body ? [` -d ${shellQuote(bodyJson)}`] : [])
|
|
612
|
+
.join(' \\\n')
|
|
613
|
+
|
|
614
|
+
const env = (v: string): string => v.replace(/\$(API_KEY|TOKEN|ACCESS_TOKEN|CREDENTIALS)/g, (_, n) => `\${process.env.${n}}`)
|
|
615
|
+
const jsUrl = fullUrl.includes('$') ? `\`${env(fullUrl)}\`` : JSON.stringify(fullUrl)
|
|
616
|
+
const jsHeaders = headers.map(([k, v]) => ` ${JSON.stringify(k)}: ${v.includes('$') ? `\`${env(v)}\`` : JSON.stringify(v)},`)
|
|
617
|
+
const javascript = [
|
|
618
|
+
`const response = await fetch(${jsUrl}, {`,
|
|
619
|
+
` method: ${JSON.stringify(method)},`,
|
|
620
|
+
...(jsHeaders.length ? [' headers: {', ...jsHeaders, ' },'] : []),
|
|
621
|
+
...(op.body ? [` body: JSON.stringify(${bodyJson.replace(/\n/g, '\n ')}),`] : []),
|
|
622
|
+
'})',
|
|
623
|
+
'const data = await response.json()',
|
|
624
|
+
].join('\n')
|
|
625
|
+
|
|
626
|
+
const py = (v: string): string => v.replace(/\$(API_KEY|TOKEN|ACCESS_TOKEN|CREDENTIALS)/g, (_, n) => `{os.environ['${n}']}`)
|
|
627
|
+
const pyStr = (v: string): string => v.includes('$') ? `f${JSON.stringify(py(v))}` : JSON.stringify(v)
|
|
628
|
+
const needsOs = headers.some(([, v]) => v.includes('$')) || fullUrl.includes('$')
|
|
629
|
+
const python = [
|
|
630
|
+
...(needsOs ? ['import os', ''] : []),
|
|
631
|
+
'import requests',
|
|
632
|
+
'',
|
|
633
|
+
`response = requests.request(`,
|
|
634
|
+
` ${JSON.stringify(method)},`,
|
|
635
|
+
` ${pyStr(fullUrl)},`,
|
|
636
|
+
...(headers.length ? [` headers={${headers.map(([k, v]) => `${JSON.stringify(k)}: ${pyStr(v)}`).join(', ')}},`] : []),
|
|
637
|
+
...(op.body ? [` json=${toPython(JSON.parse(bodyJson || 'null'))},`] : []),
|
|
638
|
+
')',
|
|
639
|
+
'data = response.json()',
|
|
640
|
+
].join('\n')
|
|
641
|
+
return { curl, javascript, python }
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function toPython(value: unknown): string {
|
|
645
|
+
if (value === null || value === undefined)
|
|
646
|
+
return 'None'
|
|
647
|
+
if (value === true)
|
|
648
|
+
return 'True'
|
|
649
|
+
if (value === false)
|
|
650
|
+
return 'False'
|
|
651
|
+
if (typeof value === 'number')
|
|
652
|
+
return String(value)
|
|
653
|
+
if (typeof value === 'string')
|
|
654
|
+
return JSON.stringify(value)
|
|
655
|
+
if (Array.isArray(value))
|
|
656
|
+
return `[${value.map(toPython).join(', ')}]`
|
|
657
|
+
return `{${Object.entries(value as JsonObject).map(([k, v]) => `${JSON.stringify(k)}: ${toPython(v)}`).join(', ')}}`
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** The whole reference, ready for a template. The document must already be valid (`loadOpenApi`). */
|
|
661
|
+
export function buildApiReference(doc: JsonObject, options: { baseUrl?: string } = {}): ApiReferenceModel {
|
|
662
|
+
const baseUrl = options.baseUrl || doc.servers?.[0]?.url || 'https://api.example.com'
|
|
663
|
+
const components = doc.components || {}
|
|
664
|
+
|
|
665
|
+
const securitySchemes: ApiSecurityScheme[] = Object.entries<JsonObject>(components.securitySchemes || {}).map(([name, raw]) => {
|
|
666
|
+
const s = resolveRef(doc, raw)
|
|
667
|
+
return {
|
|
668
|
+
name,
|
|
669
|
+
anchor: `security-${slugify(name)}`,
|
|
670
|
+
type: s.type,
|
|
671
|
+
summary: securitySummary(s),
|
|
672
|
+
description: s.description || '',
|
|
673
|
+
in: s.in,
|
|
674
|
+
paramName: s.name,
|
|
675
|
+
scheme: s.scheme,
|
|
676
|
+
}
|
|
677
|
+
})
|
|
678
|
+
|
|
679
|
+
const tagMeta = new Map<string, JsonObject>((doc.tags || []).map((t: JsonObject) => [t.name, t]))
|
|
680
|
+
const byTag = new Map<string, ApiOperation[]>()
|
|
681
|
+
const usedIds = new Set<string>()
|
|
682
|
+
|
|
683
|
+
// Paths, then 3.1 webhooks: a webhook is described like an operation, but
|
|
684
|
+
// the API sends it, so it has no request examples and no auth of its own.
|
|
685
|
+
const sources: Array<[string, JsonObject, boolean]> = [
|
|
686
|
+
...Object.entries<JsonObject>(doc.paths || {}).map(([route, item]): [string, JsonObject, boolean] => [route, item, false]),
|
|
687
|
+
...Object.entries<JsonObject>(doc.webhooks || {}).map(([name, item]): [string, JsonObject, boolean] => [name, item, true]),
|
|
688
|
+
]
|
|
689
|
+
for (const [route, rawItem, webhook] of sources) {
|
|
690
|
+
const item = resolveRef(doc, rawItem)
|
|
691
|
+
for (const method of METHODS) {
|
|
692
|
+
const raw = item[method] as JsonObject | undefined
|
|
693
|
+
if (!raw)
|
|
694
|
+
continue
|
|
695
|
+
// Path-level parameters, overridden by the operation's own of the same name and place.
|
|
696
|
+
const params = new Map<string, JsonObject>()
|
|
697
|
+
for (const p of [...(item.parameters || []), ...(raw.parameters || [])]) {
|
|
698
|
+
const r = resolveRef(doc, p)
|
|
699
|
+
params.set(`${r.in}:${r.name}`, r)
|
|
700
|
+
}
|
|
701
|
+
const parameters: ApiParameter[] = [...params.values()].map(p => ({
|
|
702
|
+
name: p.name,
|
|
703
|
+
in: p.in,
|
|
704
|
+
required: p.in === 'path' ? true : p.required === true,
|
|
705
|
+
type: typeOf(doc, p.schema),
|
|
706
|
+
description: p.description || '',
|
|
707
|
+
deprecated: p.deprecated === true,
|
|
708
|
+
example: p.example ?? resolveRef(doc, p.schema)?.example,
|
|
709
|
+
}))
|
|
710
|
+
|
|
711
|
+
let body: ApiBody | null = null
|
|
712
|
+
if (raw.requestBody) {
|
|
713
|
+
const rb = resolveRef(doc, raw.requestBody)
|
|
714
|
+
const media = pickMedia(rb.content)
|
|
715
|
+
if (media) {
|
|
716
|
+
const [mediaType, m] = media
|
|
717
|
+
const name = schemaName(m.schema)
|
|
718
|
+
body = {
|
|
719
|
+
mediaType,
|
|
720
|
+
required: rb.required === true,
|
|
721
|
+
description: rb.description || '',
|
|
722
|
+
rows: schemaRows(doc, m.schema),
|
|
723
|
+
ref: name ? `schema-${slugify(name)}` : undefined,
|
|
724
|
+
schema: name,
|
|
725
|
+
example: JSON.stringify(mediaExample(doc, m), null, 2),
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
const responses: ApiResponse[] = Object.entries<JsonObject>(raw.responses || {}).map(([status, rawResponse]) => {
|
|
731
|
+
const r = resolveRef(doc, rawResponse)
|
|
732
|
+
const media = pickMedia(r.content)
|
|
733
|
+
const name = media ? schemaName(media[1].schema) : undefined
|
|
734
|
+
return {
|
|
735
|
+
status,
|
|
736
|
+
description: r.description || '',
|
|
737
|
+
mediaType: media ? media[0] : '',
|
|
738
|
+
rows: media ? schemaRows(doc, media[1].schema) : [],
|
|
739
|
+
ref: name ? `schema-${slugify(name)}` : undefined,
|
|
740
|
+
schema: name,
|
|
741
|
+
example: media ? JSON.stringify(mediaExample(doc, media[1]), null, 2) : '',
|
|
742
|
+
headers: Object.entries<JsonObject>(r.headers || {}).map(([headerName, rawHeader]) => {
|
|
743
|
+
const h = resolveRef(doc, rawHeader) || {}
|
|
744
|
+
return { name: headerName, type: typeOf(doc, h.schema), description: h.description || '', required: h.required === true }
|
|
745
|
+
}),
|
|
746
|
+
}
|
|
747
|
+
})
|
|
748
|
+
|
|
749
|
+
const requirements: JsonObject[] = webhook ? (raw.security ?? []) : (raw.security ?? doc.security ?? [])
|
|
750
|
+
const security = requirements.map(req => Object.entries<string[]>(req).map(([name, scopes]) => ({ name, anchor: `security-${slugify(name)}`, scopes: scopes || [] })))
|
|
751
|
+
.filter(alt => alt.length > 0)
|
|
752
|
+
|
|
753
|
+
let id = typeof raw.operationId === 'string' && raw.operationId ? raw.operationId : `${method}-${route}`
|
|
754
|
+
let anchor = `${webhook ? 'webhook' : 'op'}-${slugify(id)}`
|
|
755
|
+
for (let n = 2; usedIds.has(anchor); n++)
|
|
756
|
+
anchor = `${webhook ? 'webhook' : 'op'}-${slugify(id)}-${n}`
|
|
757
|
+
usedIds.add(anchor)
|
|
758
|
+
id = raw.operationId || id
|
|
759
|
+
|
|
760
|
+
const tag = webhook ? 'Webhooks' : Array.isArray(raw.tags) && raw.tags.length ? String(raw.tags[0]) : 'Endpoints'
|
|
761
|
+
const partial = {
|
|
762
|
+
id,
|
|
763
|
+
anchor,
|
|
764
|
+
method: method.toUpperCase(),
|
|
765
|
+
path: route,
|
|
766
|
+
summary: raw.summary || '',
|
|
767
|
+
description: raw.description || '',
|
|
768
|
+
deprecated: raw.deprecated === true,
|
|
769
|
+
tag,
|
|
770
|
+
parameters,
|
|
771
|
+
body,
|
|
772
|
+
responses,
|
|
773
|
+
security,
|
|
774
|
+
}
|
|
775
|
+
const op: ApiOperation = { ...partial, webhook, examples: webhook ? null : requestExamples(partial, baseUrl, securitySchemes) }
|
|
776
|
+
if (!byTag.has(tag))
|
|
777
|
+
byTag.set(tag, [])
|
|
778
|
+
byTag.get(tag)!.push(op)
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Tags in the document's order, then any others in the order first used.
|
|
783
|
+
const order = [...(doc.tags || []).map((t: JsonObject) => t.name), ...byTag.keys()].filter((t, i, all) => byTag.has(t) && all.indexOf(t) === i)
|
|
784
|
+
const tags: ApiTag[] = order.map(name => ({
|
|
785
|
+
name,
|
|
786
|
+
anchor: `tag-${slugify(name)}`,
|
|
787
|
+
description: tagMeta.get(name)?.description || '',
|
|
788
|
+
operations: byTag.get(name)!,
|
|
789
|
+
}))
|
|
790
|
+
|
|
791
|
+
const schemas: ApiSchema[] = Object.entries<JsonObject>(components.schemas || {}).map(([name, raw]) => {
|
|
792
|
+
const s = resolveRef(doc, raw)
|
|
793
|
+
return {
|
|
794
|
+
name,
|
|
795
|
+
anchor: `schema-${slugify(name)}`,
|
|
796
|
+
description: s?.description || '',
|
|
797
|
+
type: typeOf(doc, { ...s, $ref: undefined }),
|
|
798
|
+
rows: schemaRows(doc, raw),
|
|
799
|
+
}
|
|
800
|
+
})
|
|
801
|
+
|
|
802
|
+
const toc: ApiReferenceModel['toc'] = [
|
|
803
|
+
...(securitySchemes.length ? [{ text: 'Authentication', anchor: 'authentication', children: securitySchemes.map(s => ({ text: s.name, anchor: s.anchor })) }] : []),
|
|
804
|
+
...tags.map(t => ({ text: t.name, anchor: t.anchor, children: t.operations.map(o => ({ text: o.summary || `${o.method} ${o.path}`, anchor: o.anchor, method: o.method })) })),
|
|
805
|
+
...(schemas.length ? [{ text: 'Schemas', anchor: 'schemas', children: schemas.map(s => ({ text: s.name, anchor: s.anchor })) }] : []),
|
|
806
|
+
]
|
|
807
|
+
|
|
808
|
+
const search: ApiReferenceModel['search'] = [
|
|
809
|
+
...tags.map(t => ({ title: t.name, anchor: t.anchor, text: t.description, kind: 'tag' as const })),
|
|
810
|
+
...tags.flatMap(t => t.operations.map(o => ({ title: o.summary || `${o.method} ${o.path}`, anchor: o.anchor, text: `${o.method} ${o.path} ${o.description}`.trim(), kind: 'operation' as const }))),
|
|
811
|
+
...schemas.map(s => ({ title: s.name, anchor: s.anchor, text: s.description, kind: 'schema' as const })),
|
|
812
|
+
]
|
|
813
|
+
|
|
814
|
+
return {
|
|
815
|
+
title: doc.info.title,
|
|
816
|
+
version: doc.info.version || '',
|
|
817
|
+
description: doc.info.description || '',
|
|
818
|
+
baseUrl,
|
|
819
|
+
tags,
|
|
820
|
+
schemas,
|
|
821
|
+
securitySchemes,
|
|
822
|
+
toc,
|
|
823
|
+
search,
|
|
824
|
+
}
|
|
825
|
+
}
|