@kubb/ast 5.0.0-beta.80 → 5.0.0-beta.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,27 +1,1492 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-CNktS9qV.js";
2
- import { $ as schemaTypes, A as sourceDef, B as createConst, C as createExport, D as exportDef, E as createSource, F as arrowFunctionDef, G as functionDef, H as createJsx, I as breakDef, J as typeDef, K as jsxDef, L as constDef, N as contentDef, O as fileDef, P as createContent, Q as narrowSchema, R as createArrowFunction, S as inputDef, T as createImport, U as createText, V as createFunction, W as createType, Y as defineNode, Z as isHttpOperationNode, _ as createOperation, a as nodeDefs, b as requestBodyDef, c as createResponse, d as propertyDef, f as createParameter, g as outputDef, h as createOutput, i as walk, k as importDef, l as responseDef, m as optionality, o as createSchema, p as parameterDef, q as textDef, r as transform, s as schemaDef, t as collect, u as createProperty, v as operationDef, w as createFile, x as createInput, y as createRequestBody, z as createBreak } from "./visitor-Dk0DNLfC.js";
3
- import { n as composeMacros, r as defineMacro, t as applyMacros } from "./defineMacro-CqX4m8Dq.js";
2
+ import { hash } from "node:crypto";
3
+ import path from "node:path";
4
+ //#region src/constants.ts
5
+ const visitorDepths = {
6
+ shallow: "shallow",
7
+ deep: "deep"
8
+ };
9
+ /**
10
+ * Schema type discriminators used by all AST schema nodes.
11
+ *
12
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
13
+ */
14
+ const schemaTypes = {
15
+ /**
16
+ * Text value.
17
+ */
18
+ string: "string",
19
+ /**
20
+ * Floating-point number (`float`, `double`).
21
+ */
22
+ number: "number",
23
+ /**
24
+ * Whole number (`int32`). Use `bigint` for `int64`.
25
+ */
26
+ integer: "integer",
27
+ /**
28
+ * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
29
+ */
30
+ bigint: "bigint",
31
+ /**
32
+ * Boolean value.
33
+ */
34
+ boolean: "boolean",
35
+ /**
36
+ * Explicit null value.
37
+ */
38
+ null: "null",
39
+ /**
40
+ * Any value (no type restriction).
41
+ */
42
+ any: "any",
43
+ /**
44
+ * Unknown value (must be narrowed before usage).
45
+ */
46
+ unknown: "unknown",
47
+ /**
48
+ * No return value (`void`).
49
+ */
50
+ void: "void",
51
+ /**
52
+ * Object with named properties.
53
+ */
54
+ object: "object",
55
+ /**
56
+ * Sequential list of items.
57
+ */
58
+ array: "array",
59
+ /**
60
+ * Fixed-length list with position-specific items.
61
+ */
62
+ tuple: "tuple",
63
+ /**
64
+ * "One of" multiple schema members.
65
+ */
66
+ union: "union",
67
+ /**
68
+ * "All of" multiple schema members.
69
+ */
70
+ intersection: "intersection",
71
+ /**
72
+ * Enum schema.
73
+ */
74
+ enum: "enum",
75
+ /**
76
+ * Reference to another schema.
77
+ */
78
+ ref: "ref",
79
+ /**
80
+ * Calendar date (for example `2026-03-24`).
81
+ */
82
+ date: "date",
83
+ /**
84
+ * Date-time value (for example `2026-03-24T09:00:00Z`).
85
+ */
86
+ datetime: "datetime",
87
+ /**
88
+ * Time-only value (for example `09:00:00`).
89
+ */
90
+ time: "time",
91
+ /**
92
+ * UUID value.
93
+ */
94
+ uuid: "uuid",
95
+ /**
96
+ * Email address value.
97
+ */
98
+ email: "email",
99
+ /**
100
+ * URL value.
101
+ */
102
+ url: "url",
103
+ /**
104
+ * IPv4 address value.
105
+ */
106
+ ipv4: "ipv4",
107
+ /**
108
+ * IPv6 address value.
109
+ */
110
+ ipv6: "ipv6",
111
+ /**
112
+ * Binary/blob value.
113
+ */
114
+ blob: "blob",
115
+ /**
116
+ * Impossible value (`never`).
117
+ */
118
+ never: "never"
119
+ };
120
+ //#endregion
4
121
  //#region src/defineDialect.ts
