@kubb/ast 5.0.0-beta.5 → 5.0.0-beta.50

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 (48) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +28 -19
  3. package/dist/index.cjs +878 -788
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +33 -3326
  6. package/dist/index.js +863 -750
  7. package/dist/index.js.map +1 -1
  8. package/dist/types-BaaNZbSi.d.ts +3581 -0
  9. package/dist/types.cjs +0 -0
  10. package/dist/types.d.ts +2 -0
  11. package/dist/types.js +1 -0
  12. package/dist/utils-BIcKgbbc.js +626 -0
  13. package/dist/utils-BIcKgbbc.js.map +1 -0
  14. package/dist/utils-CMRZrT-w.cjs +794 -0
  15. package/dist/utils-CMRZrT-w.cjs.map +1 -0
  16. package/dist/utils.cjs +18 -0
  17. package/dist/utils.d.ts +205 -0
  18. package/dist/utils.js +2 -0
  19. package/package.json +13 -5
  20. package/src/constants.ts +10 -49
  21. package/src/dedupe.ts +200 -0
  22. package/src/dialect.ts +58 -0
  23. package/src/dispatch.ts +53 -0
  24. package/src/factory.ts +154 -21
  25. package/src/guards.ts +18 -48
  26. package/src/index.ts +11 -8
  27. package/src/infer.ts +16 -14
  28. package/src/nodes/base.ts +2 -0
  29. package/src/nodes/code.ts +22 -28
  30. package/src/nodes/content.ts +37 -0
  31. package/src/nodes/file.ts +17 -15
  32. package/src/nodes/function.ts +11 -11
  33. package/src/nodes/http.ts +1 -35
  34. package/src/nodes/index.ts +10 -12
  35. package/src/nodes/operation.ts +98 -62
  36. package/src/nodes/response.ts +21 -14
  37. package/src/nodes/root.ts +72 -10
  38. package/src/nodes/schema.ts +18 -15
  39. package/src/printer.ts +44 -38
  40. package/src/resolvers.ts +5 -19
  41. package/src/signature.ts +232 -0
  42. package/src/transformers.ts +21 -16
  43. package/src/types.ts +8 -18
  44. package/src/{utils.ts → utils/ast.ts} +125 -84
  45. package/src/utils/index.ts +295 -0
  46. package/src/visitor.ts +239 -281
  47. package/src/refs.ts +0 -67
  48. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
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
+ }
@@ -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
+ }
package/src/factory.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash } from 'node:crypto'
1
+ import { hash } from 'node:crypto'
2
2
  import path from 'node:path'
3
3
  import { trimExtName } from '@internals/utils'
4
4
  import type { InferSchemaNode } from './infer.ts'
