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

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-Bh5E_Il6.cjs +114 -0
  4. package/dist/defineMacro-Bh5E_Il6.cjs.map +1 -0
  5. package/dist/defineMacro-CVrU3ajV.js +98 -0
  6. package/dist/defineMacro-CVrU3ajV.js.map +1 -0
  7. package/dist/defineMacro-D9ekmTW5.d.ts +466 -0
  8. package/dist/index-q_ldM1YP.d.ts +2422 -0
  9. package/dist/index.cjs +198 -2239
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts +97 -3399
  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-Dme8H-sR.d.ts +211 -0
  20. package/dist/refs-8IwpesXW.cjs +157 -0
  21. package/dist/refs-8IwpesXW.cjs.map +1 -0
  22. package/dist/refs-D2qwT5ck.js +117 -0
  23. package/dist/refs-D2qwT5ck.js.map +1 -0
  24. package/dist/rolldown-runtime-CNktS9qV.js +17 -0
  25. package/dist/types-Df1jVmRy.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 +808 -0
  30. package/dist/utils.cjs.map +1 -0
  31. package/dist/utils.d.ts +381 -0
  32. package/dist/utils.js +777 -0
  33. package/dist/utils.js.map +1 -0
  34. package/dist/visitor-CLLDwBvv.cjs +1743 -0
  35. package/dist/visitor-CLLDwBvv.cjs.map +1 -0
  36. package/dist/visitor-DG5ROqRx.js +1307 -0
  37. package/dist/visitor-DG5ROqRx.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,1307 @@
