@kubb/ast 5.0.0-beta.7 → 5.0.0-beta.71

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 (65) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +53 -27
  3. package/dist/defineMacro-5Dvct8k_.cjs +114 -0
  4. package/dist/defineMacro-5Dvct8k_.cjs.map +1 -0
  5. package/dist/defineMacro-BXpTwp0y.d.ts +466 -0
  6. package/dist/defineMacro-VfsvblGi.js +98 -0
  7. package/dist/defineMacro-VfsvblGi.js.map +1 -0
  8. package/dist/index-DJEyS5y6.d.ts +2428 -0
  9. package/dist/index.cjs +198 -2239
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts +98 -3400
  12. package/dist/index.js +149 -2160
  13. package/dist/index.js.map +1 -1
  14. package/dist/macros.cjs +130 -0
  15. package/dist/macros.cjs.map +1 -0
  16. package/dist/macros.d.ts +61 -0
  17. package/dist/macros.js +128 -0
  18. package/dist/macros.js.map +1 -0
  19. package/dist/operationParams-BaY12i2I.d.ts +148 -0
  20. package/dist/refs-D18OeCgb.js +117 -0
  21. package/dist/refs-D18OeCgb.js.map +1 -0
  22. package/dist/refs-DuP3_Leg.cjs +157 -0
  23. package/dist/refs-DuP3_Leg.cjs.map +1 -0
  24. package/dist/rolldown-runtime-CNktS9qV.js +17 -0
  25. package/dist/types-BsP1SK9j.d.ts +244 -0
  26. package/dist/types.cjs +0 -0
  27. package/dist/types.d.ts +5 -0
  28. package/dist/types.js +1 -0
  29. package/dist/utils.cjs +803 -0
  30. package/dist/utils.cjs.map +1 -0
  31. package/dist/utils.d.ts +354 -0
  32. package/dist/utils.js +777 -0
  33. package/dist/utils.js.map +1 -0
  34. package/dist/visitor-CQdSiClY.cjs +1749 -0
  35. package/dist/visitor-CQdSiClY.cjs.map +1 -0
  36. package/dist/visitor-dcVC5TOW.js +1313 -0
  37. package/dist/visitor-dcVC5TOW.js.map +1 -0
  38. package/package.json +17 -5
  39. package/dist/chunk--u3MIqq1.js +0 -8
  40. package/src/constants.ts +0 -228
  41. package/src/factory.ts +0 -742
  42. package/src/guards.ts +0 -110
  43. package/src/index.ts +0 -46
  44. package/src/infer.ts +0 -130
  45. package/src/mocks.ts +0 -176
  46. package/src/nodes/base.ts +0 -56
  47. package/src/nodes/code.ts +0 -304
  48. package/src/nodes/file.ts +0 -230
  49. package/src/nodes/function.ts +0 -223
  50. package/src/nodes/http.ts +0 -119
  51. package/src/nodes/index.ts +0 -86
  52. package/src/nodes/operation.ts +0 -111
  53. package/src/nodes/output.ts +0 -26
  54. package/src/nodes/parameter.ts +0 -41
  55. package/src/nodes/property.ts +0 -34
  56. package/src/nodes/response.ts +0 -43
  57. package/src/nodes/root.ts +0 -64
  58. package/src/nodes/schema.ts +0 -656
  59. package/src/printer.ts +0 -250
  60. package/src/refs.ts +0 -67
  61. package/src/resolvers.ts +0 -45
  62. package/src/transformers.ts +0 -159
  63. package/src/types.ts +0 -70
  64. package/src/utils.ts +0 -915
  65. package/src/visitor.ts +0 -592
