@kubb/ast 5.0.0-beta.6 → 5.0.0-beta.60

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 (78) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +50 -27
  3. package/dist/chunk-CNktS9qV.js +17 -0
  4. package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
  5. package/dist/factory-Cl8Z7mcc.cjs +299 -0
  6. package/dist/factory-Cl8Z7mcc.cjs.map +1 -0
  7. package/dist/factory-Du7nEP4B.js +282 -0
  8. package/dist/factory-Du7nEP4B.js.map +1 -0
  9. package/dist/factory.cjs +29 -0
  10. package/dist/factory.d.ts +62 -0
  11. package/dist/factory.js +3 -0
  12. package/dist/index-BzjwdK2M.d.ts +2433 -0
  13. package/dist/index.cjs +442 -2180
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.ts +93 -3408
  16. package/dist/index.js +392 -2101
  17. package/dist/index.js.map +1 -1
  18. package/dist/operationParams-BZ07xDm0.d.ts +204 -0
  19. package/dist/response-DKxTr522.js +683 -0
  20. package/dist/response-DKxTr522.js.map +1 -0
  21. package/dist/response-DS5S3IG4.cjs +1058 -0
  22. package/dist/response-DS5S3IG4.cjs.map +1 -0
  23. package/dist/types-olVl9v5p.d.ts +764 -0
  24. package/dist/types.cjs +0 -0
  25. package/dist/types.d.ts +5 -0
  26. package/dist/types.js +1 -0
  27. package/dist/utils-D83JA6Xx.cjs +1645 -0
  28. package/dist/utils-D83JA6Xx.cjs.map +1 -0
  29. package/dist/utils-Dj_KoXMv.js +1389 -0
  30. package/dist/utils-Dj_KoXMv.js.map +1 -0
  31. package/dist/utils.cjs +34 -0
  32. package/dist/utils.d.ts +332 -0
  33. package/dist/utils.js +3 -0
  34. package/package.json +17 -6
  35. package/src/constants.ts +19 -64
  36. package/src/dedupe.ts +239 -0
  37. package/src/dialect.ts +53 -0
  38. package/src/factory.ts +67 -678
  39. package/src/guards.ts +10 -92
  40. package/src/index.ts +16 -43
  41. package/src/infer.ts +16 -14
  42. package/src/mocks.ts +7 -127
  43. package/src/node.ts +128 -0
  44. package/src/nodes/base.ts +5 -12
  45. package/src/nodes/code.ts +165 -74
  46. package/src/nodes/content.ts +56 -0
  47. package/src/nodes/file.ts +97 -36
  48. package/src/nodes/function.ts +216 -156
  49. package/src/nodes/http.ts +1 -35
  50. package/src/nodes/index.ts +23 -15
  51. package/src/nodes/input.ts +140 -0
  52. package/src/nodes/operation.ts +122 -68
  53. package/src/nodes/output.ts +23 -0
  54. package/src/nodes/parameter.ts +33 -3
  55. package/src/nodes/property.ts +36 -3
  56. package/src/nodes/requestBody.ts +61 -0
  57. package/src/nodes/response.ts +58 -13
  58. package/src/nodes/schema.ts +93 -17
  59. package/src/printer.ts +48 -42
  60. package/src/registry.ts +75 -0
  61. package/src/signature.ts +207 -0
  62. package/src/transformers.ts +50 -18
  63. package/src/types.ts +7 -68
  64. package/src/utils/codegen.ts +104 -0
  65. package/src/utils/extractStringsFromNodes.ts +34 -0
  66. package/src/utils/fileMerge.ts +184 -0
  67. package/src/utils/index.ts +11 -0
  68. package/src/utils/operationParams.ts +353 -0
  69. package/src/utils/refs.ts +112 -0
  70. package/src/utils/schemaGraph.ts +169 -0
  71. package/src/utils/schemaTraversal.ts +86 -0
  72. package/src/utils/strings.ts +139 -0
  73. package/src/visitor.ts +227 -289
  74. package/dist/chunk--u3MIqq1.js +0 -8
  75. package/src/nodes/root.ts +0 -64
  76. package/src/refs.ts +0 -67
  77. package/src/resolvers.ts +0 -45
  78. package/src/utils.ts +0 -915
