@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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README-zh-CN.md +75 -0
  3. package/README.md +74 -2
  4. package/bin/kawapress-openapi.mjs +10 -0
  5. package/package.json +67 -3
  6. package/src/cli.ts +35 -0
  7. package/src/commands.ts +28 -0
  8. package/src/components/KawaOpenApiBody.vue +20 -0
  9. package/src/components/KawaOpenApiBodyView.vue +41 -0
  10. package/src/components/KawaOpenApiCard.vue +33 -0
  11. package/src/components/KawaOpenApiEndpoint.vue +186 -0
  12. package/src/components/KawaOpenApiFieldList.vue +35 -0
  13. package/src/components/KawaOpenApiJourney.vue +100 -0
  14. package/src/components/KawaOpenApiMap.vue +50 -0
  15. package/src/components/KawaOpenApiParameters.vue +24 -0
  16. package/src/components/KawaOpenApiPayload.vue +77 -0
  17. package/src/components/KawaOpenApiRef.vue +21 -0
  18. package/src/components/KawaOpenApiResponses.vue +37 -0
  19. package/src/components/KawaOpenApiSamples.vue +39 -0
  20. package/src/components/KawaOpenApiTabs.vue +68 -0
  21. package/src/components/openapi.css +550 -0
  22. package/src/components/validate.ts +138 -0
  23. package/src/data/body.ts +115 -0
  24. package/src/data/components.ts +687 -0
  25. package/src/data/fields.ts +129 -0
  26. package/src/data/payload.ts +214 -0
  27. package/src/data/rules.ts +67 -0
  28. package/src/data/samples.ts +187 -0
  29. package/src/data/text.ts +85 -0
  30. package/src/data/typescript.ts +105 -0
  31. package/src/env.d.ts +8 -0
  32. package/src/index.ts +123 -0
  33. package/src/options.ts +53 -0
  34. package/src/pages.ts +120 -0
  35. package/src/read/arazzo.ts +168 -0
  36. package/src/read/document.ts +91 -0
  37. package/src/read/example.ts +143 -0
  38. package/src/read/model.ts +341 -0
  39. package/src/read/schema.ts +212 -0
  40. package/src/render/labels.ts +283 -0
  41. package/src/render/pages.ts +237 -0
  42. package/src/render/routes.ts +48 -0
  43. package/src/runtime-plugin.ts +12 -0
  44. package/src/service.ts +128 -0
  45. package/src/snapshot/history.ts +188 -0
  46. package/src/snapshot/snapshot.ts +91 -0
  47. package/src/tag.ts +114 -0
  48. package/src/types.ts +207 -0
  49. package/src/vite.ts +169 -0
