@kubb/ast 5.0.0-beta.4 → 5.0.0-beta.40
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/README.md +17 -8
- package/dist/index.cjs +866 -395
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +33 -3310
- package/dist/index.js +859 -391
- package/dist/index.js.map +1 -1
- package/dist/types-CEIHPTfs.d.ts +3596 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -0
- package/package.json +8 -4
- package/src/constants.ts +2 -52
- package/src/dedupe.ts +200 -0
- package/src/dialect.ts +58 -0
- package/src/dispatch.ts +53 -0
- package/src/factory.ts +133 -17
- package/src/guards.ts +18 -48
- package/src/index.ts +9 -5
- package/src/infer.ts +16 -14
- package/src/nodes/base.ts +2 -0
- package/src/nodes/code.ts +22 -22
- package/src/nodes/content.ts +37 -0
- package/src/nodes/file.ts +16 -14
- package/src/nodes/function.ts +11 -11
- package/src/nodes/index.ts +7 -3
- package/src/nodes/operation.ts +98 -62
- package/src/nodes/response.ts +21 -14
- package/src/nodes/root.ts +72 -10
- package/src/nodes/schema.ts +12 -9
- package/src/printer.ts +42 -36
- package/src/refs.ts +0 -54
- package/src/resolvers.ts +4 -4
- package/src/signature.ts +232 -0
- package/src/transformers.ts +20 -15
- package/src/types.ts +9 -2
- package/src/utils.ts +118 -77
- package/src/visitor.ts +237 -279
- /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
package/dist/types.cjs
ADDED
|
File without changes
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { $t as ScalarSchemaType, At as FunctionParameterNode, Bt as DateSchemaNode, C as PrinterFactoryOptions, Ct as HttpStatusCode, D as DistributiveOmit, Dt as ParameterNode, Et as ParameterLocation, Ft as FileNode, Gt as IntersectionSchemaNode, Ht as EnumSchemaNode, It as ImportNode, Jt as NumberSchemaNode, Kt as Ipv4SchemaNode, Lt as SourceNode, Mt as ParameterGroupNode, Nt as ParamsTypeNode, O as UserFileNode, Ot as FunctionNodeType, Pt as ExportNode, Qt as ScalarSchemaNode, Rt as ArraySchemaNode, S as Printer, Sn as VisitorDepth, St as ResponseNode, Tt as StatusCode, Ut as EnumValueNode, Vt as DatetimeSchemaNode, Wt as FormatStringSchemaNode, Xt as PrimitiveSchemaType, Yt as ObjectSchemaNode, Zt as RefSchemaNode, _ as VisitorContext, _n as TypeDeclarationNode, _t as HttpMethod, an as TimeSchemaNode, bn as NodeKind, bt as OperationNodeBase, cn as PropertyNode, ct as DedupePlan, d as AsyncVisitor, dn as CodeNode, dt as Node, en as SchemaNode, et as InferSchemaNode, f as CollectOptions, fn as ConstNode, ft as InputMeta, g as Visitor, gn as TextNode, gt as GenericOperationNode, h as TransformOptions, hn as JsxNode, ht as OutputNode, in as StringSchemaNode, it as SchemaDialect, jt as FunctionParametersNode, kt as FunctionParamNode, ln as ArrowFunctionNode, m as ParentOf, mn as JSDocNode, mt as InputStreamNode, nn as SchemaType, nt as DispatchRule, on as UnionSchemaNode, ot as BuildDedupePlanOptions, p as CollectVisitor, pn as FunctionNode, pt as InputNode, qt as Ipv6SchemaNode, rn as SpecialSchemaType, sn as UrlSchemaNode, st as DedupeCanonical, t as OperationParamsResolver, tn as SchemaNodeByType, tt as ParserOptions, un as BreakNode, v as WalkOptions, vn as TypeNode, vt as HttpOperationNode, w as PrinterPartial, wt as MediaType, xn as ScalarPrimitive, xt as OperationProtocol, yn as BaseNode, yt as OperationNode, zt as ComplexSchemaType } from "./types-CEIHPTfs.js";
|
|
2
|
+
export type { ArraySchemaNode, ArrowFunctionNode, AsyncVisitor, BaseNode, BreakNode, BuildDedupePlanOptions, CodeNode, CollectOptions, CollectVisitor, ComplexSchemaType, ConstNode, DateSchemaNode, DatetimeSchemaNode, DedupeCanonical, DedupePlan, DispatchRule, DistributiveOmit, EnumSchemaNode, EnumValueNode, ExportNode, FileNode, FormatStringSchemaNode, FunctionNode, FunctionNodeType, FunctionParamNode, FunctionParameterNode, FunctionParametersNode, GenericOperationNode, HttpMethod, HttpOperationNode, HttpStatusCode, ImportNode, InferSchemaNode, InputMeta, InputNode, InputStreamNode, IntersectionSchemaNode, Ipv4SchemaNode, Ipv6SchemaNode, JSDocNode, JsxNode, MediaType, Node, NodeKind, NumberSchemaNode, ObjectSchemaNode, OperationNode, OperationNodeBase, OperationParamsResolver, OperationProtocol, OutputNode, ParameterGroupNode, ParameterLocation, ParameterNode, ParamsTypeNode, ParentOf, ParserOptions, PrimitiveSchemaType, Printer, PrinterFactoryOptions, PrinterPartial, PropertyNode, RefSchemaNode, ResponseNode, ScalarPrimitive, ScalarSchemaNode, ScalarSchemaType, SchemaDialect, SchemaNode, SchemaNodeByType, SchemaType, SourceNode, SpecialSchemaType, StatusCode, StringSchemaNode, TextNode, TimeSchemaNode, TransformOptions, TypeDeclarationNode, TypeNode, UnionSchemaNode, UrlSchemaNode, UserFileNode, Visitor, VisitorContext, VisitorDepth, WalkOptions };
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/ast",
|
|
3
|
-
"version": "5.0.0-beta.
|
|
4
|
-
"description": "Spec-agnostic AST layer for Kubb. Defines
|
|
3
|
+
"version": "5.0.0-beta.40",
|
|
4
|
+
"description": "Spec-agnostic AST layer for Kubb. Defines the node tree, visitor pattern, factory functions, and type guards used across all code generation plugins.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ast",
|
|
7
7
|
"codegen",
|
|
8
8
|
"kubb",
|
|
9
|
-
"openapi",
|
|
10
9
|
"typescript"
|
|
11
10
|
],
|
|
12
11
|
"license": "MIT",
|
|
@@ -33,6 +32,10 @@
|
|
|
33
32
|
"import": "./dist/index.js",
|
|
34
33
|
"require": "./dist/index.cjs"
|
|
35
34
|
},
|
|
35
|
+
"./types": {
|
|
36
|
+
"import": "./dist/types.js",
|
|
37
|
+
"require": "./dist/types.cjs"
|
|
38
|
+
},
|
|
36
39
|
"./package.json": "./package.json"
|
|
37
40
|
},
|
|
38
41
|
"publishConfig": {
|
|
@@ -40,7 +43,7 @@
|
|
|
40
43
|
"registry": "https://registry.npmjs.org/"
|
|
41
44
|
},
|
|
42
45
|
"devDependencies": {
|
|
43
|
-
"@types/node": "^
|
|
46
|
+
"@types/node": "^22.19.19",
|
|
44
47
|
"@internals/utils": "0.0.0"
|
|
45
48
|
},
|
|
46
49
|
"engines": {
|
|
@@ -53,6 +56,7 @@
|
|
|
53
56
|
"lint:fix": "oxlint --fix .",
|
|
54
57
|
"release": "pnpm publish --no-git-check",
|
|
55
58
|
"release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check",
|
|
59
|
+
"release:stage": "pnpm stage publish --no-git-check",
|
|
56
60
|
"start": "tsdown --watch",
|
|
57
61
|
"test": "vitest --passWithNoTests",
|
|
58
62
|
"typecheck": "tsc -p ./tsconfig.json --noEmit --emitDeclarationOnly false"
|
package/src/constants.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import type { NodeKind } from './nodes/base.ts'
|
|
2
|
-
import type { MediaType } from './nodes/http.ts'
|
|
3
1
|
import type { HttpMethod } from './nodes/operation.ts'
|
|
4
2
|
import type { SchemaType } from './nodes/schema.ts'
|
|
5
3
|
|
|
6
4
|
/**
|
|
7
5
|
* Traversal depth for AST visitor utilities.
|
|
8
6
|
*
|
|
9
|
-
* - `'shallow'`
|
|
10
|
-
* - `'deep'`
|
|
7
|
+
* - `'shallow'` visits only the immediate node, skipping children.
|
|
8
|
+
* - `'deep'` recursively visits all descendant nodes.
|
|
11
9
|
*/
|
|
12
10
|
export type VisitorDepth = 'shallow' | 'deep'
|
|
13
11
|
|
|
@@ -16,26 +14,6 @@ export const visitorDepths = {
|
|
|
16
14
|
deep: 'deep',
|
|
17
15
|
} as const satisfies Record<VisitorDepth, VisitorDepth>
|
|
18
16
|
|
|
19
|
-
export const nodeKinds = {
|
|
20
|
-
input: 'Input',
|
|
21
|
-
output: 'Output',
|
|
22
|
-
operation: 'Operation',
|
|
23
|
-
schema: 'Schema',
|
|
24
|
-
property: 'Property',
|
|
25
|
-
parameter: 'Parameter',
|
|
26
|
-
response: 'Response',
|
|
27
|
-
functionParameter: 'FunctionParameter',
|
|
28
|
-
parameterGroup: 'ParameterGroup',
|
|
29
|
-
functionParameters: 'FunctionParameters',
|
|
30
|
-
type: 'Type',
|
|
31
|
-
file: 'File',
|
|
32
|
-
import: 'Import',
|
|
33
|
-
export: 'Export',
|
|
34
|
-
source: 'Source',
|
|
35
|
-
text: 'Text',
|
|
36
|
-
break: 'Break',
|
|
37
|
-
} as const satisfies Record<string, NodeKind>
|
|
38
|
-
|
|
39
17
|
/**
|
|
40
18
|
* Schema type discriminators used by all AST schema nodes.
|
|
41
19
|
*
|
|
@@ -198,31 +176,3 @@ export const httpMethods = {
|
|
|
198
176
|
* ```
|
|
199
177
|
*/
|
|
200
178
|
export const WALK_CONCURRENCY = 30
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Common MIME types used in request/response content negotiation.
|
|
204
|
-
*
|
|
205
|
-
* Covers JSON, XML, form data, PDFs, images, audio, and video formats.
|
|
206
|
-
* Use these as keys when serializing request/response bodies.
|
|
207
|
-
*/
|
|
208
|
-
export const mediaTypes = {
|
|
209
|
-
applicationJson: 'application/json',
|
|
210
|
-
applicationXml: 'application/xml',
|
|
211
|
-
applicationFormUrlEncoded: 'application/x-www-form-urlencoded',
|
|
212
|
-
applicationOctetStream: 'application/octet-stream',
|
|
213
|
-
applicationPdf: 'application/pdf',
|
|
214
|
-
applicationZip: 'application/zip',
|
|
215
|
-
applicationGraphql: 'application/graphql',
|
|
216
|
-
multipartFormData: 'multipart/form-data',
|
|
217
|
-
textPlain: 'text/plain',
|
|
218
|
-
textHtml: 'text/html',
|
|
219
|
-
textCsv: 'text/csv',
|
|
220
|
-
textXml: 'text/xml',
|
|
221
|
-
imagePng: 'image/png',
|
|
222
|
-
imageJpeg: 'image/jpeg',
|
|
223
|
-
imageGif: 'image/gif',
|
|
224
|
-
imageWebp: 'image/webp',
|
|
225
|
-
imageSvgXml: 'image/svg+xml',
|
|
226
|
-
audioMpeg: 'audio/mpeg',
|
|
227
|
-
videoMp4: 'video/mp4',
|
|
228
|
-
} as const satisfies Record<string, MediaType>
|
package/src/dedupe.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { createSchema } from './factory.ts'
|
|
2
|
+
import type { Node, OperationNode, SchemaNode } from './nodes/index.ts'
|
|
3
|
+
import { signatureOf } from './signature.ts'
|
|
4
|
+
import { collectLazy, transform } from './visitor.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A canonical destination for a deduplicated shape: the shared schema name and
|
|
8
|
+
* the synthetic `$ref` path that points at it.
|
|
9
|
+
*/
|
|
10
|
+
export type DedupeCanonical = {
|
|
11
|
+
/**
|
|
12
|
+
* Canonical schema name every duplicate occurrence refers to.
|
|
13
|
+
*/
|
|
14
|
+
name: string
|
|
15
|
+
/**
|
|
16
|
+
* `$ref` path stored on the generated `ref` nodes (for example `#/components/schemas/Status`).
|
|
17
|
+
*/
|
|
18
|
+
ref: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The result of {@link buildDedupePlan}: a lookup from structural signature to its
|
|
23
|
+
* canonical target, plus the freshly hoisted definitions that must be added to
|
|
24
|
+
* the schema list.
|
|
25
|
+
*/
|
|
26
|
+
export type DedupePlan = {
|
|
27
|
+
/**
|
|
28
|
+
* Maps a structural signature to the canonical schema that represents it.
|
|
29
|
+
*/
|
|
30
|
+
canonicalBySignature: Map<string, DedupeCanonical>
|
|
31
|
+
/**
|
|
32
|
+
* New top-level schema definitions created for inline shapes that had no existing
|
|
33
|
+
* named component. Nested duplicates inside each definition are already collapsed.
|
|
34
|
+
*/
|
|
35
|
+
hoisted: Array<SchemaNode>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Options that inject the naming and candidate policy into {@link buildDedupePlan}.
|
|
40
|
+
* The mechanics (grouping, counting, rewriting) live here. The policy lives in the caller.
|
|
41
|
+
*/
|
|
42
|
+
export type BuildDedupePlanOptions = {
|
|
43
|
+
/**
|
|
44
|
+
* Returns `true` when a node should be deduplicated. This is the only gate, so it must
|
|
45
|
+
* reject both ineligible kinds (return `false` for anything other than, say, enums and
|
|
46
|
+
* objects) and unsafe shapes (e.g. nodes that reference a circular schema).
|
|
47
|
+
*/
|
|
48
|
+
isCandidate: (node: SchemaNode) => boolean
|
|
49
|
+
/**
|
|
50
|
+
* Produces the canonical name for an inline shape with no existing named component.
|
|
51
|
+
* Return `null` to leave the shape inline (for example when no contextual name exists).
|
|
52
|
+
*/
|
|
53
|
+
nameFor: (node: SchemaNode, signature: string) => string | null
|
|
54
|
+
/**
|
|
55
|
+
* Builds the `$ref` path for a canonical name.
|
|
56
|
+
*/
|
|
57
|
+
refFor: (name: string) => string
|
|
58
|
+
/**
|
|
59
|
+
* Minimum number of occurrences before a shape is deduplicated.
|
|
60
|
+
*
|
|
61
|
+
* @default 2
|
|
62
|
+
*/
|
|
63
|
+
minOccurrences?: number
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Builds the shared `ref` replacement for a duplicate occurrence, carrying the
|
|
68
|
+
* usage-slot and documentation fields that are not part of the canonical type.
|
|
69
|
+
*/
|
|
70
|
+
function createRefNode(node: SchemaNode, canonical: DedupeCanonical): SchemaNode {
|
|
71
|
+
return createSchema({
|
|
72
|
+
type: 'ref',
|
|
73
|
+
name: canonical.name,
|
|
74
|
+
ref: canonical.ref,
|
|
75
|
+
optional: node.optional,
|
|
76
|
+
nullish: node.nullish,
|
|
77
|
+
readOnly: node.readOnly,
|
|
78
|
+
writeOnly: node.writeOnly,
|
|
79
|
+
deprecated: node.deprecated,
|
|
80
|
+
description: node.description,
|
|
81
|
+
default: node.default,
|
|
82
|
+
example: node.example,
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Rewrites a node, replacing every candidate sub-schema whose signature has a canonical
|
|
88
|
+
* target with a `ref` to that target. Replacing a node with a `ref` prunes its subtree,
|
|
89
|
+
* so nested duplicates inside a replaced shape are not visited again.
|
|
90
|
+
*
|
|
91
|
+
* Pass `skipRootMatch` when rewriting a canonical definition so its own root is not
|
|
92
|
+
* turned into a reference to itself. Nested duplicates are still collapsed.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```ts
|
|
96
|
+
* const next = applyDedupe(operationNode, plan.canonicalBySignature)
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export function applyDedupe(node: SchemaNode, canonicalBySignature: ReadonlyMap<string, DedupeCanonical>, skipRootMatch?: boolean): SchemaNode
|
|
100
|
+
export function applyDedupe(node: OperationNode, canonicalBySignature: ReadonlyMap<string, DedupeCanonical>, skipRootMatch?: boolean): OperationNode
|
|
101
|
+
export function applyDedupe(node: Node, canonicalBySignature: ReadonlyMap<string, DedupeCanonical>, skipRootMatch = false): Node {
|
|
102
|
+
if (canonicalBySignature.size === 0) return node
|
|
103
|
+
|
|
104
|
+
const root = node
|
|
105
|
+
|
|
106
|
+
return transform(node, {
|
|
107
|
+
schema(schemaNode) {
|
|
108
|
+
const signature = signatureOf(schemaNode)
|
|
109
|
+
if (skipRootMatch && schemaNode === root) return undefined
|
|
110
|
+
|
|
111
|
+
const canonical = canonicalBySignature.get(signature)
|
|
112
|
+
if (!canonical) return undefined
|
|
113
|
+
|
|
114
|
+
return createRefNode(schemaNode, canonical)
|
|
115
|
+
},
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Strips usage-slot flags from a hoisted definition and applies its canonical name.
|
|
121
|
+
* A standalone definition is never optional, so `optional`/`nullish` are cleared.
|
|
122
|
+
*/
|
|
123
|
+
function cleanDefinition(node: SchemaNode, name: string): SchemaNode {
|
|
124
|
+
return { ...node, name, optional: undefined, nullish: undefined }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
|
|
129
|
+
*
|
|
130
|
+
* A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
|
|
131
|
+
* is a named top-level schema, that name becomes the canonical (so other top-level duplicates
|
|
132
|
+
* and inline copies turn into references to it). Otherwise a new definition is hoisted using
|
|
133
|
+
* `nameFor`. The plan is then applied per node with {@link applyDedupe}.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
|
|
138
|
+
* isCandidate: (node) => node.type === 'enum' || node.type === 'object',
|
|
139
|
+
* nameFor: (node) => node.name ?? null,
|
|
140
|
+
* refFor: (name) => `#/components/schemas/${name}`,
|
|
141
|
+
* })
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
export function buildDedupePlan(roots: ReadonlyArray<Node>, options: BuildDedupePlanOptions): DedupePlan {
|
|
145
|
+
const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options
|
|
146
|
+
|
|
147
|
+
const topLevelNodes = new Set<SchemaNode>()
|
|
148
|
+
|
|
149
|
+
type Group = {
|
|
150
|
+
count: number
|
|
151
|
+
representative: SchemaNode
|
|
152
|
+
topLevelName?: string
|
|
153
|
+
}
|
|
154
|
+
const groups = new Map<string, Group>()
|
|
155
|
+
|
|
156
|
+
function record(schemaNode: SchemaNode): void {
|
|
157
|
+
const signature = signatureOf(schemaNode)
|
|
158
|
+
if (!isCandidate(schemaNode)) return
|
|
159
|
+
|
|
160
|
+
const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name
|
|
161
|
+
const group = groups.get(signature)
|
|
162
|
+
if (group) {
|
|
163
|
+
group.count++
|
|
164
|
+
if (isTopLevel && !group.topLevelName) group.topLevelName = schemaNode.name!
|
|
165
|
+
} else {
|
|
166
|
+
groups.set(signature, { count: 1, representative: schemaNode, topLevelName: isTopLevel ? schemaNode.name! : undefined })
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
for (const root of roots) {
|
|
171
|
+
if (root.kind === 'Schema') topLevelNodes.add(root)
|
|
172
|
+
for (const schemaNode of collectLazy<SchemaNode>(root, { schema: (node) => node })) {
|
|
173
|
+
record(schemaNode)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const canonicalBySignature = new Map<string, DedupeCanonical>()
|
|
178
|
+
const pendingHoists: Array<{ name: string; representative: SchemaNode }> = []
|
|
179
|
+
|
|
180
|
+
for (const [signature, group] of groups) {
|
|
181
|
+
if (group.count < minOccurrences) continue
|
|
182
|
+
|
|
183
|
+
if (group.topLevelName) {
|
|
184
|
+
canonicalBySignature.set(signature, { name: group.topLevelName, ref: refFor(group.topLevelName) })
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const name = nameFor(group.representative, signature)
|
|
189
|
+
if (!name) continue
|
|
190
|
+
|
|
191
|
+
canonicalBySignature.set(signature, { name, ref: refFor(name) })
|
|
192
|
+
pendingHoists.push({ name, representative: group.representative })
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Build hoisted definitions only after every canonical name is known, so nested
|
|
196
|
+
// duplicates inside a definition also resolve to refs.
|
|
197
|
+
const hoisted = pendingHoists.map(({ name, representative }) => cleanDefinition(applyDedupe(representative, canonicalBySignature, true), name))
|
|
198
|
+
|
|
199
|
+
return { canonicalBySignature, hoisted }
|
|
200
|
+
}
|
package/src/dialect.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The spec-specific decisions a schema parser makes when converting a source document's schemas
|
|
3
|
+
* into Kubb AST nodes. Everything else in an adapter's schema pipeline is generic JSON Schema,
|
|
4
|
+
* shared across specs, so the dialect is the one seam where specs differ, like a database driver
|
|
5
|
+
* targeting Postgres vs MySQL. Pair it with {@link dispatch}: the rule table picks which converter
|
|
6
|
+
* runs, the dialect answers the spec-specific questions inside it.
|
|
7
|
+
*
|
|
8
|
+
* The guards (`isReference`, `isDiscriminator`) are type predicates, so converters narrow the
|
|
9
|
+
* schema after a check and the type parameters carry the narrowed types through.
|
|
10
|
+
*
|
|
11
|
+
* This is the seam for the JSON Schema family: OpenAPI, AsyncAPI, and plain JSON Schema share
|
|
12
|
+
* `$ref`, `allOf`/`oneOf`, `enum`, and `format` and differ only in these few decisions. A spec on
|
|
13
|
+
* a different type system (GraphQL, with non-null wrappers and named-type references instead of
|
|
14
|
+
* `$ref`) skips `SchemaDialect` and reuses the universal layer directly: the `Adapter` port, the
|
|
15
|
+
* AST factories, and {@link dispatch} with its own rule table.
|
|
16
|
+
*
|
|
17
|
+
* @typeParam TSchema - The adapter's schema object type (e.g. an OpenAPI `SchemaObject`).
|
|
18
|
+
* @typeParam TRef - The narrowed `$ref` pointer type `isReference` proves.
|
|
19
|
+
* @typeParam TDiscriminated - The narrowed discriminated-schema type `isDiscriminator` proves.
|
|
20
|
+
* @typeParam TDocument - The source document `resolveRef` resolves against.
|
|
21
|
+
*/
|
|
22
|
+
export type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {
|
|
23
|
+
/** Identifies the dialect in logs and while debugging dispatch. */
|
|
24
|
+
name: string
|
|
25
|
+
/** Whether a schema should be treated as nullable. */
|
|
26
|
+
isNullable: (schema?: TSchema) => boolean
|
|
27
|
+
/** Whether a value is a `$ref` pointer object. */
|
|
28
|
+
isReference: (value?: unknown) => value is TRef
|
|
29
|
+
/** Whether a schema carries a structured discriminator (polymorphism). */
|
|
30
|
+
isDiscriminator: (value?: unknown) => value is TDiscriminated
|
|
31
|
+
/** Whether a schema represents binary data (converted to a `blob` node). */
|
|
32
|
+
isBinary: (schema: TSchema) => boolean
|
|
33
|
+
/** Resolves a local `$ref` pointer against the document, or nullish when it cannot. */
|
|
34
|
+
resolveRef: <TResolved>(document: TDocument, ref: string) => TResolved | null | undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Identity helper that types a {@link SchemaDialect} for an adapter. Like
|
|
39
|
+
* `defineParser`, it adds no runtime behavior, it pins the dialect's type for
|
|
40
|
+
* inference and gives adapter authors a discoverable anchor.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* export const oasDialect = defineSchemaDialect({
|
|
45
|
+
* name: 'oas',
|
|
46
|
+
* isNullable,
|
|
47
|
+
* isReference,
|
|
48
|
+
* isDiscriminator,
|
|
49
|
+
* isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
|
|
50
|
+
* resolveRef,
|
|
51
|
+
* })
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export function defineSchemaDialect<TSchema, TRef, TDiscriminated, TDocument>(
|
|
55
|
+
dialect: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>,
|
|
56
|
+
): SchemaDialect<TSchema, TRef, TDiscriminated, TDocument> {
|
|
57
|
+
return dialect
|
|
58
|
+
}
|
package/src/dispatch.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One entry in an ordered dispatch table: a predicate paired with a converter.
|
|
3
|
+
*
|
|
4
|
+
* @typeParam TContext - Per-input context handed to every rule. A spec adapter typically
|
|
5
|
+
* pre-computes this once per node (the source spec node plus derived fields like a
|
|
6
|
+
* normalized type or resolved options) so individual rules stay cheap predicates.
|
|
7
|
+
* @typeParam TNode - The node a rule produces, e.g. a Kubb AST `SchemaNode`.
|
|
8
|
+
*/
|
|
9
|
+
export type DispatchRule<TContext, TNode> = {
|
|
10
|
+
/** Identifies the rule when reading the table or debugging which branch ran. */
|
|
11
|
+
name: string
|
|
12
|
+
/** Returns `true` when this rule is responsible for the given context. */
|
|
13
|
+
match: (context: TContext) => boolean
|
|
14
|
+
/**
|
|
15
|
+
* Produces a node for the context, or `null` to fall through to the next rule.
|
|
16
|
+
*
|
|
17
|
+
* Returning `null` lets a broad `match` defer: e.g. "has a `format`" matches many schemas,
|
|
18
|
+
* but only some formats are convertible, the rest fall through to plain `type` handling.
|
|
19
|
+
*/
|
|
20
|
+
convert: (context: TContext) => TNode | null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Walks an ordered list of {@link DispatchRule}s and returns the first node produced.
|
|
25
|
+
*
|
|
26
|
+
* This is the shared backbone for spec adapters (OpenAPI today, AsyncAPI and others later).
|
|
27
|
+
* The contract an adapter follows is intentionally minimal:
|
|
28
|
+
*
|
|
29
|
+
* context → [rule.match → rule.convert] → node
|
|
30
|
+
*
|
|
31
|
+
* An adapter derives a context from a source spec node, then declares an ordered table of
|
|
32
|
+
* rules mapping spec shapes onto Kubb AST nodes. To add support for a new spec, write a new
|
|
33
|
+
* context type and a new rules table, the traversal here is reused unchanged.
|
|
34
|
+
*
|
|
35
|
+
* Order is significant: earlier rules win, so list higher-precedence or more specific shapes
|
|
36
|
+
* first (e.g. composition keywords before plain `type`). A rule whose `match` returns `true`
|
|
37
|
+
* may still `convert` to `null` to defer to later rules. When no rule produces a node this
|
|
38
|
+
* returns `null`, leaving the caller to apply its own fallback.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* const node = dispatch(schemaRules, schemaContext) ?? createSchema({ type: fallbackType })
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export function dispatch<TContext, TNode>(rules: ReadonlyArray<DispatchRule<TContext, TNode>>, context: TContext): TNode | null {
|
|
46
|
+
for (const rule of rules) {
|
|
47
|
+
if (!rule.match(context)) continue
|
|
48
|
+
const node = rule.convert(context)
|
|
49
|
+
if (node !== null && node !== undefined) return node
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return null
|
|
53
|
+
}
|