package/dist/index.cjs CHANGED
@@ -1,2033 +1,434 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
- //#endregion
24
- let node_crypto = require("node:crypto");
25
- let node_path = require("node:path");
26
- node_path = __toESM(node_path, 1);
27
- //#region src/constants.ts
28
- const visitorDepths = {
29
- shallow: "shallow",
30
- deep: "deep"
31
- };
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
- /**
52
- * Schema type discriminators used by all AST schema nodes.
53
- *
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.
57
- */
58
- const schemaTypes = {
59
- /**
60
- * Text value.
61
- */
62
- string: "string",
63
- /**
64
- * Floating-point number (`float`, `double`).
65
- */
66
- number: "number",
67
- /**
68
- * Whole number (`int32`). Use `bigint` for `int64`.
69
- */
70
- integer: "integer",
71
- /**
72
- * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
73
- */
74
- bigint: "bigint",
75
- /**
76
- * Boolean value
77
- */
78
- boolean: "boolean",
79
- /**
80
- * Explicit null value.
81
- */
82
- null: "null",
83
- /**
84
- * Any value (no type restriction).
85
- */
86
- any: "any",
87
- /**
88
- * Unknown value (must be narrowed before usage).
89
- */
90
- unknown: "unknown",
91
- /**
92
- * No return value (`void`).
93
- */
94
- void: "void",
95
- /**
96
- * Object with named properties.
97
- */
98
- object: "object",
99
- /**
100
- * Sequential list of items.
101
- */
102
- array: "array",
103
- /**
104
- * Fixed-length list with position-specific items.
105
- */
106
- tuple: "tuple",
107
- /**
108
- * "One of" multiple schema members.
109
- */
110
- union: "union",
111
- /**
112
- * "All of" multiple schema members.
113
- */
114
- intersection: "intersection",
115
- /**
116
- * Enum schema.
117
- */
118
- enum: "enum",
119
- /**
120
- * Reference to another schema.
121
- */
122
- ref: "ref",
123
- /**
124
- * Calendar date (for example `2026-03-24`).
125
- */
126
- date: "date",
127
- /**
128
- * Date-time value (for example `2026-03-24T09:00:00Z`).
129
- */
130
- datetime: "datetime",
131
- /**
132
- * Time-only value (for example `09:00:00`).
133
- */
134
- time: "time",
135
- /**
136
- * UUID value.
137
- */
138
- uuid: "uuid",
139
- /**
140
- * Email address value.
141
- */
142
- email: "email",
143
- /**
144
- * URL value.
145
- */
146
- url: "url",
147
- /**
148
- * IPv4 address value.
149
- */
150
- ipv4: "ipv4",
151
- /**
152
- * IPv6 address value.
153
- */
154
- ipv6: "ipv6",
155
- /**
156
- * Binary/blob value.
157
- */
158
- blob: "blob",
159
- /**
160
- * Impossible value (`never`).
161
- */
162
- never: "never"
163
- };
164
- /**
165
- * Scalar primitive schema types used for union simplification and type narrowing.
166
- *
167
- * Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
168
- */
169
- const SCALAR_PRIMITIVE_TYPES = new Set([
170
- "string",
171
- "number",
172
- "integer",
173
- "bigint",
174
- "boolean"
175
- ]);
176
- /**
177
- * Type guard that returns `true` when `type` is a scalar primitive schema type.
178
- *
179
- * Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
180
- */
181
- function isScalarPrimitive(type) {
182
- return SCALAR_PRIMITIVE_TYPES.has(type);
183
- }
184
- /**
185
- * HTTP method identifiers used by operation nodes.
186
- *
187
- * Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
188
- */
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
- };
226
- //#endregion
227
- //#region ../../internals/utils/src/casing.ts
228
- /**
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.
234
- */
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
- }
242
- /**
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.
255
- */
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);
274
- }
275
- /**
276
- * Converts `text` to PascalCase.
277
- * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
278
- *
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.
381
- *
382
- * @example
383
- * ```ts
384
- * isValidVarName('status') // true
385
- * isValidVarName('class') // false (reserved word)
386
- * isValidVarName('42foo') // false (starts with digit)
387
- * ```
388
- */
389
- function isValidVarName(name) {
390
- if (!name || reservedWords.has(name)) return false;
391
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
392
- }
393
- //#endregion
394
- //#region ../../internals/utils/src/string.ts
395
- /**
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'
404
- */
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
412
- /**
413
- * Narrows a `SchemaNode` to the variant that matches `type`.
414
- *
415
- * @example
416
- * ```ts
417
- * const schema = createSchema({ type: 'string' })
418
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | undefined
419
- * ```
420
- */
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
- }
427
- /**
428
- * Returns `true` when the input is an `InputNode`.
429
- *
430
- * @example
431
- * ```ts
432
- * if (isInputNode(node)) {
433
- * console.log(node.schemas.length)
434
- * }
435
- * ```
436
- */
437
- const isInputNode = isKind("Input");
438
- /**
439
- * Returns `true` when the input is an `OutputNode`.
440
- *
441
- * @example
442
- * ```ts
443
- * if (isOutputNode(node)) {
444
- * console.log(node.files.length)
445
- * }
446
- * ```
447
- */
448
- const isOutputNode = isKind("Output");
449
- /**
450
- * Returns `true` when the input is an `OperationNode`.
451
- *
452
- * @example
453
- * ```ts
454
- * if (isOperationNode(node)) {
455
- * console.log(node.operationId)
456
- * }
457
- * ```
458
- */
459
- const isOperationNode = isKind("Operation");
460
- /**
461
- * Returns `true` when the input is a `SchemaNode`.
462
- *
463
- * @example
464
- * ```ts
465
- * if (isSchemaNode(node)) {
466
- * console.log(node.type)
467
- * }
468
- * ```
469
- */
470
- const isSchemaNode = isKind("Schema");
471
- //#endregion
472
- //#region src/refs.ts
473
- /**
474
- * Returns the last path segment of a reference string.
475
- *
476
- * Example: `#/components/schemas/Pet` becomes `Pet`.
477
- *
478
- * @example
479
- * ```ts
480
- * extractRefName('#/components/schemas/Pet') // 'Pet'
481
- * ```
482
- */
483
- function extractRefName(ref) {
484
- return ref.split("/").at(-1) ?? ref;
485
- }
486
- //#endregion
487
- //#region src/visitor.ts
488
- /**
489
- * Creates a small async concurrency limiter.
490
- *
491
- * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
492
- *
493
- * @example
494
- * ```ts
495
- * const limit = createLimit(2)
496
- * for (const task of [taskA, taskB, taskC]) {
497
- * await limit(() => task())
498
- * }
499
- * // only 2 tasks run at the same time
500
- * ```
501
- */
502
- function createLimit(concurrency) {
503
- let active = 0;
504
- const queue = [];
505
- function next() {
506
- if (active < concurrency && queue.length > 0) {
507
- active++;
508
- queue.shift()();
509
- }
510
- }
511
- return function limit(fn) {
512
- return new Promise((resolve, reject) => {
513
- queue.push(() => {
514
- Promise.resolve(fn()).then(resolve, reject).finally(() => {
515
- active--;
516
- next();
517
- });
518
- });
519
- next();
520
- });
521
- };
522
- }
523
- /**
524
- * Returns the immediate traversable children of `node`.
525
- *
526
- * For `Schema` nodes, children (`properties`, `items`, `members`, and non-boolean
527
- * `additionalProperties`) are only included
528
- * when `recurse` is `true`; shallow mode skips them.
529
- *
530
- * @example
531
- * ```ts
532
- * const children = getChildren(operationNode, true)
533
- * // returns parameters, requestBody schema (if present), and responses
534
- * ```
535
- */
536
- function getChildren(node, recurse) {
537
- switch (node.kind) {
538
- case "Input": return [...node.schemas, ...node.operations];
539
- case "Output": return [];
540
- case "Operation": return [
541
- ...node.parameters,
542
- ...node.requestBody?.content?.flatMap((c) => c.schema ? [c.schema] : []) ?? [],
543
- ...node.responses
544
- ];
545
- case "Schema": {
546
- const children = [];
547
- if (!recurse) return [];
548
- if ("properties" in node && node.properties.length > 0) children.push(...node.properties);
549
- if ("items" in node && node.items) children.push(...node.items);
550
- if ("members" in node && node.members) children.push(...node.members);
551
- if ("additionalProperties" in node && node.additionalProperties && node.additionalProperties !== true) children.push(node.additionalProperties);
552
- return children;
553
- }
554
- case "Property": return [node.schema];
555
- case "Parameter": return [node.schema];
556
- case "Response": return node.schema ? [node.schema] : [];
557
- case "FunctionParameter":
558
- case "ParameterGroup":
559
- case "FunctionParameters":
560
- case "Type": return [];
561
- default: return [];
562
- }
563
- }
564
- /**
565
- * Depth-first traversal for side effects. Visitor return values are ignored.
566
- * Sibling nodes at each level are visited concurrently up to `options.concurrency`
567
- * (default: `WALK_CONCURRENCY`).
568
- *
569
- * @example
570
- * ```ts
571
- * await walk(root, {
572
- * operation(node) {
573
- * console.log(node.operationId)
574
- * },
575
- * })
576
- * ```
577
- *
578
- * @example
579
- * ```ts
580
- * // Visit only the current node
581
- * await walk(root, { depth: 'shallow', root: () => {} })
582
- * ```
583
- */
584
- async function walk(node, options) {
585
- return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
586
- }
587
- async function _walk(node, visitor, recurse, limit, parent) {
588
- switch (node.kind) {
589
- case "Input":
590
- await limit(() => visitor.input?.(node, { parent }));
591
- break;
592
- case "Output":
593
- await limit(() => visitor.output?.(node, { parent }));
594
- break;
595
- case "Operation":
596
- await limit(() => visitor.operation?.(node, { parent }));
597
- break;
598
- case "Schema":
599
- await limit(() => visitor.schema?.(node, { parent }));
600
- break;
601
- case "Property":
602
- await limit(() => visitor.property?.(node, { parent }));
603
- break;
604
- case "Parameter":
605
- await limit(() => visitor.parameter?.(node, { parent }));
606
- break;
607
- case "Response":
608
- await limit(() => visitor.response?.(node, { parent }));
609
- break;
610
- case "FunctionParameter":
611
- case "ParameterGroup":
612
- case "FunctionParameters": break;
613
- }
614
- const children = getChildren(node, recurse);
615
- for (const child of children) await _walk(child, visitor, recurse, limit, node);
616
- }
617
- function transform(node, options) {
618
- const { depth, parent, ...visitor } = options;
619
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
620
- switch (node.kind) {
621
- case "Input": {
622
- let input = node;
623
- const replaced = visitor.input?.(input, { parent });
624
- if (replaced) input = replaced;
625
- return {
626
- ...input,
627
- schemas: input.schemas.map((s) => transform(s, {
628
- ...options,
629
- parent: input
630
- })),
631
- operations: input.operations.map((op) => transform(op, {
632
- ...options,
633
- parent: input
634
- }))
635
- };
636
- }
637
- case "Output": {
638
- let output = node;
639
- const replaced = visitor.output?.(output, { parent });
640
- if (replaced) output = replaced;
641
- return output;
642
- }
643
- case "Operation": {
644
- let op = node;
645
- const replaced = visitor.operation?.(op, { parent });
646
- if (replaced) op = replaced;
647
- return {
648
- ...op,
649
- parameters: op.parameters.map((p) => transform(p, {
650
- ...options,
651
- parent: op
652
- })),
653
- requestBody: op.requestBody ? {
654
- ...op.requestBody,
655
- content: op.requestBody.content?.map((c) => ({
656
- ...c,
657
- schema: c.schema ? transform(c.schema, {
658
- ...options,
659
- parent: op
660
- }) : void 0
661
- }))
662
- } : void 0,
663
- responses: op.responses.map((r) => transform(r, {
664
- ...options,
665
- parent: op
666
- }))
667
- };
668
- }
669
- case "Schema": {
670
- let schema = node;
671
- const replaced = visitor.schema?.(schema, { parent });
672
- if (replaced) schema = replaced;
673
- const childOptions = {
674
- ...options,
675
- parent: schema
676
- };
677
- return {
678
- ...schema,
679
- ..."properties" in schema && recurse ? { properties: schema.properties.map((p) => transform(p, childOptions)) } : {},
680
- ..."items" in schema && recurse ? { items: schema.items?.map((i) => transform(i, childOptions)) } : {},
681
- ..."members" in schema && recurse ? { members: schema.members?.map((m) => transform(m, childOptions)) } : {},
682
- ..."additionalProperties" in schema && recurse && schema.additionalProperties && schema.additionalProperties !== true ? { additionalProperties: transform(schema.additionalProperties, childOptions) } : {}
683
- };
684
- }
685
- case "Property": {
686
- let prop = node;
687
- const replaced = visitor.property?.(prop, { parent });
688
- if (replaced) prop = replaced;
689
- return createProperty({
690
- ...prop,
691
- schema: transform(prop.schema, {
692
- ...options,
693
- parent: prop
694
- })
695
- });
696
- }
697
- case "Parameter": {
698
- let param = node;
699
- const replaced = visitor.parameter?.(param, { parent });
700
- if (replaced) param = replaced;
701
- return createParameter({
702
- ...param,
703
- schema: transform(param.schema, {
704
- ...options,
705
- parent: param
706
- })
707
- });
708
- }
709
- case "Response": {
710
- let response = node;
711
- const replaced = visitor.response?.(response, { parent });
712
- if (replaced) response = replaced;
713
- return {
714
- ...response,
715
- schema: transform(response.schema, {
716
- ...options,
717
- parent: response
718
- })
719
- };
720
- }
721
- case "FunctionParameter":
722
- case "ParameterGroup":
723
- case "FunctionParameters":
724
- case "Type": return node;
725
- default: return node;
726
- }
727
- }
728
- /**
729
- * Runs a depth-first synchronous collection pass.
730
- *
731
- * Non-`undefined` values returned by visitor callbacks are appended to the result.
732
- *
733
- * @example
734
- * ```ts
735
- * const ids = collect(root, {
736
- * operation(node) {
737
- * return node.operationId
738
- * },
739
- * })
740
- * ```
741
- *
742
- * @example
743
- * ```ts
744
- * // Collect from only the current node
745
- * const values = collect(root, { depth: 'shallow', root: () => 'root' })
746
- * ```
747
- */
748
- function collect(node, options) {
749
- const { depth, parent, ...visitor } = options;
750
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
751
- const results = [];
752
- let v;
753
- switch (node.kind) {
754
- case "Input":
755
- v = visitor.input?.(node, { parent });
756
- break;
757
- case "Output":
758
- v = visitor.output?.(node, { parent });
759
- break;
760
- case "Operation":
761
- v = visitor.operation?.(node, { parent });
762
- break;
763
- case "Schema":
764
- v = visitor.schema?.(node, { parent });
765
- break;
766
- case "Property":
767
- v = visitor.property?.(node, { parent });
768
- break;
769
- case "Parameter":
770
- v = visitor.parameter?.(node, { parent });
771
- break;
772
- case "Response":
773
- v = visitor.response?.(node, { parent });
774
- break;
775
- case "FunctionParameter":
776
- case "ParameterGroup":
777
- case "FunctionParameters": break;
778
- }
779
- if (v !== void 0) results.push(v);
780
- for (const child of getChildren(node, recurse)) for (const item of collect(child, {
781
- ...options,
782
- parent: node
783
- })) results.push(item);
784
- return results;
785
- }
786
- //#endregion
787
- //#region src/utils.ts
788
- const plainStringTypes = new Set([
789
- "string",
790
- "uuid",
791
- "email",
792
- "url",
793
- "datetime"
794
- ]);
795
- /**
796
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
797
- *
798
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
799
- * override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
800
- *
801
- * @example
802
- * ```ts
803
- * // Ref with description override
804
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
805
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
806
- * ```
807
- */
808
- function syncSchemaRef(node) {
809
- const ref = narrowSchema(node, "ref");
810
- if (!ref) return node;
811
- if (!ref.schema) return node;
812
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
813
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
814
- return createSchema({
815
- ...ref.schema,
816
- ...definedOverrides
817
- });
818
- }
819
- /**
820
- * Type guard that returns `true` when a schema emits as a plain `string` type.
821
- *
822
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
823
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
824
- */
825
- function isStringType(node) {
826
- if (plainStringTypes.has(node.type)) return true;
827
- const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
828
- if (temporal) return temporal.representation !== "date";
829
- return false;
830
- }
831
- /**
832
- * Applies casing rules to parameter names and returns a new parameter array.
833
- *
834
- * Use this before passing parameters to schema builders so output property keys match
835
- * the desired casing while preserving `OperationNode.parameters` for other consumers.
836
- * The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
837
- */
838
- function caseParams(params, casing) {
839
- if (!casing) return params;
840
- return params.map((param) => {
841
- const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
842
- return {
843
- ...param,
844
- name: transformed
845
- };
846
- });
847
- }
848
- /**
849
- * Creates a single-property object schema used as a discriminator literal.
850
- *
851
- * @example
852
- * ```ts
853
- * createDiscriminantNode({ propertyName: 'type', value: 'dog' })
854
- * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
855
- * ```
856
- */
857
- function createDiscriminantNode({ propertyName, value }) {
858
- return createSchema({
859
- type: "object",
860
- primitive: "object",
861
- properties: [createProperty({
862
- name: propertyName,
863
- schema: createSchema({
864
- type: "enum",
865
- primitive: "string",
866
- enumValues: [value]
867
- }),
868
- required: true
869
- })]
870
- });
871
- }
872
- function resolveParamsType({ node, param, resolver }) {
873
- if (!resolver) return createParamsType({
874
- variant: "reference",
875
- name: param.schema.primitive ?? "unknown"
876
- });
877
- const individualName = resolver.resolveParamName(node, param);
878
- const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
879
- const groupResolvers = {
880
- path: resolver.resolvePathParamsName,
881
- query: resolver.resolveQueryParamsName,
882
- header: resolver.resolveHeaderParamsName
883
- };
884
- const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
885
- if (groupName && groupName !== individualName) return createParamsType({
886
- variant: "member",
887
- base: groupName,
888
- key: param.name
889
- });
890
- return createParamsType({
891
- variant: "reference",
892
- name: individualName
893
- });
894
- }
895
- /**
896
- * Converts an `OperationNode` into function parameters for code generation.
897
- *
898
- * Centralizes parameter grouping logic for all plugins. Provide a `resolver` for type name resolution
899
- * and `extraParams` for plugin-specific trailing parameters (e.g., `options` objects).
900
- * Supports three grouping modes: `object` (single destructured param), `inline` (separate params),
901
- * and `inlineSpread` (rest parameter). Use `CreateOperationParamsOptions` to fine-tune output.
902
- */
903
- function createOperationParams(node, options) {
904
- const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
905
- const dataName = paramNames?.data ?? "data";
906
- const paramsName = paramNames?.params ?? "params";
907
- const headersName = paramNames?.headers ?? "headers";
908
- const pathName = paramNames?.path ?? "pathParams";
909
- const wrapType = (type) => createParamsType({
910
- variant: "reference",
911
- name: typeWrapper ? typeWrapper(type) : type
912
- });
913
- const wrapTypeNode = (type) => type.kind === "ParamsType" && type.variant === "reference" ? wrapType(type.name) : type;
914
- const casedParams = caseParams(node.parameters, paramsCasing);
915
- const pathParams = casedParams.filter((p) => p.in === "path");
916
- const queryParams = casedParams.filter((p) => p.in === "query");
917
- const headerParams = casedParams.filter((p) => p.in === "header");
918
- const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
919
- const bodyRequired = node.requestBody?.required ?? false;
920
- const queryGroupType = resolver ? resolveGroupType({
921
- node,
922
- params: queryParams,
923
- groupMethod: resolver.resolveQueryParamsName,
924
- resolver
925
- }) : void 0;
926
- const headerGroupType = resolver ? resolveGroupType({
927
- node,
928
- params: headerParams,
929
- groupMethod: resolver.resolveHeaderParamsName,
930
- resolver
931
- }) : void 0;
932
- const params = [];
933
- if (paramsType === "object") {
934
- const children = [
935
- ...pathParams.map((p) => {
936
- const type = resolveParamsType({
937
- node,
938
- param: p,
939
- resolver
940
- });
941
- return createFunctionParameter({
942
- name: p.name,
943
- type: wrapTypeNode(type),
944
- optional: !p.required
945
- });
946
- }),
947
- ...bodyType ? [createFunctionParameter({
948
- name: dataName,
949
- type: bodyType,
950
- optional: !bodyRequired
951
- })] : [],
952
- ...buildGroupParam({
953
- name: paramsName,
954
- node,
955
- params: queryParams,
956
- groupType: queryGroupType,
957
- resolver,
958
- wrapType
959
- }),
960
- ...buildGroupParam({
961
- name: headersName,
962
- node,
963
- params: headerParams,
964
- groupType: headerGroupType,
965
- resolver,
966
- wrapType
967
- })
968
- ];
969
- if (children.length) params.push(createParameterGroup({
970
- properties: children,
971
- default: children.every((c) => c.optional) ? "{}" : void 0
972
- }));
973
- } else {
974
- if (pathParams.length) if (pathParamsType === "inlineSpread") {
975
- const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]) ?? void 0;
976
- params.push(createFunctionParameter({
977
- name: pathName,
978
- type: spreadType ? wrapType(spreadType) : void 0,
979
- rest: true
980
- }));
981
- } else {
982
- const pathChildren = pathParams.map((p) => {
983
- const type = resolveParamsType({
984
- node,
985
- param: p,
986
- resolver
987
- });
988
- return createFunctionParameter({
989
- name: p.name,
990
- type: wrapTypeNode(type),
991
- optional: !p.required
992
- });
993
- });
994
- params.push(createParameterGroup({
995
- properties: pathChildren,
996
- inline: pathParamsType === "inline",
997
- default: pathParamsDefault ?? (pathChildren.every((c) => c.optional) ? "{}" : void 0)
998
- }));
999
- }
1000
- if (bodyType) params.push(createFunctionParameter({
1001
- name: dataName,
1002
- type: bodyType,
1003
- optional: !bodyRequired
1004
- }));
1005
- params.push(...buildGroupParam({
1006
- name: paramsName,
1007
- node,
1008
- params: queryParams,
1009
- groupType: queryGroupType,
1010
- resolver,
1011
- wrapType
1012
- }));
1013
- params.push(...buildGroupParam({
1014
- name: headersName,
1015
- node,
1016
- params: headerParams,
1017
- groupType: headerGroupType,
1018
- resolver,
1019
- wrapType
1020
- }));
1021
- }
1022
- params.push(...extraParams);
1023
- return createFunctionParameters({ params });
1024
- }
1025
- /**
1026
- * Builds a single {@link FunctionParameterNode} for a query or header group.
1027
- * Returns an empty array when there are no params to emit.
1028
- *
1029
- * If a pre-resolved `groupType` is provided it emits `name: GroupType`.
1030
- * Otherwise, it builds an inline struct from the individual params.
1031
- */
1032
- function buildGroupParam({ name, node, params, groupType, resolver, wrapType }) {
1033
- if (groupType) return [createFunctionParameter({
1034
- name,
1035
- type: groupType.type.kind === "ParamsType" && groupType.type.variant === "reference" ? wrapType(groupType.type.name) : groupType.type,
1036
- optional: groupType.optional
1037
- })];
1038
- if (params.length) return [createFunctionParameter({
1039
- name,
1040
- type: toStructType({
1041
- node,
1042
- params,
1043
- resolver
1044
- }),
1045
- optional: params.every((p) => !p.required)
1046
- })];
1047
- return [];
1048
- }
1049
- /**
1050
- * Derives a {@link ParamGroupType} from the resolver's group method.
1051
- * Returns `undefined` when the group name equals the individual param name (no real group).
1052
- */
1053
- function resolveGroupType({ node, params, groupMethod, resolver }) {
1054
- if (!params.length) return;
1055
- const firstParam = params[0];
1056
- const groupName = groupMethod.call(resolver, node, firstParam);
1057
- if (groupName === resolver.resolveParamName(node, firstParam)) return;
1058
- const allOptional = params.every((p) => !p.required);
1059
- return {
1060
- type: createParamsType({
1061
- variant: "reference",
1062
- name: groupName
1063
- }),
1064
- optional: allOptional
1065
- };
1066
- }
1067
- /**
1068
- * Builds a {@link TypeNode} with `variant: 'struct'` for an inline anonymous type grouping named fields.
1069
- *
1070
- * Used when query or header parameters have no dedicated group type name.
1071
- * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
1072
- */
1073
- function toStructType({ node, params, resolver }) {
1074
- return createParamsType({
1075
- variant: "struct",
1076
- properties: params.map((p) => ({
1077
- name: p.name,
1078
- optional: !p.required,
1079
- type: resolveParamsType({
1080
- node,
1081
- param: p,
1082
- resolver
1083
- })
1084
- }))
1085
- });
1086
- }
1087
- function sourceKey(source) {
1088
- return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
1089
- }
1090
- function pathTypeKey(path, isTypeOnly) {
1091
- return `${path}:${isTypeOnly ?? false}`;
1092
- }
1093
- function exportKey(path, name, isTypeOnly, asAlias) {
1094
- return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
1095
- }
1096
- function importKey(path, name, isTypeOnly) {
1097
- return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
1098
- }
1099
- /**
1100
- * Computes a multi-level sort key for exports and imports:
1101
- * non-array names first (wildcards/namespace aliases); type-only before value; alphabetical path; unnamed before named.
1102
- */
1103
- function sortKey(node) {
1104
- const isArray = Array.isArray(node.name) ? "1" : "0";
1105
- const typeOnly = node.isTypeOnly ? "0" : "1";
1106
- const hasName = node.name != null ? "1" : "0";
1107
- const name = Array.isArray(node.name) ? [...node.name].sort().join("\0") : node.name ?? "";
1108
- return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
1109
- }
1110
- /**
1111
- * Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
1112
- *
1113
- * Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
1114
- */
1115
- function combineSources(sources) {
1116
- const seen = /* @__PURE__ */ new Map();
1117
- for (const source of sources) {
1118
- const key = sourceKey(source);
1119
- if (!seen.has(key)) seen.set(key, source);
1120
- }
1121
- return [...seen.values()];
1122
- }
1123
- /**
1124
- * Deduplicates and merges `ExportNode` objects by path and type.
1125
- *
1126
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
1127
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
1128
- */
1129
- function combineExports(exports) {
1130
- const result = [];
1131
- const namedByPath = /* @__PURE__ */ new Map();
1132
- const seen = /* @__PURE__ */ new Set();
1133
- const keyed = exports.map((node) => ({
1134
- node,
1135
- key: sortKey(node)
1136
- }));
1137
- keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
1138
- for (const { node: curr } of keyed) {
1139
- const { name, path, isTypeOnly, asAlias } = curr;
1140
- if (Array.isArray(name)) {
1141
- if (!name.length) continue;
1142
- const key = pathTypeKey(path, isTypeOnly);
1143
- 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 {
1149
- const newItem = {
1150
- ...curr,
1151
- name: [...new Set(name)]
1152
- };
1153
- result.push(newItem);
1154
- namedByPath.set(key, newItem);
1155
- }
1156
- } else {
1157
- const key = exportKey(path, name, isTypeOnly, asAlias);
1158
- if (!seen.has(key)) {
1159
- result.push(curr);
1160
- seen.add(key);
1161
- }
1162
- }
1163
- }
1164
- return result;
1165
- }
1166
- /**
1167
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
1168
- *
1169
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
1170
- * `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
- */
1174
- function combineImports(imports, exports, source) {
1175
- const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
1176
- const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
1177
- const importNameMemo = /* @__PURE__ */ new Map();
1178
- const canonicalizeName = (n) => {
1179
- if (typeof n === "string") return n;
1180
- const key = `${n.propertyName}:${n.name ?? ""}`;
1181
- if (!importNameMemo.has(key)) importNameMemo.set(key, n);
1182
- return importNameMemo.get(key);
1183
- };
1184
- const result = [];
1185
- const namedByPath = /* @__PURE__ */ new Map();
1186
- const seen = /* @__PURE__ */ new Set();
1187
- const keyed = imports.map((node) => ({
1188
- node,
1189
- key: sortKey(node)
1190
- }));
1191
- keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
1192
- for (const { node: curr } of keyed) {
1193
- if (curr.path === curr.root) continue;
1194
- const { path, isTypeOnly } = curr;
1195
- let { name } = curr;
1196
- if (Array.isArray(name)) {
1197
- name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
1198
- if (!name.length) continue;
1199
- const key = pathTypeKey(path, isTypeOnly);
1200
- 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 {
1206
- const newItem = {
1207
- ...curr,
1208
- name
1209
- };
1210
- result.push(newItem);
1211
- namedByPath.set(key, newItem);
1212
- }
1213
- } else {
1214
- if (name && !isUsed(name)) continue;
1215
- const key = importKey(path, name, isTypeOnly);
1216
- if (!seen.has(key)) {
1217
- result.push(curr);
1218
- seen.add(key);
1219
- }
1220
- }
1221
- }
1222
- return result;
1223
- }
1224
- /**
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.
1229
- */
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
- }
1247
- /**
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.
1252
- *
1253
- * @example
1254
- * ```ts
1255
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
1256
- * // => 'Pet'
1257
- * ```
1258
- */
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
- }
1264
- /**
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.
1269
- *
1270
- * @example Collect refs from a single schema
1271
- * ```ts
1272
- * const names = collectReferencedSchemaNames(petSchema)
1273
- * // → Set { 'Category', 'Tag' }
1274
- * ```
1275
- *
1276
- * @example Accumulate refs from multiple schemas into one set
1277
- * ```ts
1278
- * const out = new Set<string>()
1279
- * for (const schema of schemas) {
1280
- * collectReferencedSchemaNames(schema, out)
1281
- * }
1282
- * ```
1283
- */
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
- }
1294
- /**
1295
- * Collects the names of all top-level schemas transitively used by a set of operations.
1296
- *
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.
1300
- *
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.
1304
- *
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)
1309
- *
1310
- * for (const schema of inputNode.schemas) {
1311
- * if (schema.name && !allowed.has(schema.name)) continue
1312
- * // … generate schema
1313
- * }
1314
- * ```
1315
- *
1316
- * @example Check whether a specific schema is needed
1317
- * ```ts
1318
- * const allowed = collectUsedSchemaNames(includedOps, inputNode.schemas)
1319
- * allowed.has('OrderStatus') // false when no included operation references OrderStatus
1320
- * ```
1321
- */
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);
1369
- }
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;
1388
- }
1389
- //#endregion
1390
- //#region src/factory.ts
1391
- /**
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.
1396
- */
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
- }
1405
- /**
1406
- * Creates an `InputNode` with stable defaults for `schemas` and `operations`.
1407
- *
1408
- * @example
1409
- * ```ts
1410
- * const input = createInput()
1411
- * // { kind: 'Input', schemas: [], operations: [] }
1412
- * ```
1413
- *
1414
- * @example
1415
- * ```ts
1416
- * const input = createInput({ schemas: [petSchema] })
1417
- * // keeps default operations: []
1418
- * ```
1419
- */
1420
- function createInput(overrides = {}) {
1421
- return {
1422
- schemas: [],
1423
- operations: [],
1424
- ...overrides,
1425
- kind: "Input"
1426
- };
1427
- }
1428
- /**
1429
- * Creates an `OutputNode` with a stable default for `files`.
1430
- *
1431
- * @example
1432
- * ```ts
1433
- * const output = createOutput()
1434
- * // { kind: 'Output', files: [] }
1435
- * ```
1436
- *
1437
- * @example
1438
- * ```ts
1439
- * const output = createOutput({ files: [petFile] })
1440
- * ```
1441
- */
1442
- function createOutput(overrides = {}) {
1443
- return {
1444
- files: [],
1445
- ...overrides,
1446
- kind: "Output"
1447
- };
1448
- }
1449
- /**
1450
- * Creates an `OperationNode` with default empty arrays for `tags`, `parameters`, and `responses`.
1451
- *
1452
- * @example
1453
- * ```ts
1454
- * const operation = createOperation({
1455
- * operationId: 'getPetById',
1456
- * method: 'GET',
1457
- * path: '/pet/{petId}',
1458
- * })
1459
- * // tags, parameters, and responses are []
1460
- * ```
1461
- *
1462
- * @example
1463
- * ```ts
1464
- * const operation = createOperation({
1465
- * operationId: 'findPets',
1466
- * method: 'GET',
1467
- * path: '/pet/findByStatus',
1468
- * tags: ['pet'],
1469
- * })
1470
- * ```
1471
- */
1472
- function createOperation(props) {
1473
- return {
1474
- tags: [],
1475
- parameters: [],
1476
- responses: [],
1477
- ...props,
1478
- kind: "Operation"
1479
- };
1480
- }
1481
- /**
1482
- * Maps schema `type` to its underlying `primitive`.
1483
- * Primitive types map to themselves; special string formats map to `'string'`.
1484
- * Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
1485
- */
1486
- const TYPE_TO_PRIMITIVE = {
1487
- string: "string",
1488
- number: "number",
1489
- integer: "integer",
1490
- bigint: "bigint",
1491
- boolean: "boolean",
1492
- null: "null",
1493
- any: "any",
1494
- unknown: "unknown",
1495
- void: "void",
1496
- never: "never",
1497
- object: "object",
1498
- array: "array",
1499
- date: "date",
1500
- uuid: "string",
1501
- email: "string",
1502
- url: "string",
1503
- datetime: "string",
1504
- time: "string"
1505
- };
1506
- function createSchema(props) {
1507
- const inferredPrimitive = TYPE_TO_PRIMITIVE[props.type];
1508
- if (props["type"] === "object") return {
1509
- properties: [],
1510
- primitive: "object",
1511
- ...props,
1512
- kind: "Schema"
1513
- };
1514
- return {
1515
- primitive: inferredPrimitive,
1516
- ...props,
1517
- kind: "Schema"
1518
- };
1519
- }
1520
- /**
1521
- * Creates a `PropertyNode`.
1522
- *
1523
- * `required` defaults to `false`.
1524
- * `schema.optional` and `schema.nullish` are derived from `required` and `schema.nullable`.
1525
- *
1526
- * @example
1527
- * ```ts
1528
- * const property = createProperty({
1529
- * name: 'status',
1530
- * schema: createSchema({ type: 'string' }),
1531
- * })
1532
- * // required=false, schema.optional=true
1533
- * ```
1534
- *
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
- * ```
1544
- */
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
- };
1553
- }
1554
- /**
1555
- * Creates a `ParameterNode`.
1556
- *
1557
- * `required` defaults to `false`.
1558
- * Nested schema flags are set from `required` and `schema.nullable`.
1559
- *
1560
- * @example
1561
- * ```ts
1562
- * const param = createParameter({
1563
- * name: 'petId',
1564
- * in: 'path',
1565
- * required: true,
1566
- * schema: createSchema({ type: 'string' }),
1567
- * })
1568
- * ```
1569
- *
1570
- * @example
1571
- * ```ts
1572
- * const param = createParameter({
1573
- * name: 'status',
1574
- * in: 'query',
1575
- * schema: createSchema({ type: 'string', nullable: true }),
1576
- * })
1577
- * // required=false, schema.nullish=true
1578
- * ```
1579
- */
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
- };
1588
- }
1589
- /**
1590
- * Creates a `ResponseNode`.
1591
- *
1592
- * @example
1593
- * ```ts
1594
- * const response = createResponse({
1595
- * statusCode: '200',
1596
- * description: 'Success',
1597
- * schema: createSchema({ type: 'object', properties: [] }),
1598
- * })
1599
- * ```
1600
- */
1601
- function createResponse(props) {
1602
- return {
1603
- ...props,
1604
- kind: "Response"
1605
- };
1606
- }
1607
- /**
1608
- * Creates a `FunctionParameterNode`.
1609
- *
1610
- * `optional` defaults to `false`.
1611
- *
1612
- * @example Required typed param
1613
- * ```ts
1614
- * createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }) })
1615
- * // → petId: string
1616
- * ```
1617
- *
1618
- * @example Optional param
1619
- * ```ts
1620
- * createFunctionParameter({ name: 'params', type: createParamsType({ variant: 'reference', name: 'QueryParams' }), optional: true })
1621
- * // → params?: QueryParams
1622
- * ```
1623
- *
1624
- * @example Param with default (implicitly optional; cannot combine with `optional: true`)
1625
- * ```ts
1626
- * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), default: '{}' })
1627
- * // → config: RequestConfig = {}
1628
- * ```
1629
- */
1630
- function createFunctionParameter(props) {
1631
- return {
1632
- optional: false,
1633
- ...props,
1634
- kind: "FunctionParameter"
1635
- };
2
+ const require_response = require("./response-DS5S3IG4.cjs");
3
+ const require_utils = require("./utils-D83JA6Xx.cjs");
4
+ const require_factory = require("./factory-Cl8Z7mcc.cjs");
5
+ let node_crypto = require("node:crypto");
6
+ //#region src/signature.ts
7
+ /**
8
+ * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.
9
+ */
10
+ function flagsDescriptor(node) {
11
+ return `${node.primitive ?? ""};${node.format ?? ""};${node.nullable ? 1 : 0}`;
12
+ }
13
+ function refTargetName(node) {
14
+ if (node.ref) return require_utils.extractRefName(node.ref);
15
+ return node.name ?? "";
16
+ }
17
+ const arrayTupleFields = [
18
+ {
19
+ kind: "children",
20
+ key: "items",
21
+ prefix: "i"
22
+ },
23
+ {
24
+ kind: "child",
25
+ key: "rest",
26
+ prefix: "r"
27
+ },
28
+ {
29
+ kind: "scalar",
30
+ key: "min",
31
+ prefix: "mn"
32
+ },
33
+ {
34
+ kind: "scalar",
35
+ key: "max",
36
+ prefix: "mx"
37
+ },
38
+ {
39
+ kind: "bool",
40
+ key: "unique",
41
+ prefix: "u"
42
+ }
43
+ ];
44
+ const numericFields = [
45
+ {
46
+ kind: "scalar",
47
+ key: "min",
48
+ prefix: "mn"
49
+ },
50
+ {
51
+ kind: "scalar",
52
+ key: "max",
53
+ prefix: "mx"
54
+ },
55
+ {
56
+ kind: "scalar",
57
+ key: "exclusiveMinimum",
58
+ prefix: "emn"
59
+ },
60
+ {
61
+ kind: "scalar",
62
+ key: "exclusiveMaximum",
63
+ prefix: "emx"
64
+ },
65
+ {
66
+ kind: "scalar",
67
+ key: "multipleOf",
68
+ prefix: "mo"
69
+ }
70
+ ];
71
+ const rangeFields = [{
72
+ kind: "scalar",
73
+ key: "min",
74
+ prefix: "mn"
75
+ }, {
76
+ kind: "scalar",
77
+ key: "max",
78
+ prefix: "mx"
79
+ }];
80
+ /**
81
+ * Maps each node `type` to its ordered shape-contributing fields. Types absent from the map
82
+ * (boolean, null, any, and other scalars) fall back to `${type}|${flags}`.
83
+ */
84
+ const SHAPE_KEYS = {
85
+ object: [
86
+ { kind: "objectProps" },
87
+ { kind: "additionalProps" },
88
+ { kind: "patternProps" },
89
+ {
90
+ kind: "scalar",
91
+ key: "minProperties",
92
+ prefix: "mn"
93
+ },
94
+ {
95
+ kind: "scalar",
96
+ key: "maxProperties",
97
+ prefix: "mx"
98
+ }
99
+ ],
100
+ array: arrayTupleFields,
101
+ tuple: arrayTupleFields,
102
+ union: [
103
+ {
104
+ kind: "scalar",
105
+ key: "strategy",
106
+ prefix: "s"
107
+ },
108
+ {
109
+ kind: "scalar",
110
+ key: "discriminatorPropertyName",
111
+ prefix: "d"
112
+ },
113
+ {
114
+ kind: "children",
115
+ key: "members",
116
+ prefix: "m"
117
+ }
118
+ ],
119
+ intersection: [{
120
+ kind: "children",
121
+ key: "members",
122
+ prefix: "m"
123
+ }],
124
+ enum: [{ kind: "enumValues" }],
125
+ ref: [{ kind: "refTarget" }],
126
+ string: [
127
+ {
128
+ kind: "scalar",
129
+ key: "min",
130
+ prefix: "mn"
131
+ },
132
+ {
133
+ kind: "scalar",
134
+ key: "max",
135
+ prefix: "mx"
136
+ },
137
+ {
138
+ kind: "scalar",
139
+ key: "pattern",
140
+ prefix: "pt"
141
+ }
142
+ ],
143
+ number: numericFields,
144
+ integer: numericFields,
145
+ bigint: numericFields,
146
+ url: [
147
+ {
148
+ kind: "scalar",
149
+ key: "path",
150
+ prefix: "path"
151
+ },
152
+ {
153
+ kind: "scalar",
154
+ key: "min",
155
+ prefix: "mn"
156
+ },
157
+ {
158
+ kind: "scalar",
159
+ key: "max",
160
+ prefix: "mx"
161
+ }
162
+ ],
163
+ uuid: rangeFields,
164
+ email: rangeFields,
165
+ datetime: [{
166
+ kind: "bool",
167
+ key: "offset",
168
+ prefix: "o"
169
+ }, {
170
+ kind: "bool",
171
+ key: "local",
172
+ prefix: "l"
173
+ }],
174
+ date: [{
175
+ kind: "scalar",
176
+ key: "representation",
177
+ prefix: "rep"
178
+ }],
179
+ time: [{
180
+ kind: "scalar",
181
+ key: "representation",
182
+ prefix: "rep"
183
+ }]
184
+ };
185
+ function serializeShapeField(field, node, record) {
186
+ switch (field.kind) {
187
+ case "scalar": return `${field.prefix}:${record[field.key] ?? ""}`;
188
+ case "bool": return `${field.prefix}:${record[field.key] ? 1 : 0}`;
189
+ case "child": {
190
+ const child = record[field.key];
191
+ return `${field.prefix}:${child ? signatureOf(child) : ""}`;
192
+ }
193
+ case "children": {
194
+ const children = record[field.key] ?? [];
195
+ return `${field.prefix}[${children.map((c) => signatureOf(c)).join(",")}]`;
196
+ }
197
+ case "objectProps": return `p[${(node.properties ?? []).map((prop) => `${prop.name}${prop.required ? "!" : "?"}${signatureOf(prop.schema)}`).join(",")}]`;
198
+ case "additionalProps": {
199
+ const obj = node;
200
+ if (typeof obj.additionalProperties === "boolean") return `ab:${obj.additionalProperties}`;
201
+ if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`;
202
+ return "";
203
+ }
204
+ case "patternProps": {
205
+ const obj = node;
206
+ return `pp[${obj.patternProperties ? Object.keys(obj.patternProperties).sort().map((key) => `${key}=${signatureOf(obj.patternProperties[key])}`).join(",") : ""}]`;
207
+ }
208
+ case "enumValues": {
209
+ const en = node;
210
+ let values = "";
211
+ if (en.namedEnumValues?.length) values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(",");
212
+ else if (en.enumValues?.length) values = en.enumValues.map((value) => `${value === null ? "null" : typeof value}:${String(value)}`).join(",");
213
+ return `v[${values}]`;
214
+ }
215
+ case "refTarget": return `->${refTargetName(node)}`;
216
+ }
1636
217
  }
1637
218
  /**
1638
- * Creates a {@link TypeNode} representing a language-agnostic structured type expression.
1639
- *
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, …).
1643
- *
1644
- * @example Reference type (TypeScript: `QueryParams`)
1645
- * ```ts
1646
- * createParamsType({ variant: 'reference', name: 'QueryParams' })
1647
- * ```
1648
- *
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
- * ```
1653
- *
1654
- * @example Member type (TypeScript: `DeletePetPathParams['petId']`)
1655
- * ```ts
1656
- * createParamsType({ variant: 'member', base: 'DeletePetPathParams', key: 'petId' })
1657
- * ```
219
+ * Builds the local shape descriptor that {@link signatureOf} hashes: the node's kind, flags,
220
+ * constraints, and its children's signatures.
1658
221
  */
1659
- function createParamsType(props) {
1660
- return {
1661
- ...props,
1662
- kind: "ParamsType"
1663
- };
222
+ function describeShape(node) {
223
+ const flags = flagsDescriptor(node);
224
+ const fields = SHAPE_KEYS[node.type];
225
+ if (!fields) return `${node.type}|${flags}`;
226
+ const record = node;
227
+ const parts = [`${node.type}|${flags}`];
228
+ for (const field of fields) parts.push(serializeShapeField(field, node, record));
229
+ return parts.join("|");
1664
230
  }
1665
231
  /**
1666
- * Creates a `ParameterGroupNode` representing a group of related parameters treated as a unit.
1667
- *
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
- * ```
1680
- *
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
1689
- * ```
232
+ * Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so
233
+ * a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.
234
+ * Reuse is safe because a signature depends only on content, and nodes are immutable once created.
1690
235
  */
1691
- function createParameterGroup(props) {
1692
- return {
1693
- ...props,
1694
- kind: "ParameterGroup"
1695
- };
1696
- }
236
+ const signatureCache = /* @__PURE__ */ new WeakMap();
1697
237
  /**
1698
- * Creates a `FunctionParametersNode` from an ordered list of parameters.
1699
- *
1700
- * @example
1701
- * ```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
- * })
1708
- * ```
238
+ * Computes a deterministic, shape-only signature (a content hash) for a schema node. Two schemas
239
+ * share a signature when they are structurally identical, ignoring documentation (`name`, `title`,
240
+ * `description`, `example`, `default`, `deprecated`) and usage-slot flags (`optional`, `nullish`,
241
+ * `readOnly`, `writeOnly`). `nullable` is kept because it changes the produced type, and `ref`
242
+ * nodes compare by target name, which also terminates on circular shapes.
1709
243
  *
1710
- * @example
244
+ * @example Two enums with different descriptions share a signature
1711
245
  * ```ts
1712
- * const empty = createFunctionParameters()
1713
- * // { kind: 'FunctionParameters', params: [] }
246
+ * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===
247
+ * signatureOf(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))
1714
248
  * ```
1715
249
  */
1716
- function createFunctionParameters(props = {}) {
1717
- return {
1718
- params: [],
1719
- ...props,
1720
- kind: "FunctionParameters"
1721
- };
250
+ function signatureOf(node) {
251
+ const cached = signatureCache.get(node);
252
+ if (cached !== void 0) return cached;
253
+ const signature = (0, node_crypto.hash)("sha256", describeShape(node), "hex");
254
+ signatureCache.set(node, signature);
255
+ return signature;
1722
256
  }
1723
- /**
1724
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1725
- *
1726
- * @example Named import
1727
- * ```ts
1728
- * createImport({ name: ['useState'], path: 'react' })
1729
- * // import { useState } from 'react'
1730
- * ```
1731
- *
1732
- * @example Type-only import
1733
- * ```ts
1734
- * createImport({ name: ['FC'], path: 'react', isTypeOnly: true })
1735
- * // import type { FC } from 'react'
1736
- * ```
1737
- */
1738
- function createImport(props) {
1739
- return {
1740
- ...props,
1741
- kind: "Import"
1742
- };
257
+ //#endregion
258
+ //#region src/dedupe.ts
259
+ /**
260
+ * Builds the shared `ref` replacement for a duplicate occurrence, carrying the
261
+ * usage-slot and documentation fields that are not part of the canonical type.
262
+ */
263
+ function createRefNode(node, canonical) {
264
+ return require_response.createSchema({
265
+ type: "ref",
266
+ name: canonical.name,
267
+ ref: canonical.ref,
268
+ optional: node.optional,
269
+ nullish: node.nullish,
270
+ readOnly: node.readOnly,
271
+ writeOnly: node.writeOnly,
272
+ deprecated: node.deprecated,
273
+ description: node.description,
274
+ default: node.default,
275
+ example: node.example
276
+ });
1743
277
  }
1744
- /**
1745
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1746
- *
1747
- * @example Named export
1748
- * ```ts
1749
- * createExport({ name: ['Pet'], path: './Pet' })
1750
- * // export { Pet } from './Pet'
1751
- * ```
1752
- *
1753
- * @example Wildcard export
1754
- * ```ts
1755
- * createExport({ path: './utils' })
1756
- * // export * from './utils'
1757
- * ```
1758
- */
1759
- function createExport(props) {
1760
- return {
1761
- ...props,
1762
- kind: "Export"
1763
- };
278
+ function applyDedupe(node, plan, skipRootMatch = false) {
279
+ const { canonicalBySignature, aliasNames } = plan;
280
+ if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node;
281
+ const root = node;
282
+ return require_utils.transform(node, { schema(schemaNode) {
283
+ if (schemaNode.type === "ref") {
284
+ const target = schemaNode.ref ? require_utils.extractRefName(schemaNode.ref) : schemaNode.name;
285
+ const canonical = target ? aliasNames.get(target) : void 0;
286
+ return canonical ? {
287
+ ...schemaNode,
288
+ name: canonical.name,
289
+ ref: canonical.ref
290
+ } : void 0;
291
+ }
292
+ const signature = signatureOf(schemaNode);
293
+ if (skipRootMatch && schemaNode === root) return void 0;
294
+ const canonical = canonicalBySignature.get(signature);
295
+ if (!canonical) return void 0;
296
+ return createRefNode(schemaNode, canonical);
297
+ } });
1764
298
  }
1765
299
  /**
1766
- * Creates a `SourceNode` representing a fragment of source code within a file.
1767
- *
1768
- * @example
1769
- * ```ts
1770
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1771
- * ```
300
+ * Strips usage-slot flags from a hoisted definition and applies its canonical name.
301
+ * A standalone definition is never optional, so `optional`/`nullish` are cleared.
1772
302
  */
1773
- function createSource(props) {
303
+ function cleanDefinition(node, name) {
1774
304
  return {
1775
- ...props,
1776
- kind: "Source"
305
+ ...node,
306
+ name,
307
+ optional: void 0,
308
+ nullish: void 0
1777
309
  };
1778
310
  }
1779
311
  /**
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`
312
+ * Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
1786
313
  *
1787
- * Deduplicates:
1788
- * - `sources` via `combineSources`
1789
- * - `exports` via `combineExports`
1790
- * - `imports` via `combineImports` (also filters unused imports)
1791
- *
1792
- * @throws {Error} when `baseName` has no extension.
314
+ * A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
315
+ * is a named top-level schema, the first one becomes the canonical (so other top-level
316
+ * duplicates and inline copies turn into references to it). Every other top-level name with
317
+ * the same content is recorded in `aliasNames`, so refs to it can be repointed at the
318
+ * canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied
319
+ * per node with {@link applyDedupe}.
1793
320
  *
1794
321
  * @example
1795
322
  * ```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'
1806
- * ```
1807
- */
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
- };
1826
- }
1827
- /**
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
- * ```
1844
- *
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
- * ```
1854
- */
1855
- function createConst(props) {
1856
- return {
1857
- ...props,
1858
- kind: "Const"
1859
- };
1860
- }
1861
- /**
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
- * ```
1882
- */
1883
- function createType(props) {
1884
- return {
1885
- ...props,
1886
- kind: "Type"
1887
- };
1888
- }
1889
- /**
1890
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
1891
- *
1892
- * Mirrors the `Function` component from `@kubb/renderer-jsx`.
1893
- * The component's `children` are represented as `nodes`.
1894
- *
1895
- * @example Simple function
1896
- * ```ts
1897
- * createFunction({ name: 'getPet' })
1898
- * // function getPet() { ... }
1899
- * ```
1900
- *
1901
- * @example Exported async function with return type
1902
- * ```ts
1903
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
1904
- * // export async function fetchPet(): Promise<Pet> { ... }
1905
- * ```
1906
- *
1907
- * @example Function with generics and params
1908
- * ```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 { ... }
1917
- * ```
1918
- */
1919
- function createFunction(props) {
1920
- return {
1921
- ...props,
1922
- kind: "Function"
1923
- };
1924
- }
1925
- /**
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',
323
+ * const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
324
+ * isCandidate: (node) => node.type === 'enum' || node.type === 'object',
325
+ * nameFor: (node) => node.name ?? null,
326
+ * refFor: (name) => `#/components/schemas/${name}`,
1952
327
  * })
1953
- * // export const fetchPet = async <T>(id: string): Promise<T> => { ... }
1954
- * ```
1955
- */
1956
- function createArrowFunction(props) {
1957
- return {
1958
- ...props,
1959
- kind: "ArrowFunction"
1960
- };
1961
- }
1962
- /**
1963
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
1964
- *
1965
- * Use this instead of bare strings when building `nodes` arrays so that every
1966
- * entry in the array is a typed {@link CodeNode}.
1967
- *
1968
- * @example
1969
- * ```ts
1970
- * createText('return fetch(id)')
1971
- * // { kind: 'Text', value: 'return fetch(id)' }
1972
328
  * ```
1973
329
  */
1974
- function createText(value) {
330
+ function buildDedupePlan(roots, options) {
331
+ const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options;
332
+ const topLevelNodes = /* @__PURE__ */ new Set();
333
+ const groups = /* @__PURE__ */ new Map();
334
+ function record(schemaNode) {
335
+ const signature = signatureOf(schemaNode);
336
+ if (!isCandidate(schemaNode)) return;
337
+ const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name;
338
+ const group = groups.get(signature);
339
+ if (group) {
340
+ group.count++;
341
+ if (isTopLevel) group.topLevelNames.push(schemaNode.name);
342
+ } else groups.set(signature, {
343
+ count: 1,
344
+ representative: schemaNode,
345
+ topLevelNames: isTopLevel ? [schemaNode.name] : []
346
+ });
347
+ }
348
+ for (const root of roots) {
349
+ if (root.kind === "Schema") topLevelNodes.add(root);
350
+ for (const schemaNode of require_utils.collectLazy(root, { schema: (node) => node })) record(schemaNode);
351
+ }
352
+ const canonicalBySignature = /* @__PURE__ */ new Map();
353
+ const aliasNames = /* @__PURE__ */ new Map();
354
+ const pendingHoists = [];
355
+ for (const [signature, group] of groups) {
356
+ if (group.count < minOccurrences) continue;
357
+ const [firstName, ...duplicateNames] = group.topLevelNames;
358
+ if (firstName) {
359
+ const canonical = {
360
+ name: firstName,
361
+ ref: refFor(firstName)
362
+ };
363
+ canonicalBySignature.set(signature, canonical);
364
+ for (const duplicate of duplicateNames) aliasNames.set(duplicate, canonical);
365
+ continue;
366
+ }
367
+ const name = nameFor(group.representative, signature);
368
+ if (!name) continue;
369
+ canonicalBySignature.set(signature, {
370
+ name,
371
+ ref: refFor(name)
372
+ });
373
+ pendingHoists.push({
374
+ name,
375
+ representative: group.representative
376
+ });
377
+ }
1975
378
  return {
1976
- value,
1977
- kind: "Text"
379
+ canonicalBySignature,
380
+ aliasNames,
381
+ hoisted: pendingHoists.map(({ name, representative }) => cleanDefinition(applyDedupe(representative, {
382
+ canonicalBySignature,
383
+ aliasNames
384
+ }, true), name))
1978
385
  };
1979
386
  }
387
+ //#endregion
388
+ //#region src/dialect.ts
1980
389
  /**
1981
- * Creates a {@link BreakNode} representing a line break in the source output.
1982
- *
1983
- * Corresponds to `<br/>` in JSX components. Prints as an empty string which,
1984
- * when joined with `\n` by `printNodes`, produces a blank line.
1985
- *
1986
- * @example
1987
- * ```ts
1988
- * createBreak()
1989
- * // { kind: 'Break' }
1990
- * ```
1991
- */
1992
- function createBreak() {
1993
- return { kind: "Break" };
1994
- }
1995
- /**
1996
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
1997
- *
1998
- * Use this to embed JSX markup (including fragments `<>…</>`) directly in generated code.
390
+ * Types a {@link SchemaDialect} for an adapter. Adds no runtime behavior and only pins the
391
+ * dialect's type for inference.
1999
392
  *
2000
393
  * @example
2001
394
  * ```ts
2002
- * createJsx('<>\n <a href={href}>Open</a>\n</>')
2003
- * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
395
+ * export const oasDialect = defineSchemaDialect({
396
+ * name: 'oas',
397
+ * isNullable,
398
+ * isReference,
399
+ * isDiscriminator,
400
+ * isBinary: (schema) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',
401
+ * resolveRef,
402
+ * })
2004
403
  * ```
2005
404
  */
2006
- function createJsx(value) {
2007
- return {
2008
- value,
2009
- kind: "Jsx"
2010
- };
405
+ function defineSchemaDialect(dialect) {
406
+ return dialect;
2011
407
  }
2012
408
  //#endregion
2013
409
  //#region src/printer.ts
2014
410
  /**
2015
- * Creates a schema printer factory.
2016
- *
2017
- * This function wraps a builder and makes options optional at call sites.
411
+ * Defines a schema printer: a function that takes a `SchemaNode` and emits
412
+ * code in your target language. Each plugin that produces code from schemas
413
+ * (TypeScript types, Zod schemas, Faker factories) ships a printer built
414
+ * with this helper.
2018
415
  *
2019
416
  * 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
417
  *
2027
- * When no `print` override is provided, `printer.print` falls back to `printer.transform` (the node-level dispatcher).
418
+ * - `name` unique identifier for the printer.
419
+ * - `options` stored on the returned printer instance.
420
+ * - `nodes` map of `SchemaType` → handler. Handlers return the rendered
421
+ * output (a string, a TypeScript AST node, ...) for that schema type.
422
+ * - `print` (optional), top-level override exposed as `printer.print`.
423
+ * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
2028
424
  *
2029
- * @example Basic usage Zod schema printer
425
+ * Without a `print` override, `printer.print` falls back to `printer.transform`
426
+ * (the node-level dispatcher).
427
+ *
428
+ * @example Tiny Zod printer
2030
429
  * ```ts
430
+ * import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
431
+ *
2031
432
  * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
2032
433
  *
2033
434
  * export const zodPrinter = definePrinter<PrinterZod>((options) => ({
@@ -2036,7 +437,9 @@ function createJsx(value) {
2036
437
  * nodes: {
2037
438
  * string: () => 'z.string()',
2038
439
  * object(node) {
2039
- * const props = node.properties.map(p => `${p.name}: ${this.transform(p.schema)}`).join(', ')
440
+ * const props = node.properties
441
+ * .map((p) => `${p.name}: ${this.transform(p.schema)}`)
442
+ * .join(', ')
2040
443
  * return `z.object({ ${props} })`
2041
444
  * },
2042
445
  * },
@@ -2048,11 +451,11 @@ function definePrinter(build) {
2048
451
  }
2049
452
  /**
2050
453
  * Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
2051
- **
454
+ *
2052
455
  * @example
2053
456
  * ```ts
2054
- * export const defineFunctionPrinter = createPrinterFactory<FunctionNode, FunctionNodeType, FunctionNodeByType>(
2055
- * (node) => kindToHandlerKey[node.kind],
457
+ * export const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
458
+ * (node) => node.kind,
2056
459
  * )
2057
460
  * ```
2058
461
  */
@@ -2064,7 +467,7 @@ function createPrinterFactory(getKey) {
2064
467
  options: resolvedOptions,
2065
468
  transform: (node) => {
2066
469
  const key = getKey(node);
2067
- if (key === void 0) return null;
470
+ if (key === null) return null;
2068
471
  const handler = nodes[key];
2069
472
  if (!handler) return null;
2070
473
  return handler.call(context, node);
@@ -2080,198 +483,57 @@ function createPrinterFactory(getKey) {
2080
483
  };
2081
484
  }
2082
485
  //#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(" "));
2097
- }
2098
- /**
2099
- * Collects import entries for all `ref` schema nodes in `node`.
2100
- */
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
- } });
2110
- }
2111
- //#endregion
2112
- //#region src/transformers.ts
2113
- /**
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.
2118
- *
2119
- * @example
2120
- * ```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
2145
- })
2146
- });
2147
- })
2148
- });
2149
- }
2150
- /**
2151
- * Merges adjacent anonymous object members into a single anonymous object member.
2152
- *
2153
- * @example
2154
- * ```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
- * ])
2159
- * ```
2160
- */
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
- }
2174
- }
2175
- acc.push(member);
2176
- return acc;
2177
- }, []);
2178
- }
2179
- /**
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
- * ```
2190
- */
2191
- function simplifyUnion(members) {
2192
- const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
2193
- if (!scalarPrimitives.size) return members;
2194
- return members.filter((member) => {
2195
- const enumNode = narrowSchema(member, "enum");
2196
- if (!enumNode) return true;
2197
- const primitive = enumNode.primitive;
2198
- if (!primitive) return true;
2199
- if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
2200
- if (scalarPrimitives.has(primitive)) return false;
2201
- if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
2202
- return true;
2203
- });
2204
- }
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)
2214
- };
2215
- return propNode;
2216
- }
2217
- //#endregion
2218
- exports.caseParams = caseParams;
2219
- exports.childName = childName;
2220
- exports.collect = collect;
2221
- exports.collectImports = collectImports;
2222
- exports.collectReferencedSchemaNames = collectReferencedSchemaNames;
2223
- exports.collectUsedSchemaNames = collectUsedSchemaNames;
2224
- 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;
486
+ exports.applyDedupe = applyDedupe;
487
+ exports.arrowFunctionDef = require_response.arrowFunctionDef;
488
+ exports.breakDef = require_response.breakDef;
489
+ exports.buildDedupePlan = buildDedupePlan;
490
+ exports.collect = require_utils.collect;
491
+ exports.constDef = require_response.constDef;
492
+ exports.contentDef = require_response.contentDef;
2243
493
  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;