5
122
  /**
6
- * Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the
7
- * dialect's type for inference.
123
+ * Types a {@link Dialect} for an adapter. Adds no runtime behavior and only pins the
124
+ * dialect's type for inference.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * export const oasDialect = defineDialect({
129
+ * name: 'oas',
130
+ * schema: {
131
+ * isNullable,
132
+ * isReference,
133
+ * isDiscriminator,
134
+ * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
135
+ * resolveRef,
136
+ * },
137
+ * })
138
+ * ```
139
+ */
140
+ function defineDialect(dialect) {
141
+ return dialect;
142
+ }
143
+ //#endregion
144
+ //#region src/guards.ts
145
+ /**
146
+ * Narrows a `SchemaNode` to the variant that matches `type`.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * const schema = createSchema({ type: 'string' })
151
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
152
+ * ```
153
+ */
154
+ function narrowSchema(node, type) {
155
+ return node?.type === type ? node : null;
156
+ }
157
+ /**
158
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * if (isHttpOperationNode(node)) {
163
+ * console.log(node.method, node.path)
164
+ * }
165
+ * ```
166
+ */
167
+ function isHttpOperationNode(node) {
168
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
169
+ }
170
+ //#endregion
171
+ //#region src/defineNode.ts
172
+ /**
173
+ * Visitor callback names, one per traversable node kind, in traversal order.
174
+ * Kept in sync with the keys of `Visitor` in `visitor.ts`.
175
+ */
176
+ const visitorKeys = [
177
+ "input",
178
+ "output",
179
+ "operation",
180
+ "schema",
181
+ "property",
182
+ "parameter",
183
+ "response"
184
+ ];
185
+ /**
186
+ * Builds a type guard that matches nodes of the given `kind`.
187
+ */
188
+ function isKind(kind) {
189
+ return (node) => node?.kind === kind;
190
+ }
191
+ /**
192
+ * Defines a node once and derives its `create` builder, `is` guard, and traversal
193
+ * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
194
+ * `kind`, so node construction lives in one place without scattered `as` casts.
195
+ *
196
+ * @example Simple node
197
+ * ```ts
198
+ * const importDef = defineNode<ImportNode>({ kind: 'Import' })
199
+ * const createImport = importDef.create
200
+ * ```
201
+ *
202
+ * @example Node with a build hook
203
+ * ```ts
204
+ * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
205
+ * kind: 'Property',
206
+ * build: (props) => ({ ...props, required: props.required ?? false }),
207
+ * children: ['schema'],
208
+ * visitorKey: 'property',
209
+ * })
210
+ * ```
211
+ */
212
+ function defineNode(config) {
213
+ const { kind, defaults, build, children, visitorKey } = config;
214
+ function create(input) {
215
+ const base = build ? build(input) : input;
216
+ const node = {
217
+ kind,
218
+ ...defaults,
219
+ ...base
220
+ };
221
+ node.kind = kind;
222
+ return node;
223
+ }
224
+ return {
225
+ kind,
226
+ create,
227
+ is: isKind(kind),
228
+ children,
229
+ visitorKey
230
+ };
231
+ }
232
+ //#endregion
233
+ //#region src/nodes/code.ts
234
+ /**
235
+ * Definition for the {@link ConstNode}.
236
+ */
237
+ const constDef = defineNode({ kind: "Const" });
238
+ /**
239
+ * Definition for the {@link TypeNode}.
240
+ */
241
+ const typeDef = defineNode({ kind: "Type" });
242
+ /**
243
+ * Definition for the {@link FunctionNode}.
244
+ */
245
+ const functionDef = defineNode({ kind: "Function" });
246
+ /**
247
+ * Definition for the {@link ArrowFunctionNode}.
248
+ */
249
+ const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
250
+ /**
251
+ * Definition for the {@link TextNode}.
252
+ */
253
+ const textDef = defineNode({
254
+ kind: "Text",
255
+ build: (value) => ({ value })
256
+ });
257
+ /**
258
+ * Definition for the {@link BreakNode}.
259
+ */
260
+ const breakDef = defineNode({
261
+ kind: "Break",
262
+ build: () => ({})
263
+ });
264
+ /**
265
+ * Definition for the {@link JsxNode}.
266
+ */
267
+ const jsxDef = defineNode({
268
+ kind: "Jsx",
269
+ build: (value) => ({ value })
270
+ });
271
+ /**
272
+ * Creates a `ConstNode` representing a TypeScript `const` declaration.
273
+ *
274
+ * @example Exported constant with type and `as const`
275
+ * ```ts
276
+ * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
277
+ * // export const pets: Pet[] = ... as const
278
+ * ```
279
+ */
280
+ const createConst = constDef.create;
281
+ /**
282
+ * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
283
+ *
284
+ * @example
285
+ * ```ts
286
+ * createType({ name: 'Pet', export: true })
287
+ * // export type Pet = ...
288
+ * ```
289
+ */
290
+ const createType = typeDef.create;
291
+ /**
292
+ * Creates a `FunctionNode` representing a TypeScript `function` declaration.
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
297
+ * // export async function fetchPet(): Promise<Pet> { ... }
298
+ * ```
299
+ */
300
+ const createFunction = functionDef.create;
301
+ /**
302
+ * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
307
+ * // export const double = (n: number) => ...
308
+ * ```
309
+ */
310
+ const createArrowFunction = arrowFunctionDef.create;
311
+ /**
312
+ * Creates a {@link TextNode} representing a raw string fragment in the source output.
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * createText('return fetch(id)')
317
+ * // { kind: 'Text', value: 'return fetch(id)' }
318
+ * ```
319
+ */
320
+ const createText = textDef.create;
321
+ /**
322
+ * Creates a {@link BreakNode} representing a line break in the source output.
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * createBreak()
327
+ * // { kind: 'Break' }
328
+ * ```
329
+ */
330
+ function createBreak() {
331
+ return breakDef.create();
332
+ }
333
+ /**
334
+ * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
335
+ *
336
+ * @example
337
+ * ```ts
338
+ * createJsx('<>\n <a href={href}>Open</a>\n</>')
339
+ * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
340
+ * ```
341
+ */
342
+ const createJsx = jsxDef.create;
343
+ //#endregion
344
+ //#region src/nodes/content.ts
345
+ /**
346
+ * Definition for the {@link ContentNode}.
347
+ */
348
+ const contentDef = defineNode({
349
+ kind: "Content",
350
+ children: ["schema"]
351
+ });
352
+ /**
353
+ * Creates a `ContentNode` for a single request-body or response content type.
354
+ */
355
+ const createContent = contentDef.create;
356
+ //#endregion
357
+ //#region ../../internals/utils/src/casing.ts
358
+ /**
359
+ * Shared implementation for camelCase and PascalCase conversion.
360
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
361
+ * and capitalizes each word according to `pascal`.
362
+ *
363
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
364
+ */
365
+ function toCamelOrPascal(text, pascal) {
366
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
367
+ if (word.length > 1 && word === word.toUpperCase()) return word;
368
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
369
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
370
+ }
371
+ /**
372
+ * Converts `text` to PascalCase.
373
+ *
374
+ * @example Word boundaries
375
+ * `pascalCase('hello-world') // 'HelloWorld'`
376
+ *
377
+ * @example With a suffix
378
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
379
+ */
380
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
381
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
382
+ }
383
+ //#endregion
384
+ //#region ../../internals/utils/src/fs.ts
385
+ /**
386
+ * Strips the file extension from a path or file name.
387
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
388
+ *
389
+ * @example
390
+ * trimExtName('petStore.ts') // 'petStore'
391
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
392
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
393
+ * trimExtName('noExtension') // 'noExtension'
394
+ */
395
+ function trimExtName(text) {
396
+ const dotIndex = text.lastIndexOf(".");
397
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
398
+ return text;
399
+ }
400
+ //#endregion
401
+ //#region ../../internals/utils/src/promise.ts
402
+ /**
403
+ * Wraps `factory` with a keyed cache backed by the provided store.
404
+ *
405
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
406
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
407
+ * nest two `memoize` calls — the outer keyed by the first argument, the
408
+ * inner (created once per outer miss) keyed by the second.
409
+ *
410
+ * Because the cache is owned by the caller, it can be shared, inspected, or
411
+ * cleared independently of the memoized function.
412
+ *
413
+ * @example Single WeakMap key
414
+ * ```ts
415
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
416
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
417
+ * ```
418
+ *
419
+ * @example Single Map key (primitive)
420
+ * ```ts
421
+ * const cache = new Map<string, Resolver>()
422
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
423
+ * ```
424
+ *
425
+ * @example Two-level (object + primitive)
426
+ * ```ts
427
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
428
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
429
+ * fn(params)('camelcase')
430
+ * ```
431
+ */
432
+ function memoize(store, factory) {
433
+ return (key) => {
434
+ if (store.has(key)) return store.get(key);
435
+ const value = factory(key);
436
+ store.set(key, value);
437
+ return value;
438
+ };
439
+ }
440
+ //#endregion
441
+ //#region ../../internals/utils/src/reserved.ts
442
+ /**
443
+ * JavaScript and Java reserved words.
444
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
445
+ */
446
+ const reservedWords = /* @__PURE__ */ new Set([
447
+ "abstract",
448
+ "arguments",
449
+ "boolean",
450
+ "break",
451
+ "byte",
452
+ "case",
453
+ "catch",
454
+ "char",
455
+ "class",
456
+ "const",
457
+ "continue",
458
+ "debugger",
459
+ "default",
460
+ "delete",
461
+ "do",
462
+ "double",
463
+ "else",
464
+ "enum",
465
+ "eval",
466
+ "export",
467
+ "extends",
468
+ "false",
469
+ "final",
470
+ "finally",
471
+ "float",
472
+ "for",
473
+ "function",
474
+ "goto",
475
+ "if",
476
+ "implements",
477
+ "import",
478
+ "in",
479
+ "instanceof",
480
+ "int",
481
+ "interface",
482
+ "let",
483
+ "long",
484
+ "native",
485
+ "new",
486
+ "null",
487
+ "package",
488
+ "private",
489
+ "protected",
490
+ "public",
491
+ "return",
492
+ "short",
493
+ "static",
494
+ "super",
495
+ "switch",
496
+ "synchronized",
497
+ "this",
498
+ "throw",
499
+ "throws",
500
+ "transient",
501
+ "true",
502
+ "try",
503
+ "typeof",
504
+ "var",
505
+ "void",
506
+ "volatile",
507
+ "while",
508
+ "with",
509
+ "yield",
510
+ "Array",
511
+ "Date",
512
+ "hasOwnProperty",
513
+ "Infinity",
514
+ "isFinite",
515
+ "isNaN",
516
+ "isPrototypeOf",
517
+ "length",
518
+ "Math",
519
+ "name",
520
+ "NaN",
521
+ "Number",
522
+ "Object",
523
+ "prototype",
524
+ "String",
525
+ "toString",
526
+ "undefined",
527
+ "valueOf"
528
+ ]);
529
+ /**
530
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
531
+ *
532
+ * @example
533
+ * ```ts
534
+ * isValidVarName('status') // true
535
+ * isValidVarName('class') // false (reserved word)
536
+ * isValidVarName('42foo') // false (starts with digit)
537
+ * ```
538
+ */
539
+ function isValidVarName(name) {
540
+ if (!name || reservedWords.has(name)) return false;
541
+ return isIdentifier(name);
542
+ }
543
+ /**
544
+ * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
545
+ *
546
+ * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
547
+ * even though they are not valid variable names, so use this (not {@link isValidVarName}) when
548
+ * deciding whether an object key needs quoting.
549
+ *
550
+ * @example
551
+ * ```ts
552
+ * isIdentifier('name') // true
553
+ * isIdentifier('x-total')// false
554
+ * ```
555
+ */
556
+ function isIdentifier(name) {
557
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
558
+ }
559
+ //#endregion
560
+ //#region ../../internals/utils/src/string.ts
561
+ /**
562
+ * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
563
+ * any backslash or single quote in the content.
564
+ *
565
+ * @example
566
+ * ```ts
567
+ * singleQuote('foo') // "'foo'"
568
+ * singleQuote("o'clock") // "'o\\'clock'"
569
+ * ```
570
+ */
571
+ function singleQuote(value) {
572
+ if (value === void 0 || value === null) return "''";
573
+ return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
574
+ }
575
+ //#endregion
576
+ //#region src/utils/extractStringsFromNodes.ts
577
+ /**
578
+ * Extracts all string content from a `CodeNode` tree recursively.
579
+ *
580
+ * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
581
+ * and nested node content. Used to build the full source string for import filtering.
582
+ */
583
+ function extractStringsFromNodes(nodes) {
584
+ if (!nodes?.length) return "";
585
+ const collected = [];
586
+ for (const node of nodes) {
587
+ if (typeof node === "string") {
588
+ if (node) collected.push(node);
589
+ continue;
590
+ }
591
+ if (node.kind === "Text") {
592
+ if (node.value) collected.push(node.value);
593
+ continue;
594
+ }
595
+ if (node.kind === "Break") continue;
596
+ if (node.kind === "Jsx") {
597
+ if (node.value) collected.push(node.value);
598
+ continue;
599
+ }
600
+ const parts = [];
601
+ if ("params" in node && node.params) parts.push(node.params);
602
+ if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
603
+ if ("returnType" in node && node.returnType) parts.push(node.returnType);
604
+ if ("type" in node && typeof node.type === "string") parts.push(node.type);
605
+ const nested = extractStringsFromNodes(node.nodes);
606
+ if (nested) parts.push(nested);
607
+ if (parts.length) collected.push(parts.join("\n"));
608
+ }
609
+ return collected.join("\n");
610
+ }
611
+ //#endregion
612
+ //#region src/utils/fileMerge.ts
613
+ function sourceKey(source) {
614
+ return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
615
+ }
616
+ function pathTypeKey(path, isTypeOnly) {
617
+ return `${path}:${isTypeOnly ?? false}`;
618
+ }
619
+ function exportKey(path, name, isTypeOnly, asAlias) {
620
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
621
+ }
622
+ function importKey(path, name, isTypeOnly) {
623
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
624
+ }
625
+ /**
626
+ * Computes a multi-level sort key for exports and imports:
627
+ * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
628
+ */
629
+ function sortKey(node) {
630
+ const isArray = Array.isArray(node.name) ? "1" : "0";
631
+ const typeOnly = node.isTypeOnly ? "0" : "1";
632
+ const hasName = node.name != null ? "1" : "0";
633
+ const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
634
+ return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
635
+ }
636
+ /**
637
+ * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
638
+ * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
639
+ * the deduplicated array in original order.
640
+ */
641
+ function combineSources(sources) {
642
+ const seen = /* @__PURE__ */ new Map();
643
+ for (const source of sources) {
644
+ const key = sourceKey(source);
645
+ if (!seen.has(key)) seen.set(key, source);
646
+ }
647
+ return [...seen.values()];
648
+ }
649
+ /**
650
+ * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
651
+ *
652
+ * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
653
+ */
654
+ function mergeNameArrays(existing, incoming) {
655
+ const merged = new Set(existing);
656
+ for (const name of incoming) merged.add(name);
657
+ return [...merged];
658
+ }
659
+ /**
660
+ * Deduplicates and merges `ExportNode` objects by path and type.
661
+ *
662
+ * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
663
+ * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
664
+ */
665
+ function combineExports(exports) {
666
+ const result = [];
667
+ const namedByPath = /* @__PURE__ */ new Map();
668
+ const seen = /* @__PURE__ */ new Set();
669
+ const keyed = exports.map((node) => ({
670
+ node,
671
+ key: sortKey(node)
672
+ }));
673
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
674
+ for (const { node: curr } of keyed) {
675
+ const { name, path, isTypeOnly, asAlias } = curr;
676
+ if (Array.isArray(name)) {
677
+ if (!name.length) continue;
678
+ const key = pathTypeKey(path, isTypeOnly);
679
+ const existing = namedByPath.get(key);
680
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
681
+ else {
682
+ const newItem = {
683
+ ...curr,
684
+ name: [...new Set(name)]
685
+ };
686
+ result.push(newItem);
687
+ namedByPath.set(key, newItem);
688
+ }
689
+ } else {
690
+ const key = exportKey(path, name, isTypeOnly, asAlias);
691
+ if (!seen.has(key)) {
692
+ result.push(curr);
693
+ seen.add(key);
694
+ }
695
+ }
696
+ }
697
+ return result;
698
+ }
699
+ /**
700
+ * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
701
+ *
702
+ * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
703
+ * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
704
+ */
705
+ function combineImports(imports, exports, source) {
706
+ const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
707
+ const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
708
+ const importNameMemo = /* @__PURE__ */ new Map();
709
+ const canonicalizeName = (n) => {
710
+ if (typeof n === "string") return n;
711
+ const key = `${n.propertyName}:${n.name ?? ""}`;
712
+ if (!importNameMemo.has(key)) importNameMemo.set(key, n);
713
+ return importNameMemo.get(key);
714
+ };
715
+ const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
716
+ for (const node of imports) {
717
+ if (!Array.isArray(node.name)) continue;
718
+ if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
719
+ }
720
+ const result = [];
721
+ const namedByPath = /* @__PURE__ */ new Map();
722
+ const seen = /* @__PURE__ */ new Set();
723
+ const keyed = imports.map((node) => ({
724
+ node,
725
+ key: sortKey(node)
726
+ }));
727
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
728
+ for (const { node: curr } of keyed) {
729
+ if (curr.path === curr.root) continue;
730
+ const { path, isTypeOnly } = curr;
731
+ let { name } = curr;
732
+ if (Array.isArray(name)) {
733
+ name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
734
+ if (!name.length) continue;
735
+ const key = pathTypeKey(path, isTypeOnly);
736
+ const existing = namedByPath.get(key);
737
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
738
+ else {
739
+ const newItem = {
740
+ ...curr,
741
+ name
742
+ };
743
+ result.push(newItem);
744
+ namedByPath.set(key, newItem);
745
+ }
746
+ } else {
747
+ if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
748
+ const key = importKey(path, name, isTypeOnly);
749
+ if (!seen.has(key)) {
750
+ result.push(curr);
751
+ seen.add(key);
752
+ }
753
+ }
754
+ }
755
+ return result;
756
+ }
757
+ //#endregion
758
+ //#region src/nodes/file.ts
759
+ /**
760
+ * Definition for the {@link ImportNode}.
761
+ */
762
+ const importDef = defineNode({ kind: "Import" });
763
+ /**
764
+ * Definition for the {@link ExportNode}.
765
+ */
766
+ const exportDef = defineNode({ kind: "Export" });
767
+ /**
768
+ * Definition for the {@link SourceNode}.
769
+ */
770
+ const sourceDef = defineNode({ kind: "Source" });
771
+ /**
772
+ * Definition for the {@link FileNode}. The fully resolved builder lives in
773
+ * `createFile`, so this definition only supplies the guard.
774
+ */
775
+ const fileDef = defineNode({ kind: "File" });
776
+ /**
777
+ * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
778
+ *
779
+ * @example Named import
780
+ * ```ts
781
+ * createImport({ name: ['useState'], path: 'react' })
782
+ * // import { useState } from 'react'
783
+ * ```
784
+ */
785
+ const createImport = importDef.create;
786
+ /**
787
+ * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
788
+ *
789
+ * @example Named export
790
+ * ```ts
791
+ * createExport({ name: ['Pet'], path: './Pet' })
792
+ * // export { Pet } from './Pet'
793
+ * ```
794
+ */
795
+ const createExport = exportDef.create;
796
+ /**
797
+ * Creates a `SourceNode` representing a fragment of source code within a file.
798
+ *
799
+ * @example
800
+ * ```ts
801
+ * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
802
+ * ```
803
+ */
804
+ const createSource = sourceDef.create;
805
+ /**
806
+ * Creates a fully resolved `FileNode` from a file input descriptor.
807
+ *
808
+ * Computes:
809
+ * - `id` SHA256 hash of the file path
810
+ * - `name` `baseName` without extension
811
+ * - `extname` extension extracted from `baseName`
812
+ *
813
+ * Deduplicates:
814
+ * - `sources` via `combineSources`
815
+ * - `exports` via `combineExports`
816
+ * - `imports` via `combineImports` (also filters unused imports)
817
+ *
818
+ * @throws {Error} when `baseName` has no extension.
819
+ *
820
+ * @example
821
+ * ```ts
822
+ * const file = createFile({
823
+ * baseName: 'petStore.ts',
824
+ * path: 'src/models/petStore.ts',
825
+ * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
826
+ * imports: [createImport({ name: ['z'], path: 'zod' })],
827
+ * exports: [createExport({ name: ['Pet'], path: './petStore' })],
828
+ * })
829
+ * // file.id = SHA256 hash of 'src/models/petStore.ts'
830
+ * // file.name = 'petStore'
831
+ * // file.extname = '.ts'
832
+ * ```
833
+ *
834
+ * @example Copy a real file into the output verbatim
835
+ * ```ts
836
+ * const file = createFile({
837
+ * baseName: 'client.ts',
838
+ * path: 'src/gen/client.ts',
839
+ * copy: '/abs/path/to/templates/client.ts',
840
+ * })
841
+ * ```
842
+ */
843
+ function createFile(input) {
844
+ const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
845
+ if (!extname) throw new Error(`No extname found for ${input.baseName}`);
846
+ const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
847
+ let resolvedImports = [];
848
+ if (input.imports?.length) {
849
+ const source = extractStringsFromNodes((input.sources ?? []).flatMap((item) => item.nodes ?? [])) || void 0;
850
+ const combinedImports = combineImports(input.imports, resolvedExports, source);
851
+ const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
852
+ const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
853
+ resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
854
+ if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
855
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
856
+ if (!kept.length) return [];
857
+ return [kept.length === imp.name.length ? imp : {
858
+ ...imp,
859
+ name: kept
860
+ }];
861
+ });
862
+ }
863
+ const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
864
+ return {
865
+ kind: "File",
866
+ ...input,
867
+ id: hash("sha256", input.path, "hex"),
868
+ name: trimExtName(input.baseName),
869
+ extname,
870
+ imports: resolvedImports,
871
+ exports: resolvedExports,
872
+ sources: resolvedSources,
873
+ meta: input.meta ?? {}
874
+ };
875
+ }
876
+ //#endregion
877
+ //#region src/nodes/input.ts
878
+ /**
879
+ * Definition for the {@link InputNode}.
880
+ */
881
+ const inputDef = defineNode({
882
+ kind: "Input",
883
+ defaults: {
884
+ schemas: [],
885
+ operations: [],
886
+ meta: {
887
+ circularNames: [],
888
+ enumNames: []
889
+ }
890
+ },
891
+ children: ["schemas", "operations"],
892
+ visitorKey: "input"
893
+ });
894
+ /**
895
+ * Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
896
+ * `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
897
+ * `schemas`/`operations`. Both variants get the defaulted `meta`.
898
+ *
899
+ * @example Eager
900
+ * ```ts
901
+ * const input = createInput()
902
+ * // { kind: 'Input', schemas: [], operations: [] }
903
+ * ```
904
+ *
905
+ * @example Streaming
906
+ * ```ts
907
+ * const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
908
+ * ```
909
+ */
910
+ function createInput(options = {}) {
911
+ const { stream, ...overrides } = options;
912
+ if (stream) return {
913
+ kind: "Input",
914
+ meta: {
915
+ circularNames: [],
916
+ enumNames: []
917
+ },
918
+ ...overrides
919
+ };
920
+ return inputDef.create(overrides);
921
+ }
922
+ //#endregion
923
+ //#region src/nodes/requestBody.ts
924
+ /**
925
+ * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
926
+ * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
927
+ */
928
+ const requestBodyDef = defineNode({
929
+ kind: "RequestBody",
930
+ children: ["content"]
931
+ });
932
+ /**
933
+ * Creates a `RequestBodyNode`.
934
+ */
935
+ const createRequestBody = requestBodyDef.create;
936
+ //#endregion
937
+ //#region src/nodes/operation.ts
938
+ /**
939
+ * Definition for the {@link OperationNode}. HTTP operations (those carrying both
940
+ * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
941
+ * normalized into a `RequestBodyNode`.
942
+ */
943
+ const operationDef = defineNode({
944
+ kind: "Operation",
945
+ build: (props) => {
946
+ const { requestBody, ...rest } = props;
947
+ const isHttp = rest.method !== void 0 && rest.path !== void 0;
948
+ return {
949
+ tags: [],
950
+ parameters: [],
951
+ responses: [],
952
+ ...rest,
953
+ ...isHttp ? { protocol: "http" } : {},
954
+ requestBody: requestBody ? createRequestBody(requestBody) : void 0
955
+ };
956
+ },
957
+ children: [
958
+ "parameters",
959
+ "requestBody",
960
+ "responses"
961
+ ],
962
+ visitorKey: "operation"
963
+ });
964
+ function createOperation(props) {
965
+ return operationDef.create(props);
966
+ }
967
+ //#endregion
968
+ //#region src/nodes/output.ts
969
+ /**
970
+ * Definition for the {@link OutputNode}.
971
+ */
972
+ const outputDef = defineNode({
973
+ kind: "Output",
974
+ defaults: { files: [] },
975
+ visitorKey: "output"
976
+ });
977
+ /**
978
+ * Creates an `OutputNode` with a stable default for `files`.
979
+ *
980
+ * @example
981
+ * ```ts
982
+ * const output = createOutput()
983
+ * // { kind: 'Output', files: [] }
984
+ * ```
985
+ */
986
+ function createOutput(overrides = {}) {
987
+ return outputDef.create(overrides);
988
+ }
989
+ //#endregion
990
+ //#region src/optionality.ts
991
+ /**
992
+ * Generic JSON Schema optionality: a non-required field is optional, and a
993
+ * non-required nullable field is nullish.
994
+ */
995
+ function optionality(schema, required) {
996
+ const nullable = schema.nullable ?? false;
997
+ return {
998
+ ...schema,
999
+ optional: !required && !nullable ? true : void 0,
1000
+ nullish: !required && nullable ? true : void 0
1001
+ };
1002
+ }
1003
+ //#endregion
1004
+ //#region src/nodes/parameter.ts
1005
+ /**
1006
+ * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
1007
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
1008
+ */
1009
+ const parameterDef = defineNode({
1010
+ kind: "Parameter",
1011
+ build: (props) => {
1012
+ const required = props.required ?? false;
1013
+ return {
1014
+ ...props,
1015
+ required,
1016
+ schema: optionality(props.schema, required)
1017
+ };
1018
+ },
1019
+ children: ["schema"],
1020
+ visitorKey: "parameter"
1021
+ });
1022
+ /**
1023
+ * Creates a `ParameterNode`.
1024
+ *
1025
+ * @example
1026
+ * ```ts
1027
+ * const param = createParameter({
1028
+ * name: 'petId',
1029
+ * in: 'path',
1030
+ * required: true,
1031
+ * schema: createSchema({ type: 'string' }),
1032
+ * })
1033
+ * ```
1034
+ */
1035
+ const createParameter = parameterDef.create;
1036
+ //#endregion
1037
+ //#region src/nodes/property.ts
1038
+ /**
1039
+ * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
1040
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
1041
+ */
1042
+ const propertyDef = defineNode({
1043
+ kind: "Property",
1044
+ build: (props) => {
1045
+ const required = props.required ?? false;
1046
+ return {
1047
+ ...props,
1048
+ required,
1049
+ schema: optionality(props.schema, required)
1050
+ };
1051
+ },
1052
+ children: ["schema"],
1053
+ visitorKey: "property"
1054
+ });
1055
+ /**
1056
+ * Creates a `PropertyNode`.
1057
+ *
1058
+ * @example
1059
+ * ```ts
1060
+ * const property = createProperty({
1061
+ * name: 'status',
1062
+ * required: true,
1063
+ * schema: createSchema({ type: 'string', nullable: true }),
1064
+ * })
1065
+ * // required=true, no optional/nullish
1066
+ * ```
1067
+ */
1068
+ const createProperty = propertyDef.create;
1069
+ //#endregion
1070
+ //#region src/nodes/response.ts
1071
+ /**
1072
+ * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
1073
+ * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
1074
+ */
1075
+ const responseDef = defineNode({
1076
+ kind: "Response",
1077
+ build: (props) => {
1078
+ const { schema, mediaType, keysToOmit, content, ...rest } = props;
1079
+ const entries = content ?? (schema ? [createContent({
1080
+ contentType: mediaType ?? "application/json",
1081
+ schema,
1082
+ keysToOmit: keysToOmit ?? null
1083
+ })] : void 0);
1084
+ return {
1085
+ ...rest,
1086
+ content: entries
1087
+ };
1088
+ },
1089
+ children: ["content"],
1090
+ visitorKey: "response"
1091
+ });
1092
+ /**
1093
+ * Creates a `ResponseNode`.
1094
+ *
1095
+ * @example
1096
+ * ```ts
1097
+ * const response = createResponse({
1098
+ * statusCode: '200',
1099
+ * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
1100
+ * })
1101
+ * ```
1102
+ */
1103
+ const createResponse = responseDef.create;
1104
+ //#endregion
1105
+ //#region src/nodes/schema.ts
1106
+ /**
1107
+ * Maps schema `type` to its underlying `primitive`.
1108
+ * Primitive types map to themselves and special string formats map to `'string'`.
1109
+ * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
1110
+ */
1111
+ const TYPE_TO_PRIMITIVE = {
1112
+ string: "string",
1113
+ number: "number",
1114
+ integer: "integer",
1115
+ bigint: "bigint",
1116
+ boolean: "boolean",
1117
+ null: "null",
1118
+ any: "any",
1119
+ unknown: "unknown",
1120
+ void: "void",
1121
+ never: "never",
1122
+ object: "object",
1123
+ array: "array",
1124
+ date: "date",
1125
+ uuid: "string",
1126
+ email: "string",
1127
+ url: "string",
1128
+ datetime: "string",
1129
+ time: "string"
1130
+ };
1131
+ /**
1132
+ * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
1133
+ * empty array, and `primitive` is inferred from `type` when not explicitly provided.
1134
+ */
1135
+ const schemaDef = defineNode({
1136
+ kind: "Schema",
1137
+ build: (props) => {
1138
+ if (props.type === "object") return {
1139
+ properties: [],
1140
+ primitive: "object",
1141
+ ...props
1142
+ };
1143
+ return {
1144
+ primitive: TYPE_TO_PRIMITIVE[props.type],
1145
+ ...props
1146
+ };
1147
+ },
1148
+ children: [
1149
+ "properties",
1150
+ "items",
1151
+ "members",
1152
+ "additionalProperties"
1153
+ ],
1154
+ visitorKey: "schema"
1155
+ });
1156
+ function createSchema(props) {
1157
+ return schemaDef.create(props);
1158
+ }
1159
+ //#endregion
1160
+ //#region src/registry.ts
1161
+ /**
1162
+ * Every node definition. Adding a node means adding its `defineNode` to one
1163
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
1164
+ */
1165
+ const nodeDefs = [
1166
+ inputDef,
1167
+ outputDef,
1168
+ operationDef,
1169
+ requestBodyDef,
1170
+ contentDef,
1171
+ responseDef,
1172
+ schemaDef,
1173
+ propertyDef,
1174
+ parameterDef,
1175
+ constDef,
1176
+ typeDef,
1177
+ functionDef,
1178
+ arrowFunctionDef,
1179
+ textDef,
1180
+ breakDef,
1181
+ jsxDef,
1182
+ importDef,
1183
+ exportDef,
1184
+ sourceDef,
1185
+ fileDef
1186
+ ];
1187
+ //#endregion
1188
+ //#region src/visitor.ts
1189
+ /**
1190
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
1191
+ * Derived from each definition's `children`.
1192
+ */
1193
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
1194
+ /**
1195
+ * Maps a node kind to the matching visitor callback name. Derived from each
1196
+ * definition's `visitorKey`.
1197
+ */
1198
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1199
+ /**
1200
+ * Creates a small async concurrency limiter.
1201
+ *
1202
+ * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
1203
+ *
1204
+ * @example
1205
+ * ```ts
1206
+ * const limit = createLimit(2)
1207
+ * for (const task of [taskA, taskB, taskC]) {
1208
+ * await limit(() => task())
1209
+ * }
1210
+ * // only 2 tasks run at the same time
1211
+ * ```
1212
+ */
1213
+ function createLimit(concurrency) {
1214
+ let active = 0;
1215
+ const queue = [];
1216
+ function next() {
1217
+ if (active < concurrency && queue.length > 0) {
1218
+ active++;
1219
+ queue.shift()();
1220
+ }
1221
+ }
1222
+ return function limit(fn) {
1223
+ return new Promise((resolve, reject) => {
1224
+ queue.push(() => {
1225
+ Promise.resolve(fn()).then(resolve, reject).finally(() => {
1226
+ active--;
1227
+ next();
1228
+ });
1229
+ });
1230
+ next();
1231
+ });
1232
+ };
1233
+ }
1234
+ const visitorKeysByKind = VISITOR_KEYS;
1235
+ /**
1236
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1237
+ */
1238
+ function isNode(value) {
1239
+ return typeof value === "object" && value !== null && typeof value.kind === "string";
1240
+ }
1241
+ /**
1242
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1243
+ *
1244
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1245
+ *
1246
+ * @example
1247
+ * ```ts
1248
+ * const children = getChildren(operationNode, true)
1249
+ * // returns parameters, the request body, and responses
1250
+ * ```
1251
+ */
1252
+ function* getChildren(node, recurse) {
1253
+ if (node.kind === "Schema" && !recurse) return;
1254
+ const keys = visitorKeysByKind[node.kind];
1255
+ if (!keys) return;
1256
+ const record = node;
1257
+ for (const key of keys) {
1258
+ const value = record[key];
1259
+ if (Array.isArray(value)) {
1260
+ for (const item of value) if (isNode(item)) yield item;
1261
+ } else if (isNode(value)) yield value;
1262
+ }
1263
+ }
1264
+ /**
1265
+ * Runs the visitor callback that matches `node.kind` with the traversal
1266
+ * context. The result is a replacement node, a collected value, or `undefined`
1267
+ * when no callback is registered for the kind.
1268
+ *
1269
+ * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
1270
+ * in one place. `TResult` is the caller's expected return: the same node type
1271
+ * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
1272
+ */
1273
+ function applyVisitor(node, visitor, parent) {
1274
+ const key = VISITOR_KEY_BY_KIND[node.kind];
1275
+ if (!key) return void 0;
1276
+ const fn = visitor[key];
1277
+ return fn?.(node, { parent });
1278
+ }
1279
+ /**
1280
+ * Async depth-first traversal for side effects. Visitor return values are
1281
+ * ignored. Use `transform` when you want to rewrite nodes.
1282
+ *
1283
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
1284
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
1285
+ * work. Lower values reduce memory pressure.
1286
+ *
1287
+ * @example Log every operation
1288
+ * ```ts
1289
+ * await walk(root, {
1290
+ * operation(node) {
1291
+ * console.log(node.operationId)
1292
+ * },
1293
+ * })
1294
+ * ```
1295
+ *
1296
+ * @example Only visit the root node
1297
+ * ```ts
1298
+ * await walk(root, { depth: 'shallow', input: () => {} })
1299
+ * ```
1300
+ */
1301
+ async function walk(node, options) {
1302
+ return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
1303
+ }
1304
+ async function _walk(node, visitor, recurse, limit, parent) {
1305
+ await limit(() => applyVisitor(node, visitor, parent));
1306
+ let pending;
1307
+ for (const child of getChildren(node, recurse)) (pending ??= []).push(_walk(child, visitor, recurse, limit, node));
1308
+ if (pending) await Promise.all(pending);
1309
+ }
1310
+ function transform(node, options) {
1311
+ const { depth, parent, ...visitor } = options;
1312
+ return transformNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1313
+ }
1314
+ /**
1315
+ * Visits a single node, then immutably rebuilds its children. Returns the original
1316
+ * reference when neither the visitor nor the child rebuild changed anything, so callers
1317
+ * can detect "nothing changed" by identity and ancestors avoid reallocating.
1318
+ */
1319
+ function transformNode(node, visitor, recurse, parent) {
1320
+ return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
1321
+ }
1322
+ /**
1323
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1324
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1325
+ * `Schema` children are skipped in shallow mode.
1326
+ */
1327
+ function transformChildren(node, visitor, recurse) {
1328
+ if (node.kind === "Schema" && !recurse) return node;
1329
+ const keys = visitorKeysByKind[node.kind];
1330
+ if (!keys) return node;
1331
+ const record = node;
1332
+ let updates;
1333
+ for (const key of keys) {
1334
+ if (!(key in record)) continue;
1335
+ const value = record[key];
1336
+ if (Array.isArray(value)) {
1337
+ let mapped;
1338
+ for (const [i, item] of value.entries()) {
1339
+ const next = isNode(item) ? transformNode(item, visitor, recurse, node) : item;
1340
+ if (mapped) {
1341
+ mapped.push(next);
1342
+ continue;
1343
+ }
1344
+ if (next !== item) mapped = [...value.slice(0, i), next];
1345
+ }
1346
+ if (mapped) (updates ??= {})[key] = mapped;
1347
+ } else if (isNode(value)) {
1348
+ const next = transformNode(value, visitor, recurse, node);
1349
+ if (next !== value) (updates ??= {})[key] = next;
1350
+ }
1351
+ }
1352
+ return updates ? {
1353
+ ...node,
1354
+ ...updates
1355
+ } : node;
1356
+ }
1357
+ /**
1358
+ * Lazy depth-first collection pass. Yields every non-null value returned by
1359
+ * the visitor callbacks. Use `collect` for the eager array form.
1360
+ *
1361
+ * @example Collect every operationId
1362
+ * ```ts
1363
+ * const ids: string[] = []
1364
+ * for (const id of collectLazy<string>(root, {
1365
+ * operation(node) {
1366
+ * return node.operationId
1367
+ * },
1368
+ * })) {
1369
+ * ids.push(id)
1370
+ * }
1371
+ * ```
1372
+ */
1373
+ function* collectLazy(node, options) {
1374
+ const { depth, parent, ...visitor } = options;
1375
+ yield* collectNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1376
+ }
1377
+ function* collectNode(node, visitor, recurse, parent) {
1378
+ const v = applyVisitor(node, visitor, parent);
1379
+ if (v != null) yield v;
1380
+ for (const child of getChildren(node, recurse)) yield* collectNode(child, visitor, recurse, node);
1381
+ }
1382
+ /**
1383
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
1384
+ * callbacks return into an array.
1385
+ *
1386
+ * @example Collect every operationId
1387
+ * ```ts
1388
+ * const ids = collect<string>(root, {
1389
+ * operation(node) {
1390
+ * return node.operationId
1391
+ * },
1392
+ * })
1393
+ * ```
1394
+ */
1395
+ function collect(node, options) {
1396
+ return Array.from(collectLazy(node, options));
1397
+ }
1398
+ //#endregion
1399
+ //#region src/defineMacro.ts
1400
+ /**
1401
+ * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
1402
+ * list keeps its authored order.
1403
+ */
1404
+ function enforceWeight(enforce) {
1405
+ if (enforce === "pre") return 0;
1406
+ if (enforce === "post") return 2;
1407
+ return 1;
1408
+ }
1409
+ /**
1410
+ * Types a macro for inference and a single construction site, mirroring `definePlugin`.
1411
+ * Adds no runtime behavior.
8
1412
  *
9
1413
  * @example
10
1414
  * ```ts
11
- * export const oasDialect = defineDialect({
12
- * name: 'oas',
13
- * schema: {
14
- * isNullable,
15
- * isReference,
16
- * isDiscriminator,
17
- * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
18
- * resolveRef,
1415
+ * const macroUntagged = defineMacro({
1416
+ * name: 'untagged',
1417
+ * operation(node) {
1418
+ * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
19
1419
  * },
20
1420
  * })
21
1421
  * ```
22
1422
  */