@@ -6,14 +6,20 @@ import type {
6
6
  ArrowFunctionNode,
7
7
  BreakNode,
8
8
  ConstNode,
9
+ ContentNode,
9
10
  ExportNode,
10
11
  FileNode,
11
12
  FunctionNode,
12
13
  FunctionParameterNode,
13
14
  FunctionParametersNode,
15
+ GenericOperationNode,
16
+ HttpOperationNode,
14
17
  ImportNode,
18
+ InputMeta,
15
19
  InputNode,
20
+ InputStreamNode,
16
21
  JsxNode,
22
+ Node,
17
23
  ObjectSchemaNode,
18
24
  OperationNode,
19
25
  OutputNode,
@@ -22,19 +28,23 @@ import type {
22
28
  ParamsTypeNode,
23
29
  PrimitiveSchemaType,
24
30
  PropertyNode,
31
+ RequestBodyNode,
25
32
  ResponseNode,
26
33
  SchemaNode,
27
34
  SourceNode,
28
35
  TextNode,
29
36
  TypeNode,
30
37
  } from './nodes/index.ts'
31
- import { combineExports, combineImports, combineSources, extractStringsFromNodes } from './utils.ts'
38
+ import { combineExports, combineImports, combineSources, extractStringsFromNodes } from './utils/ast.ts'
32
39
 
33
40
  /**
34
- * Syncs property/parameter schema optionality flags from `required` and `schema.nullable`.
41
+ * Updates a schema's `optional` and `nullish` flags from a parent's `required`
42
+ * value and the schema's own `nullable`. Mirrors how OpenAPI parameters and
43
+ * object properties combine "required" and "nullable" into a single AST.
35
44
  *
36
- * - `optional` is set for non-required, non-nullable schemas.
37
- * - `nullish` is set for non-required, nullable schemas.
45
+ * - Non-required + non-nullable → `optional: true`.
46
+ * - Non-required + nullable `nullish: true`.
47
+ * - Required → both flags cleared.
38
48
  */
39
49
  export function syncOptionality(schema: SchemaNode, required: boolean): SchemaNode {
40
50
  const nullable = schema.nullable ?? false
@@ -59,6 +69,32 @@ export function syncOptionality(schema: SchemaNode, required: boolean): SchemaNo
59
69
  */
60
70
  export type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never
61
71
 
72
+ /**
73
+ * Identity-preserving node update: returns `node` unchanged when every field in
74
+ * `changes` already equals (by reference) the current value, otherwise a new node
75
+ * with the changes applied.
76
+ *
77
+ * Mirrors the TypeScript compiler's `factory.updateX` contract, pair it with the
78
+ * structural sharing in {@link transform} so a no-op rewrite doesn't allocate and
79
+ * downstream passes can detect "nothing changed" by identity. Comparison is
80
+ * shallow: a structurally-equal but newly-allocated array/object counts as a change.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * update(node, { name: node.name }) // -> same `node` reference
85
+ * update(node, { name: 'renamed' }) // -> new node, `name` replaced
86
+ * ```
87
+ */
88
+ export function update<T extends Node>(node: T, changes: Partial<T>): T {
89
+ for (const key in changes) {
90
+ if (changes[key] !== node[key as keyof T]) {
91
+ return { ...node, ...changes }
92
+ }
93
+ }
94
+
95
+ return node
96
+ }
97
+
62
98
  type CreateSchemaObjectInput = Omit<ObjectSchemaNode, 'kind' | 'properties' | 'primitive'> & { properties?: Array<PropertyNode>; primitive?: 'object' }
63
99
  type CreateSchemaInput = CreateSchemaObjectInput | DistributiveOmit<Exclude<SchemaNode, ObjectSchemaNode>, 'kind'>
64
100
  type CreateSchemaOutput<T extends CreateSchemaInput> = InferSchemaNode<T> & {
@@ -84,11 +120,24 @@ export function createInput(overrides: Partial<Omit<InputNode, 'kind'>> = {}): I
84
120
  return {
85
121
  schemas: [],
86
122
  operations: [],
123
+ meta: { circularNames: [], enumNames: [] },
87
124
  ...overrides,
88
125
  kind: 'Input',
89
126
  }
90
127
  }
91
128
 
129
+ /**
130
+ * Creates an `InputStreamNode` from pre-built `AsyncIterable` sources.
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * const node = createStreamInput(schemasIterable, operationsIterable, { title: 'My API' })
135
+ * ```
136
+ */
137
+ export function createStreamInput(schemas: AsyncIterable<SchemaNode>, operations: AsyncIterable<OperationNode>, meta?: InputMeta): InputStreamNode {
138
+ return { kind: 'Input', schemas, operations, meta }
139
+ }
140
+
92
141
  /**
93
142
  * Creates an `OutputNode` with a stable default for `files`.
94
143
  *
@@ -134,21 +183,75 @@ export function createOutput(overrides: Partial<Omit<OutputNode, 'kind'>> = {}):
134
183
  * })
135
184
  * ```
136
185
  */
186
+ /**
187
+ * Loosely-typed content entry accepted by the builders, normalized into a {@link ContentNode}.
188
+ */
189
+ type UserContent = Omit<ContentNode, 'kind'>
190
+
191
+ /**
192
+ * Creates a `ContentNode` for a single request-body or response content type.
193
+ */
194
+ export function createContent(props: UserContent): ContentNode {
195
+ return {
196
+ ...props,
197
+ kind: 'Content',
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Loosely-typed request body accepted by `createOperation`, normalized into a {@link RequestBodyNode}.
203
+ */
204
+ type UserRequestBody = Omit<RequestBodyNode, 'kind' | 'content'> & {
205
+ content?: Array<UserContent>
206
+ }
207
+
208
+ /**
209
+ * Creates a `RequestBodyNode`, normalizing each content entry into a `ContentNode`.
210
+ */
211
+ export function createRequestBody(props: UserRequestBody): RequestBodyNode {
212
+ return {
213
+ ...props,
214
+ kind: 'RequestBody',
215
+ content: props.content?.map(createContent),
216
+ }
217
+ }
218
+
219
+ export function createOperation(
220
+ props: Pick<HttpOperationNode, 'operationId' | 'method' | 'path'> &
221
+ Partial<Omit<HttpOperationNode, 'kind' | 'operationId' | 'method' | 'path' | 'requestBody'>> & {
222
+ requestBody?: UserRequestBody
223
+ },
224
+ ): HttpOperationNode
137
225
  export function createOperation(
138
- props: Pick<OperationNode, 'operationId' | 'method' | 'path'> & Partial<Omit<OperationNode, 'kind' | 'operationId' | 'method' | 'path'>>,
139
- ): OperationNode {
226
+ props: Pick<GenericOperationNode, 'operationId'> &
227
+ Partial<Omit<GenericOperationNode, 'kind' | 'operationId' | 'requestBody'>> & {
228
+ requestBody?: UserRequestBody
229
+ },
230
+ ): GenericOperationNode
231
+ export function createOperation(props: {
232
+ operationId: string
233
+ method?: HttpOperationNode['method']
234
+ path?: HttpOperationNode['path']
235
+ requestBody?: UserRequestBody
236
+ [key: string]: unknown
237
+ }): OperationNode {
238
+ const { requestBody, ...rest } = props
239
+ const isHttp = rest.method !== undefined && rest.path !== undefined
240
+
140
241
  return {
141
242
  tags: [],
142
243
  parameters: [],
143
244
  responses: [],
144
- ...props,
245
+ ...rest,
246
+ ...(isHttp ? { protocol: 'http' } : {}),
145
247
  kind: 'Operation',
146
- }
248
+ requestBody: requestBody ? createRequestBody(requestBody) : undefined,
249
+ } as OperationNode
147
250
  }
148
251
 
149
252
  /**
150
253
  * Maps schema `type` to its underlying `primitive`.
151
- * Primitive types map to themselves; special string formats map to `'string'`.
254
+ * Primitive types map to themselves. Special string formats map to `'string'`.
152
255
  * Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
153
256
  */
154
257
  const TYPE_TO_PRIMITIVE: Partial<Record<SchemaNode['type'], PrimitiveSchemaType>> = {
@@ -304,21 +407,34 @@ export function createParameter(
304
407
  /**
305
408
  * Creates a `ResponseNode`.
306
409
  *
410
+ * Response body schemas live inside `content`. For convenience a single legacy `schema`
411
+ * (with optional `mediaType`/`keysToOmit`) is normalized into one `content` entry, so the same
412
+ * schema is never stored both at the node root and inside `content`.
413
+ *
307
414
  * @example
308
415
  * ```ts
309
416
  * const response = createResponse({
310
417
  * statusCode: '200',
311
- * description: 'Success',
312
- * schema: createSchema({ type: 'object', properties: [] }),
418
+ * content: [{ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) }],
313
419
  * })
314
420
  * ```
315
421
  */
316
422
  export function createResponse(
317
- props: Pick<ResponseNode, 'statusCode' | 'schema'> & Partial<Omit<ResponseNode, 'kind' | 'statusCode' | 'schema'>>,
423
+ props: Pick<ResponseNode, 'statusCode'> &
424
+ Partial<Omit<ResponseNode, 'kind' | 'statusCode' | 'content'>> & {
425
+ content?: Array<UserContent>
426
+ schema?: SchemaNode
427
+ mediaType?: string | null
428
+ keysToOmit?: Array<string> | null
429
+ },
318
430
  ): ResponseNode {
431
+ const { schema, mediaType, keysToOmit, content, ...rest } = props
432
+ const entries = content ?? (schema ? [{ contentType: mediaType ?? 'application/json', schema, keysToOmit: keysToOmit ?? null }] : undefined)
433
+
319
434
  return {
320
- ...props,
435
+ ...rest,
321
436
  kind: 'Response',
437
+ content: entries?.map(createContent),
322
438
  }
323
439
  }
324
440
 
@@ -339,7 +455,7 @@ export function createResponse(
339
455
  * // → params?: QueryParams
340
456
  * ```
341
457
  *
342
- * @example Param with default (implicitly optional; cannot combine with `optional: true`)
458
+ * @example Param with default (implicitly optional. Cannot combine with `optional: true`)
343
459
  * ```ts
344
460
  * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), default: '{}' })
345
461
  * // → config: RequestConfig = {}
@@ -409,7 +525,7 @@ export function createParamsType(
409
525
  * // call → { id, name }
410
526
  * ```
411
527
  *
412
- * @example Inline (spread) children emitted as individual top-level parameters
528
+ * @example Inline (spread), children emitted as individual top-level parameters
413
529
  * ```ts
414
530
  * createParameterGroup({
415
531
  * properties: [createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false })],
@@ -512,9 +628,9 @@ export type UserFileNode<TMeta extends object = object> = Omit<FileNode<TMeta>,
512
628
  * Creates a fully resolved `FileNode` from a file input descriptor.
513
629
  *
514
630
  * Computes:
515
- * - `id` SHA256 hash of the file path
516
- * - `name` `baseName` without extension
517
- * - `extname` extension extracted from `baseName`
631
+ * - `id` SHA256 hash of the file path
632
+ * - `name` `baseName` without extension
633
+ * - `extname` extension extracted from `baseName`
518
634
  *
519
635
  * Deduplicates:
520
636
  * - `sources` via `combineSources`
@@ -551,13 +667,30 @@ export function createFile<TMeta extends object = object>(input: UserFileNode<TM
551
667
  .filter(Boolean)
552
668
  .join('\n\n')
553
669
  const resolvedExports = input.exports?.length ? combineExports(input.exports) : []
554
- const resolvedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || undefined) : []
670
+ const combinedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || undefined) : []
671
+ const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name): name is string => Boolean(name)))
672
+ const nameOf = (item: string | { propertyName: string; name?: string }): string => (typeof item === 'string' ? item : (item.name ?? item.propertyName))
673
+ // Drop self-imports. Consolidating output (`mode: 'file'`) can place a symbol's
674
+ // definition and a cross-file import of it in the same file. The first pass catches imports that
675
+ // resolve to this file's own path. The second drops imports of names the file already defines,
676
+ // the case consolidation produces when the import path no longer matches `input.path`. Sources
677
+ // stay intact, so the local definition remains. Bare specifiers like `'zod'` never match a path.
678
+ const resolvedImports = combinedImports
679
+ .filter((imp) => imp.path !== input.path)
680
+ .flatMap((imp) => {
681
+ if (!Array.isArray(imp.name)) {
682
+ return typeof imp.name === 'string' && localNames.has(imp.name) ? [] : [imp]
683
+ }
684
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)))
685
+ if (!kept.length) return []
686
+ return [kept.length === imp.name.length ? imp : { ...imp, name: kept }]
687
+ })
555
688
  const resolvedSources = input.sources?.length ? combineSources(input.sources) : []