494
+ exports.defineNode = require_response.defineNode;
2250
495
  exports.definePrinter = definePrinter;
2251
- exports.enumPropName = enumPropName;
2252
- exports.extractRefName = extractRefName;
2253
- exports.extractStringsFromNodes = extractStringsFromNodes;
2254
- 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;
2262
- exports.isStringType = isStringType;
2263
- exports.mediaTypes = mediaTypes;
2264
- exports.mergeAdjacentObjects = mergeAdjacentObjects;
2265
- exports.narrowSchema = narrowSchema;
2266
- exports.nodeKinds = nodeKinds;
2267
- exports.resolveRefName = resolveRefName;
2268
- exports.schemaTypes = schemaTypes;
2269
- exports.setDiscriminatorEnum = setDiscriminatorEnum;
2270
- exports.setEnumName = setEnumName;
2271
- exports.simplifyUnion = simplifyUnion;
2272
- exports.syncOptionality = syncOptionality;
2273
- exports.syncSchemaRef = syncSchemaRef;
2274
- exports.transform = transform;
2275
- exports.walk = walk;
496
+ exports.defineSchemaDialect = defineSchemaDialect;
497
+ exports.exportDef = require_response.exportDef;
498
+ exports.extractStringsFromNodes = require_response.extractStringsFromNodes;
499
+ Object.defineProperty(exports, "factory", {
500
+ enumerable: true,
501
+ get: function() {
502
+ return require_factory.factory_exports;
503
+ }
504
+ });
505
+ exports.fileDef = require_response.fileDef;
506
+ exports.functionDef = require_response.functionDef;
507
+ exports.functionParameterDef = require_response.functionParameterDef;
508
+ exports.functionParametersDef = require_response.functionParametersDef;
509
+ exports.httpMethods = require_utils.httpMethods;
510
+ exports.importDef = require_response.importDef;
511
+ exports.indexedAccessTypeDef = require_response.indexedAccessTypeDef;
512
+ exports.inputDef = require_response.inputDef;
513
+ exports.isHttpOperationNode = require_utils.isHttpOperationNode;
514
+ exports.jsxDef = require_response.jsxDef;
515
+ exports.mergeAdjacentObjectsLazy = require_utils.mergeAdjacentObjectsLazy;
516
+ exports.narrowSchema = require_utils.narrowSchema;
517
+ exports.nodeDefs = require_utils.nodeDefs;
518
+ exports.objectBindingPatternDef = require_response.objectBindingPatternDef;
519
+ exports.operationDef = require_response.operationDef;
520
+ exports.outputDef = require_response.outputDef;
521
+ exports.parameterDef = require_response.parameterDef;
522
+ exports.propertyDef = require_response.propertyDef;
523
+ exports.requestBodyDef = require_response.requestBodyDef;
524
+ exports.responseDef = require_response.responseDef;
525
+ exports.schemaDef = require_response.schemaDef;
526
+ exports.schemaTypes = require_utils.schemaTypes;
527
+ exports.setDiscriminatorEnum = require_utils.setDiscriminatorEnum;
528
+ exports.setEnumName = require_utils.setEnumName;
529
+ exports.signatureOf = signatureOf;
530
+ exports.simplifyUnion = require_utils.simplifyUnion;
531
+ exports.sourceDef = require_response.sourceDef;
532
+ exports.syncOptionality = require_response.syncOptionality;
533
+ exports.textDef = require_response.textDef;
534
+ exports.transform = require_utils.transform;
535
+ exports.typeDef = require_response.typeDef;
536
+ exports.typeLiteralDef = require_response.typeLiteralDef;
537
+ exports.walk = require_utils.walk;
2276
538
 
2277
539
  //# sourceMappingURL=index.cjs.map