@kubb/ast 5.0.0-beta.75 → 5.0.0-beta.77

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