23
- function defineDialect(dialect) {
24
- return dialect;
1423
+ function defineMacro(macro) {
1424
+ return macro;
1425
+ }
1426
+ /**
1427
+ * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
1428
+ * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
1429
+ * original reference (structural sharing).
1430
+ */
1431
+ function chain({ macros, key, node, context }) {
1432
+ let current = node;
1433
+ for (const macro of macros) {
1434
+ const callback = macro[key];
1435
+ if (!callback) continue;
1436
+ if (macro.when && !macro.when(current)) continue;
1437
+ const next = callback(current, context);
1438
+ if (next != null) current = next;
1439
+ }
1440
+ return current === node ? void 0 : current;
1441
+ }
1442
+ /**
1443
+ * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
1444
+ * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
1445
+ * sequentially per node so later macros see earlier output. This differs from a plain visitor, which
1446
+ * has no names, ordering, or composition.
1447
+ *
1448
+ * @example
1449
+ * ```ts
1450
+ * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
1451
+ * const next = transform(root, visitor)
1452
+ * ```
1453
+ */
1454
+ function composeMacros(macros) {
1455
+ const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce));
1456
+ const visitor = {};
1457
+ for (const key of visitorKeys) {
1458
+ if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
1459
+ const callback = (node, context) => chain({
1460
+ macros: ordered,
1461
+ key,
1462
+ node,
1463
+ context
1464
+ });
1465
+ visitor[key] = callback;
1466
+ }
1467
+ return visitor;
1468
+ }
1469
+ /**
1470
+ * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
1471
+ * structural sharing, so an empty or no-op macro list returns the same reference. Pass
1472
+ * `depth: 'shallow'` to rewrite the root node only.
1473
+ *
1474
+ * @example
1475
+ * ```ts
1476
+ * const next = applyMacros(root, [macroIntegerToString])
1477
+ * ```
1478
+ *
1479
+ * @example Apply to the root node only
1480
+ * ```ts
1481
+ * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
1482
+ * ```
1483
+ */
1484
+ function applyMacros(root, macros, options) {
1485
+ if (macros.length === 0) return root;
1486
+ return transform(root, {
1487
+ ...composeMacros(macros),
1488
+ ...options
1489
+ });
25
1490
  }
