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

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