@@ -0,0 +1,105 @@
1
+ import type { Direction, SchemaTable } from '../read/example'
2
+ import type { SchemaNode } from '../types'
3
+ import { resolveNode, visibleOn } from '../read/example'
4
+
5
+ /**
6
+ * TypeScript declarations for a schema: `interface` for objects, `type` for
7
+ * everything else. Named models keep their names; the declaration of a named
8
+ * root uses that name, an inline root uses `fallbackName`.
9
+ */
10
+ export function typescriptOf(schema: SchemaNode, schemas: SchemaTable, fallbackName: string, direction: Direction): string {
11
+ const name = schema.kind === 'ref' && schema.ref ? identifier(schema.ref) : fallbackName
12
+ const target = resolveNode(schema, schemas)
13
+ const comment = jsDoc(target, '')
14
+ if (target.kind === 'object' && (target.properties?.length || target.additionalProperties)) {
15
+ return `${comment}interface ${name} ${objectType(target, schemas, direction, '', 0)}`
16
+ }
17
+ return `${comment}type ${name} = ${typeOf(target, schemas, direction, '', 0)}`
18
+ }
19
+
20
+ function objectType(node: SchemaNode, schemas: SchemaTable, direction: Direction, indent: string, depth: number): string {
21
+ const inner = `${indent} `
22
+ const members: string[] = []
23
+ for (const property of node.properties ?? []) {
24
+ if (!visibleOn(property.schema, schemas, direction)) {
25
+ continue
26
+ }
27
+ const doc = jsDoc(property.schema.kind === 'ref' ? { ...resolveNode(property.schema, schemas), description: property.schema.description, deprecated: false, since: undefined } : property.schema, inner)
28
+ const key = /^[A-Z_$][\w$]*$/i.test(property.name) ? property.name : JSON.stringify(property.name)
29
+ members.push(`${doc}${inner}${key}${property.required ? '' : '?'}: ${typeOf(property.schema, schemas, direction, inner, depth + 1)}`)
30
+ }
31
+ if (node.additionalProperties) {
32
+ const value = node.additionalProperties === true ? 'unknown' : typeOf(node.additionalProperties, schemas, direction, inner, depth + 1)
33
+ members.push(`${inner}[key: string]: ${value}`)
34
+ }
35
+ return members.length === 0 ? '{}' : `{\n${members.join('\n')}\n${indent}}`
36
+ }
37
+
38
+ function typeOf(node: SchemaNode, schemas: SchemaTable, direction: Direction, indent: string, depth: number): string {
39
+ const nullable = node.nullable ? ' | null' : ''
40
+ if (node.kind === 'ref' && node.ref) {
41
+ return `${identifier(node.ref)}${resolveNode(node, schemas).nullable ? ' | null' : ''}`
42
+ }
43
+ if (node.enum?.length) {
44
+ return `${node.enum.map(value => (typeof value === 'string' ? `'${value.replaceAll('\'', '\\\'')}'` : JSON.stringify(value))).join(' | ')}${nullable}`
45
+ }
46
+ if (depth > 6) {
47
+ return 'unknown'
48
+ }
49
+ switch (node.kind) {
50
+ case 'string':
51
+ return `string${nullable}`
52
+ case 'integer':
53
+ case 'number':
54
+ return `number${nullable}`
55
+ case 'boolean':
56
+ return `boolean${nullable}`
57
+ case 'null':
58
+ return 'null'
59
+ case 'array': {
60
+ const item = node.items ? typeOf(node.items, schemas, direction, indent, depth + 1) : 'unknown'
61
+ return `${/[ |&{]/.test(item) ? `Array<${item}>` : `${item}[]`}${nullable}`
62
+ }
63
+ case 'union':
64
+ return `${(node.variants ?? []).map(variant => typeOf(variant, schemas, direction, indent, depth + 1)).join(' | ') || 'unknown'}${nullable}`
65
+ case 'object':
66
+ return `${objectType(node, schemas, direction, indent, depth)}${nullable}`
67
+ default:
68
+ return node.properties?.length ? `${objectType(node, schemas, direction, indent, depth)}${nullable}` : 'unknown'
69
+ }
70
+ }
71
+
72
+ function jsDoc(node: Pick<SchemaNode, 'description' | 'deprecated' | 'since' | 'format'> & { default?: unknown }, indent: string): string {
73
+ const lines = node.description ? node.description.trim().split('\n').map(line => line.trimEnd().replaceAll('*/', '*\\/')) : []
74
+ if (node.format && !['int32', 'int64', 'float', 'double'].includes(node.format)) {
75
+ lines.push(`@format ${node.format}`)
76
+ }
77
+ if (node.default !== undefined) {
78
+ lines.push(`@default ${JSON.stringify(node.default)}`)
79
+ }
80
+ if (node.since) {
81
+ lines.push(`@since ${node.since}`)
82
+ }
83
+ if (node.deprecated) {
84
+ lines.push('@deprecated')
85
+ }
86
+ if (lines.length === 0) {
87
+ return ''
88
+ }
89
+ if (lines.length === 1) {
90
+ return `${indent}/** ${lines[0]} */\n`
91
+ }
92
+ return `${indent}/**\n${lines.map(line => `${indent} *${line ? ` ${line}` : ''}`).join('\n')}\n${indent} */\n`
93
+ }
94
+
95
+ /** A model name as a TypeScript identifier. */
96
+ export function identifier(name: string): string {
97
+ const cleaned = name.replaceAll(/[^\w$]+(.)?/g, (_match, next: string | undefined) => next?.toUpperCase() ?? '')
98
+ return /^\d/.test(cleaned) ? `_${cleaned}` : cleaned || 'Model'
99
+ }
100
+
101
+ /** `createOrder` → `CreateOrder`. */
102
+ export function pascalCase(text: string): string {
103
+ const id = identifier(text.replaceAll(/[-_\s]+(.)?/g, (_match, next: string | undefined) => next?.toUpperCase() ?? ''))
104
+ return id.charAt(0).toUpperCase() + id.slice(1)
105
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ interface ImportMetaEnv {
2
+ /** Set by `@kawapress/plugin-llms` while it compiles pages to Markdown. */
3
+ readonly SSG_MD: boolean
4
+ }
5
+
6
+ interface ImportMeta {
7
+ readonly env: ImportMetaEnv
8
+ }
package/src/index.ts ADDED
@@ -0,0 +1,123 @@
1
+ import type { KawaPressPlugin, LocaleConfig, ResolvedSiteConfig } from 'kawapress'
2
+ import type { MarkdownExit } from 'markdown-exit'
3
+ import type { ResolvedOpenApiOptions } from './options'
4
+ import type { OpenApiPluginOptions } from './types'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { addPageComponent, definePlugin, resolveLocaleIndex } from 'kawapress'
7
+ import { DEFAULT_ROUTE, localePrefix, normalizeRoute, resolveOpenApiOptions } from './options'
8
+ import { registerOpenApiPages } from './pages'
9
+ import { OpenApiService } from './service'
10
+ import { installOpenApiTags } from './tag'
11
+ import { createOpenApiVitePlugin } from './vite'
12
+
13
+ export type {
14
+ HttpMethod,
15
+ OpenApiAction,
16
+ OpenApiBody,
17
+ OpenApiModel,
18
+ OpenApiOperation,
19
+ OpenApiParameter,
20
+ OpenApiPluginOptions,
21
+ OpenApiResource,
22
+ OpenApiResponse,
23
+ OpenApiSampleLanguage,
24
+ OpenApiSchemaEntry,
25
+ OpenApiSecurityScheme,
26
+ OpenApiServer,
27
+ OpenApiWorkflow,
28
+ SchemaKind,
29
+ SchemaNode,
30
+ SchemaProperty,
31
+ WorkflowStep,
32
+ WorkflowValue,
33
+ } from './types'
34
+
35
+ const PLUGIN_NAME = '@kawapress/plugin-openapi'
36
+ /** The locale of a site without `locales`. */
37
+ const DEFAULT_LOCALES = { root: { label: 'English', lang: 'en' } }
38
+
39
+ /** Component file of each kind of tag. */
40
+ const COMPONENT_FILES: Record<string, string> = {
41
+ endpoint: 'KawaOpenApiEndpoint',
42
+ parameters: 'KawaOpenApiParameters',
43
+ request: 'KawaOpenApiBody',
44
+ schema: 'KawaOpenApiBody',
45
+ responses: 'KawaOpenApiResponses',
46
+ samples: 'KawaOpenApiSamples',
47
+ card: 'KawaOpenApiCard',
48
+ map: 'KawaOpenApiMap',
49
+ journey: 'KawaOpenApiJourney',
50
+ ref: 'KawaOpenApiRef',
51
+ }
52
+
53
+ /** What tools need from a configured plugin. */
54
+ export interface OpenApiPluginHandle {
55
+ readonly options: OpenApiPluginOptions
56
+ /** Options with absolute paths; available after `configResolved()`. */
57
+ resolved: () => ResolvedOpenApiOptions
58
+ service: OpenApiService
59
+ }
60
+
61
+ export type OpenApiPlugin = KawaPressPlugin & { readonly openapi: OpenApiPluginHandle }
62
+
63
+ export function openapiPlugin(options: OpenApiPluginOptions): OpenApiPlugin {
64
+ let site: ResolvedSiteConfig | undefined
65
+ let resolved: ResolvedOpenApiOptions | undefined
66
+ let markdown: MarkdownExit | undefined
67
+ let locales: Readonly<Record<string, LocaleConfig>> = DEFAULT_LOCALES
68
+
69
+ const getResolved = (): ResolvedOpenApiOptions => {
70
+ if (!resolved) {
71
+ throw new Error('KawaPress OpenAPI: the site config is not resolved yet.')
72
+ }
73
+ return resolved
74
+ }
75
+ const service = new OpenApiService(getResolved)
76
+ const warn = (message: string): void => console.warn(`KawaPress OpenAPI: ${message}`)
77
+
78
+ const plugin = definePlugin({
79
+ name: PLUGIN_NAME,
80
+ setup(api) {
81
+ // Page groups must be declared before the page registry exists, which is before `configResolved()`.
82
+ api.config((config) => {
83
+ locales = config.locales ?? DEFAULT_LOCALES
84
+ registerOpenApiPages(api, {
85
+ options: getResolved,
86
+ locales,
87
+ only: options.locales,
88
+ route: normalizeRoute(options.route ?? DEFAULT_ROUTE),
89
+ service,
90
+ warn,
91
+ })
92
+ })
93
+ api.configResolved((config) => {
94
+ site = config
95
+ resolved = resolveOpenApiOptions(options, config.root)
96
+ })
97
+ api.markdown((compiler) => {
98
+ markdown = compiler
99
+ installOpenApiTags(compiler, {
100
+ prefixOf: path => localePrefix(resolveLocaleIndex(path, Object.keys(site?.locales ?? {}))),
101
+ onComponent: (env, component) => addPageComponent(env, component),
102
+ })
103
+ })
104
+ api.vite((viteConfig) => {
105
+ viteConfig.plugins = [
106
+ ...(viteConfig.plugins ?? []),
107
+ createOpenApiVitePlugin({
108
+ service,
109
+ options: getResolved,
110
+ base: () => site?.base ?? '/',
111
+ markdown: () => markdown,
112
+ languageOf: prefix => locales[prefix ? prefix.slice(1) : 'root']?.lang,
113
+ component: kind => fileURLToPath(new URL(`./components/${COMPONENT_FILES[kind] ?? 'KawaOpenApiRef'}.vue`, import.meta.url)),
114
+ }),
115
+ ]
116
+ })
117
+ },
118
+ })
119
+
120
+ return Object.assign(plugin, { openapi: { options, resolved: getResolved, service } })
121
+ }
122
+
123
+ export default openapiPlugin
package/src/options.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { OpenApiPluginOptions, OpenApiSampleLanguage } from './types'
2
+ import { isAbsolute, resolve } from 'node:path'
3
+
4
+ export const DEFAULT_ROUTE = 'openapi/'
5
+ export const DEFAULT_SNAPSHOT_DIR = 'openapi-snapshots'
6
+ export const DEFAULT_SAMPLES: readonly OpenApiSampleLanguage[] = ['curl', 'javascript', 'python']
7
+
8
+ export interface ResolvedOpenApiOptions {
9
+ root: string
10
+ /** Absolute path of the OpenAPI document. */
11
+ spec: string
12
+ /** Absolute paths of the Arazzo files. */
13
+ workflows: string[]
14
+ /** `/openapi/`. */
15
+ route: string
16
+ snapshotDir: string
17
+ tryIt: false | { server?: string }
18
+ samples: readonly OpenApiSampleLanguage[]
19
+ }
20
+
21
+ export function resolveOpenApiOptions(options: OpenApiPluginOptions, root: string): ResolvedOpenApiOptions {
22
+ if (!options.spec) {
23
+ throw new Error('KawaPress OpenAPI: the option "spec" is required, for example spec: \'./openapi.yaml\'.')
24
+ }
25
+ const at = (path: string): string => (isAbsolute(path) ? path : resolve(root, path))
26
+ const workflows = options.workflows === undefined ? [] : Array.isArray(options.workflows) ? options.workflows : [options.workflows]
27
+ const samples = options.samples ?? DEFAULT_SAMPLES
28
+ const unknown = samples.filter(language => !DEFAULT_SAMPLES.includes(language))
29
+ if (unknown.length > 0) {
30
+ throw new Error(`KawaPress OpenAPI: the option "samples" lists ${unknown.join(', ')}; the languages are ${DEFAULT_SAMPLES.join(', ')}.`)
31
+ }
32
+ const server = options.tryIt === false ? undefined : options.tryIt?.server?.replace(/\/+$/, '')
33
+ return {
34
+ root,
35
+ spec: at(options.spec),
36
+ workflows: workflows.map(at),
37
+ route: normalizeRoute(options.route ?? DEFAULT_ROUTE),
38
+ snapshotDir: at(options.snapshotDir ?? DEFAULT_SNAPSHOT_DIR),
39
+ tryIt: options.tryIt === false ? false : server ? { server } : {},
40
+ samples,
41
+ }
42
+ }
43
+
44
+ /** `openapi` / `/openapi` / `/openapi/` all become `/openapi/`. */
45
+ export function normalizeRoute(route: string): string {
46
+ const segments = route.split('/').filter(Boolean)
47
+ return segments.length === 0 ? '/' : `/${segments.join('/')}/`
48
+ }
49
+
50
+ /** URL prefix of a locale key: `root` has none, `en` is `/en`. */
51
+ export function localePrefix(key: string): string {
52
+ return key === 'root' ? '' : `/${key}`
53
+ }
package/src/pages.ts ADDED
@@ -0,0 +1,120 @@
1
+ import type { GeneratorPluginAPI, LocaleConfig, PluginPagesContext } from 'kawapress'
2
+ import type { ResolvedOpenApiOptions } from './options'
3
+ import type { PageContext } from './render/pages'
4
+ import type { LoadedApi, OpenApiService } from './service'
5
+ import { join } from 'node:path'
6
+ import { localePrefix } from './options'
7
+ import { labelsForLanguage } from './render/labels'
8
+ import { renderChangesPage, renderJourneyPage, renderModelPage, renderOperationPage, renderOverviewPage, renderResourcePage } from './render/pages'
9
+ import { createOpenApiLinks, modelSlug } from './render/routes'
10
+ import { SNAPSHOT_PATTERN } from './service'
11
+ import { diffSnapshots, sortSnapshots } from './snapshot/history'
12
+ import { createSnapshot } from './snapshot/snapshot'
13
+
14
+ export interface OpenApiPagesDeps {
15
+ /** The resolved options; only read while pages are generated. */
16
+ options: () => ResolvedOpenApiOptions
17
+ locales: Readonly<Record<string, LocaleConfig>>
18
+ only: readonly string[] | undefined
19
+ /** Mount path, normalized. */
20
+ route: string
21
+ service: OpenApiService
22
+ warn: (message: string) => void
23
+ }
24
+
25
+ /** The page of the changes group; its parameter lets the group produce no page at all. */
26
+ const CHANGES_PAGE = 'changes'
27
+
28
+ /**
29
+ * Registers the pages of every locale: resource map, resources, operations,
30
+ * models, journeys and changes. Routes depend only on the locale keys, so the
31
+ * groups are declared before the site root is known.
32
+ */
33
+ export function registerOpenApiPages(api: GeneratorPluginAPI, deps: OpenApiPagesDeps): void {
34
+ const reported = new WeakSet<LoadedApi>()
35
+
36
+ for (const key of localeKeys(deps)) {
37
+ const prefix = localePrefix(key)
38
+ const labels = labelsForLanguage(deps.locales[key]?.lang)
39
+ const base = `${prefix}${deps.route}`
40
+ const register = (route: string, generate: (context: PluginPagesContext) => Promise<unknown>): void => {
41
+ api.pages(route, generate as never)
42
+ }
43
+
44
+ const prepare = async (context: PluginPagesContext): Promise<{ loaded: LoadedApi, page: PageContext }> => {
45
+ const options = deps.options()
46
+ await Promise.all([options.spec, ...options.workflows].map(file => context.read(file)))
47
+ await context.glob(join(options.snapshotDir, SNAPSHOT_PATTERN))
48
+ const loaded = await deps.service.get()
49
+ if (!reported.has(loaded)) {
50
+ reported.add(loaded)
51
+ report(loaded, deps.warn)
52
+ }
53
+ return { loaded, page: { labels, links: createOpenApiLinks(loaded.model, prefix, deps.route) } }
54
+ }
55
+
56
+ register(base, async (context) => {
57
+ const { loaded, page } = await prepare(context)
58
+ return renderOverviewPage(loaded, page)
59
+ })
60
+ register(`${base}[resource]/`, async (context) => {
61
+ const { loaded, page } = await prepare(context)
62
+ return loaded.model.resources.map(resource => ({ resource: resource.slug, ...renderResourcePage(resource, loaded.model, page) }))
63
+ })
64
+ register(`${base}[resource]/[operation]`, async (context) => {
65
+ const { loaded, page } = await prepare(context)
66
+ const slugs = new Map(loaded.model.resources.map(resource => [resource.name, resource.slug]))
67
+ return loaded.model.operations.map(operation => ({
68
+ resource: slugs.get(operation.resource)!,
69
+ operation: operation.slug,
70
+ ...renderOperationPage(operation, page),
71
+ }))
72
+ })
73
+ register(`${base}models/[model]`, async (context) => {
74
+ const { loaded, page } = await prepare(context)
75
+ return loaded.model.schemas.map(entry => ({ model: modelSlug(entry.name), ...renderModelPage(entry, loaded.model, page) }))
76
+ })
77
+ register(`${base}journeys/[journey]`, async (context) => {
78
+ const { loaded, page } = await prepare(context)
79
+ return loaded.model.workflows.map(workflow => ({ journey: workflow.slug, ...renderJourneyPage(workflow, deps.options().root, page) }))
80
+ })
81
+ register(`${base}[changes]`, async (context) => {
82
+ const { loaded, page } = await prepare(context)
83
+ return loaded.snapshots.length > 1 ? [{ changes: CHANGES_PAGE, ...renderChangesPage(loaded, page) }] : []
84
+ })
85
+ }
86
+ }
87
+
88
+ function localeKeys({ locales, only }: OpenApiPagesDeps): readonly string[] {
89
+ const all = Object.keys(locales)
90
+ const keys = only ?? all
91
+ const unknown = keys.filter(key => !all.includes(key))
92
+ if (unknown.length > 0) {
93
+ throw new Error(`KawaPress OpenAPI: the option "locales" lists ${unknown.join(', ')}, but the site only has ${all.join(', ')}.`)
94
+ }
95
+ return keys
96
+ }
97
+
98
+ /** Build-time notes: bodies without examples, and how the spec differs from the latest snapshot. */
99
+ function report(loaded: LoadedApi, warn: (message: string) => void): void {
100
+ const missing = loaded.model.operations.filter(operation => (
101
+ operation.requestBody?.exampleGenerated
102
+ || operation.responses.some(response => response.status.startsWith('2') && response.body?.exampleGenerated)
103
+ ))
104
+ if (missing.length > 0) {
105
+ warn(`${missing.length} of ${loaded.model.operations.length} operations have a request or success response without an example; the pages show examples generated from the schema (${missing.slice(0, 3).map(operation => operation.id).join(', ')}${missing.length > 3 ? ', …' : ''}).`)
106
+ }
107
+ const latest = sortSnapshots(loaded.snapshots).at(-1)
108
+ if (!latest) {
109
+ return
110
+ }
111
+ const current = createSnapshot(loaded.model)
112
+ const changes = diffSnapshots(latest, current)
113
+ if (changes.length > 0 && latest.version !== current.version) {
114
+ const breaking = changes.filter(change => change.kind === 'breaking').length
115
+ warn(`${changes.length} changes since the snapshot of ${latest.version}${breaking ? `, ${breaking} breaking` : ''}. Run \`kawapress-openapi snapshot\` when ${current.version || 'the new version'} is released.`)
116
+ }
117
+ else if (changes.length > 0) {
118
+ warn(`the spec differs from its own snapshot ${latest.version} in ${changes.length} places; bump info.version or run \`kawapress-openapi snapshot --force\`.`)
119
+ }
120
+ }
@@ -0,0 +1,168 @@
1
+ import type { OpenApiModel, OpenApiWorkflow, WorkflowStep, WorkflowValue } from '../types'
2
+ import type { Json } from './document'
3
+ import { asString, isObject, readPointer } from './document'
4
+ import { HTTP_METHODS, slugify } from './model'
5
+
6
+ /** Key of the placeholder objects that stand for runtime expressions inside a step payload. */
7
+ export const EXPRESSION_KEY = '$kawa'
8
+
9
+ const INPUT_RE = /^\{?\$inputs\.([\w-]+)\}?$/
10
+ const OUTPUT_RE = /^\{?\$steps\.([\w-]+)\.outputs\.([\w-]+)\}?$/
11
+ const BODY_POINTER_RE = /^\$response\.body#(\/.*)?$/
12
+ const STATUS_RE = /^\$statusCode\s*==\s*(\d{3})$/
13
+
14
+ /**
15
+ * Reads the workflows of an Arazzo 1.x document and checks that every step
16
+ * calls an operation of the model.
17
+ */
18
+ export function readArazzo(document: Json, file: string, model: OpenApiModel): OpenApiWorkflow[] {
19
+ if (!/^1\./.test(asString(document.arazzo))) {
20
+ throw new Error(`${file}: only Arazzo 1.x documents are supported, found ${document.arazzo ? `arazzo: ${String(document.arazzo)}` : 'no "arazzo" field'}.`)
21
+ }
22
+ const operationIds = new Set(model.operations.map(operation => operation.id))
23
+ const byPath = new Map(model.operations.filter(operation => !operation.webhook).map(operation => [`${operation.path} ${operation.method}`, operation.id]))
24
+
25
+ return (Array.isArray(document.workflows) ? document.workflows : []).filter(isObject).map((workflow, index): OpenApiWorkflow => {
26
+ const id = asString(workflow.workflowId) || `workflow-${index + 1}`
27
+ const where = `${file}: workflow "${id}"`
28
+ const stepIds = new Set<string>()
29
+ const steps = (Array.isArray(workflow.steps) ? workflow.steps : []).filter(isObject).map((step, stepIndex): WorkflowStep => {
30
+ const stepId = asString(step.stepId) || `step-${stepIndex + 1}`
31
+ const operation = operationOf(step, operationIds, byPath, `${where}, step "${stepId}"`)
32
+ const result: WorkflowStep = {
33
+ id: stepId,
34
+ description: asString(step.description),
35
+ operation,
36
+ parameters: (Array.isArray(step.parameters) ? step.parameters : []).filter(isObject).map(parameter => ({
37
+ name: asString(parameter.name),
38
+ ...(parameter.in ? { in: asString(parameter.in) } : {}),
39
+ value: valueOf(parameter.value),
40
+ })),
41
+ outputs: Object.entries(isObject(step.outputs) ? step.outputs : {}).map(([name, expression]) => {
42
+ const text = String(expression)
43
+ const pointer = BODY_POINTER_RE.exec(text)
44
+ return { name, expression: text, ...(pointer ? { pointer: pointer[1] ?? '' } : {}) }
45
+ }),
46
+ }
47
+ if (isObject(step.requestBody) && step.requestBody.payload !== undefined) {
48
+ result.payload = mapPayload(step.requestBody.payload)
49
+ }
50
+ const status = (Array.isArray(step.successCriteria) ? step.successCriteria : [])
51
+ .filter(isObject)
52
+ .map(criterion => STATUS_RE.exec(asString(criterion.condition).trim()))
53
+ .find(Boolean)
54
+ if (status) {
55
+ result.status = status[1]
56
+ }
57
+ for (const reference of referencesOf(result)) {
58
+ if (!stepIds.has(reference.step)) {
59
+ throw new Error(`${where}, step "${stepId}" uses $steps.${reference.step}.outputs.${reference.output}, but no earlier step is called "${reference.step}".`)
60
+ }
61
+ }
62
+ stepIds.add(stepId)
63
+ return result
64
+ })
65
+
66
+ const inputs = isObject(workflow.inputs) && isObject(workflow.inputs.properties) ? workflow.inputs.properties : {}
67
+ return {
68
+ id,
69
+ slug: slugify(id) || `workflow-${index + 1}`,
70
+ summary: asString(workflow.summary),
71
+ description: asString(workflow.description),
72
+ file,
73
+ inputs: Object.entries(inputs).map(([name, schema]) => ({
74
+ name,
75
+ type: isObject(schema) ? asString(schema.type) || 'any' : 'any',
76
+ description: isObject(schema) ? asString(schema.description) : '',
77
+ })),
78
+ steps,
79
+ }
80
+ })
81
+ }
82
+
83
+ /** Every `$steps.<id>.outputs.<name>` a step reads. */
84
+ export function referencesOf(step: WorkflowStep): { step: string, output: string }[] {
85
+ const found: { step: string, output: string }[] = []
86
+ const visit = (value: unknown): void => {
87
+ if (isExpression(value)) {
88
+ const expression = value[EXPRESSION_KEY]
89
+ if (expression.kind === 'output') {
90
+ found.push({ step: expression.step, output: expression.output })
91
+ }
92
+ }
93
+ else if (Array.isArray(value)) {
94
+ value.forEach(visit)
95
+ }
96
+ else if (isObject(value)) {
97
+ Object.values(value).forEach(visit)
98
+ }
99
+ }
100
+ for (const parameter of step.parameters) {
101
+ visit({ [EXPRESSION_KEY]: parameter.value })
102
+ }
103
+ visit(step.payload)
104
+ return found
105
+ }
106
+
107
+ export function isExpression(value: unknown): value is { [EXPRESSION_KEY]: WorkflowValue } {
108
+ return isObject(value) && Object.keys(value).length === 1 && isObject(value[EXPRESSION_KEY])
109
+ }
110
+
111
+ /** The value a step output points at in an example response body. */
112
+ export function outputValue(step: WorkflowStep, output: string, body: unknown): unknown {
113
+ const found = step.outputs.find(item => item.name === output)
114
+ return found?.pointer === undefined ? undefined : readPointer(body, found.pointer)
115
+ }
116
+
117
+ function valueOf(value: unknown): WorkflowValue {
118
+ if (typeof value === 'string') {
119
+ const input = INPUT_RE.exec(value.trim())
120
+ if (input) {
121
+ return { kind: 'input', name: input[1] }
122
+ }
123
+ const output = OUTPUT_RE.exec(value.trim())
124
+ if (output) {
125
+ return { kind: 'output', step: output[1], output: output[2] }
126
+ }
127
+ }
128
+ return { kind: 'literal', value }
129
+ }
130
+
131
+ function mapPayload(value: unknown): unknown {
132
+ if (typeof value === 'string') {
133
+ const parsed = valueOf(value)
134
+ return parsed.kind === 'literal' ? value : { [EXPRESSION_KEY]: parsed }
135
+ }
136
+ if (Array.isArray(value)) {
137
+ return value.map(mapPayload)
138
+ }
139
+ if (isObject(value)) {
140
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapPayload(item)]))
141
+ }
142
+ return value
143
+ }
144
+
145
+ function operationOf(step: Json, ids: Set<string>, byPath: Map<string, string>, where: string): string {
146
+ if (typeof step.workflowId === 'string') {
147
+ throw new TypeError(`${where} calls another workflow; only steps that call an operation are supported.`)
148
+ }
149
+ if (typeof step.operationId === 'string') {
150
+ const id = step.operationId.split('.').pop()!
151
+ if (!ids.has(id)) {
152
+ throw new Error(`${where} calls the operation "${step.operationId}", which the OpenAPI document does not have.`)
153
+ }
154
+ return id
155
+ }
156
+ if (typeof step.operationPath === 'string') {
157
+ const pointer = step.operationPath.split('#')[1] ?? ''
158
+ const segments = pointer.split('/').filter(Boolean).map(segment => decodeURIComponent(segment).replaceAll('~1', '/').replaceAll('~0', '~'))
159
+ const method = segments.at(-1) ?? ''
160
+ const path = segments.at(-2) ?? ''
161
+ const id = segments[0] === 'paths' && HTTP_METHODS.includes(method as never) ? byPath.get(`${path} ${method}`) : undefined
162
+ if (!id) {
163
+ throw new Error(`${where} has the operationPath "${step.operationPath}", which does not point at an operation of the OpenAPI document.`)
164
+ }
165
+ return id
166
+ }
167
+ throw new Error(`${where} has neither an operationId nor an operationPath.`)
168
+ }
@@ -0,0 +1,91 @@
1
+ import { parse as parseYaml } from 'yaml'
2
+
3
+ export type Json = Record<string, unknown>
4
+
5
+ /** Parses a JSON or YAML file by its extension. */
6
+ export function parseDocument(text: string, file: string): Json {
7
+ let value: unknown
8
+ try {
9
+ value = /\.json$/i.test(file) ? JSON.parse(text) : parseYaml(text)
10
+ }
11
+ catch (error) {
12
+ throw new Error(`${file} is not valid ${/\.json$/i.test(file) ? 'JSON' : 'YAML'}: ${(error as Error).message}`)
13
+ }
14
+ if (!isObject(value)) {
15
+ throw new Error(`${file} does not contain an object.`)
16
+ }
17
+ return value
18
+ }
19
+
20
+ export function isObject(value: unknown): value is Json {
21
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
22
+ }
23
+
24
+ export function asString(value: unknown): string {
25
+ return typeof value === 'string' ? value : ''
26
+ }
27
+
28
+ /** Follows a JSON pointer (`/paths/~1orders/post`) inside `root`. */
29
+ export function readPointer(root: unknown, pointer: string): unknown {
30
+ if (pointer === '' || pointer === '/') {
31
+ return pointer === '' ? root : (root as Json)?.['']
32
+ }
33
+ let current: unknown = root
34
+ for (const raw of pointer.replace(/^\//, '').split('/')) {
35
+ const key = decodeURIComponent(raw).replaceAll('~1', '/').replaceAll('~0', '~')
36
+ if (Array.isArray(current)) {
37
+ current = current[Number(key)]
38
+ }
39
+ else if (isObject(current)) {
40
+ current = current[key]
41
+ }
42
+ else {
43
+ return undefined
44
+ }
45
+ }
46
+ return current
47
+ }
48
+
49
+ /**
50
+ * Resolves the in-document `$ref`s of one OpenAPI document. A reference to
51
+ * another file is an error: such documents need bundling first.
52
+ */
53
+ export class RefResolver {
54
+ constructor(readonly root: Json, readonly file: string) {}
55
+
56
+ /** Follows `$ref` chains until a plain object; `where` names the place for errors. */
57
+ deref<T = Json>(value: unknown, where: string): T {
58
+ let current = value
59
+ const seen = new Set<string>()
60
+ while (isObject(current) && typeof current.$ref === 'string') {
61
+ const ref = current.$ref
62
+ if (seen.has(ref)) {
63
+ throw new Error(`${this.file}: ${where} has a circular $ref "${ref}".`)
64
+ }
65
+ seen.add(ref)
66
+ current = this.target(ref, where)
67
+ }
68
+ return current as T
69
+ }
70
+
71
+ /** The value a `$ref` string points at. */
72
+ target(ref: string, where: string): unknown {
73
+ if (!ref.startsWith('#')) {
74
+ throw new Error(
75
+ `${this.file}: ${where} refers to "${ref}" in another file. `
76
+ + 'Only references inside the document are supported; bundle the spec first (for example with `redocly bundle`).',
77
+ )
78
+ }
79
+ const value = readPointer(this.root, ref.slice(1))
80
+ if (value === undefined) {
81
+ throw new Error(`${this.file}: ${where} refers to "${ref}", which does not exist.`)
82
+ }
83
+ return value
84
+ }
85
+ }
86
+
87
+ /** `#/components/schemas/Order` → `Order`. */
88
+ export function schemaRefName(ref: string): string | undefined {
89
+ const match = /^#\/components\/schemas\/([^/]+)$/.exec(ref)
90
+ return match ? decodeURIComponent(match[1]).replaceAll('~1', '/').replaceAll('~0', '~') : undefined
91
+ }