26
1491
  //#endregion
27
1492
  //#region src/createPrinter.ts
@@ -95,6 +1560,631 @@ function createPrinter(build) {
95
1560
  };
96
1561
  }
97
1562
  //#endregion
1563
+ //#region src/utils/codegen.ts
1564
+ /**
1565
+ * Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
1566
+ * comments.
1567
+ *
1568
+ * @example
1569
+ * ```ts
1570
+ * buildJSDoc(['@type string', '@example hello'])
1571
+ * // '/**\n * @type string\n * @example hello\n *\/\n '
1572
+ * ```
1573
+ */
1574
+ function buildJSDoc(comments, options = {}) {
1575
+ const { indent = " * ", suffix = "\n ", fallback = " " } = options;
1576
+ if (comments.length === 0) return fallback;
1577
+ return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
1578
+ }
1579
+ /**
1580
+ * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
1581
+ */
1582
+ function indentLines(text) {
1583
+ if (!text) return "";
1584
+ return text.split("\n").map((line) => line.trim() ? ` ${line}` : "").join("\n");
1585
+ }
1586
+ /**
1587
+ * Renders an object key, quoting it with single quotes only when it is not a valid identifier.
1588
+ * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
1589
+ *
1590
+ * @example
1591
+ * ```ts
1592
+ * objectKey('name') // 'name'
1593
+ * objectKey('x-total') // "'x-total'"
1594
+ * ```
1595
+ */
1596
+ function objectKey(name) {
1597
+ return isIdentifier(name) ? name : singleQuote(name);
1598
+ }
1599
+ /**
1600
+ * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
1601
+ * level and closing the brace at column zero. Entries that are themselves multi-line objects indent
1602
+ * cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
1603
+ *
1604
+ * @example
1605
+ * ```ts
1606
+ * buildObject(['id: z.number()', 'name: z.string()'])
1607
+ * // '{\n id: z.number(),\n name: z.string(),\n}'
1608
+ * ```
1609
+ */
1610
+ function buildObject(entries) {
1611
+ if (entries.length === 0) return "{}";
1612
+ return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
1613
+ }
1614
+ /**
1615
+ * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
1616
+ * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
1617
+ * one level with a trailing comma and the closing bracket at column zero. Used for member lists such
1618
+ * as `z.union([…])` and `z.array([…])`.
1619
+ *
1620
+ * @example
1621
+ * ```ts
1622
+ * buildList(['z.string()', 'z.number()'])
1623
+ * // '[z.string(), z.number()]'
1624
+ * ```
1625
+ */
1626
+ function buildList(items, brackets = ["[", "]"]) {
1627
+ const [open, close] = brackets;
1628
+ if (items.length === 0) return `${open}${close}`;
1629
+ if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
1630
+ return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
1631
+ }
1632
+ //#endregion
1633
+ //#region src/utils/refs.ts
1634
+ const plainStringTypes = /* @__PURE__ */ new Set([
1635
+ "string",
1636
+ "uuid",
1637
+ "email",
1638
+ "url",
1639
+ "datetime"
1640
+ ]);
1641
+ /**
1642
+ * Returns the last path segment of a reference string.
1643
+ *
1644
+ * @example
1645
+ * `extractRefName('#/components/schemas/Pet') // 'Pet'`
1646
+ */
1647
+ function extractRefName(ref) {
1648
+ return ref.split("/").at(-1) ?? ref;
1649
+ }
1650
+ /**
1651
+ * Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls
1652
+ * back to `name` then nested `schema.name`.
1653
+ *
1654
+ * Returns `null` for non-ref nodes or when no name resolves.
1655
+ *
1656
+ * @example
1657
+ * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
1658
+ */
1659
+ function resolveRefName(node) {
1660
+ if (!node || node.type !== "ref") return null;
1661
+ if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
1662
+ return node.name ?? node.schema?.name ?? null;
1663
+ }
1664
+ /**
1665
+ * Builds a PascalCase child schema name by joining a parent name and property name.
1666
+ * Returns `null` when there is no parent to nest under.
1667
+ *
1668
+ * @example Nested under a parent
1669
+ * `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
1670
+ *
1671
+ * @example No parent
1672
+ * `childName(undefined, 'params') // null`
1673
+ */
1674
+ function childName(parentName, propName) {
1675
+ return parentName ? pascalCase([parentName, propName].join(" ")) : null;
1676
+ }
1677
+ /**
1678
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
1679
+ * empty parts.
1680
+ *
1681
+ * @example
1682
+ * `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
1683
+ */
1684
+ function enumPropName(parentName, propName, enumSuffix) {
1685
+ return pascalCase([
1686
+ parentName,
1687
+ propName,
1688
+ enumSuffix
1689
+ ].filter(Boolean).join(" "));
1690
+ }
1691
+ /**
1692
+ * Merges a ref node with its resolved schema, giving usage-site fields precedence.
1693
+ *
1694
+ * Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
1695
+ * same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
1696
+ * `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
1697
+ * nodes and refs without a resolved `schema` are returned unchanged.
1698
+ *
1699
+ * @example
1700
+ * ```ts
1701
+ * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
1702
+ * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
1703
+ * ```
1704
+ */
1705
+ function syncSchemaRef(node) {
1706
+ const ref = narrowSchema(node, "ref");
1707
+ if (!ref) return node;
1708
+ if (!ref.schema) return node;
1709
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
1710
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
1711
+ return createSchema({
1712
+ ...ref.schema,
1713
+ ...definedOverrides
1714
+ });
1715
+ }
1716
+ /**
1717
+ * Type guard that returns `true` when a schema emits as a plain `string` type.
1718
+ *
1719
+ * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
1720
+ * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
1721
+ */
1722
+ function isStringType(node) {
1723
+ if (plainStringTypes.has(node.type)) return true;
1724
+ const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
1725
+ if (temporal) return temporal.representation !== "date";
1726
+ return false;
1727
+ }
1728
+ //#endregion
1729
+ //#region src/utils/schemaMerge.ts
1730
+ /**
1731
+ * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
1732
+ * run and pass through unchanged. The merge follows member order, so callers control which members
1733
+ * combine by where they place them in the sequence.
1734
+ *
1735
+ * @example
1736
+ * ```ts
1737
+ * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
1738
+ * ```
1739
+ */
1740
+ function* mergeAdjacentObjectsLazy(members) {
1741
+ let acc;
1742
+ for (const member of members) {
1743
+ const objectMember = narrowSchema(member, "object");
1744
+ if (objectMember && !objectMember.name && acc !== void 0) {
1745
+ const accObject = narrowSchema(acc, "object");
1746
+ if (accObject && !accObject.name) {
1747
+ acc = createSchema({
1748
+ ...accObject,
1749
+ properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
1750
+ });
1751
+ continue;
1752
+ }
1753
+ }
1754
+ if (acc !== void 0) yield acc;
1755
+ acc = member;
1756
+ }
1757
+ if (acc !== void 0) yield acc;
1758
+ }
1759
+ //#endregion
1760
+ //#region src/utils/strings.ts
1761
+ /**
1762
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
1763
+ * Returns the string unchanged when no balanced quote pair is found.
1764
+ *
1765
+ * @example
1766
+ * ```ts
1767
+ * trimQuotes('"hello"') // 'hello'
1768
+ * trimQuotes('hello') // 'hello'
1769
+ * ```
1770
+ */
1771
+ function trimQuotes(text) {
1772
+ if (text.length >= 2) {
1773
+ const first = text[0];
1774
+ const last = text[text.length - 1];
1775
+ if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
1776
+ }
1777
+ return text;
1778
+ }
1779
+ /**
1780
+ * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
1781
+ *
1782
+ * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
1783
+ * code matches the repo style without a formatter.
1784
+ *
1785
+ * @example
1786
+ * ```ts
1787
+ * stringify('hello') // "'hello'"
1788
+ * stringify('"hello"') // "'hello'"
1789
+ * ```
1790
+ */
1791
+ function stringify(value) {
1792
+ if (value === void 0 || value === null) return "''";
1793
+ return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
1794
+ }
1795
+ /**
1796
+ * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
1797
+ * and the Unicode line terminators U+2028 and U+2029.
1798
+ *
1799
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
1800
+ *
1801
+ * @example
1802
+ * ```ts
1803
+ * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
1804
+ * ```
1805
+ */
1806
+ function jsStringEscape(input) {
1807
+ return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
1808
+ switch (character) {
1809
+ case "\"":
1810
+ case "'":
1811
+ case "\\": return `\\${character}`;
1812
+ case "\n": return "\\n";
1813
+ case "\r": return "\\r";
1814
+ case "\u2028": return "\\u2028";
1815
+ case "\u2029": return "\\u2029";
1816
+ default: return "";
1817
+ }
1818
+ });
1819
+ }
1820
+ /**
1821
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
1822
+ * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
1823
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
1824
+ *
1825
+ * @example
1826
+ * ```ts
1827
+ * toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
1828
+ * toRegExpString('^(?im)foo', null) // '/^foo/im'
1829
+ * ```
1830
+ */
1831
+ function toRegExpString(text, func = "RegExp") {
1832
+ const raw = trimQuotes(text);
1833
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
1834
+ const replacementTarget = match?.[1] ?? "";
1835
+ const matchedFlags = match?.[2];
1836
+ const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
1837
+ const { source, flags } = new RegExp(cleaned, matchedFlags);
1838
+ if (func === null) return `/${source}/${flags}`;
1839
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
1840
+ }
1841
+ /**
1842
+ * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
1843
+ * objects recurse with fixed indentation, so the result drops straight into an object literal
1844
+ * without re-parsing.
1845
+ *
1846
+ * @example
1847
+ * ```ts
1848
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
1849
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
1850
+ * ```
1851
+ */
1852
+ function stringifyObject(value) {
1853
+ return Object.entries(value).map(([key, val]) => {
1854
+ if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
1855
+ return `${key}: ${val}`;
1856
+ }).filter(Boolean).join(",\n");
1857
+ }
1858
+ /**
1859
+ * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
1860
+ * `accessor`. Returns `null` for an empty path.
1861
+ *
1862
+ * @example
1863
+ * ```ts
1864
+ * getNestedAccessor('pagination.next.id', 'lastPage')
1865
+ * // "lastPage?.['pagination']?.['next']?.['id']"
1866
+ * ```
1867
+ */
1868
+ function getNestedAccessor(param, accessor) {
1869
+ const parts = Array.isArray(param) ? param : param.split(".");
1870
+ if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
1871
+ return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
1872
+ }
1873
+ //#endregion
1874
+ //#region src/utils/schemaGraph.ts
1875
+ /**
1876
+ * Memoized inner pass that walks a single node and returns the names of every schema it references.
1877
+ */
1878
+ const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
1879
+ const refs = /* @__PURE__ */ new Set();
1880
+ collect(node, { schema(child) {
1881
+ if (child.type === "ref") {
1882
+ const name = resolveRefName(child);
1883
+ if (name) refs.add(name);
1884
+ }
1885
+ } });
1886
+ return refs;
1887
+ });
1888
+ /**
1889
+ * Collects the names of every ref found anywhere inside a node's own subtree.
1890
+ *
1891
+ * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
1892
+ * to accumulate names from several nodes into one set.
1893
+ *
1894
+ * @example Collect refs from a single schema
1895
+ * ```ts
1896
+ * const names = collectReferencedSchemaNames(petSchema)
1897
+ * // Set { 'Category', 'Tag' }
1898
+ * ```
1899
+ *
1900
+ * @example Accumulate refs from multiple schemas into one set
1901
+ * ```ts
1902
+ * const out = new Set<string>()
1903
+ * for (const schema of schemas) {
1904
+ * collectReferencedSchemaNames(schema, out)
1905
+ * }
1906
+ * ```
1907
+ */
1908
+ function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
1909
+ if (!node) return out;
1910
+ for (const name of collectSchemaRefs(node)) out.add(name);
1911
+ return out;
1912
+ }
1913
+ /**
1914
+ * Memoized two-level cache keyed first on the operations array, then on the schemas array.
1915
+ */
1916
+ const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
1917
+ function computeUsedSchemaNames(operations, schemas) {
1918
+ const schemaMap = /* @__PURE__ */ new Map();
1919
+ for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
1920
+ const result = /* @__PURE__ */ new Set();
1921
+ function visitSchema(schema) {
1922
+ const directRefs = collectReferencedSchemaNames(schema);
1923
+ for (const name of directRefs) if (!result.has(name)) {
1924
+ result.add(name);
1925
+ const namedSchema = schemaMap.get(name);
1926
+ if (namedSchema) visitSchema(namedSchema);
1927
+ }
1928
+ }
1929
+ for (const op of operations) for (const schema of collectLazy(op, {
1930
+ depth: "shallow",
1931
+ schema: (node) => node
1932
+ })) visitSchema(schema);
1933
+ return result;
1934
+ }
1935
+ /**
1936
+ * Collects the names of all top-level schemas transitively used by a set of operations.
1937
+ *
1938
+ * An operation uses a schema when its parameters, request body, or responses reference it, directly
1939
+ * or through other named schemas. Once a name is added to the result it is not revisited, so
1940
+ * reference cycles terminate.
1941
+ *
1942
+ * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
1943
+ *
1944
+ * @example Only generate schemas referenced by included operations
1945
+ * ```ts
1946
+ * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
1947
+ * const allowed = collectUsedSchemaNames(includedOps, schemas)
1948
+ *
1949
+ * for (const schema of schemas) {
1950
+ * if (schema.name && !allowed.has(schema.name)) continue
1951
+ * // generate schema
1952
+ * }
1953
+ * ```
1954
+ */
1955
+ function collectUsedSchemaNames(operations, schemas) {
1956
+ return collectUsedSchemaNamesMemo(operations)(schemas);
1957
+ }
1958
+ const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
1959
+ const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
1960
+ const graph = /* @__PURE__ */ new Map();
1961
+ for (const schema of schemas) {
1962
+ if (!schema.name) continue;
1963
+ graph.set(schema.name, collectReferencedSchemaNames(schema));
1964
+ }
1965
+ const circular = /* @__PURE__ */ new Set();
1966
+ for (const start of graph.keys()) {
1967
+ const visited = /* @__PURE__ */ new Set();
1968
+ const stack = [...graph.get(start) ?? []];
1969
+ while (stack.length > 0) {
1970
+ const node = stack.pop();
1971
+ if (node === start) {
1972
+ circular.add(start);
1973
+ break;
1974
+ }
1975
+ if (visited.has(node)) continue;
1976
+ visited.add(node);
1977
+ const next = graph.get(node);
1978
+ if (next) for (const r of next) stack.push(r);
1979
+ }
1980
+ }
1981
+ return circular;
1982
+ });
1983
+ /**
1984
+ * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
1985
+ *
1986
+ * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
1987
+ * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
1988
+ * linear in the size of the schema graph.
1989
+ *
1990
+ * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
1991
+ */
1992
+ function findCircularSchemas(schemas) {
1993
+ if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
1994
+ return findCircularSchemasMemo(schemas);
1995
+ }
1996
+ /**
1997
+ * Returns `true` when a schema, or anything nested inside it, references a circular schema.
1998
+ *
1999
+ * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
2000
+ * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
2001
+ *
2002
+ * @note Stops at the first matching circular ref.
2003
+ */
2004
+ function containsCircularRef(node, { circularSchemas, excludeName }) {
2005
+ if (!node || circularSchemas.size === 0) return false;
2006
+ for (const _ of collectLazy(node, { schema(child) {
2007
+ if (child.type !== "ref") return null;
2008
+ const name = resolveRefName(child);
2009
+ return name && name !== excludeName && circularSchemas.has(name) ? true : null;
2010
+ } })) return true;
2011
+ return false;
2012
+ }
2013
+ //#endregion
2014
+ //#region src/utils/schemaTraversal.ts
2015
+ /**
2016
+ * Maps each property of an object schema to its transformed output. Pairs every result with the
2017
+ * original property so the printer keeps full control over modifiers, getters, and key syntax.
2018
+ *
2019
+ * @example
2020
+ * ```ts
2021
+ * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
2022
+ * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
2023
+ * ```
2024
+ */
2025
+ function mapSchemaProperties(node, transform) {
2026
+ return node.properties.map((property) => ({
2027
+ name: property.name,
2028
+ property,
2029
+ output: transform(property.schema)
2030
+ }));
2031
+ }
2032
+ /**
2033
+ * Maps each member of a union or intersection schema to its transformed output, pairing every
2034
+ * result with the original member.
2035
+ */
2036
+ function mapSchemaMembers(node, transform) {
2037
+ return (node.members ?? []).map((schema) => ({
2038
+ schema,
2039
+ output: transform(schema)
2040
+ }));
2041
+ }
2042
+ /**
2043
+ * Maps each item of an array or tuple schema to its transformed output, pairing every result with
2044
+ * the original item.
2045
+ */
2046
+ function mapSchemaItems(node, transform) {
2047
+ return (node.items ?? []).map((schema) => ({
2048
+ schema,
2049
+ output: transform(schema)
2050
+ }));
2051
+ }
2052
+ /**
2053
+ * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
2054
+ * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
2055
+ * of a recursive schema until first access.
2056
+ *
2057
+ * @example
2058
+ * ```ts
2059
+ * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
2060
+ * // "get parent() { return z.lazy(() => Pet) }"
2061
+ * ```
2062
+ */
2063
+ function lazyGetter({ name, body }) {
2064
+ return `get ${objectKey(name)}() { return ${body} }`;
2065
+ }
2066
+ //#endregion
2067
+ //#region src/macros/macroDiscriminatorEnum.ts
2068
+ /**
2069
+ * Builds a macro that replaces a discriminator property's schema with a string enum of the given
2070
+ * values. Object schemas that lack the property are returned unchanged.
2071
+ *
2072
+ * @example
2073
+ * ```ts
2074
+ * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
2075
+ * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
2076
+ * ```
2077
+ */
2078
+ function macroDiscriminatorEnum({ propertyName, values, enumName }) {
2079
+ return defineMacro({
2080
+ name: "discriminator-enum",
2081
+ schema(node) {
2082
+ const objectNode = narrowSchema(node, "object");
2083
+ if (!objectNode?.properties?.length) return void 0;
2084
+ if (!objectNode.properties.some((prop) => prop.name === propertyName)) return void 0;
2085
+ return createSchema({
2086
+ ...objectNode,
2087
+ properties: objectNode.properties.map((prop) => {
2088
+ if (prop.name !== propertyName) return prop;
2089
+ return createProperty({
2090
+ ...prop,
2091
+ schema: createSchema({
2092
+ type: "enum",
2093
+ primitive: "string",
2094
+ enumValues: values,
2095
+ name: enumName,
2096
+ readOnly: prop.schema.readOnly,
2097
+ writeOnly: prop.schema.writeOnly
2098
+ })
2099
+ });
2100
+ })
2101
+ });
2102
+ }
2103
+ });
2104
+ }
2105
+ //#endregion
2106
+ //#region src/macros/macroEnumName.ts
2107
+ /**
2108
+ * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
2109
+ * are left anonymous. Non-enum nodes are returned unchanged.
2110
+ *
2111
+ * @example
2112
+ * ```ts
2113
+ * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
2114
+ * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
2115
+ * ```
2116
+ */
2117
+ function macroEnumName({ parentName, propName, enumSuffix }) {
2118
+ return defineMacro({
2119
+ name: "enum-name",
2120
+ schema(node) {
2121
+ const enumNode = narrowSchema(node, "enum");
2122
+ if (enumNode?.primitive === "boolean") return {
2123
+ ...node,
2124
+ name: null
2125
+ };
2126
+ if (enumNode) return {
2127
+ ...node,
2128
+ name: enumPropName(parentName, propName, enumSuffix)
2129
+ };
2130
+ }
2131
+ });
2132
+ }
2133
+ //#endregion
2134
+ //#region src/macros/macroSimplifyUnion.ts
2135
+ /**
2136
+ * Scalar primitive schema types used for union simplification and type narrowing.
2137
+ */
2138
+ const SCALAR_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
2139
+ "string",
2140
+ "number",
2141
+ "integer",
2142
+ "bigint",
2143
+ "boolean"
2144
+ ]);
2145
+ function isScalarPrimitive(type) {
2146
+ return SCALAR_PRIMITIVE_TYPES.has(type);
2147
+ }
2148
+ /**
2149
+ * Filters union members, dropping enum members that a broader scalar primitive already covers.
2150
+ */
2151
+ function simplifyUnionMembers(members) {
2152
+ const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
2153
+ if (!scalarPrimitives.size) return members;
2154
+ return members.filter((member) => {
2155
+ const enumNode = narrowSchema(member, "enum");
2156
+ if (!enumNode) return true;
2157
+ const primitive = enumNode.primitive;
2158
+ if (!primitive) return true;
2159
+ if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
2160
+ if (scalarPrimitives.has(primitive)) return false;
2161
+ if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
2162
+ return true;
2163
+ });
2164
+ }
2165
+ /**
2166
+ * Removes union members a broader scalar primitive already covers, such as a multi-value string enum
2167
+ * sitting next to a plain `string`. Single-value enums are kept.
2168
+ *
2169
+ * @example
2170
+ * ```ts
2171
+ * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
2172
+ * ```
2173
+ */
2174
+ const macroSimplifyUnion = defineMacro({
2175
+ name: "simplify-union",
2176
+ schema(node) {
2177
+ const unionNode = narrowSchema(node, "union");
2178
+ if (!unionNode?.members?.length) return void 0;
2179
+ const simplified = simplifyUnionMembers(unionNode.members);
2180
+ if (simplified.length === unionNode.members.length) return void 0;
2181
+ return {
2182
+ ...unionNode,
2183
+ members: simplified
2184
+ };
2185
+ }
2186
+ });
2187
+ //#endregion
98
2188
  //#region src/factory.ts
