@kubb/ast 5.0.0-beta.9 → 5.0.0-beta.93

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,929 +117,341 @@ const schemaTypes = {
138
117
  */
139
118
  never: "never"
140
119
  };
120
+ //#endregion
121
+ //#region src/guards.ts
141
122
  /**
142
- * Scalar primitive schema types used for union simplification and type narrowing.
143
- *
144
- * Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
145
- */
146
- const SCALAR_PRIMITIVE_TYPES = new Set([
147
- "string",
148
- "number",
149
- "integer",
150
- "bigint",
151
- "boolean"
152
- ]);
153
- /**
154
- * Type guard that returns `true` when `type` is a scalar primitive schema type.
123
+ * Narrows a `SchemaNode` to the variant that matches `type`.
155
124
  *
156
- * Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
125
+ * @example
126
+ * ```ts
127
+ * const schema = createSchema({ type: 'string' })
128
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
129
+ * ```
157
130
  */
158
- function isScalarPrimitive(type) {
159
- return SCALAR_PRIMITIVE_TYPES.has(type);
131
+ function narrowSchema(node, type) {
132
+ return node?.type === type ? node : null;
160
133
  }
161
134
  /**
162
- * HTTP method identifiers used by operation nodes.
135
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
163
136
  *
164
- * Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
137
+ * @example
138
+ * ```ts
139
+ * if (isHttpOperationNode(node)) {
140
+ * console.log(node.method, node.path)
141
+ * }
142
+ * ```
165
143
  */
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
- };
176
- /**
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
- };
144
+ function isHttpOperationNode(node) {
145
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
146
+ }
203
147
  //#endregion
204
- //#region ../../internals/utils/src/casing.ts
148
+ //#region src/defineNode.ts
205
149
  /**
206
- * Shared implementation for camelCase and PascalCase conversion.
207
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
208
- * and capitalizes each word according to `pascal`.
209
- *
210
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
150
+ * Visitor callback names, one per traversable node kind, in traversal order.
151
+ * Kept in sync with the keys of `Visitor` in `visitor.ts`.
211
152
  */
212
- function toCamelOrPascal(text, pascal) {
213
- 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
- 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);
217
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
218
- }
153
+ const visitorKeys = [
154
+ "input",
155
+ "output",
156
+ "operation",
157
+ "schema",
158
+ "property",
159
+ "parameter",
160
+ "response"
161
+ ];
219
162
  /**
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.
223
- *
224
- * Only splits on dots followed by a letter so that version numbers
225
- * embedded in operationIds (e.g. `v2025.0`) are kept intact.
226
- *
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.
163
+ * Builds a type guard that matches nodes of the given `kind`.
232
164
  */
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("/");
236
- }
237
- /**
238
- * Converts `text` to camelCase.
239
- * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
240
- *
241
- * @example
242
- * camelCase('hello-world') // 'helloWorld'
243
- * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
244
- */
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);
165
+ function isKind(kind) {
166
+ return (node) => node?.kind === kind;
251
167
  }
252
168
  /**
253
- * Converts `text` to PascalCase.
254
- * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
169
+ * Defines a node once and derives its `create` builder, `is` guard, and traversal
170
+ * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
171
+ * `kind`, so node construction lives in one place without scattered `as` casts.
255
172
  *
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);
266
- }
267
- //#endregion
268
- //#region ../../internals/utils/src/reserved.ts
269
- /**
270
- * JavaScript and Java reserved words.
271
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
272
- */
273
- const reservedWords = new Set([
274
- "abstract",
275
- "arguments",
276
- "boolean",
277
- "break",
278
- "byte",
279
- "case",
280
- "catch",
281
- "char",
282
- "class",
283
- "const",
284
- "continue",
285
- "debugger",
286
- "default",
287
- "delete",
288
- "do",
289
- "double",
290
- "else",
291
- "enum",
292
- "eval",
293
- "export",
294
- "extends",
295
- "false",
296
- "final",
297
- "finally",
298
- "float",
299
- "for",
300
- "function",
301
- "goto",
302
- "if",
303
- "implements",
304
- "import",
305
- "in",
306
- "instanceof",
307
- "int",
308
- "interface",
309
- "let",
310
- "long",
311
- "native",
312
- "new",
313
- "null",
314
- "package",
315
- "private",
316
- "protected",
317
- "public",
318
- "return",
319
- "short",
320
- "static",
321
- "super",
322
- "switch",
323
- "synchronized",
324
- "this",
325
- "throw",
326
- "throws",
327
- "transient",
328
- "true",
329
- "try",
330
- "typeof",
331
- "var",
332
- "void",
333
- "volatile",
334
- "while",
335
- "with",
336
- "yield",
337
- "Array",
338
- "Date",
339
- "hasOwnProperty",
340
- "Infinity",
341
- "isFinite",
342
- "isNaN",
343
- "isPrototypeOf",
344
- "length",
345
- "Math",
346
- "name",
347
- "NaN",
348
- "Number",
349
- "Object",
350
- "prototype",
351
- "String",
352
- "toString",
353
- "undefined",
354
- "valueOf"
355
- ]);
356
- /**
357
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
173
+ * @example Simple node
174
+ * ```ts
175
+ * const importDef = defineNode<ImportNode>({ kind: 'Import' })
176
+ * const createImport = importDef.create
177
+ * ```
358
178
  *
359
- * @example
179
+ * @example Node with a build hook
360
180
  * ```ts
361
- * isValidVarName('status') // true
362
- * isValidVarName('class') // false (reserved word)
363
- * isValidVarName('42foo') // false (starts with digit)
181
+ * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
182
+ * kind: 'Property',
183
+ * build: (props) => ({ ...props, required: props.required ?? false }),
184
+ * children: ['schema'],
185
+ * visitorKey: 'property',
186
+ * })
364
187
  * ```
365
188
  */
366
- function isValidVarName(name) {
367
- if (!name || reservedWords.has(name)) return false;
368
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
189
+ function defineNode(config) {
190
+ const { kind, defaults, build, children, visitorKey } = config;
191
+ function create(input) {
192
+ const base = build ? build(input) : input;
193
+ const node = {
194
+ kind,
195
+ ...defaults,
196
+ ...base
197
+ };
198
+ node.kind = kind;
199
+ return node;
200
+ }
201
+ return {
202
+ kind,
203
+ create,
204
+ is: isKind(kind),
205
+ children,
206
+ visitorKey
207
+ };
369
208
  }
370
209
  //#endregion
371
- //#region ../../internals/utils/src/string.ts
210
+ //#region src/nodes/code.ts
372
211
  /**
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.
375
- *
376
- * @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'
212
+ * Definition for the {@link ConstNode}.
381
213
  */
382
- function trimExtName(text) {
383
- const dotIndex = text.lastIndexOf(".");
384
- if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
385
- return text;
386
- }
387
- //#endregion
388
- //#region src/guards.ts
214
+ const constDef = defineNode({ kind: "Const" });
389
215
  /**
390
- * Narrows a `SchemaNode` to the variant that matches `type`.
216
+ * Definition for the {@link TypeNode}.
217
+ */
218
+ const typeDef = defineNode({ kind: "Type" });
219
+ /**
220
+ * Definition for the {@link FunctionNode}.
221
+ */
222
+ const functionDef = defineNode({ kind: "Function" });
223
+ /**
224
+ * Definition for the {@link ArrowFunctionNode}.
225
+ */
226
+ const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
227
+ /**
228
+ * Definition for the {@link TextNode}.
229
+ */
230
+ const textDef = defineNode({
231
+ kind: "Text",
232
+ build: (value) => ({ value })
233
+ });
234
+ /**
235
+ * Definition for the {@link BreakNode}.
236
+ */
237
+ const breakDef = defineNode({
238
+ kind: "Break",
239
+ build: () => ({})
240
+ });
241
+ /**
242
+ * Definition for the {@link JsxNode}.
243
+ */
244
+ const jsxDef = defineNode({
245
+ kind: "Jsx",
246
+ build: (value) => ({ value })
247
+ });
248
+ /**
249
+ * Creates a `ConstNode` representing a TypeScript `const` declaration.
391
250
  *
392
- * @example
251
+ * @example Exported constant with type and `as const`
393
252
  * ```ts
394
- * const schema = createSchema({ type: 'string' })
395
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | undefined
253
+ * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
254
+ * // export const pets: Pet[] = ... as const
396
255
  * ```
397
256
  */
398
- function narrowSchema(node, type) {
399
- return node?.type === type ? node : void 0;
400
- }
401
- function isKind(kind) {
402
- return (node) => node.kind === kind;
403
- }
257
+ const createConst = constDef.create;
404
258
  /**
405
- * Returns `true` when the input is an `InputNode`.
259
+ * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
406
260
  *
407
261
  * @example
408
262
  * ```ts
409
- * if (isInputNode(node)) {
410
- * console.log(node.schemas.length)
411
- * }
263
+ * createType({ name: 'Pet', export: true })
264
+ * // export type Pet = ...
412
265
  * ```
413
266
  */
414
- const isInputNode = isKind("Input");
267
+ const createType = typeDef.create;
415
268
  /**
416
- * Returns `true` when the input is an `OutputNode`.
269
+ * Creates a `FunctionNode` representing a TypeScript `function` declaration.
417
270
  *
418
271
  * @example
419
272
  * ```ts
420
- * if (isOutputNode(node)) {
421
- * console.log(node.files.length)
422
- * }
273
+ * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
274
+ * // export async function fetchPet(): Promise<Pet> { ... }
423
275
  * ```
424
276
  */
425
- const isOutputNode = isKind("Output");
277
+ const createFunction = functionDef.create;
426
278
  /**
427
- * Returns `true` when the input is an `OperationNode`.
279
+ * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
428
280
  *
429
281
  * @example
430
282
  * ```ts
431
- * if (isOperationNode(node)) {
432
- * console.log(node.operationId)
433
- * }
283
+ * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
284
+ * // export const double = (n: number) => ...
434
285
  * ```
435
286
  */
436
- const isOperationNode = isKind("Operation");
287
+ const createArrowFunction = arrowFunctionDef.create;
437
288
  /**
438
- * Returns `true` when the input is a `SchemaNode`.
289
+ * Creates a {@link TextNode} representing a raw string fragment in the source output.
439
290
  *
440
291
  * @example
441
292
  * ```ts
442
- * if (isSchemaNode(node)) {
443
- * console.log(node.type)
444
- * }
293
+ * createText('return fetch(id)')
294
+ * // { kind: 'Text', value: 'return fetch(id)' }
445
295
  * ```
446
296
  */
447
- const isSchemaNode = isKind("Schema");
448
- //#endregion
449
- //#region src/refs.ts
297
+ const createText = textDef.create;
450
298
  /**
451
- * Returns the last path segment of a reference string.
452
- *
453
- * Example: `#/components/schemas/Pet` becomes `Pet`.
299
+ * Creates a {@link BreakNode} representing a line break in the source output.
454
300
  *
455
301
  * @example
456
302
  * ```ts
457
- * extractRefName('#/components/schemas/Pet') // 'Pet'
303
+ * createBreak()
304
+ * // { kind: 'Break' }
458
305
  * ```
459
306
  */
460
- function extractRefName(ref) {
461
- return ref.split("/").at(-1) ?? ref;
307
+ function createBreak() {
308
+ return breakDef.create();
462
309
  }
463
- //#endregion
464
- //#region src/visitor.ts
465
310
  /**
466
- * Creates a small async concurrency limiter.
467
- *
468
- * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
311
+ * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
469
312
  *
470
313
  * @example
471
314
  * ```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
315
+ * createJsx('<>\n <a href={href}>Open</a>\n</>')
316
+ * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
477
317
  * ```
478
318
  */
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
- };
319
+ const createJsx = jsxDef.create;
320
+ //#endregion
321
+ //#region src/nodes/content.ts
322
+ /**
323
+ * Definition for the {@link ContentNode}.
324
+ */
325
+ const contentDef = defineNode({
326
+ kind: "Content",
327
+ children: ["schema"]
328
+ });
329
+ /**
330
+ * Creates a `ContentNode` for a single request-body or response content type.
331
+ */
332
+ const createContent = contentDef.create;
333
+ //#endregion
334
+ //#region ../../internals/utils/src/casing.ts
335
+ /**
336
+ * Shared implementation for camelCase and PascalCase conversion.
337
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
338
+ * and capitalizes each word according to `pascal`.
339
+ *
340
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
341
+ */
342
+ function toCamelOrPascal(text, pascal) {
343
+ 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) => {
344
+ if (word.length > 1 && word === word.toUpperCase()) return word;
345
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
346
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
499
347
  }
500
348
  /**
501
- * Returns the immediate traversable children of `node`.
349
+ * Converts `text` to PascalCase.
502
350
  *
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.
351
+ * @example Word boundaries
352
+ * `pascalCase('hello-world') // 'HelloWorld'`
506
353
  *
507
- * @example
508
- * ```ts
509
- * const children = getChildren(operationNode, true)
510
- * // returns parameters, requestBody schema (if present), and responses
511
- * ```
354
+ * @example With a suffix
355
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
512
356
  */
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
- }
357
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
358
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
540
359
  }