@@ -0,0 +1,1749 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __name = (target, value) => __defProp(target, "name", {
5
+ value,
6
+ configurable: true
7
+ });
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __exportAll = (all, no_symbols) => {
13
+ let target = {};
14
+ for (var name in all) __defProp(target, name, {
15
+ get: all[name],
16
+ enumerable: true
17
+ });
18
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
19
+ return target;
20
+ };
21
+ var __copyProps = (to, from, except, desc) => {
22
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
23
+ key = keys[i];
24
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
25
+ get: ((k) => from[k]).bind(null, key),
26
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
27
+ });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
32
+ value: mod,
33
+ enumerable: true
34
+ }) : target, mod));
35
+ //#endregion
36
+ let node_crypto = require("node:crypto");
37
+ let node_path = require("node:path");
38
+ node_path = __toESM(node_path, 1);
39
+ //#region src/constants.ts
40
+ const visitorDepths = {
41
+ shallow: "shallow",
42
+ deep: "deep"
43
+ };
44
+ /**
45
+ * Schema type discriminators used by all AST schema nodes.
46
+ *
47
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
48
+ */
49
+ const schemaTypes = {
50
+ /**
51
+ * Text value.
52
+ */
53
+ string: "string",
54
+ /**
55
+ * Floating-point number (`float`, `double`).
56
+ */
57
+ number: "number",
58
+ /**
59
+ * Whole number (`int32`). Use `bigint` for `int64`.
60
+ */
61
+ integer: "integer",
62
+ /**
63
+ * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
64
+ */
65
+ bigint: "bigint",
66
+ /**
67
+ * Boolean value.
68
+ */
69
+ boolean: "boolean",
70
+ /**
71
+ * Explicit null value.
72
+ */
73
+ null: "null",
74
+ /**
75
+ * Any value (no type restriction).
76
+ */
77
+ any: "any",
78
+ /**
79
+ * Unknown value (must be narrowed before usage).
80
+ */
81
+ unknown: "unknown",
82
+ /**
83
+ * No return value (`void`).
84
+ */
85
+ void: "void",
86
+ /**
87
+ * Object with named properties.
88
+ */
89
+ object: "object",
90
+ /**
91
+ * Sequential list of items.
92
+ */
93
+ array: "array",
94
+ /**
95
+ * Fixed-length list with position-specific items.
96
+ */
97
+ tuple: "tuple",
98
+ /**
99
+ * "One of" multiple schema members.
100
+ */
101
+ union: "union",
102
+ /**
103
+ * "All of" multiple schema members.
104
+ */
105
+ intersection: "intersection",
106
+ /**
107
+ * Enum schema.
108
+ */
109
+ enum: "enum",
110
+ /**
111
+ * Reference to another schema.
112
+ */
113
+ ref: "ref",
114
+ /**
115
+ * Calendar date (for example `2026-03-24`).
116
+ */
117
+ date: "date",
118
+ /**
119
+ * Date-time value (for example `2026-03-24T09:00:00Z`).
120
+ */
121
+ datetime: "datetime",
122
+ /**
123
+ * Time-only value (for example `09:00:00`).
124
+ */
125
+ time: "time",
126
+ /**
127
+ * UUID value.
128
+ */
129
+ uuid: "uuid",
130
+ /**
131
+ * Email address value.
132
+ */
133
+ email: "email",
134
+ /**
135
+ * URL value.
136
+ */
137
+ url: "url",
138
+ /**
139
+ * IPv4 address value.
140
+ */
141
+ ipv4: "ipv4",
142
+ /**
143
+ * IPv6 address value.
144
+ */
145
+ ipv6: "ipv6",
146
+ /**
147
+ * Binary/blob value.
148
+ */
149
+ blob: "blob",
150
+ /**
151
+ * Impossible value (`never`).
152
+ */
153
+ never: "never"
154
+ };
155
+ /**
156
+ * One indentation level, derived from {@link INDENT_SIZE}.
157
+ */
158
+ const INDENT = Array.from({ length: 2 }, () => " ").join("");
159
+ //#endregion
160
+ //#region src/guards.ts
161
+ /**
162
+ * Narrows a `SchemaNode` to the variant that matches `type`.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const schema = createSchema({ type: 'string' })
167
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
168
+ * ```
169
+ */
170
+ function narrowSchema(node, type) {
171
+ return node?.type === type ? node : null;
172
+ }
173
+ /**
174
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * if (isHttpOperationNode(node)) {
179
+ * console.log(node.method, node.path)
180
+ * }
181
+ * ```
182
+ */
183
+ function isHttpOperationNode(node) {
184
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
185
+ }
186
+ //#endregion
187
+ //#region src/defineNode.ts
188
+ /**
189
+ * Visitor callback names, one per traversable node kind, in traversal order.
190
+ * Kept in sync with the keys of `Visitor` in `visitor.ts`.
191
+ */
192
+ const visitorKeys = [
193
+ "input",
194
+ "output",
195
+ "operation",
196
+ "schema",
197
+ "property",
198
+ "parameter",
199
+ "response"
200
+ ];
201
+ /**
202
+ * Builds a type guard that matches nodes of the given `kind`.
203
+ */
204
+ function isKind(kind) {
205
+ return (node) => node?.kind === kind;
206
+ }
207
+ /**
208
+ * Defines a node once and derives its `create` builder, `is` guard, and traversal
209
+ * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
210
+ * `kind`, so node construction lives in one place without scattered `as` casts.
211
+ *
212
+ * @example Simple node
213
+ * ```ts
214
+ * const importDef = defineNode<ImportNode>({ kind: 'Import' })
215
+ * const createImport = importDef.create
216
+ * ```
217
+ *
218
+ * @example Node with a build hook
219
+ * ```ts
220
+ * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
221
+ * kind: 'Property',
222
+ * build: (props) => ({ ...props, required: props.required ?? false }),
223
+ * children: ['schema'],
224
+ * visitorKey: 'property',
225
+ * })
226
+ * ```
227
+ */
228
+ function defineNode(config) {
229
+ const { kind, defaults, build, children, visitorKey } = config;
230
+ function create(input) {
231
+ const base = build ? build(input) : input;
232
+ return {
233
+ ...defaults,
234
+ ...base,
235
+ kind
236
+ };
237
+ }
238
+ return {
239
+ kind,
240
+ create,
241
+ is: isKind(kind),
242
+ children,
243
+ visitorKey
244
+ };
245
+ }
246
+ //#endregion
247
+ //#region src/nodes/code.ts
248
+ /**
249
+ * Definition for the {@link ConstNode}.
250
+ */
251
+ const constDef = defineNode({ kind: "Const" });
252
+ /**
253
+ * Definition for the {@link TypeNode}.
254
+ */
255
+ const typeDef = defineNode({ kind: "Type" });
256
+ /**
257
+ * Definition for the {@link FunctionNode}.
258
+ */
259
+ const functionDef = defineNode({ kind: "Function" });
260
+ /**
261
+ * Definition for the {@link ArrowFunctionNode}.
262
+ */
263
+ const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
264
+ /**
265
+ * Definition for the {@link TextNode}.
266
+ */
267
+ const textDef = defineNode({
268
+ kind: "Text",
269
+ build: (value) => ({ value })
270
+ });
271
+ /**
272
+ * Definition for the {@link BreakNode}.
273
+ */
274
+ const breakDef = defineNode({
275
+ kind: "Break",
276
+ build: () => ({})
277
+ });
278
+ /**
279
+ * Definition for the {@link JsxNode}.
280
+ */
281
+ const jsxDef = defineNode({
282
+ kind: "Jsx",
283
+ build: (value) => ({ value })
284
+ });
285
+ /**
286
+ * Creates a `ConstNode` representing a TypeScript `const` declaration.
287
+ *
288
+ * @example Exported constant with type and `as const`
289
+ * ```ts
290
+ * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
291
+ * // export const pets: Pet[] = ... as const
292
+ * ```
293
+ */
294
+ const createConst = constDef.create;
295
+ /**
296
+ * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * createType({ name: 'Pet', export: true })
301
+ * // export type Pet = ...
302
+ * ```
303
+ */
304
+ const createType = typeDef.create;
305
+ /**
306
+ * Creates a `FunctionNode` representing a TypeScript `function` declaration.
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
311
+ * // export async function fetchPet(): Promise<Pet> { ... }
312
+ * ```
313
+ */
314
+ const createFunction = functionDef.create;
315
+ /**
316
+ * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
321
+ * // export const double = (n: number) => ...
322
+ * ```
323
+ */
324
+ const createArrowFunction = arrowFunctionDef.create;
325
+ /**
326
+ * Creates a {@link TextNode} representing a raw string fragment in the source output.
327
+ *
328
+ * @example
329
+ * ```ts
330
+ * createText('return fetch(id)')
331
+ * // { kind: 'Text', value: 'return fetch(id)' }
332
+ * ```
333
+ */
334
+ const createText = textDef.create;
335
+ /**
336
+ * Creates a {@link BreakNode} representing a line break in the source output.
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * createBreak()
341
+ * // { kind: 'Break' }
342
+ * ```
343
+ */
344
+ function createBreak() {
345
+ return breakDef.create();
346
+ }
347
+ /**
348
+ * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
349
+ *
350
+ * @example
351
+ * ```ts
352
+ * createJsx('<>\n <a href={href}>Open</a>\n</>')
353
+ * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
354
+ * ```
355
+ */
356
+ const createJsx = jsxDef.create;
357
+ //#endregion
358
+ //#region src/nodes/content.ts
359
+ /**
360
+ * Definition for the {@link ContentNode}.
361
+ */
362
+ const contentDef = defineNode({
363
+ kind: "Content",
364
+ children: ["schema"]
365
+ });
366
+ /**
367
+ * Creates a `ContentNode` for a single request-body or response content type.
368
+ */
369
+ const createContent = contentDef.create;
370
+ //#endregion
371
+ //#region ../../internals/utils/src/casing.ts
372
+ /**
373
+ * Shared implementation for camelCase and PascalCase conversion.
374
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
375
+ * and capitalizes each word according to `pascal`.
376
+ *
377
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
378
+ */
379
+ function toCamelOrPascal(text, pascal) {
380
+ 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) => {
381
+ if (word.length > 1 && word === word.toUpperCase()) return word;
382
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
383
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
384
+ }
385
+ /**
386
+ * Converts `text` to camelCase.
387
+ *
388
+ * @example Word boundaries
389
+ * `camelCase('hello-world') // 'helloWorld'`
390
+ *
391
+ * @example With a prefix
392
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
393
+ */
394
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
395
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
396
+ }
397
+ /**
398
+ * Converts `text` to PascalCase.
399
+ *
400
+ * @example Word boundaries
401
+ * `pascalCase('hello-world') // 'HelloWorld'`
402
+ *
403
+ * @example With a suffix
404
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
405
+ */
406
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
407
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
408
+ }
409
+ //#endregion
410
+ //#region ../../internals/utils/src/fs.ts
411
+ /**
412
+ * Strips the file extension from a path or file name.
413
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
414
+ *
415
+ * @example
416
+ * trimExtName('petStore.ts') // 'petStore'
417
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
418
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
419
+ * trimExtName('noExtension') // 'noExtension'
420
+ */
421
+ function trimExtName(text) {
422
+ const dotIndex = text.lastIndexOf(".");
423
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
424
+ return text;
425
+ }
426
+ //#endregion
427
+ //#region src/utils/extractStringsFromNodes.ts
428
+ /**
429
+ * Extracts all string content from a `CodeNode` tree recursively.
430
+ *
431
+ * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
432
+ * and nested node content. Used to build the full source string for import filtering.
433
+ */
434
+ function extractStringsFromNodes(nodes) {
435
+ if (!nodes?.length) return "";
436
+ return nodes.map((node) => {
437
+ if (typeof node === "string") return node;
438
+ if (node.kind === "Text") return node.value;
439
+ if (node.kind === "Break") return "";
440
+ if (node.kind === "Jsx") return node.value;
441
+ const parts = [];
442
+ if ("params" in node && node.params) parts.push(node.params);
443
+ if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
444
+ if ("returnType" in node && node.returnType) parts.push(node.returnType);
445
+ if ("type" in node && typeof node.type === "string") parts.push(node.type);
446
+ const nested = extractStringsFromNodes(node.nodes);
447
+ if (nested) parts.push(nested);
448
+ return parts.join("\n");
449
+ }).filter(Boolean).join("\n");
450
+ }
451
+ //#endregion
452
+ //#region src/utils/fileMerge.ts
453
+ function sourceKey(source) {
454
+ return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
455
+ }
456
+ function pathTypeKey(path, isTypeOnly) {
457
+ return `${path}:${isTypeOnly ?? false}`;
458
+ }
459
+ function exportKey(path, name, isTypeOnly, asAlias) {
460
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
461
+ }
462
+ function importKey(path, name, isTypeOnly) {
463
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
464
+ }
465
+ /**
466
+ * Computes a multi-level sort key for exports and imports:
467
+ * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
468
+ */
469
+ function sortKey(node) {
470
+ const isArray = Array.isArray(node.name) ? "1" : "0";
471
+ const typeOnly = node.isTypeOnly ? "0" : "1";
472
+ const hasName = node.name != null ? "1" : "0";
473
+ const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
474
+ return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
475
+ }
476
+ /**
477
+ * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
478
+ * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
479
+ * the deduplicated array in original order.
480
+ */
481
+ function combineSources(sources) {
482
+ const seen = /* @__PURE__ */ new Map();
483
+ for (const source of sources) {
484
+ const key = sourceKey(source);
485
+ if (!seen.has(key)) seen.set(key, source);
486
+ }
487
+ return [...seen.values()];
488
+ }
489
+ /**
490
+ * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
491
+ *
492
+ * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
493
+ */
494
+ function mergeNameArrays(existing, incoming) {
495
+ const merged = new Set(existing);
496
+ for (const name of incoming) merged.add(name);
497
+ return [...merged];
498
+ }
499
+ /**
500
+ * Deduplicates and merges `ExportNode` objects by path and type.
501
+ *
502
+ * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
503
+ * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
504
+ */
505
+ function combineExports(exports) {
506
+ const result = [];
507
+ const namedByPath = /* @__PURE__ */ new Map();
508
+ const seen = /* @__PURE__ */ new Set();
509
+ const keyed = exports.map((node) => ({
510
+ node,
511
+ key: sortKey(node)
512
+ }));
513
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
514
+ for (const { node: curr } of keyed) {
515
+ const { name, path, isTypeOnly, asAlias } = curr;
516
+ if (Array.isArray(name)) {
517
+ if (!name.length) continue;
518
+ const key = pathTypeKey(path, isTypeOnly);
519
+ const existing = namedByPath.get(key);
520
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
521
+ else {
522
+ const newItem = {
523
+ ...curr,
524
+ name: [...new Set(name)]
525
+ };
526
+ result.push(newItem);
527
+ namedByPath.set(key, newItem);
528
+ }
529
+ } else {
530
+ const key = exportKey(path, name, isTypeOnly, asAlias);
531
+ if (!seen.has(key)) {
532
+ result.push(curr);
533
+ seen.add(key);
534
+ }
535
+ }
536
+ }
537
+ return result;
538
+ }
539
+ /**
540
+ * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
541
+ *
542
+ * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
543
+ * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
544
+ */
545
+ function combineImports(imports, exports, source) {
546
+ const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
547
+ const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
548
+ const importNameMemo = /* @__PURE__ */ new Map();
549
+ const canonicalizeName = (n) => {
550
+ if (typeof n === "string") return n;
551
+ const key = `${n.propertyName}:${n.name ?? ""}`;
552
+ if (!importNameMemo.has(key)) importNameMemo.set(key, n);
553
+ return importNameMemo.get(key);
554
+ };
555
+ const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
556
+ for (const node of imports) {
557
+ if (!Array.isArray(node.name)) continue;
558
+ if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
559
+ }
560
+ const result = [];
561
+ const namedByPath = /* @__PURE__ */ new Map();
562
+ const seen = /* @__PURE__ */ new Set();
563
+ const keyed = imports.map((node) => ({
564
+ node,
565
+ key: sortKey(node)
566
+ }));
567
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
568
+ for (const { node: curr } of keyed) {
569
+ if (curr.path === curr.root) continue;
570
+ const { path, isTypeOnly } = curr;
571
+ let { name } = curr;
572
+ if (Array.isArray(name)) {
573
+ name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
574
+ if (!name.length) continue;
575
+ const key = pathTypeKey(path, isTypeOnly);
576
+ const existing = namedByPath.get(key);
577
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
578
+ else {
579
+ const newItem = {
580
+ ...curr,
581
+ name
582
+ };
583
+ result.push(newItem);
584
+ namedByPath.set(key, newItem);
585
+ }
586
+ } else {
587
+ if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
588
+ const key = importKey(path, name, isTypeOnly);
589
+ if (!seen.has(key)) {
590
+ result.push(curr);
591
+ seen.add(key);
592
+ }
593
+ }
594
+ }
595
+ return result;
596
+ }
597
+ //#endregion
598
+ //#region src/nodes/file.ts
599
+ /**
600
+ * Definition for the {@link ImportNode}.
601
+ */
602
+ const importDef = defineNode({ kind: "Import" });
603
+ /**
604
+ * Definition for the {@link ExportNode}.
605
+ */
606
+ const exportDef = defineNode({ kind: "Export" });
607
+ /**
608
+ * Definition for the {@link SourceNode}.
609
+ */
610
+ const sourceDef = defineNode({ kind: "Source" });
611
+ /**
612
+ * Definition for the {@link FileNode}. The fully resolved builder lives in
613
+ * `createFile`, so this definition only supplies the guard.
614
+ */
615
+ const fileDef = defineNode({ kind: "File" });
616
+ /**
617
+ * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
618
+ *
619
+ * @example Named import
620
+ * ```ts
621
+ * createImport({ name: ['useState'], path: 'react' })
622
+ * // import { useState } from 'react'
623
+ * ```
624
+ */
625
+ const createImport = importDef.create;
626
+ /**
627
+ * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
628
+ *
629
+ * @example Named export
630
+ * ```ts
631
+ * createExport({ name: ['Pet'], path: './Pet' })
632
+ * // export { Pet } from './Pet'
633
+ * ```
634
+ */
635
+ const createExport = exportDef.create;
636
+ /**
637
+ * Creates a `SourceNode` representing a fragment of source code within a file.
638
+ *
639
+ * @example
640
+ * ```ts
641
+ * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
642
+ * ```
643
+ */
644
+ const createSource = sourceDef.create;
645
+ /**
646
+ * Creates a fully resolved `FileNode` from a file input descriptor.
647
+ *
648
+ * Computes:
649
+ * - `id` SHA256 hash of the file path
650
+ * - `name` `baseName` without extension
651
+ * - `extname` extension extracted from `baseName`
652
+ *
653
+ * Deduplicates:
654
+ * - `sources` via `combineSources`
655
+ * - `exports` via `combineExports`
656
+ * - `imports` via `combineImports` (also filters unused imports)
657
+ *
658
+ * @throws {Error} when `baseName` has no extension.
659
+ *
660
+ * @example
661
+ * ```ts
662
+ * const file = createFile({
663
+ * baseName: 'petStore.ts',
664
+ * path: 'src/models/petStore.ts',
665
+ * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
666
+ * imports: [createImport({ name: ['z'], path: 'zod' })],
667
+ * exports: [createExport({ name: ['Pet'], path: './petStore' })],
668
+ * })
669
+ * // file.id = SHA256 hash of 'src/models/petStore.ts'
670
+ * // file.name = 'petStore'
671
+ * // file.extname = '.ts'
672
+ * ```
673
+ *
674
+ * @example Copy a real file into the output verbatim
675
+ * ```ts
676
+ * const file = createFile({
677
+ * baseName: 'client.ts',
678
+ * path: 'src/gen/client.ts',
679
+ * copy: '/abs/path/to/templates/client.ts',
680
+ * })
681
+ * ```
682
+ */
683
+ function createFile(input) {
684
+ const extname = node_path.default.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
685
+ if (!extname) throw new Error(`No extname found for ${input.baseName}`);
686
+ const source = (input.sources ?? []).flatMap((item) => item.nodes ?? []).map((node) => extractStringsFromNodes([node])).filter(Boolean).join("\n\n");
687
+ const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
688
+ const combinedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || void 0) : [];
689
+ const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
690
+ const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
691
+ const resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
692
+ if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
693
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
694
+ if (!kept.length) return [];
695
+ return [kept.length === imp.name.length ? imp : {
696
+ ...imp,
697
+ name: kept
698
+ }];
699
+ });
700
+ const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
701
+ return {
702
+ kind: "File",
703
+ ...input,
704
+ id: (0, node_crypto.hash)("sha256", input.path, "hex"),
705
+ name: trimExtName(input.baseName),
706
+ extname,
707
+ imports: resolvedImports,
708
+ exports: resolvedExports,
709
+ sources: resolvedSources,
710
+ meta: input.meta ?? {}
711
+ };
712
+ }
713
+ //#endregion
714
+ //#region src/nodes/function.ts
715
+ /**
716
+ * Definition for the {@link TypeLiteralNode}.
717
+ */
718
+ const typeLiteralDef = defineNode({ kind: "TypeLiteral" });
719
+ /**
720
+ * Definition for the {@link IndexedAccessTypeNode}.
721
+ */
722
+ const indexedAccessTypeDef = defineNode({ kind: "IndexedAccessType" });
723
+ /**
724
+ * Definition for the {@link ObjectBindingPatternNode}.
725
+ */
726
+ const objectBindingPatternDef = defineNode({ kind: "ObjectBindingPattern" });
727
+ /**
728
+ * Definition for the {@link FunctionParameterNode}. `optional` defaults to `false`.
729
+ * Passing `properties` builds a destructured group: an {@link ObjectBindingPatternNode} name
730
+ * paired with a {@link TypeLiteralNode} type.
731
+ */
732
+ const functionParameterDef = defineNode({
733
+ kind: "FunctionParameter",
734
+ build: (input) => {
735
+ if ("properties" in input) return {
736
+ name: createObjectBindingPattern({ elements: input.properties.map((p) => ({ name: p.name })) }),
737
+ type: createTypeLiteral({ members: input.properties.map((p) => ({
738
+ name: p.name,
739
+ type: p.type,
740
+ optional: p.optional ?? false
741
+ })) }),
742
+ optional: input.optional ?? false,
743
+ ...input.default !== void 0 ? { default: input.default } : {}
744
+ };
745
+ return {
746
+ optional: false,
747
+ ...input
748
+ };
749
+ }
750
+ });
751
+ /**
752
+ * Definition for the {@link FunctionParametersNode}.
753
+ */
754
+ const functionParametersDef = defineNode({
755
+ kind: "FunctionParameters",
756
+ defaults: { params: [] }
757
+ });
758
+ /**
759
+ * Creates a {@link TypeLiteralNode} representing an inline anonymous object type.
760
+ *
761
+ * @example
762
+ * ```ts
763
+ * createTypeLiteral({ members: [{ name: 'petId', type: 'string', optional: false }] })
764
+ * // { petId: string }
765
+ * ```
766
+ */
767
+ const createTypeLiteral = typeLiteralDef.create;
768
+ /**
769
+ * Creates an {@link IndexedAccessTypeNode} representing a single field accessed from a named type.
770
+ *
771
+ * @example
772
+ * ```ts
773
+ * createIndexedAccessType({ target: 'DeletePetPathParams', key: 'petId' })
774
+ * // DeletePetPathParams['petId']
775
+ * ```
776
+ */
777
+ const createIndexedAccessType = indexedAccessTypeDef.create;
778
+ /**
779
+ * Creates an {@link ObjectBindingPatternNode} for a destructured parameter binding.
780
+ *
781
+ * @example
782
+ * ```ts
783
+ * createObjectBindingPattern({ elements: [{ name: 'id' }, { name: 'name' }] })
784
+ * // { id, name }
785
+ * ```
786
+ */
787
+ const createObjectBindingPattern = objectBindingPatternDef.create;
788
+ /**
789
+ * Creates a `FunctionParameterNode`. `optional` defaults to `false`.
790
+ *
791
+ * @example Optional param
792
+ * ```ts
793
+ * createFunctionParameter({ name: 'params', type: 'QueryParams', optional: true })
794
+ * // → params?: QueryParams
795
+ * ```
796
+ *
797
+ * @example Destructured group
798
+ * ```ts
799
+ * createFunctionParameter({ properties: [{ name: 'id', type: 'string' }, { name: 'name', type: 'string', optional: true }], default: '{}' })
800
+ * // → { id, name }: { id: string; name?: string } = {}
801
+ * ```
802
+ *
803
+ * @example Destructured group typed from a single reference
804
+ * ```ts
805
+ * createFunctionParameter({ name: createObjectBindingPattern({ elements: [{ name: 'path' }] }), type: "Omit<Config, 'url'>", default: '{}' })
806
+ * // → { path }: Omit<Config, 'url'> = {}
807
+ * ```
808
+ */
809
+ const createFunctionParameter = functionParameterDef.create;
810
+ /**
811
+ * Creates a `FunctionParametersNode` from an ordered list of parameters.
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * const empty = createFunctionParameters()
816
+ * // { kind: 'FunctionParameters', params: [] }
817
+ * ```
818
+ */
819
+ function createFunctionParameters(props = {}) {
820
+ return functionParametersDef.create(props);
821
+ }
822
+ //#endregion
823
+ //#region src/nodes/input.ts
824
+ /**
825
+ * Definition for the {@link InputNode}.
826
+ */
827
+ const inputDef = defineNode({
828
+ kind: "Input",
829
+ defaults: {
830
+ schemas: [],
831
+ operations: [],
832
+ meta: {
833
+ circularNames: [],
834
+ enumNames: []
835
+ }
836
+ },
837
+ children: ["schemas", "operations"],
838
+ visitorKey: "input"
839
+ });
840
+ /**
841
+ * Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
842
+ * `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
843
+ * `schemas`/`operations`. Both variants get the defaulted `meta`.
844
+ *
845
+ * @example Eager
846
+ * ```ts
847
+ * const input = createInput()
848
+ * // { kind: 'Input', schemas: [], operations: [] }
849
+ * ```
850
+ *
851
+ * @example Streaming
852
+ * ```ts
853
+ * const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
854
+ * ```
855
+ */
856
+ function createInput(options = {}) {
857
+ const { stream, ...overrides } = options;
858
+ if (stream) return {
859
+ kind: "Input",
860
+ meta: {
861
+ circularNames: [],
862
+ enumNames: []
863
+ },
864
+ ...overrides
865
+ };
866
+ return inputDef.create(overrides);
867
+ }
868
+ //#endregion
869
+ //#region src/nodes/requestBody.ts
870
+ /**
871
+ * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
872
+ * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
873
+ */
874
+ const requestBodyDef = defineNode({
875
+ kind: "RequestBody",
876
+ children: ["content"]
877
+ });
878
+ /**
879
+ * Creates a `RequestBodyNode`.
880
+ */
881
+ const createRequestBody = requestBodyDef.create;
882
+ //#endregion
883
+ //#region src/nodes/operation.ts
884
+ /**
885
+ * Definition for the {@link OperationNode}. HTTP operations (those carrying both
886
+ * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
887
+ * normalized into a `RequestBodyNode`.
888
+ */
889
+ const operationDef = defineNode({
890
+ kind: "Operation",
891
+ build: (props) => {
892
+ const { requestBody, ...rest } = props;
893
+ const isHttp = rest.method !== void 0 && rest.path !== void 0;
894
+ return {
895
+ tags: [],
896
+ parameters: [],
897
+ responses: [],
898
+ ...rest,
899
+ ...isHttp ? { protocol: "http" } : {},
900
+ requestBody: requestBody ? createRequestBody(requestBody) : void 0
901
+ };
902
+ },
903
+ children: [
904
+ "parameters",
905
+ "requestBody",
906
+ "responses"
907
+ ],
908
+ visitorKey: "operation"
909
+ });
910
+ function createOperation(props) {
911
+ return operationDef.create(props);
912
+ }
913
+ //#endregion
914
+ //#region src/nodes/output.ts
915
+ /**
916
+ * Definition for the {@link OutputNode}.
917
+ */
918
+ const outputDef = defineNode({
919
+ kind: "Output",
920
+ defaults: { files: [] },
921
+ visitorKey: "output"
922
+ });
923
+ /**
924
+ * Creates an `OutputNode` with a stable default for `files`.
925
+ *
926
+ * @example
927
+ * ```ts
928
+ * const output = createOutput()
929
+ * // { kind: 'Output', files: [] }
930
+ * ```
931
+ */
932
+ function createOutput(overrides = {}) {
933
+ return outputDef.create(overrides);
934
+ }
935
+ //#endregion
936
+ //#region src/optionality.ts
937
+ /**
938
+ * Generic JSON Schema optionality: a non-required field is optional, and a
939
+ * non-required nullable field is nullish.
940
+ */
941
+ function optionality(schema, required) {
942
+ const nullable = schema.nullable ?? false;
943
+ return {
944
+ ...schema,
945
+ optional: !required && !nullable ? true : void 0,
946
+ nullish: !required && nullable ? true : void 0
947
+ };
948
+ }
949
+ //#endregion
950
+ //#region src/nodes/parameter.ts
951
+ /**
952
+ * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
953
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
954
+ */
955
+ const parameterDef = defineNode({
956
+ kind: "Parameter",
957
+ build: (props) => {
958
+ const required = props.required ?? false;
959
+ return {
960
+ ...props,
961
+ required,
962
+ schema: optionality(props.schema, required)
963
+ };
964
+ },
965
+ children: ["schema"],
966
+ visitorKey: "parameter"
967
+ });
968
+ /**
969
+ * Creates a `ParameterNode`.
970
+ *
971
+ * @example
972
+ * ```ts
973
+ * const param = createParameter({
974
+ * name: 'petId',
975
+ * in: 'path',
976
+ * required: true,
977
+ * schema: createSchema({ type: 'string' }),
978
+ * })
979
+ * ```
980
+ */
981
+ const createParameter = parameterDef.create;
982
+ //#endregion
983
+ //#region src/nodes/property.ts
984
+ /**
985
+ * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
986
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
987
+ */
988
+ const propertyDef = defineNode({
989
+ kind: "Property",
990
+ build: (props) => {
991
+ const required = props.required ?? false;
992
+ return {
993
+ ...props,
994
+ required,
995
+ schema: optionality(props.schema, required)
996
+ };
997
+ },
998
+ children: ["schema"],
999
+ visitorKey: "property"
1000
+ });
1001
+ /**
1002
+ * Creates a `PropertyNode`.
1003
+ *
1004
+ * @example
1005
+ * ```ts
1006
+ * const property = createProperty({
1007
+ * name: 'status',
1008
+ * required: true,
1009
+ * schema: createSchema({ type: 'string', nullable: true }),
1010
+ * })
1011
+ * // required=true, no optional/nullish
1012
+ * ```
1013
+ */
1014
+ const createProperty = propertyDef.create;
1015
+ //#endregion
1016
+ //#region src/nodes/response.ts
1017
+ /**
1018
+ * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
1019
+ * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
1020
+ */
1021
+ const responseDef = defineNode({
1022
+ kind: "Response",
1023
+ build: (props) => {
1024
+ const { schema, mediaType, keysToOmit, content, ...rest } = props;
1025
+ const entries = content ?? (schema ? [createContent({
1026
+ contentType: mediaType ?? "application/json",
1027
+ schema,
1028
+ keysToOmit: keysToOmit ?? null
1029
+ })] : void 0);
1030
+ return {
1031
+ ...rest,
1032
+ content: entries
1033
+ };
1034
+ },
1035
+ children: ["content"],
1036
+ visitorKey: "response"
1037
+ });
1038
+ /**
1039
+ * Creates a `ResponseNode`.
1040
+ *
1041
+ * @example
1042
+ * ```ts
1043
+ * const response = createResponse({
1044
+ * statusCode: '200',
1045
+ * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
1046
+ * })
1047
+ * ```
1048
+ */
1049
+ const createResponse = responseDef.create;
1050
+ //#endregion
1051
+ //#region src/nodes/schema.ts
1052
+ /**
1053
+ * Maps schema `type` to its underlying `primitive`.
1054
+ * Primitive types map to themselves and special string formats map to `'string'`.
1055
+ * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
1056
+ */
1057
+ const TYPE_TO_PRIMITIVE = {
1058
+ string: "string",
1059
+ number: "number",
1060
+ integer: "integer",
1061
+ bigint: "bigint",
1062
+ boolean: "boolean",
1063
+ null: "null",
1064
+ any: "any",
1065
+ unknown: "unknown",
1066
+ void: "void",
1067
+ never: "never",
1068
+ object: "object",
1069
+ array: "array",
1070
+ date: "date",
1071
+ uuid: "string",
1072
+ email: "string",
1073
+ url: "string",
1074
+ datetime: "string",
1075
+ time: "string"
1076
+ };
1077
+ /**
1078
+ * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
1079
+ * empty array, and `primitive` is inferred from `type` when not explicitly provided.
1080
+ */
1081
+ const schemaDef = defineNode({
1082
+ kind: "Schema",
1083
+ build: (props) => {
1084
+ if (props.type === "object") return {
1085
+ properties: [],
1086
+ primitive: "object",
1087
+ ...props
1088
+ };
1089
+ return {
1090
+ primitive: TYPE_TO_PRIMITIVE[props.type],
1091
+ ...props
1092
+ };
1093
+ },
1094
+ children: [
1095
+ "properties",
1096
+ "items",
1097
+ "members",
1098
+ "additionalProperties"
1099
+ ],
1100
+ visitorKey: "schema"
1101
+ });
1102
+ function createSchema(props) {
1103
+ return schemaDef.create(props);
1104
+ }
1105
+ //#endregion
1106
+ //#region src/registry.ts
1107
+ /**
1108
+ * Every node definition. Adding a node means adding its `defineNode` to one
1109
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
1110
+ */
1111
+ const nodeDefs = [
1112
+ inputDef,
1113
+ outputDef,
1114
+ operationDef,
1115
+ requestBodyDef,
1116
+ contentDef,
1117
+ responseDef,
1118
+ schemaDef,
1119
+ propertyDef,
1120
+ parameterDef,
1121
+ functionParameterDef,
1122
+ functionParametersDef,
1123
+ typeLiteralDef,
1124
+ indexedAccessTypeDef,
1125
+ objectBindingPatternDef,
1126
+ constDef,
1127
+ typeDef,
1128
+ functionDef,
1129
+ arrowFunctionDef,
1130
+ textDef,
1131
+ breakDef,
1132
+ jsxDef,
1133
+ importDef,
1134
+ exportDef,
1135
+ sourceDef,
1136
+ fileDef
1137
+ ];
1138
+ //#endregion
1139
+ //#region src/visitor.ts
1140
+ /**
1141
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
1142
+ * Derived from each definition's `children`.
1143
+ */
1144
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
1145
+ /**
1146
+ * Maps a node kind to the matching visitor callback name. Derived from each
1147
+ * definition's `visitorKey`.
1148
+ */
1149
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1150
+ /**
1151
+ * Creates a small async concurrency limiter.
1152
+ *
1153
+ * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
1154
+ *
1155
+ * @example
1156
+ * ```ts
1157
+ * const limit = createLimit(2)
1158
+ * for (const task of [taskA, taskB, taskC]) {
1159
+ * await limit(() => task())
1160
+ * }
1161
+ * // only 2 tasks run at the same time
1162
+ * ```
1163
+ */
1164
+ function createLimit(concurrency) {
1165
+ let active = 0;
1166
+ const queue = [];
1167
+ function next() {
1168
+ if (active < concurrency && queue.length > 0) {
1169
+ active++;
1170
+ queue.shift()();
1171
+ }
1172
+ }
1173
+ return function limit(fn) {
1174
+ return new Promise((resolve, reject) => {
1175
+ queue.push(() => {
1176
+ Promise.resolve(fn()).then(resolve, reject).finally(() => {
1177
+ active--;
1178
+ next();
1179
+ });
1180
+ });
1181
+ next();
1182
+ });
1183
+ };
1184
+ }
1185
+ const visitorKeysByKind = VISITOR_KEYS;
1186
+ /**
1187
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1188
+ */
1189
+ function isNode(value) {
1190
+ return typeof value === "object" && value !== null && "kind" in value;
1191
+ }
1192
+ /**
1193
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1194
+ *
1195
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1196
+ *
1197
+ * @example
1198
+ * ```ts
1199
+ * const children = getChildren(operationNode, true)
1200
+ * // returns parameters, the request body, and responses
1201
+ * ```
1202
+ */
1203
+ function* getChildren(node, recurse) {
1204
+ if (node.kind === "Schema" && !recurse) return;
1205
+ const keys = visitorKeysByKind[node.kind];
1206
+ if (!keys) return;
1207
+ const record = node;
1208
+ for (const key of keys) {
1209
+ const value = record[key];
1210
+ if (Array.isArray(value)) {
1211
+ for (const item of value) if (isNode(item)) yield item;
1212
+ } else if (isNode(value)) yield value;
1213
+ }
1214
+ }
1215
+ /**
1216
+ * Runs the visitor callback that matches `node.kind` with the traversal
1217
+ * context. The result is a replacement node, a collected value, or `undefined`
1218
+ * when no callback is registered for the kind.
1219
+ *
1220
+ * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
1221
+ * in one place. `TResult` is the caller's expected return: the same node type
1222
+ * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
1223
+ */
1224
+ function applyVisitor(node, visitor, parent) {
1225
+ const key = VISITOR_KEY_BY_KIND[node.kind];
1226
+ if (!key) return void 0;
1227
+ const fn = visitor[key];
1228
+ return fn?.(node, { parent });
1229
+ }
1230
+ /**
1231
+ * Async depth-first traversal for side effects. Visitor return values are
1232
+ * ignored. Use `transform` when you want to rewrite nodes.
1233
+ *
1234
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
1235
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
1236
+ * work. Lower values reduce memory pressure.
1237
+ *
1238
+ * @example Log every operation
1239
+ * ```ts
1240
+ * await walk(root, {
1241
+ * operation(node) {
1242
+ * console.log(node.operationId)
1243
+ * },
1244
+ * })
1245
+ * ```
1246
+ *
1247
+ * @example Only visit the root node
1248
+ * ```ts
1249
+ * await walk(root, { depth: 'shallow', input: () => {} })
1250
+ * ```
1251
+ */
1252
+ async function walk(node, options) {
1253
+ return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
1254
+ }
1255
+ async function _walk(node, visitor, recurse, limit, parent) {
1256
+ await limit(() => applyVisitor(node, visitor, parent));
1257
+ const children = Array.from(getChildren(node, recurse));
1258
+ if (children.length === 0) return;
1259
+ await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
1260
+ }
1261
+ function transform(node, options) {
1262
+ const { depth, parent, ...visitor } = options;
1263
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
1264
+ return transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
1265
+ }
1266
+ /**
1267
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1268
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1269
+ * `Schema` children are skipped in shallow mode.
1270
+ */
1271
+ function transformChildren(node, options, recurse) {
1272
+ if (node.kind === "Schema" && !recurse) return node;
1273
+ const keys = visitorKeysByKind[node.kind];
1274
+ if (!keys) return node;
1275
+ const record = node;
1276
+ const childOptions = {
1277
+ ...options,
1278
+ parent: node
1279
+ };
1280
+ let updates;
1281
+ for (const key of keys) {
1282
+ if (!(key in record)) continue;
1283
+ const value = record[key];
1284
+ if (Array.isArray(value)) {
1285
+ let changed = false;
1286
+ const mapped = value.map((item) => {
1287
+ if (!isNode(item)) return item;
1288
+ const next = transform(item, childOptions);
1289
+ if (next !== item) changed = true;
1290
+ return next;
1291
+ });
1292
+ if (changed) (updates ??= {})[key] = mapped;
1293
+ } else if (isNode(value)) {
1294
+ const next = transform(value, childOptions);
1295
+ if (next !== value) (updates ??= {})[key] = next;
1296
+ }
1297
+ }
1298
+ return updates ? {
1299
+ ...node,
1300
+ ...updates
1301
+ } : node;
1302
+ }
1303
+ /**
1304
+ * Lazy depth-first collection pass. Yields every non-null value returned by
1305
+ * the visitor callbacks. Use `collect` for the eager array form.
1306
+ *
1307
+ * @example Collect every operationId
1308
+ * ```ts
1309
+ * const ids: string[] = []
1310
+ * for (const id of collectLazy<string>(root, {
1311
+ * operation(node) {
1312
+ * return node.operationId
1313
+ * },
1314
+ * })) {
1315
+ * ids.push(id)
1316
+ * }
1317
+ * ```
1318
+ */
1319
+ function* collectLazy(node, options) {
1320
+ const { depth, parent, ...visitor } = options;
1321
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
1322
+ const v = applyVisitor(node, visitor, parent);
1323
+ if (v != null) yield v;
1324
+ for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
1325
+ ...options,
1326
+ parent: node
1327
+ });
1328
+ }
1329
+ /**
1330
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
1331
+ * callbacks return into an array.
1332
+ *
1333
+ * @example Collect every operationId
1334
+ * ```ts
1335
+ * const ids = collect<string>(root, {
1336
+ * operation(node) {
1337
+ * return node.operationId
1338
+ * },
1339
+ * })
1340
+ * ```
1341
+ */
1342
+ function collect(node, options) {
1343
+ return Array.from(collectLazy(node, options));
1344
+ }
1345
+ //#endregion
1346
+ Object.defineProperty(exports, "INDENT", {
1347
+ enumerable: true,
1348
+ get: function() {
1349
+ return INDENT;
1350
+ }
1351
+ });
1352
+ Object.defineProperty(exports, "__exportAll", {
1353
+ enumerable: true,
1354
+ get: function() {
1355
+ return __exportAll;
1356
+ }
1357
+ });
1358
+ Object.defineProperty(exports, "__name", {
1359
+ enumerable: true,
1360
+ get: function() {
1361
+ return __name;
1362
+ }
1363
+ });
1364
+ Object.defineProperty(exports, "arrowFunctionDef", {
1365
+ enumerable: true,
1366
+ get: function() {
1367
+ return arrowFunctionDef;
1368
+ }
1369
+ });
1370
+ Object.defineProperty(exports, "breakDef", {
1371
+ enumerable: true,
1372
+ get: function() {
1373
+ return breakDef;
1374
+ }
1375
+ });
1376
+ Object.defineProperty(exports, "camelCase", {
1377
+ enumerable: true,
1378
+ get: function() {
1379
+ return camelCase;
1380
+ }
1381
+ });
1382
+ Object.defineProperty(exports, "collect", {
1383
+ enumerable: true,
1384
+ get: function() {
1385
+ return collect;
1386
+ }
1387
+ });
1388
+ Object.defineProperty(exports, "collectLazy", {
1389
+ enumerable: true,
1390
+ get: function() {
1391
+ return collectLazy;
1392
+ }
1393
+ });
1394
+ Object.defineProperty(exports, "constDef", {
1395
+ enumerable: true,
1396
+ get: function() {
1397
+ return constDef;
1398
+ }
1399
+ });
1400
+ Object.defineProperty(exports, "contentDef", {
1401
+ enumerable: true,
1402
+ get: function() {
1403
+ return contentDef;
1404
+ }
1405
+ });
1406
+ Object.defineProperty(exports, "createArrowFunction", {
1407
+ enumerable: true,
1408
+ get: function() {
1409
+ return createArrowFunction;
1410
+ }
1411
+ });
1412
+ Object.defineProperty(exports, "createBreak", {
1413
+ enumerable: true,
1414
+ get: function() {
1415
+ return createBreak;
1416
+ }
1417
+ });
1418
+ Object.defineProperty(exports, "createConst", {
1419
+ enumerable: true,
1420
+ get: function() {
1421
+ return createConst;
1422
+ }
1423
+ });
1424
+ Object.defineProperty(exports, "createContent", {
1425
+ enumerable: true,
1426
+ get: function() {
1427
+ return createContent;
1428
+ }
1429
+ });
1430
+ Object.defineProperty(exports, "createExport", {
1431
+ enumerable: true,
1432
+ get: function() {
1433
+ return createExport;
1434
+ }
1435
+ });
1436
+ Object.defineProperty(exports, "createFile", {
1437
+ enumerable: true,
1438
+ get: function() {
1439
+ return createFile;
1440
+ }
1441
+ });
1442
+ Object.defineProperty(exports, "createFunction", {
1443
+ enumerable: true,
1444
+ get: function() {
1445
+ return createFunction;
1446
+ }
1447
+ });
1448
+ Object.defineProperty(exports, "createFunctionParameter", {
1449
+ enumerable: true,
1450
+ get: function() {
1451
+ return createFunctionParameter;
1452
+ }
1453
+ });
1454
+ Object.defineProperty(exports, "createFunctionParameters", {
1455
+ enumerable: true,
1456
+ get: function() {
1457
+ return createFunctionParameters;
1458
+ }
1459
+ });
1460
+ Object.defineProperty(exports, "createImport", {
1461
+ enumerable: true,
1462
+ get: function() {
1463
+ return createImport;
1464
+ }
1465
+ });
1466
+ Object.defineProperty(exports, "createIndexedAccessType", {
1467
+ enumerable: true,
1468
+ get: function() {
1469
+ return createIndexedAccessType;
1470
+ }
1471
+ });
1472
+ Object.defineProperty(exports, "createInput", {
1473
+ enumerable: true,
1474
+ get: function() {
1475
+ return createInput;
1476
+ }
1477
+ });
1478
+ Object.defineProperty(exports, "createJsx", {
1479
+ enumerable: true,
1480
+ get: function() {
1481
+ return createJsx;
1482
+ }
1483
+ });
1484
+ Object.defineProperty(exports, "createObjectBindingPattern", {
1485
+ enumerable: true,
1486
+ get: function() {
1487
+ return createObjectBindingPattern;
1488
+ }
1489
+ });
1490
+ Object.defineProperty(exports, "createOperation", {
1491
+ enumerable: true,
1492
+ get: function() {
1493
+ return createOperation;
1494
+ }
1495
+ });
1496
+ Object.defineProperty(exports, "createOutput", {
1497
+ enumerable: true,
1498
+ get: function() {
1499
+ return createOutput;
1500
+ }
1501
+ });
1502
+ Object.defineProperty(exports, "createParameter", {
1503
+ enumerable: true,
1504
+ get: function() {
1505
+ return createParameter;
1506
+ }
1507
+ });
1508
+ Object.defineProperty(exports, "createProperty", {
1509
+ enumerable: true,
1510
+ get: function() {
1511
+ return createProperty;
1512
+ }
1513
+ });
1514
+ Object.defineProperty(exports, "createRequestBody", {
1515
+ enumerable: true,
1516
+ get: function() {
1517
+ return createRequestBody;
1518
+ }
1519
+ });
1520
+ Object.defineProperty(exports, "createResponse", {
1521
+ enumerable: true,
1522
+ get: function() {
1523
+ return createResponse;
1524
+ }
1525
+ });
1526
+ Object.defineProperty(exports, "createSchema", {
1527
+ enumerable: true,
1528
+ get: function() {
1529
+ return createSchema;
1530
+ }
1531
+ });
1532
+ Object.defineProperty(exports, "createSource", {
1533
+ enumerable: true,
1534
+ get: function() {
1535
+ return createSource;
1536
+ }
1537
+ });
1538
+ Object.defineProperty(exports, "createText", {
1539
+ enumerable: true,
1540
+ get: function() {
1541
+ return createText;
1542
+ }
1543
+ });
1544
+ Object.defineProperty(exports, "createType", {
1545
+ enumerable: true,
1546
+ get: function() {
1547
+ return createType;
1548
+ }
1549
+ });
1550
+ Object.defineProperty(exports, "createTypeLiteral", {
1551
+ enumerable: true,
1552
+ get: function() {
1553
+ return createTypeLiteral;
1554
+ }
1555
+ });
1556
+ Object.defineProperty(exports, "defineNode", {
1557
+ enumerable: true,
1558
+ get: function() {
1559
+ return defineNode;
1560
+ }
1561
+ });
1562
+ Object.defineProperty(exports, "exportDef", {
1563
+ enumerable: true,
1564
+ get: function() {
1565
+ return exportDef;
1566
+ }
1567
+ });
1568
+ Object.defineProperty(exports, "extractStringsFromNodes", {
1569
+ enumerable: true,
1570
+ get: function() {
1571
+ return extractStringsFromNodes;
1572
+ }
1573
+ });
1574
+ Object.defineProperty(exports, "fileDef", {
1575
+ enumerable: true,
1576
+ get: function() {
1577
+ return fileDef;
1578
+ }
1579
+ });
1580
+ Object.defineProperty(exports, "functionDef", {
1581
+ enumerable: true,
1582
+ get: function() {
1583
+ return functionDef;
1584
+ }
1585
+ });
1586
+ Object.defineProperty(exports, "functionParameterDef", {
1587
+ enumerable: true,
1588
+ get: function() {
1589
+ return functionParameterDef;
1590
+ }
1591
+ });
1592
+ Object.defineProperty(exports, "functionParametersDef", {
1593
+ enumerable: true,
1594
+ get: function() {
1595
+ return functionParametersDef;
1596
+ }
1597
+ });
1598
+ Object.defineProperty(exports, "importDef", {
1599
+ enumerable: true,
1600
+ get: function() {
1601
+ return importDef;
1602
+ }
1603
+ });
1604
+ Object.defineProperty(exports, "indexedAccessTypeDef", {
1605
+ enumerable: true,
1606
+ get: function() {
1607
+ return indexedAccessTypeDef;
1608
+ }
1609
+ });
1610
+ Object.defineProperty(exports, "inputDef", {
1611
+ enumerable: true,
1612
+ get: function() {
1613
+ return inputDef;
1614
+ }
1615
+ });
1616
+ Object.defineProperty(exports, "isHttpOperationNode", {
1617
+ enumerable: true,
1618
+ get: function() {
1619
+ return isHttpOperationNode;
1620
+ }
1621
+ });
1622
+ Object.defineProperty(exports, "jsxDef", {
1623
+ enumerable: true,
1624
+ get: function() {
1625
+ return jsxDef;
1626
+ }
1627
+ });
1628
+ Object.defineProperty(exports, "narrowSchema", {
1629
+ enumerable: true,
1630
+ get: function() {
1631
+ return narrowSchema;
1632
+ }
1633
+ });
1634
+ Object.defineProperty(exports, "nodeDefs", {
1635
+ enumerable: true,
1636
+ get: function() {
1637
+ return nodeDefs;
1638
+ }
1639
+ });
1640
+ Object.defineProperty(exports, "objectBindingPatternDef", {
1641
+ enumerable: true,
1642
+ get: function() {
1643
+ return objectBindingPatternDef;
1644
+ }
1645
+ });
1646
+ Object.defineProperty(exports, "operationDef", {
1647
+ enumerable: true,
1648
+ get: function() {
1649
+ return operationDef;
1650
+ }
1651
+ });
1652
+ Object.defineProperty(exports, "optionality", {
1653
+ enumerable: true,
1654
+ get: function() {
1655
+ return optionality;
1656
+ }
1657
+ });
1658
+ Object.defineProperty(exports, "outputDef", {
1659
+ enumerable: true,
1660
+ get: function() {
1661
+ return outputDef;
1662
+ }
1663
+ });
1664
+ Object.defineProperty(exports, "parameterDef", {
1665
+ enumerable: true,
1666
+ get: function() {
1667
+ return parameterDef;
1668
+ }
1669
+ });
1670
+ Object.defineProperty(exports, "pascalCase", {
1671
+ enumerable: true,
1672
+ get: function() {
1673
+ return pascalCase;
1674
+ }
1675
+ });
1676
+ Object.defineProperty(exports, "propertyDef", {
1677
+ enumerable: true,
1678
+ get: function() {
1679
+ return propertyDef;
1680
+ }
1681
+ });
1682
+ Object.defineProperty(exports, "requestBodyDef", {
1683
+ enumerable: true,
1684
+ get: function() {
1685
+ return requestBodyDef;
1686
+ }
1687
+ });
1688
+ Object.defineProperty(exports, "responseDef", {
1689
+ enumerable: true,
1690
+ get: function() {
1691
+ return responseDef;
1692
+ }
1693
+ });
1694
+ Object.defineProperty(exports, "schemaDef", {
1695
+ enumerable: true,
1696
+ get: function() {
1697
+ return schemaDef;
1698
+ }
1699
+ });
1700
+ Object.defineProperty(exports, "schemaTypes", {
1701
+ enumerable: true,
1702
+ get: function() {
1703
+ return schemaTypes;
1704
+ }
1705
+ });
1706
+ Object.defineProperty(exports, "sourceDef", {
1707
+ enumerable: true,
1708
+ get: function() {
1709
+ return sourceDef;
1710
+ }
1711
+ });
1712
+ Object.defineProperty(exports, "textDef", {
1713
+ enumerable: true,
1714
+ get: function() {
1715
+ return textDef;
1716
+ }
1717
+ });
1718
+ Object.defineProperty(exports, "transform", {
1719
+ enumerable: true,
1720
+ get: function() {
1721
+ return transform;
1722
+ }
1723
+ });
1724
+ Object.defineProperty(exports, "typeDef", {
1725
+ enumerable: true,
1726
+ get: function() {
1727
+ return typeDef;
1728
+ }
1729
+ });
1730
+ Object.defineProperty(exports, "typeLiteralDef", {
1731
+ enumerable: true,
1732
+ get: function() {
1733
+ return typeLiteralDef;
1734
+ }
1735
+ });
1736
+ Object.defineProperty(exports, "visitorKeys", {
1737
+ enumerable: true,
1738
+ get: function() {
1739
+ return visitorKeys;
1740
+ }
1741
+ });
1742
+ Object.defineProperty(exports, "walk", {
1743
+ enumerable: true,
1744
+ get: function() {
1745
+ return walk;
1746
+ }
1747
+ });
1748
+
1749
+ //# sourceMappingURL=visitor-CQdSiClY.cjs.map