@kawapress/plugin-openapi 0.0.0-stage → 0.0.1
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
package/src/service.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { ResolvedOpenApiOptions } from './options'
|
|
2
|
+
import type { OpenApiSnapshot } from './snapshot/snapshot'
|
|
3
|
+
import type { OpenApiModel } from './types'
|
|
4
|
+
import { existsSync, statSync } from 'node:fs'
|
|
5
|
+
import { readFile } from 'node:fs/promises'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { glob } from 'tinyglobby'
|
|
8
|
+
import { normalizePath } from 'vite'
|
|
9
|
+
import { readArazzo } from './read/arazzo'
|
|
10
|
+
import { parseDocument } from './read/document'
|
|
11
|
+
import { readOpenApi } from './read/model'
|
|
12
|
+
import { inferSince } from './snapshot/history'
|
|
13
|
+
import { operationKey } from './snapshot/snapshot'
|
|
14
|
+
|
|
15
|
+
/** What the pages and components read: the model, plus the snapshot history. */
|
|
16
|
+
export interface LoadedApi {
|
|
17
|
+
model: OpenApiModel
|
|
18
|
+
snapshots: OpenApiSnapshot[]
|
|
19
|
+
/** `POST /orders|request items[].quantity` → the version the facet subject first appears in. */
|
|
20
|
+
subjectSince: ReadonlyMap<string, string>
|
|
21
|
+
/** Absolute paths of the snapshot files. */
|
|
22
|
+
snapshotFiles: string[]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const SNAPSHOT_PATTERN = '*.json'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Reads and caches the API: one parse per change of the spec, the workflow
|
|
29
|
+
* files or the snapshots, shared by every page group and component.
|
|
30
|
+
*/
|
|
31
|
+
export class OpenApiService {
|
|
32
|
+
private cached: { key: string, api: LoadedApi } | undefined
|
|
33
|
+
private pending: { key: string, promise: Promise<LoadedApi> } | undefined
|
|
34
|
+
|
|
35
|
+
constructor(private options: () => ResolvedOpenApiOptions) {}
|
|
36
|
+
|
|
37
|
+
/** The latest successful result, without reading anything. */
|
|
38
|
+
peek(): LoadedApi | undefined {
|
|
39
|
+
return this.cached?.api
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Files whose change means the data is stale. */
|
|
43
|
+
watchedFiles(): Set<string> {
|
|
44
|
+
const options = this.options()
|
|
45
|
+
return new Set([options.spec, ...options.workflows, ...(this.cached?.api.snapshotFiles ?? [])].map(file => normalizePath(file)))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async get(): Promise<LoadedApi> {
|
|
49
|
+
const options = this.options()
|
|
50
|
+
const snapshotFiles = existsSync(options.snapshotDir)
|
|
51
|
+
? (await glob(SNAPSHOT_PATTERN, { cwd: options.snapshotDir, absolute: true })).sort()
|
|
52
|
+
: []
|
|
53
|
+
const files = [options.spec, ...options.workflows, ...snapshotFiles]
|
|
54
|
+
const key = files.map(file => `${file}:${stamp(file)}`).join('|')
|
|
55
|
+
if (this.cached?.key === key) {
|
|
56
|
+
return this.cached.api
|
|
57
|
+
}
|
|
58
|
+
if (this.pending?.key !== key) {
|
|
59
|
+
const promise = load(options, snapshotFiles).then((api) => {
|
|
60
|
+
this.cached = { key, api }
|
|
61
|
+
return api
|
|
62
|
+
}).finally(() => {
|
|
63
|
+
if (this.pending?.promise === promise) {
|
|
64
|
+
this.pending = undefined
|
|
65
|
+
}
|
|
66
|
+
})
|
|
67
|
+
this.pending = { key, promise }
|
|
68
|
+
}
|
|
69
|
+
return this.pending!.promise
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function stamp(file: string): string {
|
|
74
|
+
try {
|
|
75
|
+
const stats = statSync(file)
|
|
76
|
+
return `${stats.mtimeMs}:${stats.size}`
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return 'missing'
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function load(options: ResolvedOpenApiOptions, snapshotFiles: string[]): Promise<LoadedApi> {
|
|
84
|
+
const model = readOpenApi(parseDocument(await readText(options.spec, 'spec'), options.spec), options.spec)
|
|
85
|
+
for (const file of options.workflows) {
|
|
86
|
+
model.workflows.push(...readArazzo(parseDocument(await readText(file, 'workflows'), file), file, model))
|
|
87
|
+
model.sourceFiles.push(file)
|
|
88
|
+
}
|
|
89
|
+
const slugs = new Map<string, string>()
|
|
90
|
+
for (const workflow of model.workflows) {
|
|
91
|
+
const other = slugs.get(workflow.slug)
|
|
92
|
+
if (other) {
|
|
93
|
+
throw new Error(`${workflow.file}: the workflows "${other}" and "${workflow.id}" both become the page "journeys/${workflow.slug}".`)
|
|
94
|
+
}
|
|
95
|
+
slugs.set(workflow.slug, workflow.id)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const snapshots: OpenApiSnapshot[] = []
|
|
99
|
+
for (const file of snapshotFiles) {
|
|
100
|
+
const parsed = JSON.parse(await readFile(file, 'utf8')) as OpenApiSnapshot
|
|
101
|
+
if (typeof parsed?.version !== 'string' || typeof parsed.operations !== 'object') {
|
|
102
|
+
throw new TypeError(`${file} is not an OpenAPI snapshot written by kawapress-openapi.`)
|
|
103
|
+
}
|
|
104
|
+
snapshots.push(parsed)
|
|
105
|
+
}
|
|
106
|
+
const since = inferSince(snapshots)
|
|
107
|
+
for (const operation of model.operations) {
|
|
108
|
+
const inferred = since.operations.get(operationKey(operation))
|
|
109
|
+
if (!operation.since && inferred) {
|
|
110
|
+
operation.since = inferred
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return { model, snapshots, subjectSince: since.subjects, snapshotFiles }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function readText(file: string, option: string): Promise<string> {
|
|
117
|
+
try {
|
|
118
|
+
return await readFile(file, 'utf8')
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
throw new Error(`KawaPress OpenAPI: the file of the option "${option}" does not exist: ${file}`)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The snapshot file of a version. */
|
|
126
|
+
export function snapshotFile(dir: string, version: string): string {
|
|
127
|
+
return join(dir, `${version}.json`)
|
|
128
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import type { OpenApiSnapshot, ParsedFacet } from './snapshot'
|
|
2
|
+
import { parseFacet } from './snapshot'
|
|
3
|
+
|
|
4
|
+
export type ChangeKind = 'breaking' | 'added' | 'deprecated' | 'changed'
|
|
5
|
+
|
|
6
|
+
export type ChangeReason
|
|
7
|
+
= | 'operation-added'
|
|
8
|
+
| 'operation-removed'
|
|
9
|
+
| 'operation-deprecated'
|
|
10
|
+
| 'removed'
|
|
11
|
+
| 'type-changed'
|
|
12
|
+
| 'required-added'
|
|
13
|
+
| 'became-required'
|
|
14
|
+
| 'added'
|
|
15
|
+
| 'status-added'
|
|
16
|
+
| 'status-removed'
|
|
17
|
+
| 'deprecated'
|
|
18
|
+
| 'became-optional'
|
|
19
|
+
| 'undeprecated'
|
|
20
|
+
|
|
21
|
+
export interface ApiChange {
|
|
22
|
+
kind: ChangeKind
|
|
23
|
+
reason: ChangeReason
|
|
24
|
+
/** `POST /orders`. */
|
|
25
|
+
operation: string
|
|
26
|
+
/** `request items[].quantity`; absent for operation-level changes. */
|
|
27
|
+
subject?: string
|
|
28
|
+
before?: string
|
|
29
|
+
after?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface VersionChanges {
|
|
33
|
+
version: string
|
|
34
|
+
previous: string
|
|
35
|
+
changes: ApiChange[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Snapshots oldest first, by version number. */
|
|
39
|
+
export function sortSnapshots(snapshots: OpenApiSnapshot[]): OpenApiSnapshot[] {
|
|
40
|
+
return [...snapshots].sort((a, b) => compareVersions(a.version, b.version))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Changes between each pair of neighbouring snapshots, newest first. */
|
|
44
|
+
export function versionChanges(snapshots: OpenApiSnapshot[]): VersionChanges[] {
|
|
45
|
+
const sorted = sortSnapshots(snapshots)
|
|
46
|
+
const result: VersionChanges[] = []
|
|
47
|
+
for (let index = 1; index < sorted.length; index++) {
|
|
48
|
+
result.push({ version: sorted[index].version, previous: sorted[index - 1].version, changes: diffSnapshots(sorted[index - 1], sorted[index]) })
|
|
49
|
+
}
|
|
50
|
+
return result.reverse()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const KIND_ORDER: Record<ChangeKind, number> = { breaking: 0, added: 1, deprecated: 2, changed: 3 }
|
|
54
|
+
|
|
55
|
+
export function diffSnapshots(before: OpenApiSnapshot, after: OpenApiSnapshot): ApiChange[] {
|
|
56
|
+
const changes: ApiChange[] = []
|
|
57
|
+
const keys = [...new Set([...Object.keys(before.operations), ...Object.keys(after.operations)])].sort()
|
|
58
|
+
for (const key of keys) {
|
|
59
|
+
const old = before.operations[key]
|
|
60
|
+
const now = after.operations[key]
|
|
61
|
+
if (!old) {
|
|
62
|
+
changes.push({ kind: 'added', reason: 'operation-added', operation: key })
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
if (!now) {
|
|
66
|
+
changes.push({ kind: 'breaking', reason: 'operation-removed', operation: key })
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
if (!old.includes('deprecated') && now.includes('deprecated')) {
|
|
70
|
+
changes.push({ kind: 'deprecated', reason: 'operation-deprecated', operation: key })
|
|
71
|
+
}
|
|
72
|
+
changes.push(...diffFacets(key, old.filter(line => line !== 'deprecated'), now.filter(line => line !== 'deprecated')))
|
|
73
|
+
}
|
|
74
|
+
return changes.sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind])
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function diffFacets(operation: string, before: string[], after: string[]): ApiChange[] {
|
|
78
|
+
const oldBySubject = new Map(before.map(line => [parseFacet(line).subject, parseFacet(line)]))
|
|
79
|
+
const newBySubject = new Map(after.map(line => [parseFacet(line).subject, parseFacet(line)]))
|
|
80
|
+
const changes: ApiChange[] = []
|
|
81
|
+
const removedParents: string[] = []
|
|
82
|
+
|
|
83
|
+
for (const [subject, old] of oldBySubject) {
|
|
84
|
+
if (newBySubject.has(subject) || removedParents.some(parent => isInside(subject, parent))) {
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
removedParents.push(subject)
|
|
88
|
+
const status = /^response \S+$/.test(subject)
|
|
89
|
+
changes.push({ kind: 'breaking', reason: status ? 'status-removed' : 'removed', operation, subject, before: describe(old) })
|
|
90
|
+
}
|
|
91
|
+
const addedParents: string[] = []
|
|
92
|
+
for (const [subject, now] of newBySubject) {
|
|
93
|
+
const old = oldBySubject.get(subject)
|
|
94
|
+
if (!old) {
|
|
95
|
+
if (addedParents.some(parent => isInside(subject, parent))) {
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
addedParents.push(subject)
|
|
99
|
+
const request = !subject.startsWith('response')
|
|
100
|
+
if (/^response \S+$/.test(subject)) {
|
|
101
|
+
changes.push({ kind: 'added', reason: 'status-added', operation, subject })
|
|
102
|
+
}
|
|
103
|
+
else if (request && now.required && !subject.endsWith(' body')) {
|
|
104
|
+
changes.push({ kind: 'breaking', reason: 'required-added', operation, subject, after: describe(now) })
|
|
105
|
+
}
|
|
106
|
+
else if (!subject.endsWith(' body')) {
|
|
107
|
+
changes.push({ kind: 'added', reason: 'added', operation, subject, after: describe(now) })
|
|
108
|
+
}
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
if (old.type !== now.type) {
|
|
112
|
+
changes.push({ kind: 'breaking', reason: 'type-changed', operation, subject, before: describe(old), after: describe(now) })
|
|
113
|
+
}
|
|
114
|
+
else if (!subject.startsWith('response') && !old.required && now.required) {
|
|
115
|
+
changes.push({ kind: 'breaking', reason: 'became-required', operation, subject, before: describe(old), after: describe(now) })
|
|
116
|
+
}
|
|
117
|
+
else if (!subject.startsWith('response') && old.required && !now.required) {
|
|
118
|
+
changes.push({ kind: 'changed', reason: 'became-optional', operation, subject, before: describe(old), after: describe(now) })
|
|
119
|
+
}
|
|
120
|
+
if (!old.deprecated && now.deprecated) {
|
|
121
|
+
changes.push({ kind: 'deprecated', reason: 'deprecated', operation, subject })
|
|
122
|
+
}
|
|
123
|
+
else if (old.deprecated && !now.deprecated) {
|
|
124
|
+
changes.push({ kind: 'changed', reason: 'undeprecated', operation, subject })
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return changes
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `request items[].quantity` is inside `request items`. */
|
|
131
|
+
function isInside(subject: string, parent: string): boolean {
|
|
132
|
+
return subject.startsWith(`${parent}.`) || subject.startsWith(`${parent}[]`) || (/^response \S+$/.test(parent) && subject.startsWith(`${parent} `))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function describe(facet: ParsedFacet): string {
|
|
136
|
+
return `${facet.type}${facet.required ? ' (required)' : ''}`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The version each operation and facet subject first appears in. The oldest
|
|
141
|
+
* snapshot is the starting point and tells nothing, so only later ones count.
|
|
142
|
+
*/
|
|
143
|
+
export function inferSince(snapshots: OpenApiSnapshot[]): { operations: Map<string, string>, subjects: Map<string, string> } {
|
|
144
|
+
const sorted = sortSnapshots(snapshots)
|
|
145
|
+
const operations = new Map<string, string>()
|
|
146
|
+
const subjects = new Map<string, string>()
|
|
147
|
+
if (sorted.length === 0) {
|
|
148
|
+
return { operations, subjects }
|
|
149
|
+
}
|
|
150
|
+
const seenOperations = new Set(Object.keys(sorted[0].operations))
|
|
151
|
+
const seenSubjects = new Set(Object.entries(sorted[0].operations).flatMap(([key, lines]) => lines.map(line => `${key}|${parseFacet(line).subject}`)))
|
|
152
|
+
for (const snapshot of sorted.slice(1)) {
|
|
153
|
+
for (const [key, lines] of Object.entries(snapshot.operations)) {
|
|
154
|
+
if (!seenOperations.has(key)) {
|
|
155
|
+
seenOperations.add(key)
|
|
156
|
+
operations.set(key, snapshot.version)
|
|
157
|
+
}
|
|
158
|
+
for (const line of lines) {
|
|
159
|
+
const id = `${key}|${parseFacet(line).subject}`
|
|
160
|
+
if (!seenSubjects.has(id)) {
|
|
161
|
+
seenSubjects.add(id)
|
|
162
|
+
if (!operations.has(key) || operations.get(key) !== snapshot.version) {
|
|
163
|
+
subjects.set(id, snapshot.version)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return { operations, subjects }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Numeric comparison of dotted versions; pre-release tags sort before the release. */
|
|
173
|
+
export function compareVersions(a: string, b: string): number {
|
|
174
|
+
const [mainA, preA = ''] = a.replace(/^v/, '').split('-', 2)
|
|
175
|
+
const [mainB, preB = ''] = b.replace(/^v/, '').split('-', 2)
|
|
176
|
+
const partsA = mainA.split('.').map(Number)
|
|
177
|
+
const partsB = mainB.split('.').map(Number)
|
|
178
|
+
for (let index = 0; index < Math.max(partsA.length, partsB.length); index++) {
|
|
179
|
+
const difference = (partsA[index] || 0) - (partsB[index] || 0)
|
|
180
|
+
if (difference !== 0 && !Number.isNaN(difference)) {
|
|
181
|
+
return difference
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (preA === preB) {
|
|
185
|
+
return a.localeCompare(b)
|
|
186
|
+
}
|
|
187
|
+
return preA === '' ? 1 : preB === '' ? -1 : preA.localeCompare(preB)
|
|
188
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { SchemaTable } from '../read/example'
|
|
2
|
+
import type { OpenApiModel, OpenApiOperation, SchemaNode } from '../types'
|
|
3
|
+
import { flattenFields, typeLabel } from '../data/fields'
|
|
4
|
+
import { resolveNode } from '../read/example'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The shape of an API at one version: per operation, sorted "facet" lines
|
|
8
|
+
* such as `request items[].quantity: integer required`. Descriptions are left
|
|
9
|
+
* out, so editing prose is not an API change.
|
|
10
|
+
*/
|
|
11
|
+
export interface OpenApiSnapshot {
|
|
12
|
+
version: string
|
|
13
|
+
operations: Record<string, string[]>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** `POST /orders`, or `WEBHOOK order.paid`. */
|
|
17
|
+
export function operationKey(operation: Pick<OpenApiOperation, 'method' | 'path' | 'webhook'>): string {
|
|
18
|
+
return operation.webhook ? `WEBHOOK ${operation.path}` : `${operation.method.toUpperCase()} ${operation.path}`
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createSnapshot(model: OpenApiModel): OpenApiSnapshot {
|
|
22
|
+
const schemas: SchemaTable = new Map(model.schemas.map(entry => [entry.name, entry.schema]))
|
|
23
|
+
const operations: Record<string, string[]> = {}
|
|
24
|
+
for (const operation of [...model.operations].sort((a, b) => operationKey(a).localeCompare(operationKey(b)))) {
|
|
25
|
+
operations[operationKey(operation)] = facetsOf(operation, schemas)
|
|
26
|
+
}
|
|
27
|
+
return { version: model.info.version, operations }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function facetsOf(operation: OpenApiOperation, schemas: SchemaTable): string[] {
|
|
31
|
+
const facets: string[] = []
|
|
32
|
+
if (operation.deprecated) {
|
|
33
|
+
facets.push('deprecated')
|
|
34
|
+
}
|
|
35
|
+
for (const parameter of operation.parameters) {
|
|
36
|
+
facets.push(facet(`param ${parameter.in} ${parameter.name}`, parameter.schema, schemas, parameter.required, parameter.deprecated))
|
|
37
|
+
}
|
|
38
|
+
if (operation.requestBody) {
|
|
39
|
+
facets.push(...bodyFacets('request', operation.requestBody.schema, schemas, operation.requestBody.required))
|
|
40
|
+
}
|
|
41
|
+
for (const response of operation.responses) {
|
|
42
|
+
facets.push(`response ${response.status}`)
|
|
43
|
+
if (response.body) {
|
|
44
|
+
facets.push(...bodyFacets(`response ${response.status}`, response.body.schema, schemas, true))
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return facets.sort()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function bodyFacets(subject: string, schema: SchemaNode, schemas: SchemaTable, required: boolean): string[] {
|
|
51
|
+
const direction = subject === 'request' ? 'request' : 'response'
|
|
52
|
+
const target = resolveNode(schema, schemas)
|
|
53
|
+
const fields = flattenFields(schema, schemas, { direction })
|
|
54
|
+
const facets = [facet(`${subject} body`, schema, schemas, required, target.deprecated)]
|
|
55
|
+
for (const field of fields) {
|
|
56
|
+
facets.push(facet(`${subject} ${field.path}`, field.schema, schemas, field.required, field.schema.deprecated || field.target.deprecated))
|
|
57
|
+
}
|
|
58
|
+
return facets
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function facet(subject: string, schema: SchemaNode, schemas: SchemaTable, required: boolean, deprecated: boolean): string {
|
|
62
|
+
const target = resolveNode(schema, schemas)
|
|
63
|
+
const type = typeLabel(schema, schemas)
|
|
64
|
+
const values = target.enum?.length ? ` enum(${target.enum.map(value => JSON.stringify(value)).join(',')})` : ''
|
|
65
|
+
return `${subject}: ${type}${values}${required ? ' required' : ''}${deprecated ? ' deprecated' : ''}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One facet split into what the diff compares. */
|
|
69
|
+
export interface ParsedFacet {
|
|
70
|
+
subject: string
|
|
71
|
+
type: string
|
|
72
|
+
required: boolean
|
|
73
|
+
deprecated: boolean
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function parseFacet(line: string): ParsedFacet {
|
|
77
|
+
if (!line.includes(': ')) {
|
|
78
|
+
return { subject: line, type: '', required: false, deprecated: false }
|
|
79
|
+
}
|
|
80
|
+
const index = line.indexOf(': ')
|
|
81
|
+
let rest = line.slice(index + 2)
|
|
82
|
+
const deprecated = rest.endsWith(' deprecated')
|
|
83
|
+
rest = deprecated ? rest.slice(0, -' deprecated'.length) : rest
|
|
84
|
+
const required = rest.endsWith(' required')
|
|
85
|
+
rest = required ? rest.slice(0, -' required'.length) : rest
|
|
86
|
+
return { subject: line.slice(0, index), type: rest, required, deprecated }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function serializeSnapshot(snapshot: OpenApiSnapshot): string {
|
|
90
|
+
return `${JSON.stringify(snapshot, null, 2)}\n`
|
|
91
|
+
}
|
package/src/tag.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { MarkdownExit, RenderRule } from 'markdown-exit'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { INTERNAL_TAG } from './render/pages'
|
|
4
|
+
|
|
5
|
+
type RenderRuleArgs = Parameters<RenderRule>
|
|
6
|
+
|
|
7
|
+
interface TagRenderEnv {
|
|
8
|
+
/** Route of the page being compiled. */
|
|
9
|
+
path?: string
|
|
10
|
+
/** Source path of the page, for messages. */
|
|
11
|
+
sourcePath?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Module specifier prefix the Vite plugin resolves; the query says which component and data. */
|
|
15
|
+
export const COMPONENT_MODULE = 'virtual:kawapress-openapi/component'
|
|
16
|
+
|
|
17
|
+
/** The tags authors and generated pages write, and the component kind each becomes. */
|
|
18
|
+
const TAGS: Record<string, { kind?: string, required: string[], example: string }> = {
|
|
19
|
+
[INTERNAL_TAG]: { required: ['kind'], example: `<${INTERNAL_TAG} kind="endpoint" op="createOrder" />` },
|
|
20
|
+
OpenApiOperation: { kind: 'card', required: ['op'], example: '<OpenApiOperation op="createOrder" />' },
|
|
21
|
+
OpenApiSchema: { kind: 'schema', required: ['name'], example: '<OpenApiSchema name="Order" />' },
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Attributes passed on to the data module. */
|
|
25
|
+
const PASSED = ['kind', 'op', 'name', 'workflow', 'fields', 'schema', 'journey']
|
|
26
|
+
|
|
27
|
+
const ATTRIBUTE_RE = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
|
|
28
|
+
const INLINE_RE = /^:api\{([^}\n]*)\}/
|
|
29
|
+
const INLINE_ATTRIBUTE_RE = /([a-z]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'}]+))/g
|
|
30
|
+
|
|
31
|
+
export interface InstallTagsOptions {
|
|
32
|
+
/** URL prefix of the locale of a page: `''` for the root locale, `/en` for `en`. */
|
|
33
|
+
prefixOf: (path: string) => string
|
|
34
|
+
/** Declares the page component the rewritten tag uses. */
|
|
35
|
+
onComponent: (env: RenderRuleArgs[3], component: { name: string, from: string }) => void
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Makes the plugin's tags work in Markdown pages: `<OpenApiOperation>`,
|
|
40
|
+
* `<OpenApiSchema>`, the generated pages' `<KawaOpenApi>`, and the inline
|
|
41
|
+
* `:api{op=createOrder}` become page components whose data a Vite module
|
|
42
|
+
* looks up, so a wrong reference fails with the page named, and a spec change
|
|
43
|
+
* updates the page through the module graph.
|
|
44
|
+
*/
|
|
45
|
+
export function installOpenApiTags(markdown: MarkdownExit, options: InstallTagsOptions): void {
|
|
46
|
+
const names = Object.keys(TAGS).join('|')
|
|
47
|
+
const tagRe = new RegExp(`<(${names})(\\s[^>]*?)?\\s*/?>(?:\\s*</(?:${names})>)?`, 'g')
|
|
48
|
+
|
|
49
|
+
markdown.inline.ruler.before('emphasis', 'kawa_openapi_ref', (state, silent) => {
|
|
50
|
+
if (state.src.charCodeAt(state.pos) !== 0x3A /* : */) {
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
const match = INLINE_RE.exec(state.src.slice(state.pos))
|
|
54
|
+
if (!match) {
|
|
55
|
+
return false
|
|
56
|
+
}
|
|
57
|
+
if (!silent) {
|
|
58
|
+
const attributes: string[] = ['kind="ref"']
|
|
59
|
+
for (const attribute of match[1].matchAll(INLINE_ATTRIBUTE_RE)) {
|
|
60
|
+
attributes.push(`${attribute[1]}="${(attribute[2] ?? attribute[3] ?? attribute[4] ?? '').replaceAll('"', '"')}"`)
|
|
61
|
+
}
|
|
62
|
+
const token = state.push('html_inline', '', 0)
|
|
63
|
+
token.content = `<${INTERNAL_TAG} ${attributes.join(' ')} />`
|
|
64
|
+
}
|
|
65
|
+
state.pos += match[0].length
|
|
66
|
+
return true
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
for (const rule of ['html_block', 'html_inline'] as const) {
|
|
70
|
+
const original = markdown.renderer.rules[rule]
|
|
71
|
+
markdown.renderer.rules[rule] = (tokens, index, renderOptions, env, renderer) => {
|
|
72
|
+
const token = tokens[index]
|
|
73
|
+
if (token.content.includes('<OpenApi') || token.content.includes(`<${INTERNAL_TAG}`)) {
|
|
74
|
+
token.content = token.content.replace(tagRe, (_match, name: string, attributes: string | undefined) => (
|
|
75
|
+
rewriteTag(name, parseAttributes(attributes ?? ''), env, options)
|
|
76
|
+
))
|
|
77
|
+
}
|
|
78
|
+
return original
|
|
79
|
+
? original(tokens, index, renderOptions, env, renderer)
|
|
80
|
+
: token.content
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function rewriteTag(name: string, attributes: Record<string, string>, env: RenderRuleArgs[3], options: InstallTagsOptions): string {
|
|
86
|
+
const tag = TAGS[name]
|
|
87
|
+
const { path = '/', sourcePath } = (env ?? {}) as TagRenderEnv
|
|
88
|
+
const page = sourcePath ?? path
|
|
89
|
+
const missing = tag.required.find(attribute => !attributes[attribute]?.trim())
|
|
90
|
+
if (missing) {
|
|
91
|
+
throw new Error(`KawaPress OpenAPI: <${name}> on ${page} needs \`${missing}\`, for example ${tag.example}.`)
|
|
92
|
+
}
|
|
93
|
+
const passed = Object.fromEntries(PASSED.filter(key => attributes[key]?.trim()).map(key => [key, attributes[key].trim()]))
|
|
94
|
+
// The id must not end in the page's `.md`, or Markdown transforms would take the module for a page.
|
|
95
|
+
const query = new URLSearchParams({
|
|
96
|
+
...passed,
|
|
97
|
+
...(tag.kind ? { kind: tag.kind } : {}),
|
|
98
|
+
prefix: options.prefixOf(path),
|
|
99
|
+
page,
|
|
100
|
+
end: 'component',
|
|
101
|
+
})
|
|
102
|
+
const from = `${COMPONENT_MODULE}?${query.toString()}`
|
|
103
|
+
const component = `KawaOpenApi_${createHash('sha1').update(from).digest('hex').slice(0, 10)}`
|
|
104
|
+
options.onComponent(env, { name: component, from })
|
|
105
|
+
return `<${component} />`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parseAttributes(source: string): Record<string, string> {
|
|
109
|
+
const attributes: Record<string, string> = {}
|
|
110
|
+
for (const match of source.matchAll(ATTRIBUTE_RE)) {
|
|
111
|
+
attributes[match[1]] = (match[2] ?? match[3] ?? '').replaceAll('"', '"')
|
|
112
|
+
}
|
|
113
|
+
return attributes
|
|
114
|
+
}
|