360
+ //#endregion
361
+ //#region ../../internals/utils/src/fs.ts
541
362
  /**
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
- * ```
363
+ * Strips the file extension from a path or file name.
364
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
554
365
  *
555
366
  * @example
556
- * ```ts
557
- * // Visit only the current node
558
- * await walk(root, { depth: 'shallow', root: () => {} })
559
- * ```
367
+ * trimExtName('petStore.ts') // 'petStore'
368
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
369
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
370
+ * trimExtName('noExtension') // 'noExtension'
560
371
  */
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
- }
372
+ function trimExtName(text) {
373
+ const dotIndex = text.lastIndexOf(".");
374
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
375
+ return text;
704
376
  }
377
+ //#endregion
378
+ //#region ../../internals/utils/src/promise.ts
705
379
  /**
706
- * Runs a depth-first synchronous collection pass.
380
+ * Wraps `factory` with a keyed cache backed by the provided store.
707
381
  *
708
- * Non-`undefined` values returned by visitor callbacks are appended to the result.
382
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
383
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
384
+ * nest two `memoize` calls — the outer keyed by the first argument, the
385
+ * inner (created once per outer miss) keyed by the second.
709
386
  *
710
- * @example
387
+ * Because the cache is owned by the caller, it can be shared, inspected, or
388
+ * cleared independently of the memoized function.
389
+ *
390
+ * @example Single WeakMap key
711
391
  * ```ts
712
- * const ids = collect(root, {
713
- * operation(node) {
714
- * return node.operationId
715
- * },
716
- * })
392
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
393
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
717
394
  * ```
718
395
  *
719
- * @example
396
+ * @example Single Map key (primitive)
720
397
  * ```ts
721
- * // Collect from only the current node
722
- * const values = collect(root, { depth: 'shallow', root: () => 'root' })
398
+ * const cache = new Map<string, Resolver>()
399
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
723
400
  * ```
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
401
  *
778
- * @example
402
+ * @example Two-level (object + primitive)
779
403
  * ```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
404
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
405
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
406
+ * fn(params)('camelcase')
783
407
  * ```
784
408
  */
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;
409
+ function memoize(store, factory) {
410
+ return (key) => {
411
+ if (store.has(key)) return store.get(key);
412
+ const value = factory(key);
413
+ store.set(key, value);
414
+ return value;
415
+ };
807
416
  }
417
+ //#endregion
418
+ //#region src/utils/extractStringsFromNodes.ts
808
419
  /**
809
- * Applies casing rules to parameter names and returns a new parameter array.
420
+ * Extracts all string content from a `CodeNode` tree recursively.
810
421
  *
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.
422
+ * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
423
+ * and nested node content. Used to build the full source string for import filtering.
814
424
  */
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
- }));
425
+ function extractStringsFromNodes(nodes) {
426
+ if (!nodes?.length) return "";
427
+ const collected = [];
428
+ for (const node of nodes) {
429
+ if (typeof node === "string") {
430
+ if (node) collected.push(node);
431
+ continue;
976
432
  }
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
- }));
433
+ if (node.kind === "Text") {
434
+ if (node.value) collected.push(node.value);
435
+ continue;
436
+ }
437
+ if (node.kind === "Break") continue;
438
+ if (node.kind === "Jsx") {
439
+ if (node.value) collected.push(node.value);
440
+ continue;
441
+ }
442
+ const parts = [];
443
+ if ("params" in node && node.params) parts.push(node.params);
444
+ if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
445
+ if ("returnType" in node && node.returnType) parts.push(node.returnType);
446
+ if ("type" in node && typeof node.type === "string") parts.push(node.type);
447
+ const nested = extractStringsFromNodes(node.nodes);
448
+ if (nested) parts.push(nested);
449
+ if (parts.length) collected.push(parts.join("\n"));
998
450
  }
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
- });
451
+ return collected.join("\n");
1063
452
  }
453
+ //#endregion
454
+ //#region src/utils/combineFileMembers.ts
1064
455
  function sourceKey(source) {
1065
456
  return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
1066
457
  }
@@ -1075,19 +466,19 @@ function importKey(path, name, isTypeOnly) {
1075
466
  }
1076
467
  /**
1077
468
  * 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.
469
+ * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
1079
470
  */
1080
471
  function sortKey(node) {
1081
472
  const isArray = Array.isArray(node.name) ? "1" : "0";
1082
473
  const typeOnly = node.isTypeOnly ? "0" : "1";
1083
474
  const hasName = node.name != null ? "1" : "0";
1084
- const name = Array.isArray(node.name) ? [...node.name].sort().join("\0") : node.name ?? "";
475
+ const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
1085
476
  return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
1086
477
  }
1087
478
  /**
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.
479
+ * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
480
+ * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
481
+ * the deduplicated array in original order.
1091
482
  */
