@kubb/ast 5.0.0-beta.62 → 5.0.0-beta.63

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 (73) hide show
  1. package/dist/{defineMacro-Vw-xQvq7.d.ts → defineMacro-BATi7xoC.d.ts} +4 -5
  2. package/dist/{defineMacro-BryDiuQl.cjs → defineMacro-CEZHaCXE.cjs} +5 -5
  3. package/dist/defineMacro-CEZHaCXE.cjs.map +1 -0
  4. package/dist/{defineMacro-CNkUpxia.js → defineMacro-Shz8f6SG.js} +3 -3
  5. package/dist/defineMacro-Shz8f6SG.js.map +1 -0
  6. package/dist/factory.cjs +56 -56
  7. package/dist/factory.cjs.map +1 -1
  8. package/dist/factory.d.ts +5 -5
  9. package/dist/factory.js +5 -5
  10. package/dist/factory.js.map +1 -1
  11. package/dist/{index-CTaN_ee_.d.ts → index-B9cc8MBS.d.ts} +46 -113
  12. package/dist/index.cjs +142 -271
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.ts +12 -5
  15. package/dist/index.js +108 -236
  16. package/dist/index.js.map +1 -1
  17. package/dist/macros.cjs +12 -12
  18. package/dist/macros.cjs.map +1 -1
  19. package/dist/macros.d.ts +2 -2
  20. package/dist/macros.js +4 -4
  21. package/dist/macros.js.map +1 -1
  22. package/dist/{operationParams-B44p6EQy.d.ts → operationParams-k5CKwSWZ.d.ts} +9 -2
  23. package/dist/{visitor-DepQEKyp.js → refs-BjNDuCBD.js} +115 -120
  24. package/dist/refs-BjNDuCBD.js.map +1 -0
  25. package/dist/{visitor-B7Zlnp4c.cjs → refs-u5SDdyV7.cjs} +139 -144
  26. package/dist/refs-u5SDdyV7.cjs.map +1 -0
  27. package/dist/{response-BeG6hq2D.cjs → schema-BkvrrOAr.cjs} +171 -153
  28. package/dist/schema-BkvrrOAr.cjs.map +1 -0
  29. package/dist/{response-Rd1uisM1.js → schema-Cbnxmz4b.js} +166 -154
  30. package/dist/schema-Cbnxmz4b.js.map +1 -0
  31. package/dist/{types-DQTgVSwE.d.ts → types-BB_xgRJ3.d.ts} +55 -79
  32. package/dist/types.d.ts +5 -5
  33. package/dist/{utils-BDI3kXlb.cjs → utils-CEepwqmb.cjs} +74 -67
  34. package/dist/utils-CEepwqmb.cjs.map +1 -0
  35. package/dist/{utils-DW9rnfsD.js → utils-DaXkewb1.js} +56 -49
  36. package/dist/utils-DaXkewb1.js.map +1 -0
  37. package/dist/utils.cjs +11 -11
  38. package/dist/utils.d.ts +44 -29
  39. package/dist/utils.js +3 -3
  40. package/package.json +1 -1
  41. package/src/constants.ts +3 -6
  42. package/src/defineMacro.ts +1 -1
  43. package/src/defineNode.ts +6 -9
  44. package/src/definePrinter.ts +5 -3
  45. package/src/dialect.ts +23 -13
  46. package/src/factory.ts +4 -4
  47. package/src/index.ts +1 -1
  48. package/src/infer.ts +1 -1
  49. package/src/macros/macroEnumName.ts +1 -1
  50. package/src/nodes/code.ts +8 -5
  51. package/src/nodes/file.ts +5 -4
  52. package/src/nodes/operation.ts +3 -0
  53. package/src/nodes/parameter.ts +5 -5
  54. package/src/nodes/property.ts +5 -5
  55. package/src/nodes/schema.ts +4 -4
  56. package/src/optionality.ts +15 -0
  57. package/src/types.ts +1 -2
  58. package/src/utils/codegen.ts +6 -7
  59. package/src/utils/fileMerge.ts +7 -8
  60. package/src/utils/operationParams.ts +8 -8
  61. package/src/utils/refs.ts +14 -18
  62. package/src/utils/schemaGraph.ts +41 -33
  63. package/src/utils/schemaMerge.ts +2 -2
  64. package/src/visitor.ts +1 -1
  65. package/dist/defineMacro-BryDiuQl.cjs.map +0 -1
  66. package/dist/defineMacro-CNkUpxia.js.map +0 -1
  67. package/dist/response-BeG6hq2D.cjs.map +0 -1
  68. package/dist/response-Rd1uisM1.js.map +0 -1
  69. package/dist/utils-BDI3kXlb.cjs.map +0 -1
  70. package/dist/utils-DW9rnfsD.js.map +0 -1
  71. package/dist/visitor-B7Zlnp4c.cjs.map +0 -1
  72. package/dist/visitor-DepQEKyp.js.map +0 -1
  73. package/src/dedupe.ts +0 -231
package/dist/index.js CHANGED
@@ -1,10 +1,113 @@
1
1
  import "./chunk-CNktS9qV.js";
2
- import { a as nodeDefs, c as extractRefName, g as schemaTypes, i as walk, m as narrowSchema, n as collectLazy, p as isHttpOperationNode, r as transform, t as collect } from "./visitor-DepQEKyp.js";
3
- import { $ as schemaDef, A as fileDef, C as objectBindingPatternDef, F as arrowFunctionDef, G as functionDef, I as breakDef, J as typeDef, K as jsxDef, L as constDef, M as sourceDef, N as contentDef, Q as createSchema, S as indexedAccessTypeDef, b as functionParameterDef, c as outputDef, et as defineNode, f as requestBodyDef, i as propertyDef, j as importDef, k as exportDef, m as inputDef, n as responseDef, o as parameterDef, q as textDef, u as operationDef, w as typeLiteralDef, x as functionParametersDef } from "./response-Rd1uisM1.js";
4
- import "./utils-DW9rnfsD.js";
5
- import { n as composeMacros, r as defineMacro, t as applyMacros } from "./defineMacro-CNkUpxia.js";
2
+ import { c as collect, d as walk, f as nodeDefs, g as schemaTypes, m as narrowSchema, p as isHttpOperationNode, r as extractRefName, u as transform } from "./refs-BjNDuCBD.js";
3
+ import { $ as textDef, C as functionParameterDef, D as typeLiteralDef, E as objectBindingPatternDef, F as sourceDef, H as breakDef, M as exportDef, N as fileDef, P as importDef, Q as jsxDef, T as indexedAccessTypeDef, U as constDef, V as arrowFunctionDef, Z as functionDef, _ as inputDef, c as parameterDef, d as outputDef, et as typeDef, h as requestBodyDef, i as responseDef, l as optionality, n as schemaDef, o as propertyDef, p as operationDef, tt as defineNode, w as functionParametersDef, z as contentDef } from "./schema-Cbnxmz4b.js";
4
+ import "./utils-DaXkewb1.js";
5
+ import { n as composeMacros, r as defineMacro, t as applyMacros } from "./defineMacro-Shz8f6SG.js";
6
6
  import { t as factory_exports } from "./factory.js";
7
7
  import { hash } from "node:crypto";
8
+ //#region src/dialect.ts
9
+ /**
10
+ * Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the
11
+ * dialect's type for inference.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * export const oasDialect = defineDialect({
16
+ * name: 'oas',
17
+ * schema: {
18
+ * isNullable,
19
+ * isReference,
20
+ * isDiscriminator,
21
+ * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
22
+ * resolveRef,
23
+ * },
24
+ * dedupe: { plan },
25
+ * })
26
+ * ```
27
+ */
28
+ function defineDialect(dialect) {
29
+ return dialect;
30
+ }
31
+ //#endregion
32
+ //#region src/definePrinter.ts
33
+ /**
34
+ * Defines a schema printer: a function that takes a `SchemaNode` and emits
35
+ * code in your target language. Each plugin that produces code from schemas
36
+ * (TypeScript types, Zod schemas, Faker factories) ships a printer built
37
+ * with this helper.
38
+ *
39
+ * The builder receives resolved options and returns:
40
+ *
41
+ * - `name` unique identifier for the printer.
42
+ * - `options` stored on the returned printer instance.
43
+ * - `nodes` map of `SchemaType` → handler. Handlers return the rendered
44
+ * output (a string, a TypeScript AST node, ...) for that schema type.
45
+ * - `print` (optional), top-level override exposed as `printer.print`.
46
+ * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
47
+ *
48
+ * Without a `print` override, `printer.print` falls back to `printer.transform`
49
+ * (the node-level dispatcher).
50
+ *
51
+ * @example Tiny Zod printer
52
+ * ```ts
53
+ * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
54
+ *
55
+ * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
56
+ *
57
+ * export const zodPrinter = definePrinter<PrinterZod>((options) => ({
58
+ * name: 'zod',
59
+ * options: { strict: options.strict ?? true },
60
+ * nodes: {
61
+ * string: () => 'z.string()',
62
+ * object(node) {
63
+ * const props = node.properties
64
+ * .map((p) => `${p.name}: ${this.transform(p.schema)}`)
65
+ * .join(', ')
66
+ * return `z.object({ ${props} })`
67
+ * },
68
+ * },
69
+ * }))
70
+ * ```
71
+ */
72
+ function definePrinter(build) {
73
+ return createPrinterFactory((node) => node.type)(build);
74
+ }
75
+ /**
76
+ * Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its
77
+ * handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`
78
+ * itself is this factory keyed by `node.type`.
79
+ *
80
+ * @example Key a printer by `node.kind` instead of `node.type`
81
+ * ```ts
82
+ * const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
83
+ * (node) => node.kind,
84
+ * )
85
+ * ```
86
+ */
87
+ function createPrinterFactory(getKey) {
88
+ return function(build) {
89
+ return (options) => {
90
+ const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? {});
91
+ const context = {
92
+ options: resolvedOptions,
93
+ transform: (node) => {
94
+ const key = getKey(node);
95
+ if (key === null) return null;
96
+ const handler = nodes[key];
97
+ if (!handler) return null;
98
+ return handler.call(context, node);
99
+ }
100
+ };
101
+ return {
102
+ name,
103
+ options: resolvedOptions,
104
+ transform: context.transform,
105
+ print: printOverride ? printOverride.bind(context) : context.transform
106
+ };
107
+ };
108
+ };
109
+ }
110
+ //#endregion
8
111
  //#region src/signature.ts
