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