1092
483
  function combineSources(sources) {
1093
484
  const seen = /* @__PURE__ */ new Map();
@@ -1098,6 +489,16 @@ function combineSources(sources) {
1098
489
  return [...seen.values()];
1099
490
  }
1100
491
  /**
492
+ * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
493
+ *
494
+ * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
495
+ */
496
+ function mergeNameArrays(existing, incoming) {
497
+ const merged = new Set(existing);
498
+ for (const name of incoming) merged.add(name);
499
+ return [...merged];
500
+ }
501
+ /**
1101
502
  * Deduplicates and merges `ExportNode` objects by path and type.
1102
503
  *
1103
504
  * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
@@ -1118,11 +519,8 @@ function combineExports(exports) {
1118
519
  if (!name.length) continue;
1119
520
  const key = pathTypeKey(path, isTypeOnly);
1120
521
  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 {
522
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
523
+ else {
1126
524
  const newItem = {
1127
525
  ...curr,
1128
526
  name: [...new Set(name)]
@@ -1145,8 +543,6 @@ function combineExports(exports) {
1145
543
  *
1146
544
  * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
1147
545
  * `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
546
  */
1151
547
  function combineImports(imports, exports, source) {
1152
548
  const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
@@ -1158,6 +554,11 @@ function combineImports(imports, exports, source) {
1158
554
  if (!importNameMemo.has(key)) importNameMemo.set(key, n);
1159
555
  return importNameMemo.get(key);
1160
556
  };
557
+ const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
558
+ for (const node of imports) {
559
+ if (!Array.isArray(node.name)) continue;
560
+ if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
561
+ }
1161
562
  const result = [];
1162
563
  const namedByPath = /* @__PURE__ */ new Map();
1163
564
  const seen = /* @__PURE__ */ new Set();
@@ -1175,11 +576,8 @@ function combineImports(imports, exports, source) {
1175
576
  if (!name.length) continue;
1176
577
  const key = pathTypeKey(path, isTypeOnly);
1177
578
  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 {
579
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
580
+ else {
1183
581
  const newItem = {
1184
582
  ...curr,
1185
583
  name
@@ -1188,7 +586,7 @@ function combineImports(imports, exports, source) {
1188
586
  namedByPath.set(key, newItem);
1189
587
  }
1190
588
  } else {
1191
- if (name && !isUsed(name)) continue;
589
+ if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
1192
590
  const key = importKey(path, name, isTypeOnly);
1193
591
  if (!seen.has(key)) {
1194
592
  result.push(curr);
@@ -1198,210 +596,218 @@ function combineImports(imports, exports, source) {
1198
596
  }
1199
597
  return result;
1200
598
  }
599
+ //#endregion
600
+ //#region src/nodes/file.ts
1201
601
  /**
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.
602
+ * Definition for the {@link ImportNode}.
1206
603
  */
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
- }
604
+ const importDef = defineNode({ kind: "Import" });
1224
605
  /**
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.
606
+ * Definition for the {@link ExportNode}.
607
+ */
608
+ const exportDef = defineNode({ kind: "Export" });
609
+ /**
610
+ * Definition for the {@link SourceNode}.
611
+ */
612
+ const sourceDef = defineNode({ kind: "Source" });
613
+ /**
614
+ * Definition for the {@link FileNode}. The fully resolved builder lives in
615
+ * `createFile`, so this definition only supplies the guard.
616
+ */
617
+ const fileDef = defineNode({ kind: "File" });
618
+ /**
619
+ * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1229
620
  *
1230
- * @example
621
+ * @example Named import
1231
622
  * ```ts
1232
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
1233
- * // => 'Pet'
623
+ * createImport({ name: ['useState'], path: 'react' })
624
+ * // import { useState } from 'react'
1234
625
  * ```
1235
626
  */
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
- }
627
+ const createImport = importDef.create;
1241
628
  /**
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.
629
+ * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1246
630
  *
1247
- * @example Collect refs from a single schema
631
+ * @example Named export
1248
632
  * ```ts
1249
- * const names = collectReferencedSchemaNames(petSchema)
1250
- * // Set { 'Category', 'Tag' }
633
+ * createExport({ name: ['Pet'], path: './Pet' })
634
+ * // export { Pet } from './Pet'
1251
635
  * ```
636
+ */
637
+ const createExport = exportDef.create;
638
+ /**
639
+ * Creates a `SourceNode` representing a fragment of source code within a file.
1252
640
  *
1253
- * @example Accumulate refs from multiple schemas into one set
641
+ * @example
1254
642
  * ```ts
1255
- * const out = new Set<string>()
1256
- * for (const schema of schemas) {
1257
- * collectReferencedSchemaNames(schema, out)
1258
- * }
643
+ * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1259
644
  * ```
1260
645
  */
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
- }
646
+ const createSource = sourceDef.create;
1271
647
  /**
1272
- * Collects the names of all top-level schemas transitively used by a set of operations.
648
+ * Creates a fully resolved `FileNode` from a file input descriptor.
1273
649
  *
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.
650
+ * Computes:
651
+ * - `id` SHA256 hash of the file path
652
+ * - `name` `baseName` without extension
653
+ * - `extname` extension extracted from `baseName`
654
+ *
655
+ * Deduplicates:
656
+ * - `sources` via `combineSources`
657
+ * - `exports` via `combineExports`
658
+ * - `imports` via `combineImports` (also filters unused imports)
1277
659
  *
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.
660
+ * @throws {Error} when `baseName` has no extension.
1281
661
  *
1282
- * @example Only generate schemas referenced by included operations
662
+ * @example
1283
663
  * ```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
- * }
664
+ * const file = createFile({
665
+ * baseName: 'petStore.ts',
666
+ * path: 'src/models/petStore.ts',
667
+ * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
668
+ * imports: [createImport({ name: ['z'], path: 'zod' })],
669
+ * exports: [createExport({ name: ['Pet'], path: './petStore' })],
670
+ * })
671
+ * // file.id = SHA256 hash of 'src/models/petStore.ts'
672
+ * // file.name = 'petStore'
673
+ * // file.extname = '.ts'
1291
674
  * ```
1292
675
  *
1293
- * @example Check whether a specific schema is needed
676
+ * @example Copy a real file into the output verbatim
1294
677
  * ```ts
1295
- * const allowed = collectUsedSchemaNames(includedOps, inputNode.schemas)
1296
- * allowed.has('OrderStatus') // false when no included operation references OrderStatus
678
+ * const file = createFile({
679
+ * baseName: 'client.ts',
680
+ * path: 'src/gen/client.ts',
681
+ * copy: '/abs/path/to/templates/client.ts',
682
+ * })
1297
683
  * ```
1298
684
  */
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
- }
1310
- }
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;
1316
- }
1317
- /**
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.
1325
- */
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);
685
+ function createFile(input) {
686
+ const extname = path.extname(input.baseName);
687
+ if (!extname) throw new Error(`No extname found for ${input.baseName}`);
688
+ const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
689
+ const resolvedImports = (() => {
690
+ if (!input.imports?.length) return [];
691
+ const sourceParts = [];
692
+ const localNames = /* @__PURE__ */ new Set();
693
+ for (const item of input.sources ?? []) {
694
+ const extracted = item.nodes && extractStringsFromNodes(item.nodes);
695
+ if (extracted) sourceParts.push(extracted);
696
+ if (item.name) localNames.add(item.name);
1346
697
  }
1347
- }
1348
- return circular;
1349
- }
1350
- /**
1351
- * Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
1352
- *
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.
1355
- *
1356
- * @note Returns `true` for the first matching circular ref found; use for fast dependency checks.
1357
- */
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;
698
+ const source = sourceParts.join("\n") || void 0;
699
+ const combinedImports = combineImports(input.imports, resolvedExports, source);
700
+ const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
701
+ return combinedImports.flatMap((imp) => {
702
+ if (imp.path === input.path) return [];
703
+ if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
704
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
705
+ if (!kept.length) return [];
706
+ return [kept.length === imp.name.length ? imp : {
707
+ ...imp,
708
+ name: kept
709
+ }];
710
+ });
711
+ })();
712
+ const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
713
+ return {
714
+ kind: "File",
715
+ ...input,
716
+ id: hash("sha256", input.path, "hex"),
717
+ name: trimExtName(input.baseName),
718
+ extname,
719
+ imports: resolvedImports,
720
+ exports: resolvedExports,
721
+ sources: resolvedSources,
722
+ meta: input.meta ?? {}
723
+ };
1365
724
  }
1366
725
  //#endregion
1367
- //#region src/factory.ts
726
+ //#region src/nodes/input.ts
1368
727
  /**
1369
- * Syncs property/parameter schema optionality flags from `required` and `schema.nullable`.
1370
- *
1371
- * - `optional` is set for non-required, non-nullable schemas.
1372
- * - `nullish` is set for non-required, nullable schemas.
728
+ * Definition for the {@link InputNode}.
1373
729
  */
1374
- function syncOptionality(schema, required) {
1375
- const nullable = schema.nullable ?? false;
1376
- return {
1377
- ...schema,
1378
- optional: !required && !nullable ? true : void 0,
1379
- nullish: !required && nullable ? true : void 0
1380
- };
1381
- }
730
+ const inputDef = defineNode({
731
+ kind: "Input",
732
+ defaults: {
733
+ schemas: [],
734
+ operations: [],
735
+ meta: {
736
+ circularNames: [],
737
+ enumNames: []
738
+ }
739
+ },
740
+ children: ["schemas", "operations"],
741
+ visitorKey: "input"
742
+ });
1382
743
  /**
1383
- * Creates an `InputNode` with stable defaults for `schemas` and `operations`.
744
+ * Creates an `InputNode`, defaulting `schemas`/`operations` to empty arrays and `meta` per
745
+ * {@link inputDef}.
1384
746
  *
1385
747
  * @example
1386
748
  * ```ts
1387
749
  * const input = createInput()
1388
750
  * // { kind: 'Input', schemas: [], operations: [] }
1389
751
  * ```
1390
- *
1391
- * @example
1392
- * ```ts
1393
- * const input = createInput({ schemas: [petSchema] })
1394
- * // keeps default operations: []
1395
- * ```
1396
752
  */
1397
753
  function createInput(overrides = {}) {
1398
- return {
1399
- schemas: [],
1400
- operations: [],
1401
- ...overrides,
1402
- kind: "Input"
1403
- };
754
+ return inputDef.create(overrides);
755
+ }
756
+ //#endregion
757
+ //#region src/nodes/requestBody.ts
758
+ /**
759
+ * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
760
+ * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
761
+ */
762
+ const requestBodyDef = defineNode({
763
+ kind: "RequestBody",
764
+ children: ["content"]
765
+ });
766
+ /**
767
+ * Creates a `RequestBodyNode`.
768
+ */
769
+ const createRequestBody = requestBodyDef.create;
770
+ //#endregion
771
+ //#region src/nodes/operation.ts
772
+ /**
773
+ * Definition for the {@link OperationNode}. HTTP operations (those carrying both
774
+ * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
775
+ * normalized into a `RequestBodyNode`.
776
+ */
777
+ const operationDef = defineNode({
778
+ kind: "Operation",
779
+ build: (props) => {
780
+ const { requestBody, ...rest } = props;
781
+ const isHttp = rest.method !== void 0 && rest.path !== void 0;
782
+ return {
783
+ tags: [],
784
+ parameters: [],
785
+ responses: [],
786
+ ...rest,
787
+ ...isHttp ? { protocol: "http" } : {},
788
+ requestBody: requestBody ? createRequestBody(requestBody) : void 0
789
+ };
790
+ },
791
+ children: [
792
+ "parameters",
793
+ "requestBody",
794
+ "responses"
795
+ ],
796
+ visitorKey: "operation"
797
+ });
798
+ function createOperation(props) {
799
+ return operationDef.create(props);
1404
800
  }