99
2189
  var factory_exports = /* @__PURE__ */ __exportAll({
100
2190
  createArrowFunction: () => createArrowFunction,
@@ -148,24 +2238,47 @@ var exports_exports = /* @__PURE__ */ __exportAll({
148
2238
  applyMacros: () => applyMacros,
149
2239
  arrowFunctionDef: () => arrowFunctionDef,
150
2240
  breakDef: () => breakDef,
2241
+ buildJSDoc: () => buildJSDoc,
2242
+ buildList: () => buildList,
2243
+ buildObject: () => buildObject,
2244
+ childName: () => childName,
151
2245
  collect: () => collect,
2246
+ collectUsedSchemaNames: () => collectUsedSchemaNames,
152
2247
  composeMacros: () => composeMacros,
153
2248
  constDef: () => constDef,
2249
+ containsCircularRef: () => containsCircularRef,
154
2250
  contentDef: () => contentDef,
155
2251
  createPrinter: () => createPrinter,
156
2252
  defineDialect: () => defineDialect,
157
2253
  defineMacro: () => defineMacro,
158
2254
  defineNode: () => defineNode,
2255
+ enumPropName: () => enumPropName,
159
2256
  exportDef: () => exportDef,
2257
+ extractRefName: () => extractRefName,
2258
+ extractStringsFromNodes: () => extractStringsFromNodes,
160
2259
  factory: () => factory_exports,
161
2260
  fileDef: () => fileDef,
2261
+ findCircularSchemas: () => findCircularSchemas,
162
2262
  functionDef: () => functionDef,
2263
+ getNestedAccessor: () => getNestedAccessor,
163
2264
  importDef: () => importDef,
164
2265
  inputDef: () => inputDef,
165
2266
  isHttpOperationNode: () => isHttpOperationNode,
2267
+ isStringType: () => isStringType,
2268
+ isValidVarName: () => isValidVarName,
2269
+ jsStringEscape: () => jsStringEscape,
166
2270
  jsxDef: () => jsxDef,
2271
+ lazyGetter: () => lazyGetter,
2272
+ macroDiscriminatorEnum: () => macroDiscriminatorEnum,
2273
+ macroEnumName: () => macroEnumName,
2274
+ macroSimplifyUnion: () => macroSimplifyUnion,
2275
+ mapSchemaItems: () => mapSchemaItems,
2276
+ mapSchemaMembers: () => mapSchemaMembers,
2277
+ mapSchemaProperties: () => mapSchemaProperties,
2278
+ mergeAdjacentObjectsLazy: () => mergeAdjacentObjectsLazy,
167
2279
  narrowSchema: () => narrowSchema,
168
2280
  nodeDefs: () => nodeDefs,
2281
+ objectKey: () => objectKey,
169
2282
  operationDef: () => operationDef,
170
2283
  optionality: () => optionality,
171
2284
  outputDef: () => outputDef,
@@ -176,12 +2289,17 @@ var exports_exports = /* @__PURE__ */ __exportAll({
176
2289
  schemaDef: () => schemaDef,
177
2290
  schemaTypes: () => schemaTypes,
178
2291
  sourceDef: () => sourceDef,
2292
+ stringify: () => stringify,
2293
+ stringifyObject: () => stringifyObject,
2294
+ syncSchemaRef: () => syncSchemaRef,
179
2295
  textDef: () => textDef,
2296
+ toRegExpString: () => toRegExpString,
180
2297
  transform: () => transform,
2298
+ trimQuotes: () => trimQuotes,
181
2299
  typeDef: () => typeDef,
182
2300
  walk: () => walk
183
2301
  });
184
2302
  //#endregion
185
- export { applyMacros, arrowFunctionDef, exports_exports as ast, breakDef, collect, composeMacros, constDef, contentDef, createPrinter, defineDialect, defineMacro, defineNode, exportDef, factory_exports as factory, fileDef, functionDef, importDef, inputDef, isHttpOperationNode, jsxDef, narrowSchema, nodeDefs, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, textDef, transform, typeDef, walk };
2303
+ export { applyMacros, arrowFunctionDef, exports_exports as ast, breakDef, buildJSDoc, buildList, buildObject, childName, collect, collectUsedSchemaNames, composeMacros, constDef, containsCircularRef, contentDef, createPrinter, defineDialect, defineMacro, defineNode, enumPropName, exportDef, extractRefName, extractStringsFromNodes, factory_exports as factory, fileDef, findCircularSchemas, functionDef, getNestedAccessor, importDef, inputDef, isHttpOperationNode, isStringType, isValidVarName, jsStringEscape, jsxDef, lazyGetter, macroDiscriminatorEnum, macroEnumName, macroSimplifyUnion, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, narrowSchema, nodeDefs, objectKey, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, stringify, stringifyObject, syncSchemaRef, textDef, toRegExpString, transform, trimQuotes, typeDef, walk };
186
2304
 
187
2305
  //# sourceMappingURL=index.js.map