1
+ import "./rolldown-runtime-CNktS9qV.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
+ /**
121
+ * One indentation level, derived from {@link INDENT_SIZE}.
122
+ */
123
+ const INDENT = Array.from({ length: 2 }, () => " ").join("");
124
+ //#endregion
125
+ //#region src/guards.ts
126
+ /**
127
+ * Narrows a `SchemaNode` to the variant that matches `type`.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * const schema = createSchema({ type: 'string' })
132
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
133
+ * ```
134
+ */
135
+ function narrowSchema(node, type) {
136
+ return node?.type === type ? node : null;
137
+ }
138
+ /**
139
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * if (isHttpOperationNode(node)) {
144
+ * console.log(node.method, node.path)
145
+ * }
146
+ * ```
147
+ */
148
+ function isHttpOperationNode(node) {
149
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
150
+ }
151
+ //#endregion
152
+ //#region src/defineNode.ts
153
+ /**
154
+ * Visitor callback names, one per traversable node kind, in traversal order.
155
+ * Kept in sync with the keys of `Visitor` in `visitor.ts`.
156
+ */
157
+ const visitorKeys = [
158
+ "input",
159
+ "output",
160
+ "operation",
161
+ "schema",
162
+ "property",
163
+ "parameter",
164
+ "response"
165
+ ];
166
+ /**
167
+ * Builds a type guard that matches nodes of the given `kind`.
168
+ */
169
+ function isKind(kind) {
170
+ return (node) => node?.kind === kind;
171
+ }
172
+ /**
173
+ * Defines a node once and derives its `create` builder, `is` guard, and traversal
174
+ * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
175
+ * `kind`, so node construction lives in one place without scattered `as` casts.
176
+ *
177
+ * @example Simple node
178
+ * ```ts
179
+ * const importDef = defineNode<ImportNode>({ kind: 'Import' })
180
+ * const createImport = importDef.create
181
+ * ```
182
+ *
183
+ * @example Node with a build hook
184
+ * ```ts
185
+ * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
186
+ * kind: 'Property',
187
+ * build: (props) => ({ ...props, required: props.required ?? false }),
188
+ * children: ['schema'],
189
+ * visitorKey: 'property',
190
+ * })
191
+ * ```
192
+ */
193
+ function defineNode(config) {
194
+ const { kind, defaults, build, children, visitorKey } = config;
195
+ function create(input) {
196
+ const base = build ? build(input) : input;
197
+ return {
198
+ ...defaults,
199
+ ...base,
200
+ kind
201
+ };
202
+ }
203
+ return {
204
+ kind,
205
+ create,
206
+ is: isKind(kind),
207
+ children,
208
+ visitorKey
209
+ };
210
+ }
211
+ //#endregion
212
+ //#region src/nodes/code.ts
213
+ /**
214
+ * Definition for the {@link ConstNode}.
215
+ */
216
+ const constDef = defineNode({ kind: "Const" });
217
+ /**
218
+ * Definition for the {@link TypeNode}.
219
+ */
220
+ const typeDef = defineNode({ kind: "Type" });
221
+ /**
222
+ * Definition for the {@link FunctionNode}.
223
+ */
224
+ const functionDef = defineNode({ kind: "Function" });
225
+ /**
226
+ * Definition for the {@link ArrowFunctionNode}.
227
+ */
228
+ const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
229
+ /**
230
+ * Definition for the {@link TextNode}.
231
+ */
232
+ const textDef = defineNode({
233
+ kind: "Text",
234
+ build: (value) => ({ value })
235
+ });
236
+ /**
237
+ * Definition for the {@link BreakNode}.
238
+ */
239
+ const breakDef = defineNode({
240
+ kind: "Break",
241
+ build: () => ({})
242
+ });
243
+ /**
244
+ * Definition for the {@link JsxNode}.
245
+ */
246
+ const jsxDef = defineNode({
247
+ kind: "Jsx",
248
+ build: (value) => ({ value })
249
+ });
250
+ /**
251
+ * Creates a `ConstNode` representing a TypeScript `const` declaration.
252
+ *
253
+ * @example Exported constant with type and `as const`
254
+ * ```ts
255
+ * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
256
+ * // export const pets: Pet[] = ... as const
257
+ * ```
258
+ */
259
+ const createConst = constDef.create;
260
+ /**
261
+ * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * createType({ name: 'Pet', export: true })
266
+ * // export type Pet = ...
267
+ * ```
268
+ */
269
+ const createType = typeDef.create;
270
+ /**
271
+ * Creates a `FunctionNode` representing a TypeScript `function` declaration.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
276
+ * // export async function fetchPet(): Promise<Pet> { ... }
277
+ * ```
278
+ */
279
+ const createFunction = functionDef.create;
280
+ /**
281
+ * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
286
+ * // export const double = (n: number) => ...
287
+ * ```
288
+ */
289
+ const createArrowFunction = arrowFunctionDef.create;
290
+ /**
291
+ * Creates a {@link TextNode} representing a raw string fragment in the source output.
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * createText('return fetch(id)')
296
+ * // { kind: 'Text', value: 'return fetch(id)' }
297
+ * ```
298
+ */
299
+ const createText = textDef.create;
300
+ /**
301
+ * Creates a {@link BreakNode} representing a line break in the source output.
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * createBreak()
306
+ * // { kind: 'Break' }
307
+ * ```
308
+ */
309
+ function createBreak() {
310
+ return breakDef.create();
311
+ }
312
+ /**
313
+ * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * createJsx('<>\n <a href={href}>Open</a>\n</>')
318
+ * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
319
+ * ```
320
+ */
321
+ const createJsx = jsxDef.create;
322
+ //#endregion
323
+ //#region src/nodes/content.ts
324
+ /**
325
+ * Definition for the {@link ContentNode}.
326
+ */
327
+ const contentDef = defineNode({
328
+ kind: "Content",
329
+ children: ["schema"]
330
+ });
331
+ /**
332
+ * Creates a `ContentNode` for a single request-body or response content type.
333
+ */
334
+ const createContent = contentDef.create;
335
+ //#endregion
336
+ //#region ../../internals/utils/src/casing.ts
337
+ /**
338
+ * Shared implementation for camelCase and PascalCase conversion.
339
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
340
+ * and capitalizes each word according to `pascal`.
341
+ *
342
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
343
+ */
344
+ function toCamelOrPascal(text, pascal) {
345
+ 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) => {
346
+ if (word.length > 1 && word === word.toUpperCase()) return word;
347
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
348
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
349
+ }
350
+ /**
351
+ * Converts `text` to camelCase.
352
+ *
353
+ * @example Word boundaries
354
+ * `camelCase('hello-world') // 'helloWorld'`
355
+ *
356
+ * @example With a prefix
357
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
358
+ */
359
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
360
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
361
+ }
362
+ /**
363
+ * Converts `text` to PascalCase.
364
+ *
365
+ * @example Word boundaries
366
+ * `pascalCase('hello-world') // 'HelloWorld'`
367
+ *
368
+ * @example With a suffix
369
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
370
+ */
371
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
372
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
373
+ }
374
+ //#endregion
375
+ //#region ../../internals/utils/src/fs.ts
376
+ /**
377
+ * Strips the file extension from a path or file name.
378
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
379
+ *
380
+ * @example
381
+ * trimExtName('petStore.ts') // 'petStore'
382
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
383
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
384
+ * trimExtName('noExtension') // 'noExtension'
385
+ */
386
+ function trimExtName(text) {
387
+ const dotIndex = text.lastIndexOf(".");
388
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
389
+ return text;
390
+ }
391
+ //#endregion
392
+ //#region src/utils/extractStringsFromNodes.ts
393
+ /**
394
+ * Extracts all string content from a `CodeNode` tree recursively.
395
+ *
396
+ * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
397
+ * and nested node content. Used to build the full source string for import filtering.
398
+ */
399
+ function extractStringsFromNodes(nodes) {
400
+ if (!nodes?.length) return "";
401
+ return nodes.map((node) => {
402
+ if (typeof node === "string") return node;
403
+ if (node.kind === "Text") return node.value;
404
+ if (node.kind === "Break") return "";
405
+ if (node.kind === "Jsx") return node.value;
406
+ const parts = [];
407
+ if ("params" in node && node.params) parts.push(node.params);
408
+ if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
409
+ if ("returnType" in node && node.returnType) parts.push(node.returnType);
410
+ if ("type" in node && typeof node.type === "string") parts.push(node.type);
411
+ const nested = extractStringsFromNodes(node.nodes);
412
+ if (nested) parts.push(nested);
413
+ return parts.join("\n");
414
+ }).filter(Boolean).join("\n");
415
+ }
416
+ //#endregion
417
+ //#region src/utils/fileMerge.ts
418
+ function sourceKey(source) {
419
+ return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
420
+ }
421
+ function pathTypeKey(path, isTypeOnly) {
422
+ return `${path}:${isTypeOnly ?? false}`;
423
+ }
424
+ function exportKey(path, name, isTypeOnly, asAlias) {
425
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
426
+ }
427
+ function importKey(path, name, isTypeOnly) {
428
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
429
+ }
430
+ /**
431
+ * Computes a multi-level sort key for exports and imports:
432
+ * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
433
+ */
434
+ function sortKey(node) {
435
+ const isArray = Array.isArray(node.name) ? "1" : "0";
436
+ const typeOnly = node.isTypeOnly ? "0" : "1";
437
+ const hasName = node.name != null ? "1" : "0";
438
+ const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
439
+ return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
440
+ }
441
+ /**
442
+ * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
443
+ * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
444
+ * the deduplicated array in original order.
445
+ */
446
+ function combineSources(sources) {
447
+ const seen = /* @__PURE__ */ new Map();
448
+ for (const source of sources) {
449
+ const key = sourceKey(source);
450
+ if (!seen.has(key)) seen.set(key, source);
451
+ }
452
+ return [...seen.values()];
453
+ }
454
+ /**
455
+ * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
456
+ *
457
+ * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
458
+ */
459
+ function mergeNameArrays(existing, incoming) {
460
+ const merged = new Set(existing);
461
+ for (const name of incoming) merged.add(name);
462
+ return [...merged];
463
+ }
464
+ /**
465
+ * Deduplicates and merges `ExportNode` objects by path and type.
466
+ *
467
+ * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
468
+ * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
469
+ */
470
+ function combineExports(exports) {
471
+ const result = [];
472
+ const namedByPath = /* @__PURE__ */ new Map();
473
+ const seen = /* @__PURE__ */ new Set();
474
+ const keyed = exports.map((node) => ({
475
+ node,
476
+ key: sortKey(node)
477
+ }));
478
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
479
+ for (const { node: curr } of keyed) {
480
+ const { name, path, isTypeOnly, asAlias } = curr;
481
+ if (Array.isArray(name)) {
482
+ if (!name.length) continue;
483
+ const key = pathTypeKey(path, isTypeOnly);
484
+ const existing = namedByPath.get(key);
485
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
486
+ else {
487
+ const newItem = {
488
+ ...curr,
489
+ name: [...new Set(name)]
490
+ };
491
+ result.push(newItem);
492
+ namedByPath.set(key, newItem);
493
+ }
494
+ } else {
495
+ const key = exportKey(path, name, isTypeOnly, asAlias);
496
+ if (!seen.has(key)) {
497
+ result.push(curr);
498
+ seen.add(key);
499
+ }
500
+ }
501
+ }
502
+ return result;
503
+ }
504
+ /**
505
+ * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
506
+ *
507
+ * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
508
+ * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
509
+ */
510
+ function combineImports(imports, exports, source) {
511
+ const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
512
+ const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
513
+ const importNameMemo = /* @__PURE__ */ new Map();
514
+ const canonicalizeName = (n) => {
515
+ if (typeof n === "string") return n;
516
+ const key = `${n.propertyName}:${n.name ?? ""}`;
517
+ if (!importNameMemo.has(key)) importNameMemo.set(key, n);
518
+ return importNameMemo.get(key);
519
+ };
520
+ const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
521
+ for (const node of imports) {
522
+ if (!Array.isArray(node.name)) continue;
523
+ if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
524
+ }
525
+ const result = [];
526
+ const namedByPath = /* @__PURE__ */ new Map();
527
+ const seen = /* @__PURE__ */ new Set();
528
+ const keyed = imports.map((node) => ({
529
+ node,
530
+ key: sortKey(node)
531
+ }));
532
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
533
+ for (const { node: curr } of keyed) {
534
+ if (curr.path === curr.root) continue;
535
+ const { path, isTypeOnly } = curr;
536
+ let { name } = curr;
537
+ if (Array.isArray(name)) {
538
+ name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
539
+ if (!name.length) continue;
540
+ const key = pathTypeKey(path, isTypeOnly);
541
+ const existing = namedByPath.get(key);
542
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
543
+ else {
544
+ const newItem = {
545
+ ...curr,
546
+ name
547
+ };
548
+ result.push(newItem);
549
+ namedByPath.set(key, newItem);
550
+ }
551
+ } else {
552
+ if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
553
+ const key = importKey(path, name, isTypeOnly);
554
+ if (!seen.has(key)) {
555
+ result.push(curr);
556
+ seen.add(key);
557
+ }
558
+ }
559
+ }
560
+ return result;
561
+ }
562
+ //#endregion
563
+ //#region src/nodes/file.ts
564
+ /**
565
+ * Definition for the {@link ImportNode}.
566
+ */
567
+ const importDef = defineNode({ kind: "Import" });
568
+ /**
569
+ * Definition for the {@link ExportNode}.
570
+ */
571
+ const exportDef = defineNode({ kind: "Export" });
572
+ /**
573
+ * Definition for the {@link SourceNode}.
574
+ */
575
+ const sourceDef = defineNode({ kind: "Source" });
576
+ /**
577
+ * Definition for the {@link FileNode}. The fully resolved builder lives in
578
+ * `createFile`, so this definition only supplies the guard.
579
+ */
580
+ const fileDef = defineNode({ kind: "File" });
581
+ /**
582
+ * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
583
+ *
584
+ * @example Named import
585
+ * ```ts
586
+ * createImport({ name: ['useState'], path: 'react' })
587
+ * // import { useState } from 'react'
588
+ * ```
589
+ */
590
+ const createImport = importDef.create;
591
+ /**
592
+ * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
593
+ *
594
+ * @example Named export
595
+ * ```ts
596
+ * createExport({ name: ['Pet'], path: './Pet' })
597
+ * // export { Pet } from './Pet'
598
+ * ```
599
+ */
600
+ const createExport = exportDef.create;
601
+ /**
602
+ * Creates a `SourceNode` representing a fragment of source code within a file.
603
+ *
604
+ * @example
605
+ * ```ts
606
+ * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
607
+ * ```
608
+ */
609
+ const createSource = sourceDef.create;
610
+ /**
611
+ * Creates a fully resolved `FileNode` from a file input descriptor.
612
+ *
613
+ * Computes:
614
+ * - `id` SHA256 hash of the file path
615
+ * - `name` `baseName` without extension
616
+ * - `extname` extension extracted from `baseName`
617
+ *
618
+ * Deduplicates:
619
+ * - `sources` via `combineSources`
620
+ * - `exports` via `combineExports`
621
+ * - `imports` via `combineImports` (also filters unused imports)
622
+ *
623
+ * @throws {Error} when `baseName` has no extension.
624
+ *
625
+ * @example
626
+ * ```ts
627
+ * const file = createFile({
628
+ * baseName: 'petStore.ts',
629
+ * path: 'src/models/petStore.ts',
630
+ * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
631
+ * imports: [createImport({ name: ['z'], path: 'zod' })],
632
+ * exports: [createExport({ name: ['Pet'], path: './petStore' })],
633
+ * })
634
+ * // file.id = SHA256 hash of 'src/models/petStore.ts'
635
+ * // file.name = 'petStore'
636
+ * // file.extname = '.ts'
637
+ * ```
638
+ *
639
+ * @example Copy a real file into the output verbatim
640
+ * ```ts
641
+ * const file = createFile({
642
+ * baseName: 'client.ts',
643
+ * path: 'src/gen/client.ts',
644
+ * copy: '/abs/path/to/templates/client.ts',
645
+ * })
646
+ * ```
647
+ */
648
+ function createFile(input) {
649
+ const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
650
+ if (!extname) throw new Error(`No extname found for ${input.baseName}`);
651
+ const source = (input.sources ?? []).flatMap((item) => item.nodes ?? []).map((node) => extractStringsFromNodes([node])).filter(Boolean).join("\n\n");
652
+ const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
653
+ const combinedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || void 0) : [];
654
+ const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
655
+ const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
656
+ const resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
657
+ if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
658
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
659
+ if (!kept.length) return [];
660
+ return [kept.length === imp.name.length ? imp : {
661
+ ...imp,
662
+ name: kept
663
+ }];
664
+ });
665
+ const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
666
+ return {
667
+ kind: "File",
668
+ ...input,
669
+ id: hash("sha256", input.path, "hex"),
670
+ name: trimExtName(input.baseName),
671
+ extname,
672
+ imports: resolvedImports,
673
+ exports: resolvedExports,
674
+ sources: resolvedSources,
675
+ meta: input.meta ?? {}
676
+ };
677
+ }
678
+ //#endregion
679
+ //#region src/nodes/function.ts
680
+ /**
681
+ * Definition for the {@link TypeLiteralNode}.
682
+ */
683
+ const typeLiteralDef = defineNode({ kind: "TypeLiteral" });
684
+ /**
685
+ * Definition for the {@link IndexedAccessTypeNode}.
686
+ */
687
+ const indexedAccessTypeDef = defineNode({ kind: "IndexedAccessType" });
688
+ /**
689
+ * Definition for the {@link ObjectBindingPatternNode}.
690
+ */
691
+ const objectBindingPatternDef = defineNode({ kind: "ObjectBindingPattern" });
692
+ /**
693
+ * Definition for the {@link FunctionParameterNode}. `optional` defaults to `false`.
694
+ * Passing `properties` builds a destructured group: an {@link ObjectBindingPatternNode} name
695
+ * paired with a {@link TypeLiteralNode} type.
696
+ */
697
+ const functionParameterDef = defineNode({
698
+ kind: "FunctionParameter",
699
+ build: (input) => {
700
+ if ("properties" in input) return {
701
+ name: createObjectBindingPattern({ elements: input.properties.map((p) => ({ name: p.name })) }),
702
+ type: createTypeLiteral({ members: input.properties.map((p) => ({
703
+ name: p.name,
704
+ type: p.type,
705
+ optional: p.optional ?? false
706
+ })) }),
707
+ optional: input.optional ?? false,
708
+ ...input.default !== void 0 ? { default: input.default } : {}
709
+ };
710
+ return {
711
+ optional: false,
712
+ ...input
713
+ };
714
+ }
715
+ });
716
+ /**
717
+ * Definition for the {@link FunctionParametersNode}.
718
+ */
719
+ const functionParametersDef = defineNode({
720
+ kind: "FunctionParameters",
721
+ defaults: { params: [] }
722
+ });
723
+ /**
724
+ * Creates a {@link TypeLiteralNode} representing an inline anonymous object type.
725
+ *
726
+ * @example
727
+ * ```ts
728
+ * createTypeLiteral({ members: [{ name: 'petId', type: 'string', optional: false }] })
729
+ * // { petId: string }
730
+ * ```
731
+ */
732
+ const createTypeLiteral = typeLiteralDef.create;
733
+ /**
734
+ * Creates an {@link IndexedAccessTypeNode} representing a single field accessed from a named type.
735
+ *
736
+ * @example
737
+ * ```ts
738
+ * createIndexedAccessType({ target: 'DeletePetPathParams', key: 'petId' })
739
+ * // DeletePetPathParams['petId']
740
+ * ```
741
+ */
742
+ const createIndexedAccessType = indexedAccessTypeDef.create;
743
+ /**
744
+ * Creates an {@link ObjectBindingPatternNode} for a destructured parameter binding.
745
+ *
746
+ * @example
747
+ * ```ts
748
+ * createObjectBindingPattern({ elements: [{ name: 'id' }, { name: 'name' }] })
749
+ * // { id, name }
750
+ * ```
751
+ */
752
+ const createObjectBindingPattern = objectBindingPatternDef.create;
753
+ /**
754
+ * Creates a `FunctionParameterNode`. `optional` defaults to `false`.
755
+ *
756
+ * @example Optional param
757
+ * ```ts
758
+ * createFunctionParameter({ name: 'params', type: 'QueryParams', optional: true })
759
+ * // → params?: QueryParams
760
+ * ```
761
+ *
762
+ * @example Destructured group
763
+ * ```ts
764
+ * createFunctionParameter({ properties: [{ name: 'id', type: 'string' }, { name: 'name', type: 'string', optional: true }], default: '{}' })
765
+ * // → { id, name }: { id: string; name?: string } = {}
766
+ * ```
767
+ */
768
+ const createFunctionParameter = functionParameterDef.create;
769
+ /**
770
+ * Creates a `FunctionParametersNode` from an ordered list of parameters.
771
+ *
772
+ * @example
773
+ * ```ts
774
+ * const empty = createFunctionParameters()
775
+ * // { kind: 'FunctionParameters', params: [] }
776
+ * ```
777
+ */
778
+ function createFunctionParameters(props = {}) {
779
+ return functionParametersDef.create(props);
780
+ }
781
+ //#endregion
782
+ //#region src/nodes/input.ts
783
+ /**
784
+ * Definition for the {@link InputNode}.
785
+ */
786
+ const inputDef = defineNode({
787
+ kind: "Input",
788
+ defaults: {
789
+ schemas: [],
790
+ operations: [],
791
+ meta: {
792
+ circularNames: [],
793
+ enumNames: []
794
+ }
795
+ },
796
+ children: ["schemas", "operations"],
797
+ visitorKey: "input"
798
+ });
799
+ /**
800
+ * Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
801
+ * `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
802
+ * `schemas`/`operations`. Both variants get the defaulted `meta`.
803
+ *
804
+ * @example Eager
805
+ * ```ts
806
+ * const input = createInput()
807
+ * // { kind: 'Input', schemas: [], operations: [] }
808
+ * ```
809
+ *
810
+ * @example Streaming
811
+ * ```ts
812
+ * const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
813
+ * ```
814
+ */
815
+ function createInput(options = {}) {
816
+ const { stream, ...overrides } = options;
817
+ if (stream) return {
818
+ kind: "Input",
819
+ meta: {
820
+ circularNames: [],
821
+ enumNames: []
822
+ },
823
+ ...overrides
824
+ };
825
+ return inputDef.create(overrides);
826
+ }
827
+ //#endregion
828
+ //#region src/nodes/requestBody.ts
829
+ /**
830
+ * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
831
+ * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
832
+ */
833
+ const requestBodyDef = defineNode({
834
+ kind: "RequestBody",
835
+ children: ["content"]
836
+ });
837
+ /**
838
+ * Creates a `RequestBodyNode`.
839
+ */
840
+ const createRequestBody = requestBodyDef.create;
841
+ //#endregion
842
+ //#region src/nodes/operation.ts
843
+ /**
844
+ * Definition for the {@link OperationNode}. HTTP operations (those carrying both
845
+ * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
846
+ * normalized into a `RequestBodyNode`.
847
+ */
848
+ const operationDef = defineNode({
849
+ kind: "Operation",
850
+ build: (props) => {
851
+ const { requestBody, ...rest } = props;
852
+ const isHttp = rest.method !== void 0 && rest.path !== void 0;
853
+ return {
854
+ tags: [],
855
+ parameters: [],
856
+ responses: [],
857
+ ...rest,
858
+ ...isHttp ? { protocol: "http" } : {},
859
+ requestBody: requestBody ? createRequestBody(requestBody) : void 0
860
+ };
861
+ },
862
+ children: [
863
+ "parameters",
864
+ "requestBody",
865
+ "responses"
866
+ ],
867
+ visitorKey: "operation"
868
+ });
869
+ function createOperation(props) {
870
+ return operationDef.create(props);
871
+ }
872
+ //#endregion
873
+ //#region src/nodes/output.ts
874
+ /**
875
+ * Definition for the {@link OutputNode}.
876
+ */
877
+ const outputDef = defineNode({
878
+ kind: "Output",
879
+ defaults: { files: [] },
880
+ visitorKey: "output"
881
+ });
882
+ /**
883
+ * Creates an `OutputNode` with a stable default for `files`.
884
+ *
885
+ * @example
886
+ * ```ts
887
+ * const output = createOutput()
888
+ * // { kind: 'Output', files: [] }
889
+ * ```
890
+ */
891
+ function createOutput(overrides = {}) {
892
+ return outputDef.create(overrides);
893
+ }
894
+ //#endregion
895
+ //#region src/optionality.ts
896
+ /**
897
+ * Generic JSON Schema optionality: a non-required field is optional, and a
898
+ * non-required nullable field is nullish.
899
+ */
900
+ function optionality(schema, required) {
901
+ const nullable = schema.nullable ?? false;
902
+ return {
903
+ ...schema,
904
+ optional: !required && !nullable ? true : void 0,
905
+ nullish: !required && nullable ? true : void 0
906
+ };
907
+ }
908
+ //#endregion
909
+ //#region src/nodes/parameter.ts
910
+ /**
911
+ * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
912
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
913
+ */
914
+ const parameterDef = defineNode({
915
+ kind: "Parameter",
916
+ build: (props) => {
917
+ const required = props.required ?? false;
918
+ return {
919
+ ...props,
920
+ required,
921
+ schema: optionality(props.schema, required)
922
+ };
923
+ },
924
+ children: ["schema"],
925
+ visitorKey: "parameter"
926
+ });
927
+ /**
928
+ * Creates a `ParameterNode`.
929
+ *
930
+ * @example
931
+ * ```ts
932
+ * const param = createParameter({
933
+ * name: 'petId',
934
+ * in: 'path',
935
+ * required: true,
936
+ * schema: createSchema({ type: 'string' }),
937
+ * })
938
+ * ```
939
+ */
940
+ const createParameter = parameterDef.create;
941
+ //#endregion
942
+ //#region src/nodes/property.ts
943
+ /**
944
+ * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
945
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
946
+ */
947
+ const propertyDef = defineNode({
948
+ kind: "Property",
949
+ build: (props) => {
950
+ const required = props.required ?? false;
951
+ return {
952
+ ...props,
953
+ required,
954
+ schema: optionality(props.schema, required)
955
+ };
956
+ },
957
+ children: ["schema"],
958
+ visitorKey: "property"
959
+ });
960
+ /**
961
+ * Creates a `PropertyNode`.
962
+ *
963
+ * @example
964
+ * ```ts
965
+ * const property = createProperty({
966
+ * name: 'status',
967
+ * required: true,
968
+ * schema: createSchema({ type: 'string', nullable: true }),
969
+ * })
970
+ * // required=true, no optional/nullish
971
+ * ```
972
+ */
973
+ const createProperty = propertyDef.create;
974
+ //#endregion
975
+ //#region src/nodes/response.ts
976
+ /**
977
+ * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
978
+ * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
979
+ */
980
+ const responseDef = defineNode({
981
+ kind: "Response",
982
+ build: (props) => {
983
+ const { schema, mediaType, keysToOmit, content, ...rest } = props;
984
+ const entries = content ?? (schema ? [createContent({
985
+ contentType: mediaType ?? "application/json",
986
+ schema,
987
+ keysToOmit: keysToOmit ?? null
988
+ })] : void 0);
989
+ return {
990
+ ...rest,
991
+ content: entries
992
+ };
993
+ },
994
+ children: ["content"],
995
+ visitorKey: "response"
996
+ });
997
+ /**
998
+ * Creates a `ResponseNode`.
999
+ *
1000
+ * @example
1001
+ * ```ts
1002
+ * const response = createResponse({
1003
+ * statusCode: '200',
1004
+ * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
1005
+ * })
1006
+ * ```
1007
+ */
1008
+ const createResponse = responseDef.create;
1009
+ //#endregion
1010
+ //#region src/nodes/schema.ts
1011
+ /**
1012
+ * Maps schema `type` to its underlying `primitive`.
1013
+ * Primitive types map to themselves and special string formats map to `'string'`.
1014
+ * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
1015
+ */
1016
+ const TYPE_TO_PRIMITIVE = {
1017
+ string: "string",
1018
+ number: "number",
1019
+ integer: "integer",
1020
+ bigint: "bigint",
1021
+ boolean: "boolean",
1022
+ null: "null",
1023
+ any: "any",
1024
+ unknown: "unknown",
1025
+ void: "void",
1026
+ never: "never",
1027
+ object: "object",
1028
+ array: "array",
1029
+ date: "date",
1030
+ uuid: "string",
1031
+ email: "string",
1032
+ url: "string",
1033
+ datetime: "string",
1034
+ time: "string"
1035
+ };
1036
+ /**
1037
+ * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
1038
+ * empty array, and `primitive` is inferred from `type` when not explicitly provided.
1039
+ */
1040
+ const schemaDef = defineNode({
1041
+ kind: "Schema",
1042
+ build: (props) => {
1043
+ if (props.type === "object") return {
1044
+ properties: [],
1045
+ primitive: "object",
1046
+ ...props
1047
+ };
1048
+ return {
1049
+ primitive: TYPE_TO_PRIMITIVE[props.type],
1050
+ ...props
1051
+ };
1052
+ },
1053
+ children: [
1054
+ "properties",
1055
+ "items",
1056
+ "members",
1057
+ "additionalProperties"
1058
+ ],
1059
+ visitorKey: "schema"
1060
+ });
1061
+ function createSchema(props) {
1062
+ return schemaDef.create(props);
1063
+ }
1064
+ //#endregion
1065
+ //#region src/registry.ts
1066
+ /**
1067
+ * Every node definition. Adding a node means adding its `defineNode` to one
1068
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
1069
+ */
1070
+ const nodeDefs = [
1071
+ inputDef,
1072
+ outputDef,
1073
+ operationDef,
1074
+ requestBodyDef,
1075
+ contentDef,
1076
+ responseDef,
1077
+ schemaDef,
1078
+ propertyDef,
1079
+ parameterDef,
1080
+ functionParameterDef,
1081
+ functionParametersDef,
1082
+ typeLiteralDef,
1083
+ indexedAccessTypeDef,
1084
+ objectBindingPatternDef,
1085
+ constDef,
1086
+ typeDef,
1087
+ functionDef,
1088
+ arrowFunctionDef,
1089
+ textDef,
1090
+ breakDef,
1091
+ jsxDef,
1092
+ importDef,
1093
+ exportDef,
1094
+ sourceDef,
1095
+ fileDef
1096
+ ];
1097
+ //#endregion
1098
+ //#region src/visitor.ts
1099
+ /**
1100
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
1101
+ * Derived from each definition's `children`.
1102
+ */
1103
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
1104
+ /**
1105
+ * Maps a node kind to the matching visitor callback name. Derived from each
1106
+ * definition's `visitorKey`.
1107
+ */
1108
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1109
+ /**
1110
+ * Creates a small async concurrency limiter.
1111
+ *
1112
+ * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
1113
+ *
1114
+ * @example
1115
+ * ```ts
1116
+ * const limit = createLimit(2)
1117
+ * for (const task of [taskA, taskB, taskC]) {
1118
+ * await limit(() => task())
1119
+ * }
1120
+ * // only 2 tasks run at the same time
1121
+ * ```
1122
+ */
1123
+ function createLimit(concurrency) {
1124
+ let active = 0;
1125
+ const queue = [];
1126
+ function next() {
1127
+ if (active < concurrency && queue.length > 0) {
1128
+ active++;
1129
+ queue.shift()();
1130
+ }
1131
+ }
1132
+ return function limit(fn) {
1133
+ return new Promise((resolve, reject) => {
1134
+ queue.push(() => {
1135
+ Promise.resolve(fn()).then(resolve, reject).finally(() => {
1136
+ active--;
1137
+ next();
1138
+ });
1139
+ });
1140
+ next();
1141
+ });
1142
+ };
1143
+ }
1144
+ const visitorKeysByKind = VISITOR_KEYS;
1145
+ /**
1146
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1147
+ */
1148
+ function isNode(value) {
1149
+ return typeof value === "object" && value !== null && "kind" in value;
1150
+ }
1151
+ /**
1152
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1153
+ *
1154
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1155
+ *
1156
+ * @example
1157
+ * ```ts
1158
+ * const children = getChildren(operationNode, true)
1159
+ * // returns parameters, the request body, and responses
1160
+ * ```
1161
+ */
1162
+ function* getChildren(node, recurse) {
1163
+ if (node.kind === "Schema" && !recurse) return;
1164
+ const keys = visitorKeysByKind[node.kind];
1165
+ if (!keys) return;
1166
+ const record = node;
1167
+ for (const key of keys) {
1168
+ const value = record[key];
1169
+ if (Array.isArray(value)) {
1170
+ for (const item of value) if (isNode(item)) yield item;
1171
+ } else if (isNode(value)) yield value;
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Runs the visitor callback that matches `node.kind` with the traversal
1176
+ * context. The result is a replacement node, a collected value, or `undefined`
1177
+ * when no callback is registered for the kind.
1178
+ *
1179
+ * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
1180
+ * in one place. `TResult` is the caller's expected return: the same node type
1181
+ * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
1182
+ */
1183
+ function applyVisitor(node, visitor, parent) {
1184
+ const key = VISITOR_KEY_BY_KIND[node.kind];
1185
+ if (!key) return void 0;
1186
+ const fn = visitor[key];
1187
+ return fn?.(node, { parent });
1188
+ }
1189
+ /**
1190
+ * Async depth-first traversal for side effects. Visitor return values are
1191
+ * ignored. Use `transform` when you want to rewrite nodes.
1192
+ *
1193
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
1194
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
1195
+ * work. Lower values reduce memory pressure.
1196
+ *
1197
+ * @example Log every operation
1198
+ * ```ts
1199
+ * await walk(root, {
1200
+ * operation(node) {
1201
+ * console.log(node.operationId)
1202
+ * },
1203
+ * })
1204
+ * ```
1205
+ *
1206
+ * @example Only visit the root node
1207
+ * ```ts
1208
+ * await walk(root, { depth: 'shallow', input: () => {} })
1209
+ * ```
1210
+ */
1211
+ async function walk(node, options) {
1212
+ return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
1213
+ }
1214
+ async function _walk(node, visitor, recurse, limit, parent) {
1215
+ await limit(() => applyVisitor(node, visitor, parent));
1216
+ const children = Array.from(getChildren(node, recurse));
1217
+ if (children.length === 0) return;
1218
+ await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
1219
+ }
1220
+ function transform(node, options) {
1221
+ const { depth, parent, ...visitor } = options;
1222
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
1223
+ return transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
1224
+ }
1225
+ /**
1226
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1227
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1228
+ * `Schema` children are skipped in shallow mode.
1229
+ */
1230
+ function transformChildren(node, options, recurse) {
1231
+ if (node.kind === "Schema" && !recurse) return node;
1232
+ const keys = visitorKeysByKind[node.kind];
1233
+ if (!keys) return node;
1234
+ const record = node;
1235
+ const childOptions = {
1236
+ ...options,
1237
+ parent: node
1238
+ };
1239
+ let updates;
1240
+ for (const key of keys) {
1241
+ if (!(key in record)) continue;
1242
+ const value = record[key];
1243
+ if (Array.isArray(value)) {
1244
+ let changed = false;
1245
+ const mapped = value.map((item) => {
1246
+ if (!isNode(item)) return item;
1247
+ const next = transform(item, childOptions);
1248
+ if (next !== item) changed = true;
1249
+ return next;
1250
+ });
1251
+ if (changed) (updates ??= {})[key] = mapped;
1252
+ } else if (isNode(value)) {
1253
+ const next = transform(value, childOptions);
1254
+ if (next !== value) (updates ??= {})[key] = next;
1255
+ }
1256
+ }
1257
+ return updates ? {
1258
+ ...node,
1259
+ ...updates
1260
+ } : node;
1261
+ }
1262
+ /**
1263
+ * Lazy depth-first collection pass. Yields every non-null value returned by
1264
+ * the visitor callbacks. Use `collect` for the eager array form.
1265
+ *
1266
+ * @example Collect every operationId
1267
+ * ```ts
1268
+ * const ids: string[] = []
1269
+ * for (const id of collectLazy<string>(root, {
1270
+ * operation(node) {
1271
+ * return node.operationId
1272
+ * },
1273
+ * })) {
1274
+ * ids.push(id)
1275
+ * }
1276
+ * ```
1277
+ */
1278
+ function* collectLazy(node, options) {
1279
+ const { depth, parent, ...visitor } = options;
1280
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
1281
+ const v = applyVisitor(node, visitor, parent);
1282
+ if (v != null) yield v;
1283
+ for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
1284
+ ...options,
1285
+ parent: node
1286
+ });
1287
+ }
1288
+ /**
1289
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
1290
+ * callbacks return into an array.
1291
+ *
1292
+ * @example Collect every operationId
1293
+ * ```ts
1294
+ * const ids = collect<string>(root, {
1295
+ * operation(node) {
1296
+ * return node.operationId
1297
+ * },
1298
+ * })
1299
+ * ```
1300
+ */
1301
+ function collect(node, options) {
1302
+ return Array.from(collectLazy(node, options));
1303
+ }
1304
+ //#endregion
1305
+ export { createJsx as $, indexedAccessTypeDef as A, sourceDef as B, createFunctionParameter as C, createTypeLiteral as D, createObjectBindingPattern as E, createImport as F, createContent as G, camelCase as H, createSource as I, constDef as J, arrowFunctionDef as K, exportDef as L, typeLiteralDef as M, createExport as N, functionParameterDef as O, createFile as P, createFunction as Q, fileDef as R, inputDef as S, createIndexedAccessType as T, pascalCase as U, extractStringsFromNodes as V, contentDef as W, createBreak as X, createArrowFunction as Y, createConst as Z, createOperation as _, nodeDefs as a, typeDef as at, requestBodyDef as b, createResponse as c, isHttpOperationNode as ct, propertyDef as d, schemaTypes as dt, createText as et, createParameter as f, outputDef as g, createOutput as h, walk as i, textDef as it, objectBindingPatternDef as j, functionParametersDef as k, responseDef as l, narrowSchema as lt, optionality as m, collectLazy as n, functionDef as nt, createSchema as o, defineNode as ot, parameterDef as p, breakDef as q, transform as r, jsxDef as rt, schemaDef as s, visitorKeys as st, collect as t, createType as tt, createProperty as u, INDENT as ut, operationDef as v, createFunctionParameters as w, createInput as x, createRequestBody as y, importDef as z };
1306
+
1307
+ //# sourceMappingURL=visitor-DG5ROqRx.js.map