801
+ //#endregion
802
+ //#region src/nodes/output.ts
803
+ /**
804
+ * Definition for the {@link OutputNode}.
805
+ */
806
+ const outputDef = defineNode({
807
+ kind: "Output",
808
+ defaults: { files: [] },
809
+ visitorKey: "output"
810
+ });
1405
811
  /**
1406
812
  * Creates an `OutputNode` with a stable default for `files`.
1407
813
  *
@@ -1410,55 +816,131 @@ function createInput(overrides = {}) {
1410
816
  * const output = createOutput()
1411
817
  * // { kind: 'Output', files: [] }
1412
818
  * ```
1413
- *
1414
- * @example
1415
- * ```ts
1416
- * const output = createOutput({ files: [petFile] })
1417
- * ```
1418
819
  */
1419
820
  function createOutput(overrides = {}) {
821
+ return outputDef.create(overrides);
822
+ }
823
+ //#endregion
824
+ //#region src/optionality.ts
825
+ /**
826
+ * Generic JSON Schema optionality: a non-required field is optional, and a
827
+ * non-required nullable field is nullish.
828
+ */
829
+ function optionality(schema, required) {
830
+ const nullable = schema.nullable ?? false;
1420
831
  return {
1421
- files: [],
1422
- ...overrides,
1423
- kind: "Output"
832
+ ...schema,
833
+ optional: !required && !nullable ? true : void 0,
834
+ nullish: !required && nullable ? true : void 0
1424
835
  };
1425
836
  }
837
+ //#endregion
838
+ //#region src/nodes/parameter.ts
1426
839
  /**
1427
- * Creates an `OperationNode` with default empty arrays for `tags`, `parameters`, and `responses`.
1428
- *
1429
- * @example
840
+ * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
841
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
842
+ */
843
+ const parameterDef = defineNode({
844
+ kind: "Parameter",
845
+ build: (props) => {
846
+ const required = props.required ?? false;
847
+ return {
848
+ ...props,
849
+ required,
850
+ schema: optionality(props.schema, required)
851
+ };
852
+ },
853
+ children: ["schema"],
854
+ visitorKey: "parameter"
855
+ });
856
+ /**
857
+ * Creates a `ParameterNode`.
858
+ *
859
+ * @example
1430
860
  * ```ts
1431
- * const operation = createOperation({
1432
- * operationId: 'getPetById',
1433
- * method: 'GET',
1434
- * path: '/pet/{petId}',
861
+ * const param = createParameter({
862
+ * name: 'petId',
863
+ * in: 'path',
864
+ * required: true,
865
+ * schema: createSchema({ type: 'string' }),
1435
866
  * })
1436
- * // tags, parameters, and responses are []
1437
867
  * ```
868
+ */
869
+ const createParameter = parameterDef.create;
870
+ //#endregion
871
+ //#region src/nodes/property.ts
872
+ /**
873
+ * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
874
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
875
+ */
876
+ const propertyDef = defineNode({
877
+ kind: "Property",
878
+ build: (props) => {
879
+ const required = props.required ?? false;
880
+ return {
881
+ ...props,
882
+ required,
883
+ schema: optionality(props.schema, required)
884
+ };
885
+ },
886
+ children: ["schema"],
887
+ visitorKey: "property"
888
+ });
889
+ /**
890
+ * Creates a `PropertyNode`.
1438
891
  *
1439
892
  * @example
1440
893
  * ```ts
1441
- * const operation = createOperation({
1442
- * operationId: 'findPets',
1443
- * method: 'GET',
1444
- * path: '/pet/findByStatus',
1445
- * tags: ['pet'],
894
+ * const property = createProperty({
895
+ * name: 'status',
896
+ * required: true,
897
+ * schema: createSchema({ type: 'string', nullable: true }),
1446
898
  * })
899
+ * // required=true, no optional/nullish
1447
900
  * ```
1448
901
  */
1449
- function createOperation(props) {
1450
- return {
1451
- tags: [],
1452
- parameters: [],
1453
- responses: [],
1454
- ...props,
1455
- kind: "Operation"
1456
- };
1457
- }
902
+ const createProperty = propertyDef.create;
903
+ //#endregion
904
+ //#region src/nodes/response.ts
905
+ /**
906
+ * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
907
+ * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
908
+ */
909
+ const responseDef = defineNode({
910
+ kind: "Response",
911
+ build: (props) => {
912
+ const { schema, mediaType, keysToOmit, content, ...rest } = props;
913
+ const entries = content ?? (schema ? [createContent({
914
+ contentType: mediaType ?? "application/json",
915
+ schema,
916
+ keysToOmit: keysToOmit ?? null
917
+ })] : void 0);
918
+ return {
919
+ ...rest,
920
+ content: entries
921
+ };
922
+ },
923
+ children: ["content"],
924
+ visitorKey: "response"
925
+ });
926
+ /**
927
+ * Creates a `ResponseNode`.
928
+ *
929
+ * @example
930
+ * ```ts
931
+ * const response = createResponse({
932
+ * statusCode: '200',
933
+ * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
934
+ * })
935
+ * ```
936
+ */
937
+ const createResponse = responseDef.create;
938
+ //#endregion
939
+ //#region src/nodes/schema.ts
1458
940
  /**
1459
941
  * 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.
942
+ * Primitive types map to themselves and special string formats map to `'string'`.
943
+ * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
1462
944
  */
1463
945
  const TYPE_TO_PRIMITIVE = {
1464
946
  string: "string",
@@ -1480,692 +962,763 @@ const TYPE_TO_PRIMITIVE = {
1480
962
  datetime: "string",
1481
963
  time: "string"
1482
964
  };
965
+ /**
966
+ * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
967
+ * empty array, and `primitive` is inferred from `type` when not explicitly provided.
968
+ */
969
+ const schemaDef = defineNode({
970
+ kind: "Schema",
971
+ build: (props) => {
972
+ if (props.type === "object") return {
973
+ properties: [],
974
+ primitive: "object",
975
+ ...props
976
+ };
977
+ return {
978
+ primitive: TYPE_TO_PRIMITIVE[props.type],
979
+ ...props
980
+ };
981
+ },
982
+ children: [
983
+ "properties",
984
+ "items",
985
+ "members",
986
+ "additionalProperties"
987
+ ],
988
+ visitorKey: "schema"
989
+ });
1483
990
  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
- };
991
+ return schemaDef.create(props);
1496
992
  }
993
+ //#endregion
994
+ //#region src/registry.ts
995
+ /**
996
+ * Every node definition. Adding a node means adding its `defineNode` to one
997
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
998
+ */
999
+ const nodeDefs = [
1000
+ inputDef,
1001
+ outputDef,
1002
+ operationDef,
1003
+ requestBodyDef,
1004
+ contentDef,
1005
+ responseDef,
1006
+ schemaDef,
1007
+ propertyDef,
1008
+ parameterDef,
1009
+ constDef,
1010
+ typeDef,
1011
+ functionDef,
1012
+ arrowFunctionDef,
1013
+ textDef,
1014
+ breakDef,
1015
+ jsxDef,
1016
+ importDef,
1017
+ exportDef,
1018
+ sourceDef,
1019
+ fileDef
1020
+ ];
1021
+ //#endregion
1022
+ //#region src/visitor.ts
1497
1023
  /**
1498
- * Creates a `PropertyNode`.
1024
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
1025
+ * Derived from each definition's `children`.
1026
+ */
1027
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
1028
+ /**
1029
+ * Maps a node kind to the matching visitor callback name. Derived from each
1030
+ * definition's `visitorKey`.
1031
+ */
1032
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1033
+ const visitorKeysByKind = VISITOR_KEYS;
1034
+ /**
1035
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1036
+ */
1037
+ function isNode(value) {
1038
+ return typeof value === "object" && value !== null && typeof value.kind === "string";
1039
+ }
1040
+ /**
1041
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1499
1042
  *
1500
- * `required` defaults to `false`.
1501
- * `schema.optional` and `schema.nullish` are derived from `required` and `schema.nullable`.
1043
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1502
1044
  *
1503
1045
  * @example
1504
1046
  * ```ts
1505
- * const property = createProperty({
1506
- * name: 'status',
1507
- * schema: createSchema({ type: 'string' }),
1508
- * })
1509
- * // required=false, schema.optional=true
1510
- * ```
1047
+ * const children = getChildren(operationNode, true)
1048
+ * // returns parameters, the request body, and responses
1049
+ * ```
1050
+ */
1051
+ function* getChildren(node, recurse) {
1052
+ if (node.kind === "Schema" && !recurse) return;
1053
+ const keys = visitorKeysByKind[node.kind];
1054
+ if (!keys) return;
1055
+ const record = node;
1056
+ for (const key of keys) {
1057
+ const value = record[key];
1058
+ if (Array.isArray(value)) {
1059
+ for (const item of value) if (isNode(item)) yield item;
1060
+ } else if (isNode(value)) yield value;
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Runs the visitor callback that matches `node.kind` with the traversal
1065
+ * context. The result is a replacement node, a collected value, or `undefined`
1066
+ * when no callback is registered for the kind.
1511
1067
  *
1512
- * @example
1513
- * ```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
1520
- * ```
1068
+ * Shared by `transform` and `collectLazy` so node-kind dispatch lives in one place.
1069
+ * `TResult` is the caller's expected return: the same node type for `transform`,
1070
+ * the collected value type for `collectLazy`.
1521
1071
  */
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
- };
1072
+ function applyVisitor(node, visitor, parent) {
1073
+ const key = VISITOR_KEY_BY_KIND[node.kind];
1074
+ if (!key) return void 0;
1075
+ const fn = visitor[key];
1076
+ return fn?.(node, { parent });
1077
+ }
1078
+ function transform(node, options) {
1079
+ const { depth, parent, ...visitor } = options;
1080
+ return transformNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1081
+ }
1082
+ /**
1083
+ * Visits a single node, then immutably rebuilds its children. Returns the original
1084
+ * reference when neither the visitor nor the child rebuild changed anything, so callers
1085
+ * can detect "nothing changed" by identity and ancestors avoid reallocating.
1086
+ */
1087
+ function transformNode(node, visitor, recurse, parent) {
1088
+ return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
1089
+ }
1090
+ /**
1091
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1092
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1093
+ * `Schema` children are skipped in shallow mode.
1094
+ */
1095
+ function transformChildren(node, visitor, recurse) {
1096
+ if (node.kind === "Schema" && !recurse) return node;
1097
+ const keys = visitorKeysByKind[node.kind];
1098
+ if (!keys) return node;
1099
+ const record = node;
1100
+ let updates;
1101
+ for (const key of keys) {
1102
+ if (!(key in record)) continue;
1103
+ const value = record[key];
1104
+ if (Array.isArray(value)) {
1105
+ let mapped;
1106
+ for (const [i, item] of value.entries()) {
1107
+ const next = isNode(item) ? transformNode(item, visitor, recurse, node) : item;
1108
+ if (mapped) {
1109
+ mapped.push(next);
1110
+ continue;
1111
+ }
1112
+ if (next !== item) mapped = [...value.slice(0, i), next];
1113
+ }
1114
+ if (mapped) (updates ??= {})[key] = mapped;
1115
+ } else if (isNode(value)) {
1116
+ const next = transformNode(value, visitor, recurse, node);
1117
+ if (next !== value) (updates ??= {})[key] = next;
1118
+ }
1119
+ }
1120
+ return updates ? {
1121
+ ...node,
1122
+ ...updates
1123
+ } : node;
1530
1124
  }
1531
1125
  /**
1532
- * Creates a `ParameterNode`.
1126
+ * Lazy depth-first collection pass. Yields every non-null value returned by
1127
+ * the visitor callbacks. Use `collect` for the eager array form.
1533
1128
  *
1534
- * `required` defaults to `false`.
1535
- * Nested schema flags are set from `required` and `schema.nullable`.
1536
- *
1537
- * @example
1129
+ * @example Collect every operationId
1538
1130
  * ```ts
1539
- * const param = createParameter({
1540
- * name: 'petId',
1541
- * in: 'path',
1542
- * required: true,
1543
- * schema: createSchema({ type: 'string' }),
1544
- * })
1131
+ * const ids: string[] = []
1132
+ * for (const id of collectLazy<string>(root, {
1133
+ * operation(node) {
1134
+ * return node.operationId
1135
+ * },
1136
+ * })) {
1137
+ * ids.push(id)
1138
+ * }
1545
1139
  * ```
1140
+ */
1141
+ function* collectLazy(node, options) {
1142
+ const { depth, parent, ...visitor } = options;
1143
+ yield* collectNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1144
+ }
1145
+ function* collectNode(node, visitor, recurse, parent) {
1146
+ const v = applyVisitor(node, visitor, parent);
1147
+ if (v != null) yield v;
1148
+ for (const child of getChildren(node, recurse)) yield* collectNode(child, visitor, recurse, node);
1149
+ }
1150
+ /**
1151
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
1152
+ * callbacks return into an array.
1546
1153
  *
1547
- * @example
1154
+ * @example Collect every operationId
1548
1155
  * ```ts
1549
- * const param = createParameter({
1550
- * name: 'status',
1551
- * in: 'query',
1552
- * schema: createSchema({ type: 'string', nullable: true }),
1156
+ * const ids = collect<string>(root, {
1157
+ * operation(node) {
1158
+ * return node.operationId
1159
+ * },
1553
1160
  * })
1554
- * // required=false, schema.nullish=true
1555
1161
  * ```
1556
1162
  */
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
- };
1163
+ function collect(node, options) {
1164
+ return Array.from(collectLazy(node, options));
1565
1165
  }
