@kubb/ast 5.0.0-beta.8 → 5.0.0-beta.81

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