@kawapress/plugin-openapi 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README-zh-CN.md +75 -0
- package/README.md +74 -2
- package/bin/kawapress-openapi.mjs +10 -0
- package/package.json +67 -3
- package/src/cli.ts +35 -0
- package/src/commands.ts +28 -0
- package/src/components/KawaOpenApiBody.vue +20 -0
- package/src/components/KawaOpenApiBodyView.vue +41 -0
- package/src/components/KawaOpenApiCard.vue +33 -0
- package/src/components/KawaOpenApiEndpoint.vue +186 -0
- package/src/components/KawaOpenApiFieldList.vue +35 -0
- package/src/components/KawaOpenApiJourney.vue +100 -0
- package/src/components/KawaOpenApiMap.vue +50 -0
- package/src/components/KawaOpenApiParameters.vue +24 -0
- package/src/components/KawaOpenApiPayload.vue +77 -0
- package/src/components/KawaOpenApiRef.vue +21 -0
- package/src/components/KawaOpenApiResponses.vue +37 -0
- package/src/components/KawaOpenApiSamples.vue +39 -0
- package/src/components/KawaOpenApiTabs.vue +68 -0
- package/src/components/openapi.css +550 -0
- package/src/components/validate.ts +138 -0
- package/src/data/body.ts +115 -0
- package/src/data/components.ts +687 -0
- package/src/data/fields.ts +129 -0
- package/src/data/payload.ts +214 -0
- package/src/data/rules.ts +67 -0
- package/src/data/samples.ts +187 -0
- package/src/data/text.ts +85 -0
- package/src/data/typescript.ts +105 -0
- package/src/env.d.ts +8 -0
- package/src/index.ts +123 -0
- package/src/options.ts +53 -0
- package/src/pages.ts +120 -0
- package/src/read/arazzo.ts +168 -0
- package/src/read/document.ts +91 -0
- package/src/read/example.ts +143 -0
- package/src/read/model.ts +341 -0
- package/src/read/schema.ts +212 -0
- package/src/render/labels.ts +283 -0
- package/src/render/pages.ts +237 -0
- package/src/render/routes.ts +48 -0
- package/src/runtime-plugin.ts +12 -0
- package/src/service.ts +128 -0
- package/src/snapshot/history.ts +188 -0
- package/src/snapshot/snapshot.ts +91 -0
- package/src/tag.ts +114 -0
- package/src/types.ts +207 -0
- package/src/vite.ts +169 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { Direction, SchemaTable } from '../read/example'
|
|
2
|
+
import type { SchemaNode } from '../types'
|
|
3
|
+
import { resolveNode, visibleOn } from '../read/example'
|
|
4
|
+
|
|
5
|
+
/** A field of a body or model, flattened with its path. */
|
|
6
|
+
export interface FlatField {
|
|
7
|
+
/** `items[].quantity`; `[]` alone for the items of a top-level array. */
|
|
8
|
+
path: string
|
|
9
|
+
name: string
|
|
10
|
+
depth: number
|
|
11
|
+
required: boolean
|
|
12
|
+
/** The property's schema as written, maybe a named reference. */
|
|
13
|
+
schema: SchemaNode
|
|
14
|
+
/** The schema behind the reference. */
|
|
15
|
+
target: SchemaNode
|
|
16
|
+
/** Set when the field is a named model that is not expanded here (seen before, or contains itself). */
|
|
17
|
+
collapsedRef?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface FlattenOptions {
|
|
21
|
+
direction: Direction
|
|
22
|
+
/** Expand each named model only the first time it appears (field tables); otherwise only cycles stop (snapshots). */
|
|
23
|
+
expandOnce?: boolean
|
|
24
|
+
maxDepth?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The fields of an object schema (or of the items of an array schema), depth first. */
|
|
28
|
+
export function flattenFields(root: SchemaNode, schemas: SchemaTable, options: FlattenOptions): FlatField[] {
|
|
29
|
+
const { direction, expandOnce = false, maxDepth = 8 } = options
|
|
30
|
+
const rows: FlatField[] = []
|
|
31
|
+
const expanded = new Set<string>()
|
|
32
|
+
if (root.kind === 'ref' && root.ref) {
|
|
33
|
+
expanded.add(root.ref)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const visit = (node: SchemaNode, prefix: string, depth: number, trail: readonly string[]): void => {
|
|
37
|
+
const target = resolveNode(node, schemas)
|
|
38
|
+
if (depth > maxDepth) {
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
const container = target.kind === 'array' && target.items ? resolveNode(target.items, schemas) : target
|
|
42
|
+
const itemRef = target.kind === 'array' && target.items?.kind === 'ref' ? target.items.ref : undefined
|
|
43
|
+
if (target.kind === 'array') {
|
|
44
|
+
if (itemRef && trail.includes(itemRef)) {
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
if (container.properties?.length) {
|
|
48
|
+
visit(target.items!, `${prefix}[]`, depth, itemRef ? [...trail, itemRef] : trail)
|
|
49
|
+
}
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
for (const property of container.properties ?? []) {
|
|
53
|
+
if (!visibleOn(property.schema, schemas, direction)) {
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
const path = prefix ? `${prefix}.${property.name}` : property.name
|
|
57
|
+
const propertyTarget = resolveNode(property.schema, schemas)
|
|
58
|
+
const nested = propertyTarget.kind === 'array' && propertyTarget.items ? propertyTarget.items : property.schema
|
|
59
|
+
const ref = nested.kind === 'ref' ? nested.ref : undefined
|
|
60
|
+
const nestedTarget = resolveNode(nested, schemas)
|
|
61
|
+
const hasChildren = Boolean(nestedTarget.properties?.length)
|
|
62
|
+
const blocked = ref !== undefined && (trail.includes(ref) || (expandOnce && expanded.has(ref)))
|
|
63
|
+
rows.push({
|
|
64
|
+
path,
|
|
65
|
+
name: property.name,
|
|
66
|
+
depth,
|
|
67
|
+
required: property.required,
|
|
68
|
+
schema: property.schema,
|
|
69
|
+
target: propertyTarget,
|
|
70
|
+
...(blocked && hasChildren ? { collapsedRef: ref } : {}),
|
|
71
|
+
})
|
|
72
|
+
if (!hasChildren || blocked) {
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
if (ref) {
|
|
76
|
+
expanded.add(ref)
|
|
77
|
+
}
|
|
78
|
+
const childPrefix = propertyTarget.kind === 'array' ? `${path}[]` : path
|
|
79
|
+
visit(nestedTarget, childPrefix, depth + 1, ref ? [...trail, ref] : trail)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
visit(root, '', 0, root.kind === 'ref' && root.ref ? [root.ref] : [])
|
|
84
|
+
return rows
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `string`, `Order`, `LineItem[]`, `string(date-time)`, `Card | Wallet`, `integer | null`. */
|
|
88
|
+
export function typeLabel(node: SchemaNode, schemas: SchemaTable, depth = 0): string {
|
|
89
|
+
let label: string
|
|
90
|
+
if (node.kind === 'ref' && node.ref) {
|
|
91
|
+
const target = schemas.get(node.ref)
|
|
92
|
+
label = node.ref
|
|
93
|
+
if (target?.nullable) {
|
|
94
|
+
return `${label} | null`
|
|
95
|
+
}
|
|
96
|
+
return label
|
|
97
|
+
}
|
|
98
|
+
if (depth > 4) {
|
|
99
|
+
return 'object'
|
|
100
|
+
}
|
|
101
|
+
switch (node.kind) {
|
|
102
|
+
case 'array':
|
|
103
|
+
label = node.items ? `${wrap(typeLabel(node.items, schemas, depth + 1))}[]` : 'array'
|
|
104
|
+
break
|
|
105
|
+
case 'union':
|
|
106
|
+
label = node.variants?.length ? node.variants.map(variant => typeLabel(variant, schemas, depth + 1)).join(' | ') : 'any'
|
|
107
|
+
break
|
|
108
|
+
case 'object':
|
|
109
|
+
label = node.properties?.length || node.additionalProperties !== true ? 'object' : 'Record<string, any>'
|
|
110
|
+
if (!node.properties?.length && node.additionalProperties && node.additionalProperties !== true) {
|
|
111
|
+
label = `Record<string, ${typeLabel(node.additionalProperties, schemas, depth + 1)}>`
|
|
112
|
+
}
|
|
113
|
+
break
|
|
114
|
+
case 'string':
|
|
115
|
+
label = node.format ? `string(${node.format})` : 'string'
|
|
116
|
+
break
|
|
117
|
+
case 'integer':
|
|
118
|
+
case 'number':
|
|
119
|
+
label = node.format && !['int32', 'int64', 'float', 'double'].includes(node.format) ? `${node.kind}(${node.format})` : node.kind
|
|
120
|
+
break
|
|
121
|
+
default:
|
|
122
|
+
label = node.kind
|
|
123
|
+
}
|
|
124
|
+
return node.nullable && node.kind !== 'null' ? `${label} | null` : label
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function wrap(label: string): string {
|
|
128
|
+
return label.includes(' | ') ? `(${label})` : label
|
|
129
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import type { Direction, SchemaTable } from '../read/example'
|
|
2
|
+
import type { OpenApiLabels } from '../render/labels'
|
|
3
|
+
import type { SchemaNode } from '../types'
|
|
4
|
+
import { resolveNode } from '../read/example'
|
|
5
|
+
import { typeLabel } from './fields'
|
|
6
|
+
import { constraintTexts, renderProse, valueText } from './text'
|
|
7
|
+
|
|
8
|
+
export type PayloadTone = 'string' | 'number' | 'boolean' | 'null' | 'punct' | 'more'
|
|
9
|
+
|
|
10
|
+
/** One line of the annotated example. */
|
|
11
|
+
export interface PayloadLine {
|
|
12
|
+
indent: number
|
|
13
|
+
key?: string
|
|
14
|
+
/** A scalar as JSON, an opening `{` / `[`, a closing `}` / `]`, or the "… N more" text. */
|
|
15
|
+
value: string
|
|
16
|
+
tone: PayloadTone
|
|
17
|
+
comma: boolean
|
|
18
|
+
/** `integer · 1–10`; absent when the line has no schema. */
|
|
19
|
+
hint?: string
|
|
20
|
+
required?: boolean
|
|
21
|
+
deprecated?: boolean
|
|
22
|
+
since?: string
|
|
23
|
+
/** Index into `PayloadData.docs`. */
|
|
24
|
+
doc?: number
|
|
25
|
+
/** Colour index of a journey value that flows between steps. */
|
|
26
|
+
mark?: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What a line shows when it is opened. */
|
|
30
|
+
export interface PayloadDoc {
|
|
31
|
+
/** `items[].quantity`. */
|
|
32
|
+
path: string
|
|
33
|
+
type: string
|
|
34
|
+
/** Page of the named model the type is, with the site base. */
|
|
35
|
+
typeHref?: string
|
|
36
|
+
required: boolean
|
|
37
|
+
constraints: string[]
|
|
38
|
+
descriptionHtml: string
|
|
39
|
+
defaultValue?: string
|
|
40
|
+
deprecated: boolean
|
|
41
|
+
since?: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PayloadData {
|
|
45
|
+
lines: PayloadLine[]
|
|
46
|
+
docs: PayloadDoc[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface PayloadOptions {
|
|
50
|
+
schemas: SchemaTable
|
|
51
|
+
direction: Direction
|
|
52
|
+
labels: OpenApiLabels
|
|
53
|
+
/** Page of a model with the site base. */
|
|
54
|
+
modelHref: (name: string) => string | undefined
|
|
55
|
+
/** Version a field path (`items[].quantity`) first appears in, from the snapshots. */
|
|
56
|
+
sinceOf?: (path: string) => string | undefined
|
|
57
|
+
/** JSON pointer (`/items/0/id`) → colour index, for journeys. */
|
|
58
|
+
marks?: ReadonlyMap<string, number>
|
|
59
|
+
/** Leave out hints and docs (journeys show values only). */
|
|
60
|
+
bare?: boolean
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Lays an example value out as lines, each key annotated with the schema of
|
|
65
|
+
* the property it belongs to. Arrays show their first item and fold the rest.
|
|
66
|
+
*/
|
|
67
|
+
export function buildPayload(value: unknown, schema: SchemaNode | undefined, options: PayloadOptions): PayloadData {
|
|
68
|
+
const lines: PayloadLine[] = []
|
|
69
|
+
const docs: PayloadDoc[] = []
|
|
70
|
+
const { schemas } = options
|
|
71
|
+
|
|
72
|
+
const annotate = (line: PayloadLine, node: SchemaNode | undefined, path: string, required: boolean): void => {
|
|
73
|
+
if (!node || options.bare || !path) {
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
const target = resolveNode(node, schemas)
|
|
77
|
+
const constraints = constraintTexts(node, schemas, options.labels)
|
|
78
|
+
const deprecated = node.deprecated || target.deprecated
|
|
79
|
+
const since = node.since ?? target.since ?? options.sinceOf?.(path)
|
|
80
|
+
line.hint = [typeLabel(node, schemas), ...constraints.slice(0, 1)].join(' · ')
|
|
81
|
+
line.required = required
|
|
82
|
+
if (deprecated) {
|
|
83
|
+
line.deprecated = true
|
|
84
|
+
}
|
|
85
|
+
if (since) {
|
|
86
|
+
line.since = since
|
|
87
|
+
}
|
|
88
|
+
const ref = node.kind === 'ref' ? node.ref : node.kind === 'array' && node.items?.kind === 'ref' ? node.items.ref : undefined
|
|
89
|
+
const typeHref = ref ? options.modelHref(ref) : undefined
|
|
90
|
+
const description = node.description || target.description
|
|
91
|
+
docs.push({
|
|
92
|
+
path,
|
|
93
|
+
type: typeLabel(node, schemas),
|
|
94
|
+
...(typeHref ? { typeHref } : {}),
|
|
95
|
+
required,
|
|
96
|
+
constraints,
|
|
97
|
+
descriptionHtml: renderProse(description),
|
|
98
|
+
...(target.default !== undefined ? { defaultValue: valueText(target.default) } : {}),
|
|
99
|
+
deprecated,
|
|
100
|
+
...(since ? { since } : {}),
|
|
101
|
+
})
|
|
102
|
+
line.doc = docs.length - 1
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const walk = (
|
|
106
|
+
current: unknown,
|
|
107
|
+
node: SchemaNode | undefined,
|
|
108
|
+
path: string,
|
|
109
|
+
pointer: string,
|
|
110
|
+
indent: number,
|
|
111
|
+
key: string | undefined,
|
|
112
|
+
required: boolean,
|
|
113
|
+
comma: boolean,
|
|
114
|
+
): void => {
|
|
115
|
+
const target = node ? pickVariant(resolveNode(node, schemas), current, schemas) : undefined
|
|
116
|
+
const mark = options.marks?.get(pointer)
|
|
117
|
+
const markOf = mark === undefined ? {} : { mark }
|
|
118
|
+
if (Array.isArray(current)) {
|
|
119
|
+
const open: PayloadLine = { indent, value: current.length === 0 ? '[]' : '[', tone: 'punct', comma: current.length === 0 && comma, ...(key !== undefined ? { key } : {}) }
|
|
120
|
+
annotate(open, node, path, required)
|
|
121
|
+
lines.push(open)
|
|
122
|
+
if (current.length === 0) {
|
|
123
|
+
return
|
|
124
|
+
}
|
|
125
|
+
const itemNode = target?.kind === 'array' ? target.items : undefined
|
|
126
|
+
walk(current[0], itemNode, `${path}[]`, `${pointer}/0`, indent + 1, undefined, false, current.length > 1)
|
|
127
|
+
if (current.length > 1) {
|
|
128
|
+
lines.push({ indent: indent + 1, value: options.labels.moreItems(current.length - 1), tone: 'more', comma: false })
|
|
129
|
+
}
|
|
130
|
+
lines.push({ indent, value: ']', tone: 'punct', comma })
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
if (current !== null && typeof current === 'object') {
|
|
134
|
+
const entries = Object.entries(current)
|
|
135
|
+
const open: PayloadLine = { indent, value: entries.length === 0 ? '{}' : '{', tone: 'punct', comma: entries.length === 0 && comma, ...(key !== undefined ? { key } : {}), ...markOf }
|
|
136
|
+
annotate(open, node, path, required)
|
|
137
|
+
lines.push(open)
|
|
138
|
+
if (entries.length === 0) {
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
entries.forEach(([name, item], index) => {
|
|
142
|
+
const property = target?.properties?.find(candidate => candidate.name === name)
|
|
143
|
+
const extra = !property && target?.additionalProperties && target.additionalProperties !== true ? target.additionalProperties : undefined
|
|
144
|
+
walk(
|
|
145
|
+
item,
|
|
146
|
+
property?.schema ?? extra,
|
|
147
|
+
path ? `${path}.${name}` : name,
|
|
148
|
+
`${pointer}/${escapePointer(name)}`,
|
|
149
|
+
indent + 1,
|
|
150
|
+
name,
|
|
151
|
+
property?.required ?? false,
|
|
152
|
+
index < entries.length - 1,
|
|
153
|
+
)
|
|
154
|
+
})
|
|
155
|
+
lines.push({ indent, value: '}', tone: 'punct', comma })
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
const line: PayloadLine = { indent, value: JSON.stringify(current) ?? 'null', tone: toneOf(current), comma, ...(key !== undefined ? { key } : {}), ...markOf }
|
|
159
|
+
annotate(line, node, path, required)
|
|
160
|
+
lines.push(line)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
walk(value, schema, '', '', 0, undefined, false, false)
|
|
164
|
+
return { lines, docs }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function toneOf(value: unknown): PayloadTone {
|
|
168
|
+
switch (typeof value) {
|
|
169
|
+
case 'string':
|
|
170
|
+
return 'string'
|
|
171
|
+
case 'number':
|
|
172
|
+
case 'bigint':
|
|
173
|
+
return 'number'
|
|
174
|
+
case 'boolean':
|
|
175
|
+
return 'boolean'
|
|
176
|
+
default:
|
|
177
|
+
return 'null'
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** For a union, the member whose properties best match the value. */
|
|
182
|
+
function pickVariant(node: SchemaNode, value: unknown, schemas: SchemaTable): SchemaNode {
|
|
183
|
+
if (!node.variants?.length) {
|
|
184
|
+
return node
|
|
185
|
+
}
|
|
186
|
+
const keys = value !== null && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value) : []
|
|
187
|
+
let best = resolveNode(node.variants[0], schemas)
|
|
188
|
+
let bestScore = -1
|
|
189
|
+
for (const variant of node.variants) {
|
|
190
|
+
const target = resolveNode(variant, schemas)
|
|
191
|
+
const names = new Set(target.properties?.map(property => property.name))
|
|
192
|
+
const score = keys.filter(key => names.has(key)).length
|
|
193
|
+
if (score > bestScore) {
|
|
194
|
+
best = target
|
|
195
|
+
bestScore = score
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return best
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function escapePointer(key: string): string {
|
|
202
|
+
return key.replaceAll('~', '~0').replaceAll('/', '~1')
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The lines as a JSON code block with the hints as trailing comments, for Markdown output. */
|
|
206
|
+
export function payloadMarkdown(data: PayloadData): string {
|
|
207
|
+
const body = data.lines.map((line) => {
|
|
208
|
+
const key = line.key !== undefined ? `${JSON.stringify(line.key)}: ` : ''
|
|
209
|
+
const text = line.tone === 'more' ? `// ${line.value}` : `${key}${line.value}${line.comma ? ',' : ''}`
|
|
210
|
+
const notes = [line.hint, line.required ? 'required' : '', line.deprecated ? 'deprecated' : '', line.since ? `since ${line.since}` : ''].filter(Boolean).join(', ')
|
|
211
|
+
return `${' '.repeat(line.indent)}${text}${notes ? ` // ${notes}` : ''}`
|
|
212
|
+
})
|
|
213
|
+
return `\`\`\`jsonc\n${body.join('\n')}\n\`\`\``
|
|
214
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Rule } from '../components/validate'
|
|
2
|
+
import type { Direction, SchemaTable } from '../read/example'
|
|
3
|
+
import type { SchemaNode } from '../types'
|
|
4
|
+
import { resolveNode, visibleOn } from '../read/example'
|
|
5
|
+
|
|
6
|
+
/** The compact validation rule of a schema; a model that contains itself is not checked below the second level. */
|
|
7
|
+
export function ruleOf(node: SchemaNode, schemas: SchemaTable, direction: Direction, trail: readonly string[] = []): Rule | undefined {
|
|
8
|
+
if (node.kind === 'ref' && node.ref) {
|
|
9
|
+
if (trail.includes(node.ref)) {
|
|
10
|
+
return undefined
|
|
11
|
+
}
|
|
12
|
+
return ruleOf(resolveNode(node, schemas), schemas, direction, [...trail, node.ref])
|
|
13
|
+
}
|
|
14
|
+
const rule: Rule = {}
|
|
15
|
+
if (node.variants?.length) {
|
|
16
|
+
const members = node.variants.map(variant => ruleOf(variant, schemas, direction, trail))
|
|
17
|
+
if (members.includes(undefined)) {
|
|
18
|
+
return undefined
|
|
19
|
+
}
|
|
20
|
+
rule.u = members as Rule[]
|
|
21
|
+
}
|
|
22
|
+
if (['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'].includes(node.kind)) {
|
|
23
|
+
rule.t = node.kind as Rule['t']
|
|
24
|
+
}
|
|
25
|
+
if (node.nullable) {
|
|
26
|
+
rule.n = true
|
|
27
|
+
}
|
|
28
|
+
if (node.enum?.length) {
|
|
29
|
+
rule.e = node.enum
|
|
30
|
+
}
|
|
31
|
+
const c = node.constraints
|
|
32
|
+
const set = <K extends keyof Rule>(key: K, value: Rule[K] | undefined): void => {
|
|
33
|
+
if (value !== undefined) {
|
|
34
|
+
rule[key] = value
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
set('min', c.minimum)
|
|
38
|
+
set('max', c.maximum)
|
|
39
|
+
set('xmin', c.exclusiveMinimum)
|
|
40
|
+
set('xmax', c.exclusiveMaximum)
|
|
41
|
+
set('minL', c.minLength)
|
|
42
|
+
set('maxL', c.maxLength)
|
|
43
|
+
set('minI', c.minItems)
|
|
44
|
+
set('maxI', c.maxItems)
|
|
45
|
+
set('pat', c.pattern)
|
|
46
|
+
if (node.items) {
|
|
47
|
+
set('i', ruleOf(node.items, schemas, direction, trail))
|
|
48
|
+
}
|
|
49
|
+
if (node.properties?.length) {
|
|
50
|
+
const visible = node.properties.filter(property => visibleOn(property.schema, schemas, direction))
|
|
51
|
+
const required = visible.filter(property => property.required).map(property => property.name)
|
|
52
|
+
if (required.length) {
|
|
53
|
+
rule.r = required
|
|
54
|
+
}
|
|
55
|
+
const properties: Record<string, Rule> = {}
|
|
56
|
+
for (const property of visible) {
|
|
57
|
+
const child = ruleOf(property.schema, schemas, direction, trail)
|
|
58
|
+
if (child && Object.keys(child).length > 0) {
|
|
59
|
+
properties[property.name] = child
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (Object.keys(properties).length) {
|
|
63
|
+
rule.p = properties
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return rule
|
|
67
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { SchemaTable } from '../read/example'
|
|
2
|
+
import type { OpenApiModel, OpenApiOperation, OpenApiParameter, OpenApiSampleLanguage } from '../types'
|
|
3
|
+
import { exampleOf } from '../read/example'
|
|
4
|
+
|
|
5
|
+
/** What a request needs, filled with example values. */
|
|
6
|
+
export interface RequestExample {
|
|
7
|
+
method: string
|
|
8
|
+
/** Base URL of the first server, without a trailing slash. */
|
|
9
|
+
server: string
|
|
10
|
+
path: string
|
|
11
|
+
/** Path with the example values of the path parameters filled in. */
|
|
12
|
+
resolvedPath: string
|
|
13
|
+
pathParams: { name: string, value: string }[]
|
|
14
|
+
query: { name: string, value: string }[]
|
|
15
|
+
headers: { name: string, value: string }[]
|
|
16
|
+
/** `Authorization: Bearer $TOKEN` and the like, kept apart so the try-it panel can use the token field. */
|
|
17
|
+
auth?: { kind: 'bearer' | 'basic' | 'header' | 'query', name: string, placeholder: string }
|
|
18
|
+
contentType?: string
|
|
19
|
+
body?: unknown
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function requestExample(operation: OpenApiOperation, model: OpenApiModel, schemas: SchemaTable): RequestExample {
|
|
23
|
+
const valueOf = (parameter: OpenApiParameter): string => {
|
|
24
|
+
const value = parameter.example ?? exampleOf(parameter.schema, schemas, 'request', parameter.name)
|
|
25
|
+
return typeof value === 'string' ? value : JSON.stringify(value)
|
|
26
|
+
}
|
|
27
|
+
const pathParams = operation.parameters.filter(parameter => parameter.in === 'path').map(parameter => ({ name: parameter.name, value: valueOf(parameter) }))
|
|
28
|
+
let resolvedPath = operation.path
|
|
29
|
+
for (const parameter of pathParams) {
|
|
30
|
+
resolvedPath = resolvedPath.replaceAll(`{${parameter.name}}`, encodeURIComponent(parameter.value))
|
|
31
|
+
}
|
|
32
|
+
const query = operation.parameters
|
|
33
|
+
.filter(parameter => parameter.in === 'query' && (parameter.required || parameter.example !== undefined))
|
|
34
|
+
.map(parameter => ({ name: parameter.name, value: valueOf(parameter) }))
|
|
35
|
+
const headers = operation.parameters
|
|
36
|
+
.filter(parameter => parameter.in === 'header' && (parameter.required || parameter.example !== undefined))
|
|
37
|
+
.map(parameter => ({ name: parameter.name, value: valueOf(parameter) }))
|
|
38
|
+
|
|
39
|
+
const scheme = model.securitySchemes.find(item => operation.security.includes(item.name))
|
|
40
|
+
let auth: RequestExample['auth']
|
|
41
|
+
if (scheme?.type === 'http' && scheme.scheme === 'basic') {
|
|
42
|
+
auth = { kind: 'basic', name: 'Authorization', placeholder: '$USERNAME:$PASSWORD' }
|
|
43
|
+
}
|
|
44
|
+
else if (scheme?.type === 'http' || scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect') {
|
|
45
|
+
auth = { kind: 'bearer', name: 'Authorization', placeholder: '$TOKEN' }
|
|
46
|
+
}
|
|
47
|
+
else if (scheme?.type === 'apiKey' && scheme.paramName && scheme.in !== 'cookie') {
|
|
48
|
+
auth = { kind: scheme.in === 'query' ? 'query' : 'header', name: scheme.paramName, placeholder: '$API_KEY' }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
method: operation.method.toUpperCase(),
|
|
53
|
+
server: (model.servers[0]?.url ?? 'https://api.example.com').replace(/\/+$/, ''),
|
|
54
|
+
path: operation.path,
|
|
55
|
+
resolvedPath,
|
|
56
|
+
pathParams,
|
|
57
|
+
query,
|
|
58
|
+
headers,
|
|
59
|
+
...(auth ? { auth } : {}),
|
|
60
|
+
...(operation.requestBody ? { contentType: operation.requestBody.contentType, body: operation.requestBody.example } : {}),
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The request as code in each language. */
|
|
65
|
+
export function codeSamples(request: RequestExample, languages: readonly OpenApiSampleLanguage[]): { language: OpenApiSampleLanguage, label: string, lang: string, code: string }[] {
|
|
66
|
+
return languages.map((language) => {
|
|
67
|
+
switch (language) {
|
|
68
|
+
case 'curl':
|
|
69
|
+
return { language, label: 'curl', lang: 'sh', code: curlOf(request) }
|
|
70
|
+
case 'javascript':
|
|
71
|
+
return { language, label: 'JavaScript', lang: 'js', code: fetchOf(request) }
|
|
72
|
+
case 'python':
|
|
73
|
+
return { language, label: 'Python', lang: 'python', code: pythonOf(request) }
|
|
74
|
+
}
|
|
75
|
+
return { language, label: language, lang: 'text', code: '' }
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function urlOf(request: RequestExample, withAuthQuery = true): string {
|
|
80
|
+
const query = [...request.query]
|
|
81
|
+
if (withAuthQuery && request.auth?.kind === 'query') {
|
|
82
|
+
query.push({ name: request.auth.name, value: request.auth.placeholder })
|
|
83
|
+
}
|
|
84
|
+
const search = query.map(item => `${encodeURIComponent(item.name)}=${item.value.startsWith('$') ? item.value : encodeURIComponent(item.value)}`).join('&')
|
|
85
|
+
return `${request.server}${request.resolvedPath}${search ? `?${search}` : ''}`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function headerList(request: RequestExample): { name: string, value: string }[] {
|
|
89
|
+
const headers: { name: string, value: string }[] = []
|
|
90
|
+
if (request.auth?.kind === 'bearer') {
|
|
91
|
+
headers.push({ name: 'Authorization', value: `Bearer ${request.auth.placeholder}` })
|
|
92
|
+
}
|
|
93
|
+
else if (request.auth?.kind === 'basic') {
|
|
94
|
+
headers.push({ name: 'Authorization', value: `Basic ${request.auth.placeholder}` })
|
|
95
|
+
}
|
|
96
|
+
else if (request.auth?.kind === 'header') {
|
|
97
|
+
headers.push({ name: request.auth.name, value: request.auth.placeholder })
|
|
98
|
+
}
|
|
99
|
+
if (request.contentType) {
|
|
100
|
+
headers.push({ name: 'Content-Type', value: request.contentType })
|
|
101
|
+
}
|
|
102
|
+
return [...headers, ...request.headers]
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function bodyText(request: RequestExample, indent: string): string | undefined {
|
|
106
|
+
if (request.body === undefined) {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
if (typeof request.body === 'string') {
|
|
110
|
+
return request.body
|
|
111
|
+
}
|
|
112
|
+
return JSON.stringify(request.body, null, 2).replaceAll('\n', `\n${indent}`)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function curlOf(request: RequestExample): string {
|
|
116
|
+
const lines = [`curl${request.method === 'GET' ? '' : ` -X ${request.method}`} "${urlOf(request)}"`]
|
|
117
|
+
for (const header of headerList(request)) {
|
|
118
|
+
lines.push(` -H "${header.name}: ${header.value}"`)
|
|
119
|
+
}
|
|
120
|
+
const body = bodyText(request, ' ')
|
|
121
|
+
if (body !== undefined) {
|
|
122
|
+
lines.push(` -d '${body.replaceAll('\'', '\'\\\'\'')}'`)
|
|
123
|
+
}
|
|
124
|
+
return lines.join(' \\\n')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function fetchOf(request: RequestExample): string {
|
|
128
|
+
const options: string[] = []
|
|
129
|
+
if (request.method !== 'GET') {
|
|
130
|
+
options.push(` method: '${request.method}',`)
|
|
131
|
+
}
|
|
132
|
+
const headers = headerList(request).map(header => ` '${header.name}': ${header.value.includes('$') ? `\`${templateOf(header.value)}\`` : `'${header.value}'`},`)
|
|
133
|
+
if (headers.length) {
|
|
134
|
+
options.push(` headers: {\n${headers.join('\n')}\n },`)
|
|
135
|
+
}
|
|
136
|
+
if (request.body !== undefined) {
|
|
137
|
+
options.push(typeof request.body === 'string'
|
|
138
|
+
? ` body: ${JSON.stringify(request.body)},`
|
|
139
|
+
: ` body: JSON.stringify(${JSON.stringify(request.body, null, 2).replaceAll('\n', '\n ')}),`)
|
|
140
|
+
}
|
|
141
|
+
const url = urlOf(request)
|
|
142
|
+
const urlText = url.includes('$') ? `\`${templateOf(url)}\`` : `'${url}'`
|
|
143
|
+
return `const response = await fetch(${urlText}${options.length ? `, {\n${options.join('\n')}\n}` : ''})\nconst data = await response.json()`
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `Bearer $TOKEN` → `Bearer ${TOKEN}`, for a JavaScript template literal. */
|
|
147
|
+
function templateOf(text: string): string {
|
|
148
|
+
return text.replaceAll(/\$(\w+)/g, (_match, name: string) => `\${${name}}`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function pythonOf(request: RequestExample): string {
|
|
152
|
+
const args = [` "${request.server}${request.resolvedPath}",`]
|
|
153
|
+
const params = [...request.query.map(item => [item.name, JSON.stringify(item.value)])]
|
|
154
|
+
if (request.auth?.kind === 'query') {
|
|
155
|
+
params.push([request.auth.name, envOf(request.auth.placeholder)])
|
|
156
|
+
}
|
|
157
|
+
if (params.length) {
|
|
158
|
+
args.push(` params={${params.map(([name, value]) => `"${name}": ${value}`).join(', ')}},`)
|
|
159
|
+
}
|
|
160
|
+
const headers = headerList(request).filter(header => !(request.body !== undefined && typeof request.body !== 'string' && header.name === 'Content-Type'))
|
|
161
|
+
if (headers.length) {
|
|
162
|
+
args.push(` headers={${headers.map(header => `"${header.name}": ${header.value.includes('$') ? pythonTemplate(header.value) : JSON.stringify(header.value)}`).join(', ')}},`)
|
|
163
|
+
}
|
|
164
|
+
if (request.body !== undefined) {
|
|
165
|
+
args.push(typeof request.body === 'string'
|
|
166
|
+
? ` data=${JSON.stringify(request.body)},`
|
|
167
|
+
: ` json=${pythonLiteral(request.body, ' ')},`)
|
|
168
|
+
}
|
|
169
|
+
const call = `response = requests.${request.method.toLowerCase()}(\n${args.join('\n')}\n)\ndata = response.json()`
|
|
170
|
+
return `${call.includes('os.environ') ? 'import os\n' : ''}import requests\n\n${call}`
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function envOf(placeholder: string): string {
|
|
174
|
+
return `os.environ["${placeholder.replace(/^\$/, '')}"]`
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function pythonTemplate(value: string): string {
|
|
178
|
+
return `f"${value.replaceAll(/\$(\w+)/g, '{os.environ["$1"]}')}"`
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function pythonLiteral(value: unknown, indent: string): string {
|
|
182
|
+
return JSON.stringify(value, null, 4)
|
|
183
|
+
.replaceAll(/\btrue\b(?=(?:[^"]*"[^"]*")*[^"]*$)/g, 'True')
|
|
184
|
+
.replaceAll(/\bfalse\b(?=(?:[^"]*"[^"]*")*[^"]*$)/g, 'False')
|
|
185
|
+
.replaceAll(/\bnull\b(?=(?:[^"]*"[^"]*")*[^"]*$)/g, 'None')
|
|
186
|
+
.replaceAll('\n', `\n${indent}`)
|
|
187
|
+
}
|
package/src/data/text.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { SchemaTable } from '../read/example'
|
|
2
|
+
import type { OpenApiLabels } from '../render/labels'
|
|
3
|
+
import type { SchemaNode } from '../types'
|
|
4
|
+
import { createMarkdownExit } from 'markdown-exit'
|
|
5
|
+
import { resolveNode } from '../read/example'
|
|
6
|
+
|
|
7
|
+
const prose = createMarkdownExit({ html: false, linkify: true })
|
|
8
|
+
|
|
9
|
+
/** CommonMark of a description as HTML; one paragraph is rendered inline. */
|
|
10
|
+
export function renderProse(markdown: string): string {
|
|
11
|
+
const text = markdown.trim()
|
|
12
|
+
if (!text) {
|
|
13
|
+
return ''
|
|
14
|
+
}
|
|
15
|
+
return text.includes('\n\n') || /^\s*[-*\d]/m.test(text) ? prose.render(text) : prose.renderInline(text)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function escapeHtml(text: string): string {
|
|
19
|
+
return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** First sentence-sized line of a description, for one-line lists. */
|
|
23
|
+
export function firstLine(markdown: string): string {
|
|
24
|
+
return markdown.trim().split(/\n\s*\n/)[0]?.replaceAll(/\s*\n\s*/g, ' ') ?? ''
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Short constraint texts: `1–10`, `≤ 140 chars`, `whole | skim | oat`, `/^[a-z]+$/`. */
|
|
28
|
+
export function constraintTexts(node: SchemaNode, schemas: SchemaTable, labels: OpenApiLabels): string[] {
|
|
29
|
+
const target = resolveNode(node, schemas)
|
|
30
|
+
const texts: string[] = []
|
|
31
|
+
const c = target.constraints
|
|
32
|
+
const range = (min: number | undefined, max: number | undefined, unit: (n: number) => string = String): string | undefined => {
|
|
33
|
+
if (min !== undefined && max !== undefined) {
|
|
34
|
+
return min === max ? unit(min) : `${min}–${unit(max)}`
|
|
35
|
+
}
|
|
36
|
+
if (min !== undefined) {
|
|
37
|
+
return `≥ ${unit(min)}`
|
|
38
|
+
}
|
|
39
|
+
if (max !== undefined) {
|
|
40
|
+
return `≤ ${unit(max)}`
|
|
41
|
+
}
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
if (target.enum?.length) {
|
|
45
|
+
texts.push(target.enum.map(value => (typeof value === 'string' ? value : JSON.stringify(value))).join(' | '))
|
|
46
|
+
}
|
|
47
|
+
const numbers = range(c.minimum, c.maximum)
|
|
48
|
+
if (numbers) {
|
|
49
|
+
texts.push(numbers)
|
|
50
|
+
}
|
|
51
|
+
if (c.exclusiveMinimum !== undefined) {
|
|
52
|
+
texts.push(`> ${c.exclusiveMinimum}`)
|
|
53
|
+
}
|
|
54
|
+
if (c.exclusiveMaximum !== undefined) {
|
|
55
|
+
texts.push(`< ${c.exclusiveMaximum}`)
|
|
56
|
+
}
|
|
57
|
+
if (c.multipleOf !== undefined) {
|
|
58
|
+
texts.push(`× ${c.multipleOf}`)
|
|
59
|
+
}
|
|
60
|
+
const length = range(c.minLength, c.maxLength, labels.chars)
|
|
61
|
+
if (length) {
|
|
62
|
+
texts.push(length)
|
|
63
|
+
}
|
|
64
|
+
const items = range(c.minItems, c.maxItems, labels.items)
|
|
65
|
+
if (items) {
|
|
66
|
+
texts.push(items)
|
|
67
|
+
}
|
|
68
|
+
if (c.uniqueItems) {
|
|
69
|
+
texts.push('unique')
|
|
70
|
+
}
|
|
71
|
+
if (c.pattern) {
|
|
72
|
+
texts.push(`/${c.pattern}/`)
|
|
73
|
+
}
|
|
74
|
+
return texts
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A JSON value as compact text for hints and tables. */
|
|
78
|
+
export function valueText(value: unknown): string {
|
|
79
|
+
return typeof value === 'string' ? value : JSON.stringify(value)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The first paragraph as plain text, for tooltips and short summaries. */
|
|
83
|
+
export function plainLine(markdown: string | undefined): string {
|
|
84
|
+
return firstLine(markdown ?? '').replaceAll(/[*_`]/g, '').replaceAll(/\[([^\]]*)\]\([^)]*\)/g, '$1').trim()
|
|
85
|
+
}
|