1166
+ //#endregion
1167
+ //#region src/defineMacro.ts
1566
1168
  /**
1567
- * Creates a `ResponseNode`.
1169
+ * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
1170
+ * list keeps its authored order.
1171
+ */
1172
+ function enforceWeight(enforce) {
1173
+ if (enforce === "pre") return 0;
1174
+ if (enforce === "post") return 2;
1175
+ return 1;
1176
+ }
1177
+ /**
1178
+ * Types a macro for inference and a single construction site, mirroring `definePlugin`.
1179
+ * Adds no runtime behavior.
1568
1180
  *
1569
1181
  * @example
1570
1182
  * ```ts
1571
- * const response = createResponse({
1572
- * statusCode: '200',
1573
- * description: 'Success',
1574
- * schema: createSchema({ type: 'object', properties: [] }),
1183
+ * const macroUntagged = defineMacro({
1184
+ * name: 'untagged',
1185
+ * operation(node) {
1186
+ * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
1187
+ * },
1575
1188
  * })
1576
1189
  * ```
1577
1190
  */
1578
- function createResponse(props) {
1579
- return {
1580
- ...props,
1581
- kind: "Response"
1582
- };
1191
+ function defineMacro(macro) {
1192
+ return macro;
1583
1193
  }
1584
1194
  /**
1585
- * Creates a `FunctionParameterNode`.
1586
- *
1587
- * `optional` defaults to `false`.
1195
+ * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
1196
+ * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
1197
+ * original reference (structural sharing).
1198
+ */
1199
+ function chain({ macros, key, node, context }) {
1200
+ let current = node;
1201
+ for (const macro of macros) {
1202
+ const callback = macro[key];
1203
+ if (!callback) continue;
1204
+ if (macro.when && !macro.when(current)) continue;
1205
+ const next = callback(current, context);
1206
+ if (next != null) current = next;
1207
+ }
1208
+ return current === node ? void 0 : current;
1209
+ }
1210
+ /**
1211
+ * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
1212
+ * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
1213
+ * sequentially per node so later macros see earlier output. This differs from a plain visitor, which
1214
+ * has no names, ordering, or composition.
1588
1215
  *
1589
- * @example Required typed param
1216
+ * @example
1590
1217
  * ```ts
1591
- * createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }) })
1592
- * // petId: string
1218
+ * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
1219
+ * const next = transform(root, visitor)
1593
1220
  * ```
1221
+ */
1222
+ function composeMacros(macros) {
1223
+ const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce));
1224
+ const visitor = {};
1225
+ for (const key of visitorKeys) {
1226
+ if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
1227
+ const callback = (node, context) => chain({
1228
+ macros: ordered,
1229
+ key,
1230
+ node,
1231
+ context
1232
+ });
1233
+ visitor[key] = callback;
1234
+ }
1235
+ return visitor;
1236
+ }
1237
+ /**
1238
+ * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
1239
+ * structural sharing, so an empty or no-op macro list returns the same reference. Pass
1240
+ * `depth: 'shallow'` to rewrite the root node only.
1594
1241
  *
1595
- * @example Optional param
1242
+ * @example
1596
1243
  * ```ts
1597
- * createFunctionParameter({ name: 'params', type: createParamsType({ variant: 'reference', name: 'QueryParams' }), optional: true })
1598
- * // → params?: QueryParams
1244
+ * const next = applyMacros(root, [macroIntegerToString])
1599
1245
  * ```
1600
1246
  *
1601
- * @example Param with default (implicitly optional; cannot combine with `optional: true`)
1247
+ * @example Apply to the root node only
1602
1248
  * ```ts
1603
- * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), default: '{}' })
1604
- * // → config: RequestConfig = {}
1249
+ * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
1605
1250
  * ```
1606
1251
  */