9
112
  /**
10
113
  * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.
@@ -257,237 +360,6 @@ function signatureOf(node) {
257
360
  return signature;
258
361
  }
259
362
  //#endregion
260
- //#region src/dedupe.ts
261
- /**
262
- * Builds the shared `ref` replacement for a duplicate occurrence, carrying the
263
- * usage-slot and documentation fields that are not part of the canonical type.
264
- */
265
- function createRefNode(node, canonical) {
266
- return createSchema({
267
- type: "ref",
268
- name: canonical.name,
269
- ref: canonical.ref,
270
- optional: node.optional,
271
- nullish: node.nullish,
272
- readOnly: node.readOnly,
273
- writeOnly: node.writeOnly,
274
- deprecated: node.deprecated,
275
- description: node.description,
276
- default: node.default,
277
- example: node.example
278
- });
279
- }
280
- function applyDedupe(node, plan, skipRootMatch = false) {
281
- const { canonicalBySignature, aliasNames } = plan;
282
- if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node;
283
- const root = node;
284
- return transform(node, { schema(schemaNode) {
285
- if (schemaNode.type === "ref") {
286
- const target = schemaNode.ref ? extractRefName(schemaNode.ref) : schemaNode.name;
287
- const canonical = target ? aliasNames.get(target) : void 0;
288
- return canonical ? {
289
- ...schemaNode,
290
- name: canonical.name,
291
- ref: canonical.ref
292
- } : void 0;
293
- }
294
- const signature = signatureOf(schemaNode);
295
- if (skipRootMatch && schemaNode === root) return void 0;
296
- const canonical = canonicalBySignature.get(signature);
297
- if (!canonical) return void 0;
298
- return createRefNode(schemaNode, canonical);
299
- } });
300
- }
301
- /**
302
- * Strips usage-slot flags from a hoisted definition and applies its canonical name.
303
- * A standalone definition is never optional, so `optional`/`nullish` are cleared.
304
- */
305
- function cleanDefinition(node, name) {
306
- return {
307
- ...node,
308
- name,
309
- optional: void 0,
310
- nullish: void 0
311
- };
312
- }
313
- /**
314
- * Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
315
- *
316
- * A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
317
- * is a named top-level schema, the first one becomes the canonical (so other top-level
318
- * duplicates and inline copies turn into references to it). Every other top-level name with
319
- * the same content is recorded in `aliasNames`, so refs to it can be repointed at the
320
- * canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied
321
- * per node with {@link applyDedupe}.
322
- *
323
- * @example
324
- * ```ts
325
- * const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
326
- * isCandidate: (node) => node.type === 'enum' || node.type === 'object',
327
- * nameFor: (node) => node.name ?? null,
328
- * refFor: (name) => `#/components/schemas/${name}`,
329
- * })
330
- * ```
331
- */
332
- function buildDedupePlan(roots, options) {
333
- const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options;
334
- const topLevelNodes = /* @__PURE__ */ new Set();
335
- const groups = /* @__PURE__ */ new Map();
336
- function record(schemaNode) {
337
- if (!isCandidate(schemaNode)) return;
338
- const signature = signatureOf(schemaNode);
339
- const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name;
340
- const group = groups.get(signature);
341
- if (group) {
342
- group.count++;
343
- if (isTopLevel) group.topLevelNames.push(schemaNode.name);
344
- } else groups.set(signature, {
345
- count: 1,
346
- representative: schemaNode,
347
- topLevelNames: isTopLevel ? [schemaNode.name] : []
348
- });
349
- }
350
- for (const root of roots) {
351
- if (root.kind === "Schema") topLevelNodes.add(root);
352
- for (const schemaNode of collectLazy(root, { schema: (node) => node })) record(schemaNode);
353
- }
354
- const canonicalBySignature = /* @__PURE__ */ new Map();
355
- const aliasNames = /* @__PURE__ */ new Map();
356
- const pendingHoists = [];
357
- for (const [signature, group] of groups) {
358
- if (group.count < minOccurrences) continue;
359
- const [firstName, ...duplicateNames] = group.topLevelNames;
360
- if (firstName) {
361
- const canonical = {
362
- name: firstName,
363
- ref: refFor(firstName)
364
- };
365
- canonicalBySignature.set(signature, canonical);
366
- for (const duplicate of duplicateNames) aliasNames.set(duplicate, canonical);
367
- continue;
368
- }
369
- const name = nameFor(group.representative, signature);
370
- if (!name) continue;
371
- canonicalBySignature.set(signature, {
372
- name,
373
- ref: refFor(name)
374
- });
375
- pendingHoists.push({
376
- name,
377
- representative: group.representative
378
- });
379
- }
380
- return {
381
- canonicalBySignature,
382
- aliasNames,
383
- hoisted: pendingHoists.map(({ name, representative }) => cleanDefinition(applyDedupe(representative, {
384
- canonicalBySignature,
385
- aliasNames
386
- }, true), name))
387
- };
388
- }
389
- //#endregion
390
- //#region src/dialect.ts
391
- /**
392
- * Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the
393
- * dialect's type for inference.
394
- *
395
- * @example
396
- * ```ts
397
- * export const oasDialect = defineDialect({
398
- * name: 'oas',
399
- * schema: {
400
- * isNullable,
401
- * isReference,
402
- * isDiscriminator,
403
- * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
404
- * resolveRef,
405
- * optionality,
406
- * },
407
- * })
408
- * ```
409
- */
410
- function defineDialect(dialect) {
411
- return dialect;
412
- }
413
- //#endregion
414
- //#region src/definePrinter.ts
415
- /**
416
- * Defines a schema printer: a function that takes a `SchemaNode` and emits
417
- * code in your target language. Each plugin that produces code from schemas
418
- * (TypeScript types, Zod schemas, Faker factories) ships a printer built
419
- * with this helper.
420
- *
421
- * The builder receives resolved options and returns:
422
- *
423
- * - `name` unique identifier for the printer.
424
- * - `options` stored on the returned printer instance.
425
- * - `nodes` map of `SchemaType` → handler. Handlers return the rendered
426
- * output (a string, a TypeScript AST node, ...) for that schema type.
427
- * - `print` (optional), top-level override exposed as `printer.print`.
428
- * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
429
- *
430
- * Without a `print` override, `printer.print` falls back to `printer.transform`
431
- * (the node-level dispatcher).
432
- *
433
- * @example Tiny Zod printer
434
- * ```ts
435
- * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
436
- *
437
- * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
438
- *
439
- * export const zodPrinter = definePrinter<PrinterZod>((options) => ({
440
- * name: 'zod',
441
- * options: { strict: options.strict ?? true },
442
- * nodes: {
443
- * string: () => 'z.string()',
444
- * object(node) {
445
- * const props = node.properties
446
- * .map((p) => `${p.name}: ${this.transform(p.schema)}`)
447
- * .join(', ')
448
- * return `z.object({ ${props} })`
449
- * },
450
- * },
451
- * }))
452
- * ```
453
- */
454
- function definePrinter(build) {
455
- return createPrinterFactory((node) => node.type)(build);
456
- }
457
- /**
458
- * Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
459
- *
460
- * @example
461
- * ```ts
462
- * export const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
463
- * (node) => node.kind,
464
- * )
465
- * ```
466
- */
467
- function createPrinterFactory(getKey) {
468
- return function(build) {
469
- return (options) => {
470
- const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? {});
471
- const context = {
472
- options: resolvedOptions,
473
- transform: (node) => {
474
- const key = getKey(node);
475
- if (key === null) return null;
476
- const handler = nodes[key];
477
- if (!handler) return null;
478
- return handler.call(context, node);
479
- }
480
- };
481
- return {
482
- name,
483
- options: resolvedOptions,
484
- transform: context.transform,
485
- print: printOverride ? printOverride.bind(context) : context.transform
486
- };
487
- };
488
- };
489
- }
490
- //#endregion
491
- export { applyDedupe, applyMacros, arrowFunctionDef, breakDef, buildDedupePlan, collect, composeMacros, constDef, contentDef, createPrinterFactory, defineDialect, defineMacro, defineNode, definePrinter, exportDef, factory_exports as factory, fileDef, functionDef, functionParameterDef, functionParametersDef, importDef, indexedAccessTypeDef, inputDef, isHttpOperationNode, jsxDef, narrowSchema, nodeDefs, objectBindingPatternDef, operationDef, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, signatureOf, sourceDef, textDef, transform, typeDef, typeLiteralDef, walk };
363
+ export { applyMacros, arrowFunctionDef, breakDef, collect, composeMacros, constDef, contentDef, createPrinterFactory, defineDialect, defineMacro, defineNode, definePrinter, exportDef, factory_exports as factory, fileDef, functionDef, functionParameterDef, functionParametersDef, importDef, indexedAccessTypeDef, inputDef, isHttpOperationNode, jsxDef, narrowSchema, nodeDefs, objectBindingPatternDef, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, signatureOf, sourceDef, textDef, transform, typeDef, typeLiteralDef, walk };
492
364
 