556
689
 
557
690
  return {
558
691
  kind: 'File',
559
692
  ...input,
560
- id: createHash('sha256').update(input.path).digest('hex'),
693
+ id: hash('sha256', input.path, 'hex'),
561
694
  name: trimExtName(input.baseName),
562
695
  extname,
563
696
  imports: resolvedImports,
package/src/guards.ts CHANGED
@@ -1,18 +1,4 @@
1
- import type {
2
- FunctionParameterNode,
3
- FunctionParametersNode,
4
- InputNode,
5
- Node,
6
- NodeKind,
7
- OperationNode,
8
- OutputNode,
9
- ParameterGroupNode,
10
- ParameterNode,
11
- PropertyNode,
12
- ResponseNode,
13
- SchemaNode,
14
- SchemaNodeByType,
15
- } from './nodes/index.ts'
1
+ import type { HttpOperationNode, InputNode, Node, NodeKind, OperationNode, OutputNode, SchemaNode, SchemaNodeByType } from './nodes/index.ts'
16
2
 
17
3
  /**
18
4
  * Narrows a `SchemaNode` to the variant that matches `type`.
@@ -20,11 +6,11 @@ import type {
20
6
  * @example
21
7
  * ```ts
22
8
  * const schema = createSchema({ type: 'string' })
23
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | undefined
9
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
24
10
  * ```
25
11
  */
26
- export function narrowSchema<T extends SchemaNode['type']>(node: SchemaNode | undefined, type: T): SchemaNodeByType[T] | undefined {
27
- return node?.type === type ? (node as SchemaNodeByType[T]) : undefined
12
+ export function narrowSchema<T extends SchemaNode['type']>(node: SchemaNode | undefined, type: T): SchemaNodeByType[T] | null {
13
+ return node?.type === type ? (node as SchemaNodeByType[T]) : null
28
14
  }
29
15
 
30
16
  function isKind<T extends Node>(kind: NodeKind) {
@@ -67,6 +53,20 @@ export const isOutputNode = isKind<OutputNode>('Output')
67
53
  */
68
54
  export const isOperationNode = isKind<OperationNode>('Operation')
69
55
 
56
+ /**
57
+ * Narrows an `OperationNode` to an `HttpOperationNode`, guaranteeing `method` and `path`.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * if (isHttpOperationNode(node)) {
62
+ * console.log(node.method, node.path)
63
+ * }
64
+ * ```
65
+ */
66
+ export function isHttpOperationNode(node: OperationNode): node is HttpOperationNode {
67
+ return node.protocol === 'http' || (node.method !== undefined && node.path !== undefined)
68
+ }
69
+
70
70
  /**
71
71
  * Returns `true` when the input is a `SchemaNode`.
72
72
  *
@@ -78,33 +78,3 @@ export const isOperationNode = isKind<OperationNode>('Operation')
78
78
  * ```
79
79
  */
80
80
  export const isSchemaNode = isKind<SchemaNode>('Schema')
81
-
82
- /**
83
- * Returns `true` when the input is a `PropertyNode`.
84
- */
85
- export const isPropertyNode = isKind<PropertyNode>('Property')
86
-
87
- /**
88
- * Returns `true` when the input is a `ParameterNode`.
89
- */
90
- export const isParameterNode = isKind<ParameterNode>('Parameter')
91
-
92
- /**
93
- * Returns `true` when the input is a `ResponseNode`.
94
- */
95
- export const isResponseNode = isKind<ResponseNode>('Response')
96
-
97
- /**
98
- * Returns `true` when the input is a `FunctionParameterNode`.
99
- */
100
- export const isFunctionParameterNode = isKind<FunctionParameterNode>('FunctionParameter')
101
-
102
- /**
103
- * Returns `true` when the input is a `ParameterGroupNode`.
104
- */
105
- export const isParameterGroupNode = isKind<ParameterGroupNode>('ParameterGroup')
106
-
107
- /**
108
- * Returns `true` when the input is a `FunctionParametersNode`.
109
- */
110
- export const isFunctionParametersNode = isKind<FunctionParametersNode>('FunctionParameters')
package/src/index.ts CHANGED
@@ -1,4 +1,7 @@
1
- export { httpMethods, isScalarPrimitive, mediaTypes, nodeKinds, schemaTypes } from './constants.ts'
1
+ export { httpMethods, schemaTypes } from './constants.ts'
2
+ export { applyDedupe, buildDedupePlan } from './dedupe.ts'
3
+ export { defineSchemaDialect } from './dialect.ts'
4
+ export { dispatch } from './dispatch.ts'
2
5
  export {
3
6
  createArrowFunction,
4
7
  createBreak,
@@ -10,6 +13,7 @@ export {
10
13
  createFunctionParameters,
11
14
  createImport,
12
15
  createInput,
16
+ createStreamInput,
13
17
  createJsx,
14
18
  createOperation,
15
19
  createOutput,
@@ -23,16 +27,16 @@ export {
23
27
  createText,
24
28
  createType,
25
29
  syncOptionality,
30
+ update,
26
31
  } from './factory.ts'
27
- export { isInputNode, isOperationNode, isOutputNode, isSchemaNode, narrowSchema } from './guards.ts'
32
+ export { isHttpOperationNode, isInputNode, isOperationNode, isOutputNode, isSchemaNode, narrowSchema } from './guards.ts'
28
33
  export { createPrinterFactory, definePrinter } from './printer.ts'
29
- export { extractRefName } from './refs.ts'
30
- export { childName, collectImports, enumPropName, findDiscriminator } from './resolvers.ts'
31
- export { mergeAdjacentObjects, setDiscriminatorEnum, setEnumName, simplifyUnion } from './transformers.ts'
34
+ export { collectImports } from './resolvers.ts'
35
+ export { schemaSignature } from './signature.ts'
36
+ export { mergeAdjacentObjectsLazy, setDiscriminatorEnum, setEnumName, simplifyUnion } from './transformers.ts'
32
37
  export type * from './types.ts'
33
38
  export {
34
39
  caseParams,
35
- collectReferencedSchemaNames,
36
40
  collectUsedSchemaNames,
37
41
  containsCircularRef,
38
42
  createDiscriminantNode,
@@ -40,7 +44,6 @@ export {
40
44
  extractStringsFromNodes,
41
45
  findCircularSchemas,
42
46
  isStringType,
43
- resolveRefName,
44
47
  syncSchemaRef,
45
- } from './utils.ts'
48
+ } from './utils/ast.ts'
46
49
  export { collect, transform, walk } from './visitor.ts'
package/src/infer.ts CHANGED
@@ -20,15 +20,25 @@ import type {
20
20
  */
21
21
  export type ParserOptions = {
22
22
  /**
23
- * How `format: 'date-time'` schemas are represented. `false` falls through to a plain string.
23
+ * How `format: 'date-time'` schemas are represented downstream.
24
+ * - `false` falls through to a plain `string` (no validation).
25
+ * - `'string'` emits a datetime string node.
26
+ * - `'stringOffset'` emits a datetime node with timezone offset.
27
+ * - `'stringLocal'` emits a local datetime node.
28
+ * - `'date'` emits a `date` node (JavaScript `Date` object).
24
29
  */
25
30
  dateType: false | 'string' | 'stringOffset' | 'stringLocal' | 'date'
26
31
  /**
27
- * Whether `type: 'integer'` and `format: 'int64'` produce `number` or `bigint` nodes.
32
+ * How `type: 'integer'` (and `format: 'int64'`) maps to TypeScript.
33
+ * - `'bigint'` is exact for 64-bit IDs, but does not round-trip through JSON.
34
+ * - `'number'` fits most JSON APIs. Loses precision above `Number.MAX_SAFE_INTEGER`.
35
+ *
36
+ * @default 'bigint'
28
37
  */
29
38
  integerType?: 'number' | 'bigint'
30
39
  /**
31
- * AST type used when no schema type can be inferred.
40
+ * AST type used when a schema's type cannot be inferred from the spec
41
+ * (`additionalProperties: true`, missing `type`, ...).
32
42
  */
33
43
  unknownType: 'any' | 'unknown' | 'void'
34
44
  /**
@@ -36,7 +46,8 @@ export type ParserOptions = {
36
46
  */
37
47
  emptySchemaType: 'any' | 'unknown' | 'void'
38
48
  /**
39
- * Suffix appended to derived enum names when building property schema names.
49
+ * Suffix appended to derived enum names when Kubb has to invent one
50
+ * (typically for inline enums on object properties).
40
51
  */
41
52
  enumSuffix: 'enum' | (string & {})
42
53
  }
@@ -66,7 +77,7 @@ type ResolveDateTimeNode<TDateType extends ParserOptions['dateType']> = DateTime
66
77
  type SchemaNodeMap<TDateType extends ParserOptions['dateType'] = 'string'> = [
67
78
  [{ $ref: string }, RefSchemaNode],
68
79
  [{ allOf: ReadonlyArray<unknown>; properties: object }, IntersectionSchemaNode],
69
- [{ allOf: readonly [unknown, unknown, ...unknown[]] }, IntersectionSchemaNode],
80
+ [{ allOf: readonly [unknown, unknown, ...Array<unknown>] }, IntersectionSchemaNode],
70
81
  [{ allOf: ReadonlyArray<unknown> }, SchemaNode],
71
82
  [{ oneOf: ReadonlyArray<unknown> }, UnionSchemaNode],
72
83
  [{ anyOf: ReadonlyArray<unknown> }, UnionSchemaNode],
@@ -119,12 +130,3 @@ export type InferSchemaNode<
119
130
  ? TEntry[1]
120
131
  : InferSchemaNode<TSchema, TDateType, TRest>
121
132
  : SchemaNode
122
-
123
- /**
124
- * Backward-compatible alias for `InferSchemaNode`.
125
- */
126
- export type InferSchema<
127
- TSchema extends object,
128
- TDateType extends ParserOptions['dateType'] = 'string',
129
- TEntries extends ReadonlyArray<[object, SchemaNode]> = SchemaNodeMap<TDateType>,
130
- > = InferSchemaNode<TSchema, TDateType, TEntries>
package/src/nodes/base.ts CHANGED
@@ -14,6 +14,8 @@ export type NodeKind =
14
14
  | 'Property'
15
15
  | 'Parameter'
16
16
  | 'Response'
17
+ | 'RequestBody'
18
+ | 'Content'
17
19
  | 'FunctionParameter'
18
20
  | 'ParameterGroup'
19
21
  | 'FunctionParameters'