1607
- function createFunctionParameter(props) {
1608
- return {
1609
- optional: false,
1610
- ...props,
1611
- kind: "FunctionParameter"
1612
- };
1252
+ function applyMacros(root, macros, options) {
1253
+ if (macros.length === 0) return root;
1254
+ return transform(root, {
1255
+ ...composeMacros(macros),
1256
+ ...options
1257
+ });
1613
1258
  }
1259
+ //#endregion
1260
+ //#region src/createPrinter.ts
1614
1261
  /**
1615
- * Creates a {@link TypeNode} representing a language-agnostic structured type expression.
1262
+ * Creates a schema printer: a function that takes a `SchemaNode` and emits
1263
+ * code in your target language. Each plugin that produces code from schemas
1264
+ * (TypeScript types, Zod schemas, Faker factories) ships a printer built
1265
+ * with this helper.
1616
1266
  *
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, …).
1267
+ * The builder receives resolved options and returns:
1620
1268
  *
1621
- * @example Reference type (TypeScript: `QueryParams`)
1622
- * ```ts
1623
- * createParamsType({ variant: 'reference', name: 'QueryParams' })
1624
- * ```
1269
+ * - `name` unique identifier for the printer.
1270
+ * - `options` stored on the returned printer instance.
1271
+ * - `nodes` map of `SchemaType` → handler. Handlers return the rendered
1272
+ * output (a string, a TypeScript AST node, ...) for that schema type.
1273
+ * - `overrides` (optional), user-supplied handlers that win over `nodes`.
1274
+ * An override can call `this.base(node)` to reuse the handler it replaced.
1275
+ * - `print` (optional), top-level override exposed as `printer.print`.
1276
+ * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
1625
1277
  *
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
- * ```
1278
+ * Without a `print` override, `printer.print` falls back to `printer.transform`
1279
+ * (the node-level dispatcher).
1630
1280
  *
1631
- * @example Member type (TypeScript: `DeletePetPathParams['petId']`)
1281
+ * @example Tiny Zod printer
1632
1282
  * ```ts
1633
- * createParamsType({ variant: 'member', base: 'DeletePetPathParams', key: 'petId' })
1634
- * ```
1635
- */
1636
- function createParamsType(props) {
1637
- return {
1638
- ...props,
1639
- kind: "ParamsType"
1640
- };
1641
- }
1642
- /**
1643
- * Creates a `ParameterGroupNode` representing a group of related parameters treated as a unit.
1283
+ * import { createPrinter, type PrinterFactoryOptions } from '@kubb/ast'
1644
1284
  *
1645
- * @example Grouped param (TypeScript declaration)
1646
- * ```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 }
1656
- * ```
1285
+ * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
1657
1286
  *
1658
- * @example Inline (spread) children emitted as individual top-level parameters
1659
- * ```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
1287
+ * export const zodPrinter = createPrinter<PrinterZod>((options) => ({
1288
+ * name: 'zod',
1289
+ * options: { strict: options.strict ?? true },
1290
+ * nodes: {
1291
+ * string: () => 'z.string()',
1292
+ * object(node) {
1293
+ * const props = node.properties
1294
+ * .map((p) => `${p.name}: ${this.transform(p.schema)}`)
1295
+ * .join(', ')
1296
+ * return `z.object({ ${props} })`
1297
+ * },
1298
+ * },
1299
+ * }))
1666
1300
  * ```
1667
1301
  */
1668
- function createParameterGroup(props) {
1669
- return {
1670
- ...props,
1671
- kind: "ParameterGroup"
1302
+ function createPrinter(build) {
1303
+ return (options) => {
1304
+ const { name, options: resolvedOptions, nodes, overrides, print: printOverride } = build(options ?? {});
1305
+ const merged = overrides ? {
1306
+ ...nodes,
1307
+ ...overrides
1308
+ } : nodes;
1309
+ const context = {
1310
+ options: resolvedOptions,
1311
+ transform: (node) => {
1312
+ const handler = merged[node.type];
1313
+ if (!handler) return null;
1314
+ return handler.call(context, node);
1315
+ },
1316
+ base: (node) => {
1317
+ const handler = nodes[node.type];
1318
+ if (!handler) return null;
1319
+ return handler.call(context, node);
1320
+ }
1321
+ };
1322
+ return {
1323
+ name,
1324
+ options: resolvedOptions,
1325
+ transform: context.transform,
1326
+ print: printOverride ? printOverride.bind(context) : context.transform
1327
+ };
1672
1328
  };
1673
1329
  }
1330
+ //#endregion
1331
+ //#region src/utils/mergeAdjacentSchemas.ts
1674
1332
  /**
1675
- * Creates a `FunctionParametersNode` from an ordered list of parameters.
1333
+ * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
1334
+ * run and pass through unchanged. The merge follows member order, so callers control which members
1335
+ * combine by where they place them in the sequence.
1676
1336
  *
1677
1337
  * @example
1678
1338
  * ```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
- * })
1339
+ * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
1685
1340
  * ```
1341
+ */
1342
+ function* mergeAdjacentObjectsLazy(members) {
1343
+ let acc;
1344
+ for (const member of members) {
1345
+ const objectMember = narrowSchema(member, "object");
1346
+ if (objectMember && !objectMember.name && acc !== void 0) {
1347
+ const accObject = narrowSchema(acc, "object");
1348
+ if (accObject && !accObject.name) {
1349
+ acc = createSchema({
1350
+ ...accObject,
1351
+ properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
1352
+ });
1353
+ continue;
1354
+ }
1355
+ }
1356
+ if (acc !== void 0) yield acc;
1357
+ acc = member;
1358
+ }
1359
+ if (acc !== void 0) yield acc;
1360
+ }
1361
+ //#endregion
1362
+ //#region src/utils/refs.ts
1363
+ const plainStringTypes = /* @__PURE__ */ new Set([
1364
+ "string",
1365
+ "uuid",
1366
+ "email",
1367
+ "url",
1368
+ "datetime"
1369
+ ]);
1370
+ /**
1371
+ * Returns the last path segment of a reference string.
1686
1372
  *
1687
1373
  * @example
1688
- * ```ts
1689
- * const empty = createFunctionParameters()
1690
- * // { kind: 'FunctionParameters', params: [] }
1691
- * ```
1374
+ * `extractRefName('#/components/schemas/Pet') // 'Pet'`
1692
1375
  */
1693
- function createFunctionParameters(props = {}) {
1694
- return {
1695
- params: [],
1696
- ...props,
1697
- kind: "FunctionParameters"
1698
- };
1376
+ function extractRefName(ref) {
1377
+ return ref.split("/").at(-1) ?? ref;
1699
1378
  }
1700
1379
  /**
1701
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1380
+ * Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls
1381
+ * back to `name` then nested `schema.name`.
1702
1382
  *
1703
- * @example Named import
1704
- * ```ts
1705
- * createImport({ name: ['useState'], path: 'react' })
1706
- * // import { useState } from 'react'
1707
- * ```
1383
+ * Returns `null` for non-ref nodes or when no name resolves.
1708
1384
  *
1709
- * @example Type-only import
1710
- * ```ts
1711
- * createImport({ name: ['FC'], path: 'react', isTypeOnly: true })
1712
- * // import type { FC } from 'react'
1713
- * ```
1385
+ * @example
1386
+ * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
1714
1387
  */
1715
- function createImport(props) {
1716
- return {
1717
- ...props,
1718
- kind: "Import"
1719
- };
1388
+ function resolveRefName(node) {
1389
+ if (!node || node.type !== "ref") return null;
1390
+ if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
1391
+ return node.name ?? node.schema?.name ?? null;
1720
1392
  }
1721
1393
  /**
1722
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1394
+ * Builds a PascalCase child schema name by joining a parent name and property name.
1395
+ * Returns `null` when there is no parent to nest under.
1723
1396
  *
1724
- * @example Named export
1725
- * ```ts
1726
- * createExport({ name: ['Pet'], path: './Pet' })
1727
- * // export { Pet } from './Pet'
1728
- * ```
1397
+ * @example Nested under a parent
1398
+ * `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
1729
1399
  *
1730
- * @example Wildcard export
1731
- * ```ts
1732
- * createExport({ path: './utils' })
1733
- * // export * from './utils'
1734
- * ```
1400
+ * @example No parent
1401
+ * `childName(undefined, 'params') // null`
1735
1402
  */
1736
- function createExport(props) {
1737
- return {
1738
- ...props,
1739
- kind: "Export"
1740
- };
1403
+ function childName(parentName, propName) {
1404
+ return parentName ? pascalCase([parentName, propName].join(" ")) : null;
1741
1405
  }
1742
1406
  /**
1743
- * Creates a `SourceNode` representing a fragment of source code within a file.
1407
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
1408
+ * empty parts.
1744
1409
  *
1745
1410
  * @example
1746
- * ```ts
1747
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1748
- * ```
1411
+ * `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
1749
1412
  */
1750
- function createSource(props) {
1751
- return {
1752
- ...props,
1753
- kind: "Source"
1754
- };
1413
+ function enumPropName(parentName, propName, enumSuffix) {
1414
+ return pascalCase([
1415
+ parentName,
1416
+ propName,
1417
+ enumSuffix
1418
+ ].filter(Boolean).join(" "));
1755
1419
  }
1756
1420
  /**
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)
1421
+ * Merges a ref node with its resolved schema, giving usage-site fields precedence.
1768
1422
  *
1769
- * @throws {Error} when `baseName` has no extension.
1423
+ * Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
1424
+ * same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
1425
+ * `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
1426
+ * nodes and refs without a resolved `schema` are returned unchanged.
1770
1427
  *
1771
1428
  * @example
1772
1429
  * ```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'
1430
+ * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
1431
+ * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
1783
1432
  * ```
1784
1433
  */
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
- };
1434
+ function syncSchemaRef(node) {
1435
+ const ref = narrowSchema(node, "ref");
1436
+ if (!ref) return node;
1437
+ if (!ref.schema) return node;
1438
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
1439
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
1440
+ return createSchema({
1441
+ ...ref.schema,
1442
+ ...definedOverrides
1443
+ });
1803
1444
  }
1804
1445
  /**
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`.
1809
- *
1810
- * @example Simple constant
1811
- * ```ts
1812
- * createConst({ name: 'pet' })
1813
- * // const pet = ...
1814
- * ```
1815
- *
1816
- * @example Exported constant with type and `as const`
1817
- * ```ts
1818
- * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
1819
- * // export const pets: Pet[] = ... as const
1820
- * ```
1446
+ * Type guard that returns `true` when a schema emits as a plain `string` type.
1821
1447
  *
1822
- * @example With JSDoc and child nodes
1823
- * ```ts
1824
- * createConst({
1825
- * name: 'config',
1826
- * export: true,
1827
- * JSDoc: { comments: ['@description App configuration'] },
1828
- * nodes: [],
1829
- * })
1830
- * ```
1448
+ * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
1449
+ * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
1831
1450
  */
1832
- function createConst(props) {
1833
- return {
1834
- ...props,
1835
- kind: "Const"
1836
- };
1451
+ function isStringType(node) {
1452
+ if (plainStringTypes.has(node.type)) return true;
1453
+ const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
1454
+ if (temporal) return temporal.representation !== "date";
1455
+ return false;
1837
1456
  }
1457
+ //#endregion
1458
+ //#region src/utils/schemaGraph.ts
1838
1459
  /**
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`.
1843
- *
1844
- * @example Simple type alias
1845
- * ```ts
1846
- * createType({ name: 'Pet' })
1847
- * // type Pet = ...
1848
- * ```
1849
- *
1850
- * @example Exported type with JSDoc
1851
- * ```ts
1852
- * createType({
1853
- * name: 'PetStatus',
1854
- * export: true,
1855
- * JSDoc: { comments: ['@description Status of a pet'] },
1856
- * })
1857
- * // export type PetStatus = ...
1858
- * ```
1460
+ * Memoized inner pass that walks a single node and returns the names of every schema it references.
1859
1461
  */
1860
- function createType(props) {
1861
- return {
1862
- ...props,
1863
- kind: "Type"
1864
- };
1865
- }
1462
+ const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
1463
+ const refs = /* @__PURE__ */ new Set();
1464
+ collect(node, { schema(child) {
1465
+ if (child.type === "ref") {
1466
+ const name = resolveRefName(child);
1467
+ if (name) refs.add(name);
1468
+ }
1469
+ } });
1470
+ return refs;
1471
+ });
1866
1472
  /**
1867
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
1868
- *
1869
- * Mirrors the `Function` component from `@kubb/renderer-jsx`.
1870
- * The component's `children` are represented as `nodes`.
1473
+ * Collects the names of every ref found anywhere inside a node's own subtree.
1871
1474
  *
1872
- * @example Simple function
1873
- * ```ts
1874
- * createFunction({ name: 'getPet' })
1875
- * // function getPet() { ... }
1876
- * ```
1475
+ * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
1476
+ * to accumulate names from several nodes into one set.
1877
1477
  *
1878
- * @example Exported async function with return type
1478
+ * @example Collect refs from a single schema
1879
1479
  * ```ts
1880
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
1881
- * // export async function fetchPet(): Promise<Pet> { ... }
1480
+ * const names = collectReferencedSchemaNames(petSchema)
1481
+ * // Set { 'Category', 'Tag' }
1882
1482
  * ```
1883
1483
  *
1884
- * @example Function with generics and params
1484
+ * @example Accumulate refs from multiple schemas into one set
1885
1485
  * ```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 { ... }
1486
+ * const out = new Set<string>()
1487
+ * for (const schema of schemas) {
1488
+ * collectReferencedSchemaNames(schema, out)
1489
+ * }
1894
1490
  * ```
1895
1491
  */
1896
- function createFunction(props) {
1897
- return {
1898
- ...props,
1899
- kind: "Function"
1900
- };
1492
+ function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
1493
+ if (!node) return out;
1494
+ for (const name of collectSchemaRefs(node)) out.add(name);
1495
+ return out;
1901
1496
  }
1902
1497
  /**
1903
- * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
1904
- *
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
1909
- * ```ts
1910
- * createArrowFunction({ name: 'getPet' })
1911
- * // const getPet = () => { ... }
1912
- * ```
1913
- *
1914
- * @example Single-line exported arrow function
1915
- * ```ts
1916
- * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
1917
- * // export const double = (n: number) => ...
1918
- * ```
1919
- *
1920
- * @example Async arrow function with generics
1921
- * ```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> => { ... }
1931
- * ```
1498
+ * Memoized two-level cache keyed first on the operations array, then on the schemas array.
1932
1499
  */
1933
- function createArrowFunction(props) {
1934
- return {
1935
- ...props,
1936
- kind: "ArrowFunction"
1937
- };
1500
+ const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
1501
+ function computeUsedSchemaNames(operations, schemas) {
1502
+ const schemaMap = /* @__PURE__ */ new Map();
1503
+ for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
1504
+ const result = /* @__PURE__ */ new Set();
1505
+ function visitSchema(schema) {
1506
+ const directRefs = collectReferencedSchemaNames(schema);
1507
+ for (const name of directRefs) if (!result.has(name)) {
1508
+ result.add(name);
1509
+ const namedSchema = schemaMap.get(name);
1510
+ if (namedSchema) visitSchema(namedSchema);
1511
+ }
1512
+ }
1513
+ for (const op of operations) for (const schema of collectLazy(op, {
1514
+ depth: "shallow",
1515
+ schema: (node) => node
1516
+ })) visitSchema(schema);
1517
+ return result;
1938
1518
  }
1939
1519
  /**
1940
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
1520
+ * Collects the names of all top-level schemas transitively used by a set of operations.
1941
1521
  *
1942
- * Use this instead of bare strings when building `nodes` arrays so that every
1943
- * entry in the array is a typed {@link CodeNode}.
1522
+ * An operation uses a schema when its parameters, request body, or responses reference it, directly
1523
+ * or through other named schemas. Once a name is added to the result it is not revisited, so
1524
+ * reference cycles terminate.
1944
1525
  *
1945
- * @example
1526
+ * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
1527
+ *
1528
+ * @example Only generate schemas referenced by included operations
1946
1529
  * ```ts
1947
- * createText('return fetch(id)')
1948
- * // { kind: 'Text', value: 'return fetch(id)' }
1530
+ * const includedOps = operations.filter((op) => resolver.default.options(op, { options, include }) !== null)
1531
+ * const allowed = collectUsedSchemaNames(includedOps, schemas)
1532
+ *
1533
+ * for (const schema of schemas) {
1534
+ * if (schema.name && !allowed.has(schema.name)) continue
1535
+ * // generate schema
1536
+ * }
1949
1537
  * ```
1950
1538
  */
1951
- function createText(value) {
1952
- return {
1953
- value,
1954
- kind: "Text"
1955
- };
1539
+ function collectUsedSchemaNames(operations, schemas) {
1540
+ return collectUsedSchemaNamesMemo(operations)(schemas);
1956
1541
  }
1542
+ const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
1543
+ const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
1544
+ const graph = /* @__PURE__ */ new Map();
1545
+ for (const schema of schemas) {
1546
+ if (!schema.name) continue;
1547
+ graph.set(schema.name, collectReferencedSchemaNames(schema));
1548
+ }
1549
+ const circular = /* @__PURE__ */ new Set();
1550
+ for (const start of graph.keys()) {
1551
+ const visited = /* @__PURE__ */ new Set();
1552
+ const stack = [...graph.get(start) ?? []];
1553
+ while (stack.length > 0) {
1554
+ const node = stack.pop();
1555
+ if (node === start) {
1556
+ circular.add(start);
1557
+ break;
1558
+ }
1559
+ if (visited.has(node)) continue;
1560
+ visited.add(node);
1561
+ const next = graph.get(node);
1562
+ if (next) for (const r of next) stack.push(r);
1563
+ }
1564
+ }
1565
+ return circular;
1566
+ });
1957
1567
  /**
1958
- * Creates a {@link BreakNode} representing a line break in the source output.
1568
+ * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
1959
1569
  *
1960
- * Corresponds to `<br/>` in JSX components. Prints as an empty string which,
1961
- * when joined with `\n` by `printNodes`, produces a blank line.
1570
+ * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
1571
+ * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
1572
+ * linear in the size of the schema graph.
1962
1573
  *
1963
- * @example
1964
- * ```ts
1965
- * createBreak()
1966
- * // { kind: 'Break' }
1967
- * ```
1574
+ * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
1968
1575
  */
1969
- function createBreak() {
1970
- return { kind: "Break" };
1576
+ function findCircularSchemas(schemas) {
1577
+ if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
1578
+ return findCircularSchemasMemo(schemas);
1971
1579
  }
1972
1580
  /**
1973
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
1581
+ * Returns `true` when a schema, or anything nested inside it, references a circular schema.
1974
1582
  *
1975
- * Use this to embed JSX markup (including fragments `<>…</>`) directly in generated code.
1583
+ * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
1584
+ * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
1976
1585
  *
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
- * ```
1586
+ * @note Stops at the first matching circular ref.
1982
1587
  */
1983
- function createJsx(value) {
1984
- return {
1985
- value,
1986
- kind: "Jsx"
1987
- };
1588
+ function containsCircularRef(node, { circularSchemas, excludeName }) {
1589
+ if (!node || circularSchemas.size === 0) return false;
1590
+ for (const _ of collectLazy(node, { schema(child) {
1591
+ if (child.type !== "ref") return null;
1592
+ const name = resolveRefName(child);
1593
+ return name && name !== excludeName && circularSchemas.has(name) ? true : null;
1594
+ } })) return true;
1595
+ return false;
1988
1596
  }
1989
1597
  //#endregion
1990
- //#region src/printer.ts
1598
+ //#region src/utils/schemaTraversal.ts
1991
1599
  /**
1992
- * Creates a schema printer factory.
1993
- *
1994
- * This function wraps a builder and makes options optional at call sites.
1995
- *
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
1600
+ * Maps each property of an object schema to its transformed output. Pairs every result with the
1601
+ * original property so the printer keeps full control over modifiers, getters, and key syntax.
2003
1602
  *
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
1603
+ * @example
2007
1604
  * ```ts
2008
- * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
2009
- *
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
- * }))
1605
+ * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
1606
+ * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
2021
1607
  * ```
2022
1608
  */
2023
- function definePrinter(build) {
2024
- return createPrinterFactory((node) => node.type)(build);
1609
+ function mapSchemaProperties(node, transform) {
1610
+ return node.properties.map((property) => ({
1611
+ name: property.name,
1612
+ property,
1613
+ output: transform(property.schema)
1614
+ }));
2025
1615
  }
2026
1616
  /**
2027
- * Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
2028
- **
2029
- * @example
2030
- * ```ts
2031
- * export const defineFunctionPrinter = createPrinterFactory<FunctionNode, FunctionNodeType, FunctionNodeByType>(
2032
- * (node) => kindToHandlerKey[node.kind],
2033
- * )
2034
- * ```
1617
+ * Maps each member of a union or intersection schema to its transformed output, pairing every
1618
+ * result with the original member.
2035
1619
  */
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;
2067
- }
2068
- function enumPropName(parentName, propName, enumSuffix) {
2069
- return pascalCase([
2070
- parentName,
2071
- propName,
2072
- enumSuffix
2073
- ].filter(Boolean).join(" "));
1620
+ function mapSchemaMembers(node, transform) {
1621
+ return (node.members ?? []).map((schema) => ({
1622
+ schema,
1623
+ output: transform(schema)
1624
+ }));
2074
1625
  }
2075
1626
  /**
2076
- * Collects import entries for all `ref` schema nodes in `node`.
1627
+ * Maps each item of an array or tuple schema to its transformed output, pairing every result with
1628
+ * the original item.
2077
1629
  */
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
- } });
1630
+ function mapSchemaItems(node, transform) {
1631
+ return (node.items ?? []).map((schema) => ({
1632
+ schema,
1633
+ output: transform(schema)
1634
+ }));
2087
1635
  }
2088
1636
  //#endregion
2089
- //#region src/transformers.ts
1637
+ //#region src/macros/macroDiscriminatorEnum.ts
2090
1638
  /**
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.
1639
+ * Builds a macro that replaces a discriminator property's schema with a string enum of the given
1640
+ * values. Object schemas that lack the property are returned unchanged.
2095
1641
  *
2096
1642
  * @example
2097
1643
  * ```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'] })
2103
- * ```
2104
- */
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
1644
+ * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
1645
+ * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
1646
+ * ```
1647
+ */
1648
+ function macroDiscriminatorEnum({ propertyName, values, enumName }) {
1649
+ return defineMacro({
1650
+ name: "discriminator-enum",
1651
+ schema(node) {
1652
+ const objectNode = narrowSchema(node, "object");
1653
+ if (!objectNode?.properties?.length) return void 0;
1654
+ if (!objectNode.properties.some((prop) => prop.name === propertyName)) return void 0;
1655
+ return createSchema({
1656
+ ...objectNode,
1657
+ properties: objectNode.properties.map((prop) => {
1658
+ if (prop.name !== propertyName) return prop;
1659
+ return createProperty({
1660
+ ...prop,
1661
+ schema: createSchema({
1662
+ type: "enum",
1663
+ primitive: "string",
1664
+ enumValues: values,
1665
+ name: enumName,
1666
+ readOnly: prop.schema.readOnly,
1667
+ writeOnly: prop.schema.writeOnly
1668
+ })
1669
+ });
2122
1670
  })
2123
1671
  });
2124
- })
1672
+ }
2125
1673
  });
2126
1674
  }
1675
+ //#endregion
1676
+ //#region src/macros/macroEnumName.ts
2127
1677
  /**
2128
- * Merges adjacent anonymous object members into a single anonymous object member.
1678
+ * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
1679
+ * are left anonymous. Non-enum nodes are returned unchanged.
2129
1680
  *
2130
1681
  * @example
2131
1682
  * ```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
- * ])
1683
+ * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
1684
+ * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
2136
1685
  * ```
2137
1686
  */
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
- }
1687
+ function macroEnumName({ parentName, propName, enumSuffix }) {
1688
+ return defineMacro({
1689
+ name: "enum-name",
1690
+ schema(node) {
1691
+ const enumNode = narrowSchema(node, "enum");
1692
+ if (enumNode?.primitive === "boolean") return {
1693
+ ...node,
1694
+ name: null
1695
+ };
1696
+ if (enumNode) return {
1697
+ ...node,
1698
+ name: enumPropName(parentName, propName, enumSuffix)
1699
+ };
2151
1700
  }
2152
- acc.push(member);
2153
- return acc;
2154
- }, []);
1701
+ });
2155
1702
  }
1703
+ //#endregion
1704
+ //#region src/macros/macroSimplifyUnion.ts
2156
1705
  /**
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
- * ```
1706
+ * Scalar primitive schema types used for union simplification and type narrowing.
1707
+ */
1708
+ const SCALAR_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
1709
+ "string",
1710
+ "number",
1711
+ "integer",
1712
+ "bigint",
1713
+ "boolean"
1714
+ ]);
1715
+ function isScalarPrimitive(type) {
1716
+ return SCALAR_PRIMITIVE_TYPES.has(type);
1717
+ }
1718
+ /**
1719
+ * Filters union members, dropping enum members that a broader scalar primitive already covers.
2167
1720
  */
2168
- function simplifyUnion(members) {
1721
+ function simplifyUnionMembers(members) {
2169
1722
  const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
2170
1723
  if (!scalarPrimitives.size) return members;
2171
1724
  return members.filter((member) => {
@@ -2179,19 +1732,133 @@ function simplifyUnion(members) {
2179
1732
  return true;
2180
1733
  });
2181
1734
  }
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)
1735
+ /**
1736
+ * Removes union members a broader scalar primitive already covers, such as a multi-value string enum
1737
+ * sitting next to a plain `string`. Single-value enums are kept.
1738
+ *
1739
+ * @example
1740
+ * ```ts
1741
+ * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
1742
+ * ```
1743
+ */
1744
+ const macroSimplifyUnion = defineMacro({
1745
+ name: "simplify-union",
1746
+ schema(node) {
1747
+ const unionNode = narrowSchema(node, "union");
1748
+ if (!unionNode?.members?.length) return void 0;
1749
+ const simplified = simplifyUnionMembers(unionNode.members);
1750
+ if (simplified.length === unionNode.members.length) return void 0;
1751
+ return {
1752
+ ...unionNode,
1753
+ members: simplified
1754
+ };
1755
+ }
1756
+ });
1757
+ //#endregion
1758
+ //#region src/factory.ts
1759
+ var factory_exports = /* @__PURE__ */ __exportAll({
1760
+ createArrowFunction: () => createArrowFunction,
1761
+ createBreak: () => createBreak,
1762
+ createConst: () => createConst,
1763
+ createContent: () => createContent,
1764
+ createExport: () => createExport,
1765
+ createFile: () => createFile,
1766
+ createFunction: () => createFunction,
1767
+ createImport: () => createImport,
1768
+ createInput: () => createInput,
1769
+ createJsx: () => createJsx,
1770
+ createOperation: () => createOperation,
1771
+ createOutput: () => createOutput,
1772
+ createParameter: () => createParameter,
1773
+ createProperty: () => createProperty,
1774
+ createRequestBody: () => createRequestBody,
1775
+ createResponse: () => createResponse,
1776
+ createSchema: () => createSchema,
1777
+ createSource: () => createSource,
1778
+ createText: () => createText,
1779
+ createType: () => createType,
1780
+ update: () => update
1781
+ });
1782
+ /**
1783
+ * Identity-preserving node update: returns `node` unchanged when every field in
1784
+ * `changes` already equals (by reference) the current value, otherwise a new node
1785
+ * with the changes applied.
1786
+ *
1787
+ * Mirrors the TypeScript compiler's `factory.updateX` contract. Pair it with the
1788
+ * structural sharing in {@link transform} so a no-op rewrite does not allocate and
1789
+ * downstream passes can detect "nothing changed" by identity. Comparison is shallow,
1790
+ * so a structurally equal but newly allocated array or object counts as a change.
1791
+ *
1792
+ * @example
1793
+ * ```ts
1794
+ * update(node, { name: node.name }) // -> same `node` reference
1795
+ * update(node, { name: 'renamed' }) // -> new node, `name` replaced
1796
+ * ```
1797
+ */
1798
+ function update(node, changes) {
1799
+ for (const key in changes) if (changes[key] !== node[key]) return {
1800
+ ...node,
1801
+ ...changes
2191
1802
  };
2192
- return propNode;
1803
+ return node;
2193
1804
  }
2194
1805
  //#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 };
1806
+ //#region src/exports.ts
1807
+ var exports_exports = /* @__PURE__ */ __exportAll({
1808
+ applyMacros: () => applyMacros,
1809
+ arrowFunctionDef: () => arrowFunctionDef,
1810
+ breakDef: () => breakDef,
1811
+ childName: () => childName,
1812
+ collect: () => collect,
1813
+ collectUsedSchemaNames: () => collectUsedSchemaNames,
1814
+ combineExports: () => combineExports,
1815
+ combineImports: () => combineImports,
1816
+ combineSources: () => combineSources,
1817
+ composeMacros: () => composeMacros,
1818
+ constDef: () => constDef,
1819
+ containsCircularRef: () => containsCircularRef,
1820
+ contentDef: () => contentDef,
1821
+ createPrinter: () => createPrinter,
1822
+ defineMacro: () => defineMacro,
1823
+ defineNode: () => defineNode,
1824
+ enumPropName: () => enumPropName,
1825
+ exportDef: () => exportDef,
1826
+ extractRefName: () => extractRefName,
1827
+ extractStringsFromNodes: () => extractStringsFromNodes,
1828
+ factory: () => factory_exports,
1829
+ fileDef: () => fileDef,
1830
+ findCircularSchemas: () => findCircularSchemas,
1831
+ functionDef: () => functionDef,
1832
+ importDef: () => importDef,
1833
+ inputDef: () => inputDef,
1834
+ isHttpOperationNode: () => isHttpOperationNode,
1835
+ isStringType: () => isStringType,
1836
+ jsxDef: () => jsxDef,
1837
+ macroDiscriminatorEnum: () => macroDiscriminatorEnum,
1838
+ macroEnumName: () => macroEnumName,
1839
+ macroSimplifyUnion: () => macroSimplifyUnion,
1840
+ mapSchemaItems: () => mapSchemaItems,
1841
+ mapSchemaMembers: () => mapSchemaMembers,
1842
+ mapSchemaProperties: () => mapSchemaProperties,
1843
+ mergeAdjacentObjectsLazy: () => mergeAdjacentObjectsLazy,
1844
+ narrowSchema: () => narrowSchema,
1845
+ nodeDefs: () => nodeDefs,
1846
+ operationDef: () => operationDef,
1847
+ optionality: () => optionality,
1848
+ outputDef: () => outputDef,
1849
+ parameterDef: () => parameterDef,
1850
+ propertyDef: () => propertyDef,
1851
+ requestBodyDef: () => requestBodyDef,
1852
+ responseDef: () => responseDef,
1853
+ schemaDef: () => schemaDef,
1854
+ schemaTypes: () => schemaTypes,
1855
+ sourceDef: () => sourceDef,
1856
+ syncSchemaRef: () => syncSchemaRef,
1857
+ textDef: () => textDef,
1858
+ transform: () => transform,
1859
+ typeDef: () => typeDef
1860
+ });
1861
+ //#endregion
1862
+ export { applyMacros, arrowFunctionDef, exports_exports as ast, breakDef, childName, collect, collectUsedSchemaNames, combineExports, combineImports, combineSources, composeMacros, constDef, containsCircularRef, contentDef, createPrinter, defineMacro, defineNode, enumPropName, exportDef, extractRefName, extractStringsFromNodes, factory_exports as factory, fileDef, findCircularSchemas, functionDef, importDef, inputDef, isHttpOperationNode, isStringType, jsxDef, macroDiscriminatorEnum, macroEnumName, macroSimplifyUnion, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, narrowSchema, nodeDefs, operationDef, optionality, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, sourceDef, syncSchemaRef, textDef, transform, typeDef };
2196
1863
 
2197
1864
  //# sourceMappingURL=index.js.map