493
365
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["obj"],"sources":["../src/signature.ts","../src/dedupe.ts","../src/dialect.ts","../src/definePrinter.ts"],"sourcesContent":["import { hash } from 'node:crypto'\nimport type { SchemaNode } from './nodes/index.ts'\nimport { extractRefName } from './utils/index.ts'\n\n/**\n * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.\n */\nfunction flagsDescriptor(node: SchemaNode): string {\n return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`\n}\n\nfunction refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {\n if (node.ref) return extractRefName(node.ref)\n return node.name ?? ''\n}\n\ntype ScalarField = { kind: 'scalar'; key: string; prefix: string }\ntype BoolField = { kind: 'bool'; key: string; prefix: string }\ntype ChildField = { kind: 'child'; key: string; prefix: string }\ntype ChildrenField = { kind: 'children'; key: string; prefix: string }\ntype ObjectPropsField = { kind: 'objectProps' }\ntype AdditionalPropsField = { kind: 'additionalProps' }\ntype PatternPropsField = { kind: 'patternProps' }\ntype EnumValuesField = { kind: 'enumValues' }\ntype RefTargetField = { kind: 'refTarget' }\n\ntype ShapeField =\n | ScalarField\n | BoolField\n | ChildField\n | ChildrenField\n | ObjectPropsField\n | AdditionalPropsField\n | PatternPropsField\n | EnumValuesField\n | RefTargetField\n\nconst arrayTupleFields: ReadonlyArray<ShapeField> = [\n { kind: 'children', key: 'items', prefix: 'i' },\n { kind: 'child', key: 'rest', prefix: 'r' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'bool', key: 'unique', prefix: 'u' },\n]\n\nconst numericFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },\n { kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },\n { kind: 'scalar', key: 'multipleOf', prefix: 'mo' },\n]\n\nconst rangeFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n]\n\n/**\n * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map\n * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.\n */\nconst SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {\n object: [\n { kind: 'objectProps' },\n { kind: 'additionalProps' },\n { kind: 'patternProps' },\n { kind: 'scalar', key: 'minProperties', prefix: 'mn' },\n { kind: 'scalar', key: 'maxProperties', prefix: 'mx' },\n ],\n array: arrayTupleFields,\n tuple: arrayTupleFields,\n union: [\n { kind: 'scalar', key: 'strategy', prefix: 's' },\n { kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },\n { kind: 'children', key: 'members', prefix: 'm' },\n ],\n intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],\n enum: [{ kind: 'enumValues' }],\n ref: [{ kind: 'refTarget' }],\n string: [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'pattern', prefix: 'pt' },\n ],\n number: numericFields,\n integer: numericFields,\n bigint: numericFields,\n url: [\n { kind: 'scalar', key: 'path', prefix: 'path' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n ],\n uuid: rangeFields,\n email: rangeFields,\n datetime: [\n { kind: 'bool', key: 'offset', prefix: 'o' },\n { kind: 'bool', key: 'local', prefix: 'l' },\n ],\n date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n}\n\nfunction serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {\n switch (field.kind) {\n case 'scalar':\n return `${field.prefix}:${record[field.key] ?? ''}`\n case 'bool':\n return `${field.prefix}:${record[field.key] ? 1 : 0}`\n case 'child': {\n const child = record[field.key] as SchemaNode | undefined\n return `${field.prefix}:${child ? signatureOf(child) : ''}`\n }\n case 'children': {\n const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []\n return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`\n }\n case 'objectProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')\n return `p[${props}]`\n }\n case 'additionalProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`\n if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`\n return ''\n }\n case 'patternProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const pattern = obj.patternProperties\n ? Object.keys(obj.patternProperties)\n .sort()\n .map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)\n .join(',')\n : ''\n return `pp[${pattern}]`\n }\n case 'enumValues': {\n const en = node as Extract<SchemaNode, { type: 'enum' }>\n let values = ''\n if (en.namedEnumValues?.length) {\n values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')\n } else if (en.enumValues?.length) {\n values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')\n }\n return `v[${values}]`\n }\n case 'refTarget': {\n return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`\n }\n }\n}\n\n/**\n * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,\n * constraints, and its children's signatures.\n */\nfunction describeShape(node: SchemaNode): string {\n const flags = flagsDescriptor(node)\n const fields = SHAPE_KEYS[node.type]\n if (!fields) return `${node.type}|${flags}`\n\n const record = node as unknown as Record<string, unknown>\n const parts: Array<string> = [`${node.type}|${flags}`]\n for (const field of fields) {\n parts.push(serializeShapeField(field, node, record))\n }\n return parts.join('|')\n}\n\n/**\n * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so\n * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.\n * Reuse is safe because a signature depends only on content, and nodes are immutable once created.\n */\nconst signatureCache = new WeakMap<SchemaNode, string>()\n\n/**\n * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas\n * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,\n * `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,\n * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`\n * nodes compare by target name, which also terminates on circular shapes.\n *\n * @example Two enums with different descriptions share a signature\n * ```ts\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))\n * ```\n */\nexport function signatureOf(node: SchemaNode): string {\n const cached = signatureCache.get(node)\n if (cached !== undefined) return cached\n const signature = hash('sha256', describeShape(node), 'hex')\n signatureCache.set(node, signature)\n\n return signature\n}\n\n/**\n * Returns `true` when two schema nodes are structurally identical under shape-only equality,\n * meaning they produce the same TypeScript type.\n */\nexport function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {\n return signatureOf(a) === signatureOf(b)\n}\n","import type { Node, OperationNode, SchemaNode } from './nodes/index.ts'\nimport { createSchema } from './nodes/schema.ts'\nimport { signatureOf } from './signature.ts'\nimport { extractRefName } from './utils/index.ts'\nimport { collectLazy, transform } from './visitor.ts'\n\n/**\n * A canonical destination for a deduplicated shape: the shared schema name and\n * the synthetic `$ref` path that points at it.\n */\nexport type DedupeCanonical = {\n /**\n * Canonical schema name every duplicate occurrence refers to.\n */\n name: string\n /**\n * `$ref` path stored on the generated `ref` nodes (for example `#/components/schemas/Status`).\n */\n ref: string\n}\n\n/**\n * The result of {@link buildDedupePlan}: a lookup from structural signature to its\n * canonical target, plus the freshly hoisted definitions that must be added to\n * the schema list.\n */\nexport type DedupePlan = {\n /**\n * Maps a structural signature to the canonical schema that represents it.\n */\n canonicalBySignature: Map<string, DedupeCanonical>\n /**\n * Maps the name of a top-level schema that duplicates a canonical one to that canonical, so\n * references to the duplicate can be repointed at the first schema with the same content.\n */\n aliasNames: Map<string, DedupeCanonical>\n /**\n * New top-level schema definitions created for inline shapes that had no existing\n * named component. Nested duplicates inside each definition are already collapsed.\n */\n hoisted: Array<SchemaNode>\n}\n\n/**\n * The lookups {@link applyDedupe} needs from a {@link DedupePlan}.\n */\nexport type DedupeLookups = Pick<DedupePlan, 'canonicalBySignature' | 'aliasNames'>\n\n/**\n * Options that inject the naming and candidate policy into {@link buildDedupePlan}.\n * The mechanics (grouping, counting, rewriting) live here. The policy lives in the caller.\n */\nexport type BuildDedupePlanOptions = {\n /**\n * Returns `true` when a node should be deduplicated. This is the only gate, so it must\n * reject both ineligible kinds (return `false` for anything other than, say, enums and\n * objects) and unsafe shapes (e.g. nodes that reference a circular schema).\n */\n isCandidate: (node: SchemaNode) => boolean\n /**\n * Produces the canonical name for an inline shape with no existing named component.\n * Return `null` to leave the shape inline (for example when no contextual name exists).\n */\n nameFor: (node: SchemaNode, signature: string) => string | null\n /**\n * Builds the `$ref` path for a canonical name.\n */\n refFor: (name: string) => string\n /**\n * Minimum number of occurrences before a shape is deduplicated.\n *\n * @default 2\n */\n minOccurrences?: number\n}\n\n/**\n * Builds the shared `ref` replacement for a duplicate occurrence, carrying the\n * usage-slot and documentation fields that are not part of the canonical type.\n */\nfunction createRefNode(node: SchemaNode, canonical: DedupeCanonical): SchemaNode {\n return createSchema({\n type: 'ref',\n name: canonical.name,\n ref: canonical.ref,\n optional: node.optional,\n nullish: node.nullish,\n readOnly: node.readOnly,\n writeOnly: node.writeOnly,\n deprecated: node.deprecated,\n description: node.description,\n default: node.default,\n example: node.example,\n })\n}\n\n/**\n * Rewrites a node, replacing every candidate sub-schema whose signature has a canonical\n * target with a `ref` to that target. Replacing a node with a `ref` prunes its subtree,\n * so nested duplicates inside a replaced shape are not visited again. A `ref` that points\n * at a duplicate top-level schema (see `aliasNames`) is repointed at the first schema with\n * the same content.\n *\n * Pass `skipRootMatch` when rewriting a canonical definition so its own root is not\n * turned into a reference to itself. Nested duplicates are still collapsed.\n *\n * @example\n * ```ts\n * const next = applyDedupe(operationNode, plan)\n * ```\n */\nexport function applyDedupe(node: SchemaNode, plan: DedupeLookups, skipRootMatch?: boolean): SchemaNode\nexport function applyDedupe(node: OperationNode, plan: DedupeLookups, skipRootMatch?: boolean): OperationNode\nexport function applyDedupe(node: Node, plan: DedupeLookups, skipRootMatch = false): Node {\n const { canonicalBySignature, aliasNames } = plan\n if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node\n\n const root = node\n\n return transform(node, {\n schema(schemaNode) {\n if (schemaNode.type === 'ref') {\n const target = schemaNode.ref ? extractRefName(schemaNode.ref) : schemaNode.name\n const canonical = target ? aliasNames.get(target) : undefined\n\n return canonical ? { ...schemaNode, name: canonical.name, ref: canonical.ref } : undefined\n }\n\n const signature = signatureOf(schemaNode)\n if (skipRootMatch && schemaNode === root) return undefined\n\n const canonical = canonicalBySignature.get(signature)\n if (!canonical) return undefined\n\n return createRefNode(schemaNode, canonical)\n },\n })\n}\n\n/**\n * Strips usage-slot flags from a hoisted definition and applies its canonical name.\n * A standalone definition is never optional, so `optional`/`nullish` are cleared.\n */\nfunction cleanDefinition(node: SchemaNode, name: string): SchemaNode {\n return { ...node, name, optional: undefined, nullish: undefined }\n}\n\n/**\n * Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.\n *\n * A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence\n * is a named top-level schema, the first one becomes the canonical (so other top-level\n * duplicates and inline copies turn into references to it). Every other top-level name with\n * the same content is recorded in `aliasNames`, so refs to it can be repointed at the\n * canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied\n * per node with {@link applyDedupe}.\n *\n * @example\n * ```ts\n * const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {\n * isCandidate: (node) => node.type === 'enum' || node.type === 'object',\n * nameFor: (node) => node.name ?? null,\n * refFor: (name) => `#/components/schemas/${name}`,\n * })\n * ```\n */\nexport function buildDedupePlan(roots: ReadonlyArray<Node>, options: BuildDedupePlanOptions): DedupePlan {\n const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options\n\n const topLevelNodes = new Set<SchemaNode>()\n\n type Group = {\n count: number\n representative: SchemaNode\n topLevelNames: Array<string>\n }\n const groups = new Map<string, Group>()\n\n function record(schemaNode: SchemaNode): void {\n if (!isCandidate(schemaNode)) return\n const signature = signatureOf(schemaNode)\n\n const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name\n const group = groups.get(signature)\n if (group) {\n group.count++\n if (isTopLevel) group.topLevelNames.push(schemaNode.name!)\n } else {\n groups.set(signature, { count: 1, representative: schemaNode, topLevelNames: isTopLevel ? [schemaNode.name!] : [] })\n }\n }\n\n for (const root of roots) {\n if (root.kind === 'Schema') topLevelNodes.add(root)\n for (const schemaNode of collectLazy<SchemaNode>(root, { schema: (node) => node })) {\n record(schemaNode)\n }\n }\n\n const canonicalBySignature = new Map<string, DedupeCanonical>()\n const aliasNames = new Map<string, DedupeCanonical>()\n const pendingHoists: Array<{ name: string; representative: SchemaNode }> = []\n\n for (const [signature, group] of groups) {\n if (group.count < minOccurrences) continue\n\n const [firstName, ...duplicateNames] = group.topLevelNames\n if (firstName) {\n const canonical: DedupeCanonical = { name: firstName, ref: refFor(firstName) }\n canonicalBySignature.set(signature, canonical)\n for (const duplicate of duplicateNames) {\n aliasNames.set(duplicate, canonical)\n }\n continue\n }\n\n const name = nameFor(group.representative, signature)\n if (!name) continue\n\n canonicalBySignature.set(signature, { name, ref: refFor(name) })\n pendingHoists.push({ name, representative: group.representative })\n }\n\n // Build hoisted definitions only after every canonical name is known, so nested\n // duplicates inside a definition also resolve to refs.\n const hoisted = pendingHoists.map(({ name, representative }) =>\n cleanDefinition(applyDedupe(representative, { canonicalBySignature, aliasNames }, true), name),\n )\n\n return { canonicalBySignature, aliasNames, hoisted }\n}\n","import type { SchemaNode } from './nodes/index.ts'\n\n/**\n * The spec-specific questions a schema parser answers while turning a source document into Kubb\n * AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where\n * OpenAPI, AsyncAPI, and plain JSON Schema differ.\n */\nexport type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Whether the schema is nullable.\n */\n isNullable(schema?: TSchema): boolean\n /**\n * Whether the value is a `$ref` pointer.\n */\n isReference(value?: unknown): value is TRef\n /**\n * Whether the schema carries a discriminator for polymorphism.\n */\n isDiscriminator(value?: unknown): value is TDiscriminated\n /**\n * Whether the schema is binary data, converted to a `blob` node.\n */\n isBinary(schema: TSchema): boolean\n /**\n * Resolves a local `$ref` against the document, or nullish when it cannot.\n */\n resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined\n /**\n * Derives a schema's `optional`/`nullish` flags from a parent's `required` value and the\n * schema's own `nullable`. How \"required\" and \"nullable\" combine is spec-specific, so the\n * dialect owns it. Method syntax keeps a concrete dialect assignable to the base\n * `SchemaDialect` (bivariant parameters).\n */\n optionality(schema: SchemaNode, required: boolean): SchemaNode\n}\n\n/**\n * A spec adapter's dialect. `name` identifies it in logs and diagnostics; `schema` holds the\n * spec-specific schema questions the parser answers.\n */\nexport type Dialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Identifies the dialect in logs and diagnostics.\n */\n name: string\n /**\n * The spec-specific schema behavior. See {@link SchemaDialect}.\n */\n schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>\n}\n\n/**\n * Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the\n * dialect's type for inference.\n *\n * @example\n * ```ts\n * export const oasDialect = defineDialect({\n * name: 'oas',\n * schema: {\n * isNullable,\n * isReference,\n * isDiscriminator,\n * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n * resolveRef,\n * optionality,\n * },\n * })\n * ```\n */\nexport function defineDialect<TSchema, TRef, TDiscriminated, TDocument>(\n dialect: Dialect<TSchema, TRef, TDiscriminated, TDocument>,\n): Dialect<TSchema, TRef, TDiscriminated, TDocument> {\n return dialect\n}\n","import type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/index.ts'\n\n/**\n * Runtime context passed as `this` to printer handlers.\n *\n * `this.transform` dispatches to node-level handlers from `nodes`.\n *\n * @example\n * ```ts\n * const context: PrinterHandlerContext<string, {}> = {\n * options: {},\n * transform: () => 'value',\n * }\n * ```\n */\ntype PrinterHandlerContext<TOutput, TOptions extends object> = {\n /**\n * Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.\n * Use `this.transform` inside `nodes` handlers and inside the `print` override.\n */\n transform: (node: SchemaNode) => TOutput | null\n /**\n * Options for this printer instance.\n */\n options: TOptions\n}\n\n/**\n * Handler for one schema node type.\n *\n * Use a regular function (not an arrow function) if you need `this`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'string'> = function () {\n * return 'string'\n * }\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n) => TOutput | null\n\n/**\n * Partial map of per-node-type handler overrides for a printer.\n *\n * Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).\n * Supply only the handlers you want to replace. The printer's built-in\n * defaults fill in the rest.\n *\n * @example\n * ```ts\n * pluginZod({\n * printer: {\n * nodes: {\n * date(): string {\n * return 'z.string().date()'\n * },\n * } satisfies PrinterPartial<string, PrinterZodOptions>,\n * },\n * })\n * ```\n */\nexport type PrinterPartial<TOutput, TOptions extends object> = Partial<{\n [K in SchemaType]: PrinterHandler<TOutput, TOptions, K>\n}>\n\n/**\n * Generic shape used by `definePrinter`.\n *\n * - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)\n * - `TOptions` options passed to and stored on the printer instance\n * - `TOutput` the type emitted by node handlers\n * - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)\n *\n * @example\n * ```ts\n * type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>\n * ```\n */\nexport type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {\n name: TName\n options: TOptions\n output: TOutput\n printOutput: TPrintOutput\n}\n\n/**\n * Printer instance returned by a printer factory.\n *\n * @example\n * ```ts\n * const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})\n * ```\n */\nexport type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {\n /**\n * Unique identifier supplied at creation time.\n */\n name: T['name']\n /**\n * Options for this printer instance.\n */\n options: T['options']\n /**\n * Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.\n * Always dispatches through the `nodes` map. Never calls the `print` override.\n * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.\n */\n transform: (node: SchemaNode) => T['output'] | null\n /**\n * Public printer. If the builder provides a root-level `print`, this calls that\n * higher-level function (which may produce full declarations).\n * Otherwise, falls back to the node-level dispatcher.\n */\n print: (node: SchemaNode) => T['printOutput'] | null\n}\n\n/**\n * Builder function passed to `definePrinter`.\n *\n * It receives resolved options and returns:\n * - `name`\n * - `options`\n * - `nodes` handlers\n * - optional top-level `print` override\n *\n * @example\n * ```ts\n * const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })\n * ```\n */\ntype PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {\n name: T['name']\n /**\n * Options to store on the printer.\n */\n options: T['options']\n nodes: Partial<{\n [K in SchemaType]: PrinterHandler<T['output'], T['options'], K>\n }>\n /**\n * Optional root-level print override. When provided, becomes the public `printer.print`.\n * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),\n * not the override itself, so recursion is safe.\n */\n print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null\n}\n/**\n * Defines a schema printer: a function that takes a `SchemaNode` and emits\n * code in your target language. Each plugin that produces code from schemas\n * (TypeScript types, Zod schemas, Faker factories) ships a printer built\n * with this helper.\n *\n * The builder receives resolved options and returns:\n *\n * - `name` unique identifier for the printer.\n * - `options` stored on the returned printer instance.\n * - `nodes` map of `SchemaType` → handler. Handlers return the rendered\n * output (a string, a TypeScript AST node, ...) for that schema type.\n * - `print` (optional), top-level override exposed as `printer.print`.\n * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.\n *\n * Without a `print` override, `printer.print` falls back to `printer.transform`\n * (the node-level dispatcher).\n *\n * @example Tiny Zod printer\n * ```ts\n * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'\n *\n * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = definePrinter<PrinterZod>((options) => ({\n * name: 'zod',\n * options: { strict: options.strict ?? true },\n * nodes: {\n * string: () => 'z.string()',\n * object(node) {\n * const props = node.properties\n * .map((p) => `${p.name}: ${this.transform(p.schema)}`)\n * .join(', ')\n * return `z.object({ ${props} })`\n * },\n * },\n * }))\n * ```\n */\nexport function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return createPrinterFactory<SchemaNode, SchemaType, SchemaNodeByType>((node) => node.type)(build) as (options?: T['options']) => Printer<T>\n}\n\n/**\n * Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.\n *\n * @example\n * ```ts\n * export const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(\n * (node) => node.kind,\n * )\n * ```\n */\nexport function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {\n return function <T extends PrinterFactoryOptions>(\n build: (options: T['options']) => {\n name: T['name']\n options: T['options']\n nodes: Partial<{\n [K in TKey]: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNodeByKey[K],\n ) => T['output'] | null\n }>\n print?: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNode,\n ) => T['printOutput'] | null\n },\n ): (options?: T['options']) => {\n name: T['name']\n options: T['options']\n transform: (node: TNode) => T['output'] | null\n print: (node: TNode) => T['printOutput'] | null\n } {\n return (options) => {\n const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))\n\n const context = {\n options: resolvedOptions,\n transform: (node: TNode): T['output'] | null => {\n const key = getKey(node)\n if (key === null) return null\n\n const handler = nodes[key]\n\n if (!handler) return null\n\n return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)\n },\n }\n\n return {\n name,\n options: resolvedOptions,\n transform: context.transform,\n print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAOA,SAAS,gBAAgB,MAA0B;CACjD,OAAO,GAAG,KAAK,aAAa,GAAG,GAAG,KAAK,UAAU,GAAG,GAAG,KAAK,WAAW,IAAI;AAC7E;AAEA,SAAS,cAAc,MAAoD;CACzE,IAAI,KAAK,KAAK,OAAO,eAAe,KAAK,GAAG;CAC5C,OAAO,KAAK,QAAQ;AACtB;AAuBA,MAAM,mBAA8C;CAClD;EAAE,MAAM;EAAY,KAAK;EAAS,QAAQ;CAAI;CAC9C;EAAE,MAAM;EAAS,KAAK;EAAQ,QAAQ;CAAI;CAC1C;EAAE,MAAM;EAAU,KAAK;EAAO,QAAQ;CAAK;CAC3C;EAAE,MAAM;EAAU,KAAK;EAAO,QAAQ;CAAK;CAC3C;EAAE,MAAM;EAAQ,KAAK;EAAU,QAAQ;CAAI;AAC7C;AAEA,MAAM,gBAA2C;CAC/C;EAAE,MAAM;EAAU,KAAK;EAAO,QAAQ;CAAK;CAC3C;EAAE,MAAM;EAAU,KAAK;EAAO,QAAQ;CAAK;CAC3C;EAAE,MAAM;EAAU,KAAK;EAAoB,QAAQ;CAAM;CACzD;EAAE,MAAM;EAAU,KAAK;EAAoB,QAAQ;CAAM;CACzD;EAAE,MAAM;EAAU,KAAK;EAAc,QAAQ;CAAK;AACpD;AAEA,MAAM,cAAyC,CAC7C;CAAE,MAAM;CAAU,KAAK;CAAO,QAAQ;AAAK,GAC3C;CAAE,MAAM;CAAU,KAAK;CAA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MAAM,SAAS,iBAAiB,OAAO,OAAO,kBAAkB,MAAM,WAAY,CAAC,CAAkB;GAE7G,MAAM,UAAU;IACd,SAAS;IACT,YAAY,SAAoC;KAC9C,MAAM,MAAM,OAAO,IAAI;KACvB,IAAI,QAAQ,MAAM,OAAO;KAEzB,MAAM,UAAU,MAAM;KAEtB,IAAI,CAAC,SAAS,OAAO;KAErB,OAAQ,QAAsE,KAAK,SAAS,IAAI;IAClG;GACF;GAEA,OAAO;IACL;IACA,SAAS;IACT,WAAW,QAAQ;IACnB,OAAQ,gBAAgB,cAAc,KAAK,OAAO,IAAI,QAAQ;GAChE;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["obj"],"sources":["../src/dialect.ts","../src/definePrinter.ts","../src/signature.ts"],"sourcesContent":["import type { Node } from './nodes/index.ts'\n\n/**\n * The spec-specific questions a schema parser answers while turning a source document into Kubb\n * AST nodes. The rest of the pipeline is generic JSON Schema, so this is the one seam where\n * OpenAPI, AsyncAPI, and plain JSON Schema differ.\n */\nexport type SchemaDialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown> = {\n /**\n * Whether the schema is nullable.\n */\n isNullable(schema?: TSchema): boolean\n /**\n * Whether the value is a `$ref` pointer.\n */\n isReference(value?: unknown): value is TRef\n /**\n * Whether the schema carries a discriminator for polymorphism.\n */\n isDiscriminator(value?: unknown): value is TDiscriminated\n /**\n * Whether the schema is binary data, converted to a `blob` node.\n */\n isBinary(schema: TSchema): boolean\n /**\n * Resolves a local `$ref` against the document, or nullish when it cannot.\n */\n resolveRef<TResolved>(document: TDocument, ref: string): TResolved | null | undefined\n}\n\n/**\n * How a dialect collapses structurally identical schemas into shared definitions. The contract is\n * generic over the plan and context types, which the adapter supplies. The mechanics live in the\n * adapter, not here, so `@kubb/ast` carries no dedupe logic. The returned plan owns the rewriting\n * behavior, so callers interact with one object.\n */\nexport type Dedupe<TPlan = unknown, TContext = unknown> = {\n /**\n * Scans a forest of nodes and produces a plan describing which shapes to share.\n */\n plan(roots: ReadonlyArray<Node>, context: TContext): TPlan\n}\n\n/**\n * A spec adapter's dialect. `name` identifies it in logs and diagnostics, `schema` holds the\n * spec-specific schema questions the parser answers, and `dedupe` is the schema-sharing seam.\n */\nexport type Dialect<TSchema = unknown, TRef = TSchema, TDiscriminated = TSchema, TDocument = unknown, TDedupe extends Dedupe = Dedupe> = {\n /**\n * Identifies the dialect in logs and diagnostics.\n */\n name: string\n /**\n * The spec-specific schema behavior. See {@link SchemaDialect}.\n */\n schema: SchemaDialect<TSchema, TRef, TDiscriminated, TDocument>\n /**\n * The schema-sharing behavior. See {@link Dedupe}.\n */\n dedupe: TDedupe\n}\n\n/**\n * Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the\n * dialect's type for inference.\n *\n * @example\n * ```ts\n * export const oasDialect = defineDialect({\n * name: 'oas',\n * schema: {\n * isNullable,\n * isReference,\n * isDiscriminator,\n * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n * resolveRef,\n * },\n * dedupe: { plan },\n * })\n * ```\n */\nexport function defineDialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe extends Dedupe>(\n dialect: Dialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe>,\n): Dialect<TSchema, TRef, TDiscriminated, TDocument, TDedupe> {\n return dialect\n}\n","import type { SchemaNode, SchemaNodeByType, SchemaType } from './nodes/index.ts'\n\n/**\n * Runtime context passed as `this` to printer handlers.\n *\n * `this.transform` dispatches to node-level handlers from `nodes`.\n *\n * @example\n * ```ts\n * const context: PrinterHandlerContext<string, {}> = {\n * options: {},\n * transform: () => 'value',\n * }\n * ```\n */\ntype PrinterHandlerContext<TOutput, TOptions extends object> = {\n /**\n * Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.\n * Use `this.transform` inside `nodes` handlers and inside the `print` override.\n */\n transform: (node: SchemaNode) => TOutput | null\n /**\n * Options for this printer instance.\n */\n options: TOptions\n}\n\n/**\n * Handler for one schema node type.\n *\n * Use a regular function (not an arrow function) if you need `this`.\n *\n * @example\n * ```ts\n * const handler: PrinterHandler<string, {}, 'string'> = function () {\n * return 'string'\n * }\n * ```\n */\ntype PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (\n this: PrinterHandlerContext<TOutput, TOptions>,\n node: SchemaNodeByType[T],\n) => TOutput | null\n\n/**\n * Partial map of per-node-type handler overrides for a printer.\n *\n * Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).\n * Supply only the handlers you want to replace. The printer's built-in\n * defaults fill in the rest.\n *\n * @example\n * ```ts\n * pluginZod({\n * printer: {\n * nodes: {\n * date(): string {\n * return 'z.string().date()'\n * },\n * } satisfies PrinterPartial<string, PrinterZodOptions>,\n * },\n * })\n * ```\n */\nexport type PrinterPartial<TOutput, TOptions extends object> = Partial<{\n [K in SchemaType]: PrinterHandler<TOutput, TOptions, K>\n}>\n\n/**\n * Generic shape used by `definePrinter`.\n *\n * - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)\n * - `TOptions` options passed to and stored on the printer instance\n * - `TOutput` the type emitted by node handlers\n * - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)\n *\n * @example\n * ```ts\n * type MyPrinter = PrinterFactoryOptions<'my', { strict: boolean }, string>\n * ```\n */\nexport type PrinterFactoryOptions<TName extends string = string, TOptions extends object = object, TOutput = unknown, TPrintOutput = TOutput> = {\n name: TName\n options: TOptions\n output: TOutput\n printOutput: TPrintOutput\n}\n\n/**\n * Printer instance returned by a printer factory.\n *\n * @example\n * ```ts\n * const printer = definePrinter((options: {}) => ({ name: 'x', options, nodes: {} }))({})\n * ```\n */\nexport type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {\n /**\n * Unique identifier supplied at creation time.\n */\n name: T['name']\n /**\n * Options for this printer instance.\n */\n options: T['options']\n /**\n * Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.\n * Always dispatches through the `nodes` map. Never calls the `print` override.\n * Reach for it when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.\n */\n transform: (node: SchemaNode) => T['output'] | null\n /**\n * Public printer. If the builder provides a root-level `print`, this calls that\n * higher-level function (which may produce full declarations).\n * Otherwise, falls back to the node-level dispatcher.\n */\n print: (node: SchemaNode) => T['printOutput'] | null\n}\n\n/**\n * Builder function passed to `definePrinter`.\n *\n * It receives resolved options and returns:\n * - `name`\n * - `options`\n * - `nodes` handlers\n * - optional top-level `print` override\n *\n * @example\n * ```ts\n * const build = (options: {}) => ({ name: 'x' as const, options, nodes: {} })\n * ```\n */\ntype PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) => {\n name: T['name']\n /**\n * Options to store on the printer.\n */\n options: T['options']\n nodes: Partial<{\n [K in SchemaType]: PrinterHandler<T['output'], T['options'], K>\n }>\n /**\n * Optional root-level print override. When provided, becomes the public `printer.print`.\n * Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),\n * not the override itself, so recursion is safe.\n */\n print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null\n}\n/**\n * Defines a schema printer: a function that takes a `SchemaNode` and emits\n * code in your target language. Each plugin that produces code from schemas\n * (TypeScript types, Zod schemas, Faker factories) ships a printer built\n * with this helper.\n *\n * The builder receives resolved options and returns:\n *\n * - `name` unique identifier for the printer.\n * - `options` stored on the returned printer instance.\n * - `nodes` map of `SchemaType` → handler. Handlers return the rendered\n * output (a string, a TypeScript AST node, ...) for that schema type.\n * - `print` (optional), top-level override exposed as `printer.print`.\n * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.\n *\n * Without a `print` override, `printer.print` falls back to `printer.transform`\n * (the node-level dispatcher).\n *\n * @example Tiny Zod printer\n * ```ts\n * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'\n *\n * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>\n *\n * export const zodPrinter = definePrinter<PrinterZod>((options) => ({\n * name: 'zod',\n * options: { strict: options.strict ?? true },\n * nodes: {\n * string: () => 'z.string()',\n * object(node) {\n * const props = node.properties\n * .map((p) => `${p.name}: ${this.transform(p.schema)}`)\n * .join(', ')\n * return `z.object({ ${props} })`\n * },\n * },\n * }))\n * ```\n */\nexport function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOptions>(build: PrinterBuilder<T>): (options?: T['options']) => Printer<T> {\n return createPrinterFactory<SchemaNode, SchemaType, SchemaNodeByType>((node) => node.type)(build) as (options?: T['options']) => Printer<T>\n}\n\n/**\n * Generic printer factory behind `definePrinter`. Pass a `getKey` function that maps a node to its\n * handler key, and it returns a `definePrinter`-style helper for that node and key type. `definePrinter`\n * itself is this factory keyed by `node.type`.\n *\n * @example Key a printer by `node.kind` instead of `node.type`\n * ```ts\n * const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(\n * (node) => node.kind,\n * )\n * ```\n */\nexport function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {\n return function <T extends PrinterFactoryOptions>(\n build: (options: T['options']) => {\n name: T['name']\n options: T['options']\n nodes: Partial<{\n [K in TKey]: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNodeByKey[K],\n ) => T['output'] | null\n }>\n print?: (\n this: {\n transform: (node: TNode) => T['output'] | null\n options: T['options']\n },\n node: TNode,\n ) => T['printOutput'] | null\n },\n ): (options?: T['options']) => {\n name: T['name']\n options: T['options']\n transform: (node: TNode) => T['output'] | null\n print: (node: TNode) => T['printOutput'] | null\n } {\n return (options) => {\n const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))\n\n const context = {\n options: resolvedOptions,\n transform: (node: TNode): T['output'] | null => {\n const key = getKey(node)\n if (key === null) return null\n\n const handler = nodes[key]\n\n if (!handler) return null\n\n return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)\n },\n }\n\n return {\n name,\n options: resolvedOptions,\n transform: context.transform,\n print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,\n }\n }\n }\n}\n","import { hash } from 'node:crypto'\nimport type { SchemaNode } from './nodes/index.ts'\nimport { extractRefName } from './utils/index.ts'\n\n/**\n * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.\n */\nfunction flagsDescriptor(node: SchemaNode): string {\n return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`\n}\n\nfunction refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {\n if (node.ref) return extractRefName(node.ref)\n return node.name ?? ''\n}\n\ntype ScalarField = { kind: 'scalar'; key: string; prefix: string }\ntype BoolField = { kind: 'bool'; key: string; prefix: string }\ntype ChildField = { kind: 'child'; key: string; prefix: string }\ntype ChildrenField = { kind: 'children'; key: string; prefix: string }\ntype ObjectPropsField = { kind: 'objectProps' }\ntype AdditionalPropsField = { kind: 'additionalProps' }\ntype PatternPropsField = { kind: 'patternProps' }\ntype EnumValuesField = { kind: 'enumValues' }\ntype RefTargetField = { kind: 'refTarget' }\n\ntype ShapeField =\n | ScalarField\n | BoolField\n | ChildField\n | ChildrenField\n | ObjectPropsField\n | AdditionalPropsField\n | PatternPropsField\n | EnumValuesField\n | RefTargetField\n\nconst arrayTupleFields: ReadonlyArray<ShapeField> = [\n { kind: 'children', key: 'items', prefix: 'i' },\n { kind: 'child', key: 'rest', prefix: 'r' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'bool', key: 'unique', prefix: 'u' },\n]\n\nconst numericFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },\n { kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },\n { kind: 'scalar', key: 'multipleOf', prefix: 'mo' },\n]\n\nconst rangeFields: ReadonlyArray<ShapeField> = [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n]\n\n/**\n * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map\n * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.\n */\nconst SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {\n object: [\n { kind: 'objectProps' },\n { kind: 'additionalProps' },\n { kind: 'patternProps' },\n { kind: 'scalar', key: 'minProperties', prefix: 'mn' },\n { kind: 'scalar', key: 'maxProperties', prefix: 'mx' },\n ],\n array: arrayTupleFields,\n tuple: arrayTupleFields,\n union: [\n { kind: 'scalar', key: 'strategy', prefix: 's' },\n { kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },\n { kind: 'children', key: 'members', prefix: 'm' },\n ],\n intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],\n enum: [{ kind: 'enumValues' }],\n ref: [{ kind: 'refTarget' }],\n string: [\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n { kind: 'scalar', key: 'pattern', prefix: 'pt' },\n ],\n number: numericFields,\n integer: numericFields,\n bigint: numericFields,\n url: [\n { kind: 'scalar', key: 'path', prefix: 'path' },\n { kind: 'scalar', key: 'min', prefix: 'mn' },\n { kind: 'scalar', key: 'max', prefix: 'mx' },\n ],\n uuid: rangeFields,\n email: rangeFields,\n datetime: [\n { kind: 'bool', key: 'offset', prefix: 'o' },\n { kind: 'bool', key: 'local', prefix: 'l' },\n ],\n date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],\n}\n\nfunction serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {\n switch (field.kind) {\n case 'scalar':\n return `${field.prefix}:${record[field.key] ?? ''}`\n case 'bool':\n return `${field.prefix}:${record[field.key] ? 1 : 0}`\n case 'child': {\n const child = record[field.key] as SchemaNode | undefined\n return `${field.prefix}:${child ? signatureOf(child) : ''}`\n }\n case 'children': {\n const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []\n return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`\n }\n case 'objectProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')\n return `p[${props}]`\n }\n case 'additionalProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`\n if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`\n return ''\n }\n case 'patternProps': {\n const obj = node as Extract<SchemaNode, { type: 'object' }>\n const pattern = obj.patternProperties\n ? Object.keys(obj.patternProperties)\n .sort()\n .map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)\n .join(',')\n : ''\n return `pp[${pattern}]`\n }\n case 'enumValues': {\n const en = node as Extract<SchemaNode, { type: 'enum' }>\n let values = ''\n if (en.namedEnumValues?.length) {\n values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')\n } else if (en.enumValues?.length) {\n values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')\n }\n return `v[${values}]`\n }\n case 'refTarget': {\n return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`\n }\n }\n}\n\n/**\n * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,\n * constraints, and its children's signatures.\n */\nfunction describeShape(node: SchemaNode): string {\n const flags = flagsDescriptor(node)\n const fields = SHAPE_KEYS[node.type]\n if (!fields) return `${node.type}|${flags}`\n\n const record = node as unknown as Record<string, unknown>\n const parts: Array<string> = [`${node.type}|${flags}`]\n for (const field of fields) {\n parts.push(serializeShapeField(field, node, record))\n }\n return parts.join('|')\n}\n\n/**\n * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so\n * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.\n * Reuse is safe because a signature depends only on content, and nodes are immutable once created.\n */\nconst signatureCache = new WeakMap<SchemaNode, string>()\n\n/**\n * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas\n * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,\n * `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,\n * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`\n * nodes compare by target name, which also terminates on circular shapes.\n *\n * @example Two enums with different descriptions share a signature\n * ```ts\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===\n * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))\n * ```\n */\nexport function signatureOf(node: SchemaNode): string {\n const cached = signatureCache.get(node)\n if (cached !== undefined) return cached\n const signature = hash('sha256', describeShape(node), 'hex')\n signatureCache.set(node, signature)\n\n return signature\n}\n\n/**\n * Returns `true` when two schema nodes are structurally identical under shape-only equality,\n * meaning they produce the same TypeScript type.\n */\nexport function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {\n return signatureOf(a) === signatureOf(b)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,cACd,SAC4D;CAC5D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuGA,SAAgB,cAAuE,OAAkE;CACvJ,OAAO,sBAAgE,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK;AAClG;;;;;;;;;;;;;AAcA,SAAgB,qBAAkG,QAAsC;CACtJ,OAAO,SACL,OAyBA;EACA,QAAQ,YAAY;GAClB,MAAM,EAAE,MAAM,SAAS,iBAAiB,OAAO,OAAO,kBAAkB,MAAM,WAAY,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AU,GAAG,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;QACzG,IAAI,GAAG,YAAY,QACxB,SAAS,GAAG,WAAW,KAAK,UAAU,GAAG,UAAU,OAAO,SAAS,OAAO,MAAM,GAAG,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;GAE9G,OAAO,KAAK,OAAO;EACrB;EACA,KAAK,aACH,OAAO,KAAK,cAAc,IAA4C;CAE1E;AACF;;;;;AAMA,SAAS,cAAc,MAA0B;CAC/C,MAAM,QAAQ,gBAAgB,IAAI;CAClC,MAAM,SAAS,WAAW,KAAK;CAC/B,IAAI,CAAC,QAAQ,OAAO,GAAG,KAAK,KAAK,GAAG;CAEpC,MAAM,SAAS;CACf,MAAM,QAAuB,CAAC,GAAG,KAAK,KAAK,GAAG,OAAO;CACrD,KAAK,MAAM,SAAS,QAClB,MAAM,KAAK,oBAAoB,OAAO,MAAM,MAAM,CAAC;CAErD,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;AAOA,MAAM,iCAAiB,IAAI,QAA4B;;;;;;;;;;;;;;AAevD,SAAgB,YAAY,MAA0B;CACpD,MAAM,SAAS,eAAe,IAAI,IAAI;CACtC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,YAAY,KAAK,UAAU,cAAc,IAAI,GAAG,KAAK;CAC3D,eAAe,IAAI,MAAM,SAAS;CAElC,OAAO;AACT"}
package/dist/macros.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_response = require("./response-BeG6hq2D.cjs");
3
- const require_visitor = require("./visitor-B7Zlnp4c.cjs");
4
- const require_defineMacro = require("./defineMacro-BryDiuQl.cjs");
2
+ const require_schema = require("./schema-BkvrrOAr.cjs");
3
+ const require_refs = require("./refs-u5SDdyV7.cjs");
4
+ const require_defineMacro = require("./defineMacro-CEZHaCXE.cjs");
5
5
  //#region src/macros/macroDiscriminatorEnum.ts
6
6
  /**
7
7
  * Builds a macro that replaces a discriminator property's schema with a string enum of the given
@@ -17,16 +17,16 @@ function macroDiscriminatorEnum({ propertyName, values, enumName }) {
17
17
  return require_defineMacro.defineMacro({
18
18
  name: "discriminator-enum",
19
19
  schema(node) {
20
- const objectNode = require_visitor.narrowSchema(node, "object");
20
+ const objectNode = require_refs.narrowSchema(node, "object");
21
21
  if (!objectNode?.properties?.length) return void 0;
22
22
  if (!objectNode.properties.some((prop) => prop.name === propertyName)) return void 0;
23
- return require_response.createSchema({
23
+ return require_schema.createSchema({
24
24
  ...objectNode,
25
25
  properties: objectNode.properties.map((prop) => {
26
26
  if (prop.name !== propertyName) return prop;
27
- return require_response.createProperty({
27
+ return require_schema.createProperty({
28
28
  ...prop,
29
- schema: require_response.createSchema({
29
+ schema: require_schema.createSchema({
30
30
  type: "enum",
31
31
  primitive: "string",
32
32
  enumValues: values,
@@ -44,7 +44,7 @@ function macroDiscriminatorEnum({ propertyName, values, enumName }) {
44
44
  //#region src/macros/macroEnumName.ts
45
45
  /**
46
46
  * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
47
- * are left anonymous; non-enum nodes are returned unchanged.
47
+ * are left anonymous. Non-enum nodes are returned unchanged.
48
48
  *
49
49
  * @example
50
50
  * ```ts
@@ -56,14 +56,14 @@ function macroEnumName({ parentName, propName, enumSuffix }) {
56
56
  return require_defineMacro.defineMacro({
57
57
  name: "enum-name",
58
58
  schema(node) {
59
- const enumNode = require_visitor.narrowSchema(node, "enum");
59
+ const enumNode = require_refs.narrowSchema(node, "enum");
60
60
  if (enumNode?.primitive === "boolean") return {
61
61
  ...node,
62
62
  name: null
63
63
  };
64
64
  if (enumNode) return {
65
65
  ...node,
66
- name: require_visitor.enumPropName(parentName, propName, enumSuffix)
66
+ name: require_refs.enumPropName(parentName, propName, enumSuffix)
67
67
  };
68
68
  }
69
69
  });
@@ -90,7 +90,7 @@ function simplifyUnionMembers(members) {
90
90
  const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
91
91
  if (!scalarPrimitives.size) return members;
92
92
  return members.filter((member) => {
93
- const enumNode = require_visitor.narrowSchema(member, "enum");
93
+ const enumNode = require_refs.narrowSchema(member, "enum");
94
94
  if (!enumNode) return true;
95
95
  const primitive = enumNode.primitive;
96
96
  if (!primitive) return true;
@@ -112,7 +112,7 @@ function simplifyUnionMembers(members) {
112
112
  const macroSimplifyUnion = require_defineMacro.defineMacro({
113
113
  name: "simplify-union",
114
114
  schema(node) {
115
- const unionNode = require_visitor.narrowSchema(node, "union");
115
+ const unionNode = require_refs.narrowSchema(node, "union");
116
116
  if (!unionNode?.members?.length) return void 0;
117
117
  const simplified = simplifyUnionMembers(unionNode.members);
118
118
  if (simplified.length === unionNode.members.length) return void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"macros.cjs","names":["defineMacro","narrowSchema","createSchema","createProperty","defineMacro","narrowSchema","enumPropName","narrowSchema","defineMacro"],"sources":["../src/macros/macroDiscriminatorEnum.ts","../src/macros/macroEnumName.ts","../src/macros/macroSimplifyUnion.ts"],"sourcesContent":["import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { createProperty } from '../nodes/property.ts'\nimport { createSchema } from '../nodes/schema.ts'\n\ntype Props = {\n propertyName: string\n values: Array<string>\n enumName?: string\n}\n\n/**\n * Builds a macro that replaces a discriminator property's schema with a string enum of the given\n * values. Object schemas that lack the property are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })\n * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroDiscriminatorEnum({ propertyName, values, enumName }: Props) {\n return defineMacro({\n name: 'discriminator-enum',\n schema(node) {\n const objectNode = narrowSchema(node, 'object')\n if (!objectNode?.properties?.length) return undefined\n if (!objectNode.properties.some((prop) => prop.name === propertyName)) return undefined\n\n return createSchema({\n ...objectNode,\n properties: objectNode.properties.map((prop) => {\n if (prop.name !== propertyName) return prop\n\n return createProperty({\n ...prop,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: values,\n name: enumName,\n readOnly: prop.schema.readOnly,\n writeOnly: prop.schema.writeOnly,\n }),\n })\n }),\n })\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { enumPropName } from '../utils/refs.ts'\n\ntype Props = {\n parentName: string | null | undefined\n propName: string\n enumSuffix: string\n}\n\n/**\n * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums\n * are left anonymous; non-enum nodes are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })\n * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroEnumName({ parentName, propName, enumSuffix }: Props) {\n return defineMacro({\n name: 'enum-name',\n schema(node) {\n const enumNode = narrowSchema(node, 'enum')\n\n if (enumNode?.primitive === 'boolean') return { ...node, name: null }\n if (enumNode) return { ...node, name: enumPropName(parentName, propName, enumSuffix) }\n\n return undefined\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport type { SchemaNode } from '../nodes/schema.ts'\n\ntype ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'boolean'\n\n/**\n * Scalar primitive schema types used for union simplification and type narrowing.\n */\nconst SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])\n\nfunction isScalarPrimitive(type: string): type is ScalarPrimitive {\n return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)\n}\n\n/**\n * Filters union members, dropping enum members that a broader scalar primitive already covers.\n */\nfunction simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {\n const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type))\n if (!scalarPrimitives.size) return members\n\n return members.filter((member) => {\n const enumNode = narrowSchema(member, 'enum')\n if (!enumNode) return true\n\n const primitive = enumNode.primitive\n if (!primitive) return true\n\n const enumValueCount = enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0\n if (enumValueCount <= 1) return true\n\n if (scalarPrimitives.has(primitive)) return false\n if ((primitive === 'integer' || primitive === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false\n\n return true\n })\n}\n\n/**\n * Removes union members a broader scalar primitive already covers, such as a multi-value string enum\n * sitting next to a plain `string`. Single-value enums are kept.\n *\n * @example\n * ```ts\n * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })\n * ```\n */\nexport const macroSimplifyUnion = defineMacro({\n name: 'simplify-union',\n schema(node) {\n const unionNode = narrowSchema(node, 'union')\n if (!unionNode?.members?.length) return undefined\n\n const simplified = simplifyUnionMembers(unionNode.members)\n if (simplified.length === unionNode.members.length) return undefined\n\n return { ...unionNode, members: simplified }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,EAAE,cAAc,QAAQ,YAAmB;CAChF,OAAOA,oBAAAA,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,aAAaC,gBAAAA,aAAa,MAAM,QAAQ;GAC9C,IAAI,CAAC,YAAY,YAAY,QAAQ,OAAO,KAAA;GAC5C,IAAI,CAAC,WAAW,WAAW,MAAM,SAAS,KAAK,SAAS,YAAY,GAAG,OAAO,KAAA;GAE9E,OAAOC,iBAAAA,aAAa;IAClB,GAAG;IACH,YAAY,WAAW,WAAW,KAAK,SAAS;KAC9C,IAAI,KAAK,SAAS,cAAc,OAAO;KAEvC,OAAOC,iBAAAA,eAAe;MACpB,GAAG;MACH,QAAQD,iBAAAA,aAAa;OACnB,MAAM;OACN,WAAW;OACX,YAAY;OACZ,MAAM;OACN,UAAU,KAAK,OAAO;OACtB,WAAW,KAAK,OAAO;MACzB,CAAC;KACH,CAAC;IACH,CAAC;G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Aa,MAAM,OAAO;EAC5C,IAAI,CAAC,WAAW,SAAS,QAAQ,OAAO,KAAA;EAExC,MAAM,aAAa,qBAAqB,UAAU,OAAO;EACzD,IAAI,WAAW,WAAW,UAAU,QAAQ,QAAQ,OAAO,KAAA;EAE3D,OAAO;GAAE,GAAG;GAAW,SAAS;EAAW;CAC7C;AACF,CAAC"}
1
+ {"version":3,"file":"macros.cjs","names":["defineMacro","narrowSchema","createSchema","createProperty","defineMacro","narrowSchema","enumPropName","narrowSchema","defineMacro"],"sources":["../src/macros/macroDiscriminatorEnum.ts","../src/macros/macroEnumName.ts","../src/macros/macroSimplifyUnion.ts"],"sourcesContent":["import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { createProperty } from '../nodes/property.ts'\nimport { createSchema } from '../nodes/schema.ts'\n\ntype Props = {\n propertyName: string\n values: Array<string>\n enumName?: string\n}\n\n/**\n * Builds a macro that replaces a discriminator property's schema with a string enum of the given\n * values. Object schemas that lack the property are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })\n * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroDiscriminatorEnum({ propertyName, values, enumName }: Props) {\n return defineMacro({\n name: 'discriminator-enum',\n schema(node) {\n const objectNode = narrowSchema(node, 'object')\n if (!objectNode?.properties?.length) return undefined\n if (!objectNode.properties.some((prop) => prop.name === propertyName)) return undefined\n\n return createSchema({\n ...objectNode,\n properties: objectNode.properties.map((prop) => {\n if (prop.name !== propertyName) return prop\n\n return createProperty({\n ...prop,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: values,\n name: enumName,\n readOnly: prop.schema.readOnly,\n writeOnly: prop.schema.writeOnly,\n }),\n })\n }),\n })\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport { enumPropName } from '../utils/refs.ts'\n\ntype Props = {\n parentName: string | null | undefined\n propName: string\n enumSuffix: string\n}\n\n/**\n * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums\n * are left anonymous. Non-enum nodes are returned unchanged.\n *\n * @example\n * ```ts\n * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })\n * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })\n * ```\n */\nexport function macroEnumName({ parentName, propName, enumSuffix }: Props) {\n return defineMacro({\n name: 'enum-name',\n schema(node) {\n const enumNode = narrowSchema(node, 'enum')\n\n if (enumNode?.primitive === 'boolean') return { ...node, name: null }\n if (enumNode) return { ...node, name: enumPropName(parentName, propName, enumSuffix) }\n\n return undefined\n },\n })\n}\n","import { defineMacro } from '../defineMacro.ts'\nimport { narrowSchema } from '../guards.ts'\nimport type { SchemaNode } from '../nodes/schema.ts'\n\ntype ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'boolean'\n\n/**\n * Scalar primitive schema types used for union simplification and type narrowing.\n */\nconst SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])\n\nfunction isScalarPrimitive(type: string): type is ScalarPrimitive {\n return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)\n}\n\n/**\n * Filters union members, dropping enum members that a broader scalar primitive already covers.\n */\nfunction simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {\n const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type))\n if (!scalarPrimitives.size) return members\n\n return members.filter((member) => {\n const enumNode = narrowSchema(member, 'enum')\n if (!enumNode) return true\n\n const primitive = enumNode.primitive\n if (!primitive) return true\n\n const enumValueCount = enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0\n if (enumValueCount <= 1) return true\n\n if (scalarPrimitives.has(primitive)) return false\n if ((primitive === 'integer' || primitive === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false\n\n return true\n })\n}\n\n/**\n * Removes union members a broader scalar primitive already covers, such as a multi-value string enum\n * sitting next to a plain `string`. Single-value enums are kept.\n *\n * @example\n * ```ts\n * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })\n * ```\n */\nexport const macroSimplifyUnion = defineMacro({\n name: 'simplify-union',\n schema(node) {\n const unionNode = narrowSchema(node, 'union')\n if (!unionNode?.members?.length) return undefined\n\n const simplified = simplifyUnionMembers(unionNode.members)\n if (simplified.length === unionNode.members.length) return undefined\n\n return { ...unionNode, members: simplified }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,EAAE,cAAc,QAAQ,YAAmB;CAChF,OAAOA,oBAAAA,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,aAAaC,aAAAA,aAAa,MAAM,QAAQ;GAC9C,IAAI,CAAC,YAAY,YAAY,QAAQ,OAAO,KAAA;GAC5C,IAAI,CAAC,WAAW,WAAW,MAAM,SAAS,KAAK,SAAS,YAAY,GAAG,OAAO,KAAA;GAE9E,OAAOC,eAAAA,aAAa;IAClB,GAAG;IACH,YAAY,WAAW,WAAW,KAAK,SAAS;KAC9C,IAAI,KAAK,SAAS,cAAc,OAAO;KAEvC,OAAOC,eAAAA,eAAe;MACpB,GAAG;MACH,QAAQD,eAAAA,aAAa;OACnB,MAAM;OACN,WAAW;OACX,YAAY;OACZ,MAAM;OACN,UAAU,KAAK,OAAO;OACtB,WAAW,KAAK,OAAO;MACzB,CAAC;KACH,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF,CAAC;AACH;;;;;;;;;;;;;AC7BA,SAAgB,cAAc,EAAE,YAAY,UAAU,cAAqB;CACzE,OAAOE,oBAAAA,YAAY;EACjB,MAAM;EACN,OAAO,MAAM;GACX,MAAM,WAAWC,aAAAA,aAAa,MAAM,MAAM;GAE1C,IAAI,UAAU,cAAc,WAAW,OAAO;IAAE,GAAG;IAAM,MAAM;GAAK;GACpE,IAAI,UA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__name } from "./chunk-CNktS9qV.js";
2
- import { n as Macro } from "./defineMacro-Vw-xQvq7.js";
2
+ import { n as Macro } from "./defineMacro-BATi7xoC.js";
3
3
 
4
4
  //#region src/macros/macroDiscriminatorEnum.d.ts
5
5
  type Props$1 = {
@@ -31,7 +31,7 @@ type Props = {
31
31
  };
32
32
  /**
33
33
  * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
34
- * are left anonymous; non-enum nodes are returned unchanged.
34
+ * are left anonymous. Non-enum nodes are returned unchanged.
35
35
  *
36
36
  * @example
37
37
  * ```ts