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