@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
|
@@ -0,0 +1,1389 @@
|
|
|
1
|
+
import "./chunk-CNktS9qV.js";
|
|
2
|
+
import { A as contentDef, D as fileDef, E as exportDef, G as typeDef, H as functionDef, K as createProperty, M as arrowFunctionDef, N as breakDef, O as importDef, P as constDef, Q as schemaDef, S as typeLiteralDef, U as jsxDef, W as textDef, X as pascalCase, Y as camelCase, Z as createSchema, _ as createTypeLiteral, b as indexedAccessTypeDef, c as operationDef, f as inputDef, h as createIndexedAccessType, i as parameterDef, k as sourceDef, m as createFunctionParameters, n as responseDef, o as outputDef, p as createFunctionParameter, q as propertyDef, u as requestBodyDef, v as functionParameterDef, x as objectBindingPatternDef, y as functionParametersDef } from "./response-DKxTr522.js";
|
|
3
|
+
//#region src/constants.ts
|
|
4
|
+
const visitorDepths = {
|
|
5
|
+
shallow: "shallow",
|
|
6
|
+
deep: "deep"
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Schema type discriminators used by all AST schema nodes.
|
|
10
|
+
*
|
|
11
|
+
* Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
|
|
12
|
+
* Call `isScalarPrimitive()` to check for the scalar types.
|
|
13
|
+
*/
|
|
14
|
+
const schemaTypes = {
|
|
15
|
+
/**
|
|
16
|
+
* Text value.
|
|
17
|
+
*/
|
|
18
|
+
string: "string",
|
|
19
|
+
/**
|
|
20
|
+
* Floating-point number (`float`, `double`).
|
|
21
|
+
*/
|
|
22
|
+
number: "number",
|
|
23
|
+
/**
|
|
24
|
+
* Whole number (`int32`). Use `bigint` for `int64`.
|
|
25
|
+
*/
|
|
26
|
+
integer: "integer",
|
|
27
|
+
/**
|
|
28
|
+
* 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
|
|
29
|
+
*/
|
|
30
|
+
bigint: "bigint",
|
|
31
|
+
/**
|
|
32
|
+
* Boolean value.
|
|
33
|
+
*/
|
|
34
|
+
boolean: "boolean",
|
|
35
|
+
/**
|
|
36
|
+
* Explicit null value.
|
|
37
|
+
*/
|
|
38
|
+
null: "null",
|
|
39
|
+
/**
|
|
40
|
+
* Any value (no type restriction).
|
|
41
|
+
*/
|
|
42
|
+
any: "any",
|
|
43
|
+
/**
|
|
44
|
+
* Unknown value (must be narrowed before usage).
|
|
45
|
+
*/
|
|
46
|
+
unknown: "unknown",
|
|
47
|
+
/**
|
|
48
|
+
* No return value (`void`).
|
|
49
|
+
*/
|
|
50
|
+
void: "void",
|
|
51
|
+
/**
|
|
52
|
+
* Object with named properties.
|
|
53
|
+
*/
|
|
54
|
+
object: "object",
|
|
55
|
+
/**
|
|
56
|
+
* Sequential list of items.
|
|
57
|
+
*/
|
|
58
|
+
array: "array",
|
|
59
|
+
/**
|
|
60
|
+
* Fixed-length list with position-specific items.
|
|
61
|
+
*/
|
|
62
|
+
tuple: "tuple",
|
|
63
|
+
/**
|
|
64
|
+
* "One of" multiple schema members.
|
|
65
|
+
*/
|
|
66
|
+
union: "union",
|
|
67
|
+
/**
|
|
68
|
+
* "All of" multiple schema members.
|
|
69
|
+
*/
|
|
70
|
+
intersection: "intersection",
|
|
71
|
+
/**
|
|
72
|
+
* Enum schema.
|
|
73
|
+
*/
|
|
74
|
+
enum: "enum",
|
|
75
|
+
/**
|
|
76
|
+
* Reference to another schema.
|
|
77
|
+
*/
|
|
78
|
+
ref: "ref",
|
|
79
|
+
/**
|
|
80
|
+
* Calendar date (for example `2026-03-24`).
|
|
81
|
+
*/
|
|
82
|
+
date: "date",
|
|
83
|
+
/**
|
|
84
|
+
* Date-time value (for example `2026-03-24T09:00:00Z`).
|
|
85
|
+
*/
|
|
86
|
+
datetime: "datetime",
|
|
87
|
+
/**
|
|
88
|
+
* Time-only value (for example `09:00:00`).
|
|
89
|
+
*/
|
|
90
|
+
time: "time",
|
|
91
|
+
/**
|
|
92
|
+
* UUID value.
|
|
93
|
+
*/
|
|
94
|
+
uuid: "uuid",
|
|
95
|
+
/**
|
|
96
|
+
* Email address value.
|
|
97
|
+
*/
|
|
98
|
+
email: "email",
|
|
99
|
+
/**
|
|
100
|
+
* URL value.
|
|
101
|
+
*/
|
|
102
|
+
url: "url",
|
|
103
|
+
/**
|
|
104
|
+
* IPv4 address value.
|
|
105
|
+
*/
|
|
106
|
+
ipv4: "ipv4",
|
|
107
|
+
/**
|
|
108
|
+
* IPv6 address value.
|
|
109
|
+
*/
|
|
110
|
+
ipv6: "ipv6",
|
|
111
|
+
/**
|
|
112
|
+
* Binary/blob value.
|
|
113
|
+
*/
|
|
114
|
+
blob: "blob",
|
|
115
|
+
/**
|
|
116
|
+
* Impossible value (`never`).
|
|
117
|
+
*/
|
|
118
|
+
never: "never"
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Scalar primitive schema types used for union simplification and type narrowing.
|
|
122
|
+
*/
|
|
123
|
+
const SCALAR_PRIMITIVE_TYPES = new Set([
|
|
124
|
+
"string",
|
|
125
|
+
"number",
|
|
126
|
+
"integer",
|
|
127
|
+
"bigint",
|
|
128
|
+
"boolean"
|
|
129
|
+
]);
|
|
130
|
+
/**
|
|
131
|
+
* Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
|
|
132
|
+
* (for example `string | number | boolean`).
|
|
133
|
+
*/
|
|
134
|
+
function isScalarPrimitive(type) {
|
|
135
|
+
return SCALAR_PRIMITIVE_TYPES.has(type);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* HTTP method identifiers used by operation nodes.
|
|
139
|
+
*/
|
|
140
|
+
const httpMethods = {
|
|
141
|
+
get: "GET",
|
|
142
|
+
post: "POST",
|
|
143
|
+
put: "PUT",
|
|
144
|
+
patch: "PATCH",
|
|
145
|
+
delete: "DELETE",
|
|
146
|
+
head: "HEAD",
|
|
147
|
+
options: "OPTIONS",
|
|
148
|
+
trace: "TRACE"
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* One indentation level, derived from {@link INDENT_SIZE}.
|
|
152
|
+
*/
|
|
153
|
+
const INDENT = Array.from({ length: 2 }, () => " ").join("");
|
|
154
|
+
//#endregion
|
|
155
|
+
//#region ../../internals/utils/src/promise.ts
|
|
156
|
+
/**
|
|
157
|
+
* Wraps `factory` with a keyed cache backed by the provided store.
|
|
158
|
+
*
|
|
159
|
+
* Pass a `WeakMap` for object keys (results are GC-eligible when the key is
|
|
160
|
+
* collected) or a `Map` for primitive keys. For multi-argument functions,
|
|
161
|
+
* nest two `memoize` calls — the outer keyed by the first argument, the
|
|
162
|
+
* inner (created once per outer miss) keyed by the second.
|
|
163
|
+
*
|
|
164
|
+
* Because the cache is owned by the caller, it can be shared, inspected, or
|
|
165
|
+
* cleared independently of the memoized function.
|
|
166
|
+
*
|
|
167
|
+
* @example Single WeakMap key
|
|
168
|
+
* ```ts
|
|
169
|
+
* const cache = new WeakMap<SchemaNode, Set<string>>()
|
|
170
|
+
* const getRefs = memoize(cache, (node) => collectRefs(node))
|
|
171
|
+
* ```
|
|
172
|
+
*
|
|
173
|
+
* @example Single Map key (primitive)
|
|
174
|
+
* ```ts
|
|
175
|
+
* const cache = new Map<string, Resolver>()
|
|
176
|
+
* const getResolver = memoize(cache, (name) => buildResolver(name))
|
|
177
|
+
* ```
|
|
178
|
+
*
|
|
179
|
+
* @example Two-level (object + primitive)
|
|
180
|
+
* ```ts
|
|
181
|
+
* const outer = new WeakMap<Params[], Map<string, Params[]>>()
|
|
182
|
+
* const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
|
|
183
|
+
* fn(params)('camelcase')
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
function memoize(store, factory) {
|
|
187
|
+
return (key) => {
|
|
188
|
+
if (store.has(key)) return store.get(key);
|
|
189
|
+
const value = factory(key);
|
|
190
|
+
store.set(key, value);
|
|
191
|
+
return value;
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region ../../internals/utils/src/reserved.ts
|
|
196
|
+
/**
|
|
197
|
+
* JavaScript and Java reserved words.
|
|
198
|
+
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
199
|
+
*/
|
|
200
|
+
const reservedWords = new Set([
|
|
201
|
+
"abstract",
|
|
202
|
+
"arguments",
|
|
203
|
+
"boolean",
|
|
204
|
+
"break",
|
|
205
|
+
"byte",
|
|
206
|
+
"case",
|
|
207
|
+
"catch",
|
|
208
|
+
"char",
|
|
209
|
+
"class",
|
|
210
|
+
"const",
|
|
211
|
+
"continue",
|
|
212
|
+
"debugger",
|
|
213
|
+
"default",
|
|
214
|
+
"delete",
|
|
215
|
+
"do",
|
|
216
|
+
"double",
|
|
217
|
+
"else",
|
|
218
|
+
"enum",
|
|
219
|
+
"eval",
|
|
220
|
+
"export",
|
|
221
|
+
"extends",
|
|
222
|
+
"false",
|
|
223
|
+
"final",
|
|
224
|
+
"finally",
|
|
225
|
+
"float",
|
|
226
|
+
"for",
|
|
227
|
+
"function",
|
|
228
|
+
"goto",
|
|
229
|
+
"if",
|
|
230
|
+
"implements",
|
|
231
|
+
"import",
|
|
232
|
+
"in",
|
|
233
|
+
"instanceof",
|
|
234
|
+
"int",
|
|
235
|
+
"interface",
|
|
236
|
+
"let",
|
|
237
|
+
"long",
|
|
238
|
+
"native",
|
|
239
|
+
"new",
|
|
240
|
+
"null",
|
|
241
|
+
"package",
|
|
242
|
+
"private",
|
|
243
|
+
"protected",
|
|
244
|
+
"public",
|
|
245
|
+
"return",
|
|
246
|
+
"short",
|
|
247
|
+
"static",
|
|
248
|
+
"super",
|
|
249
|
+
"switch",
|
|
250
|
+
"synchronized",
|
|
251
|
+
"this",
|
|
252
|
+
"throw",
|
|
253
|
+
"throws",
|
|
254
|
+
"transient",
|
|
255
|
+
"true",
|
|
256
|
+
"try",
|
|
257
|
+
"typeof",
|
|
258
|
+
"var",
|
|
259
|
+
"void",
|
|
260
|
+
"volatile",
|
|
261
|
+
"while",
|
|
262
|
+
"with",
|
|
263
|
+
"yield",
|
|
264
|
+
"Array",
|
|
265
|
+
"Date",
|
|
266
|
+
"hasOwnProperty",
|
|
267
|
+
"Infinity",
|
|
268
|
+
"isFinite",
|
|
269
|
+
"isNaN",
|
|
270
|
+
"isPrototypeOf",
|
|
271
|
+
"length",
|
|
272
|
+
"Math",
|
|
273
|
+
"name",
|
|
274
|
+
"NaN",
|
|
275
|
+
"Number",
|
|
276
|
+
"Object",
|
|
277
|
+
"prototype",
|
|
278
|
+
"String",
|
|
279
|
+
"toString",
|
|
280
|
+
"undefined",
|
|
281
|
+
"valueOf"
|
|
282
|
+
]);
|
|
283
|
+
/**
|
|
284
|
+
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* ```ts
|
|
288
|
+
* isValidVarName('status') // true
|
|
289
|
+
* isValidVarName('class') // false (reserved word)
|
|
290
|
+
* isValidVarName('42foo') // false (starts with digit)
|
|
291
|
+
* ```
|
|
292
|
+
*/
|
|
293
|
+
function isValidVarName(name) {
|
|
294
|
+
if (!name || reservedWords.has(name)) return false;
|
|
295
|
+
return isIdentifier(name);
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
|
|
299
|
+
*
|
|
300
|
+
* Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
|
|
301
|
+
* even though they are not valid variable names, so use this (not {@link isValidVarName}) when
|
|
302
|
+
* deciding whether an object key needs quoting.
|
|
303
|
+
*
|
|
304
|
+
* @example
|
|
305
|
+
* ```ts
|
|
306
|
+
* isIdentifier('name') // true
|
|
307
|
+
* isIdentifier('x-total')// false
|
|
308
|
+
* ```
|
|
309
|
+
*/
|
|
310
|
+
function isIdentifier(name) {
|
|
311
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
312
|
+
}
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region ../../internals/utils/src/string.ts
|
|
315
|
+
/**
|
|
316
|
+
* Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
|
|
317
|
+
* any backslash or single quote in the content.
|
|
318
|
+
*
|
|
319
|
+
* @example
|
|
320
|
+
* ```ts
|
|
321
|
+
* singleQuote('foo') // "'foo'"
|
|
322
|
+
* singleQuote("o'clock") // "'o\\'clock'"
|
|
323
|
+
* ```
|
|
324
|
+
*/
|
|
325
|
+
function singleQuote(value) {
|
|
326
|
+
if (value === void 0 || value === null) return "''";
|
|
327
|
+
return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
328
|
+
}
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/utils/codegen.ts
|
|
331
|
+
/**
|
|
332
|
+
* Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
|
|
333
|
+
* comments so callers always get a usable string.
|
|
334
|
+
*
|
|
335
|
+
* @example
|
|
336
|
+
* ```ts
|
|
337
|
+
* buildJSDoc(['@type string', '@example hello'])
|
|
338
|
+
* // '/**\n * @type string\n * @example hello\n *\/\n '
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
function buildJSDoc(comments, options = {}) {
|
|
342
|
+
const { indent = " * ", suffix = "\n ", fallback = " " } = options;
|
|
343
|
+
if (comments.length === 0) return fallback;
|
|
344
|
+
return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
|
|
348
|
+
*/
|
|
349
|
+
function indentLines(text) {
|
|
350
|
+
if (!text) return "";
|
|
351
|
+
return text.split("\n").map((line) => line.trim() ? `${INDENT}${line}` : "").join("\n");
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
|
|
355
|
+
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
|
|
356
|
+
*
|
|
357
|
+
* @example
|
|
358
|
+
* ```ts
|
|
359
|
+
* objectKey('name') // 'name'
|
|
360
|
+
* objectKey('x-total') // "'x-total'"
|
|
361
|
+
* ```
|
|
362
|
+
*/
|
|
363
|
+
function objectKey(name) {
|
|
364
|
+
return isIdentifier(name) ? name : singleQuote(name);
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
368
|
+
* level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
|
|
369
|
+
* so callers never re-parse the generated code. A trailing comma is added per entry to match the
|
|
370
|
+
* formatter's multi-line style.
|
|
371
|
+
*
|
|
372
|
+
* @example
|
|
373
|
+
* ```ts
|
|
374
|
+
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
375
|
+
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
376
|
+
* ```
|
|
377
|
+
*/
|
|
378
|
+
function buildObject(entries) {
|
|
379
|
+
if (entries.length === 0) return "{}";
|
|
380
|
+
return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
384
|
+
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
385
|
+
* one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
|
|
386
|
+
* `z.array([…])`, and similar member lists so objects inside them nest correctly.
|
|
387
|
+
*
|
|
388
|
+
* @example
|
|
389
|
+
* ```ts
|
|
390
|
+
* buildList(['z.string()', 'z.number()'])
|
|
391
|
+
* // '[z.string(), z.number()]'
|
|
392
|
+
* ```
|
|
393
|
+
*/
|
|
394
|
+
function buildList(items, brackets = ["[", "]"]) {
|
|
395
|
+
const [open, close] = brackets;
|
|
396
|
+
if (items.length === 0) return `${open}${close}`;
|
|
397
|
+
if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
|
|
398
|
+
return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
|
|
399
|
+
}
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/guards.ts
|
|
402
|
+
/**
|
|
403
|
+
* Narrows a `SchemaNode` to the variant that matches `type`.
|
|
404
|
+
*
|
|
405
|
+
* @example
|
|
406
|
+
* ```ts
|
|
407
|
+
* const schema = createSchema({ type: 'string' })
|
|
408
|
+
* const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
|
|
409
|
+
* ```
|
|
410
|
+
*/
|
|
411
|
+
function narrowSchema(node, type) {
|
|
412
|
+
return node?.type === type ? node : null;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
|
|
416
|
+
*
|
|
417
|
+
* @example
|
|
418
|
+
* ```ts
|
|
419
|
+
* if (isHttpOperationNode(node)) {
|
|
420
|
+
* console.log(node.method, node.path)
|
|
421
|
+
* }
|
|
422
|
+
* ```
|
|
423
|
+
*/
|
|
424
|
+
function isHttpOperationNode(node) {
|
|
425
|
+
return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
|
|
426
|
+
}
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/utils/refs.ts
|
|
429
|
+
const plainStringTypes = new Set([
|
|
430
|
+
"string",
|
|
431
|
+
"uuid",
|
|
432
|
+
"email",
|
|
433
|
+
"url",
|
|
434
|
+
"datetime"
|
|
435
|
+
]);
|
|
436
|
+
/**
|
|
437
|
+
* Returns the last path segment of a reference string.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```ts
|
|
441
|
+
* extractRefName('#/components/schemas/Pet') // 'Pet'
|
|
442
|
+
* ```
|
|
443
|
+
*/
|
|
444
|
+
function extractRefName(ref) {
|
|
445
|
+
return ref.split("/").at(-1) ?? ref;
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
|
|
449
|
+
*
|
|
450
|
+
* Returns `null` for non-ref nodes or when no name resolves.
|
|
451
|
+
*
|
|
452
|
+
* @example
|
|
453
|
+
* ```ts
|
|
454
|
+
* resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
|
|
455
|
+
* // => 'Pet'
|
|
456
|
+
* ```
|
|
457
|
+
*/
|
|
458
|
+
function resolveRefName(node) {
|
|
459
|
+
if (!node || node.type !== "ref") return null;
|
|
460
|
+
if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
|
|
461
|
+
return node.name ?? node.schema?.name ?? null;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Builds a PascalCase child schema name by joining a parent name and property name.
|
|
465
|
+
* Returns `null` when there is no parent to nest under.
|
|
466
|
+
*
|
|
467
|
+
* @example
|
|
468
|
+
* ```ts
|
|
469
|
+
* childName('Order', 'shipping_address') // 'OrderShippingAddress'
|
|
470
|
+
* childName(undefined, 'params') // null
|
|
471
|
+
* ```
|
|
472
|
+
*/
|
|
473
|
+
function childName(parentName, propName) {
|
|
474
|
+
return parentName ? pascalCase([parentName, propName].join(" ")) : null;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
|
|
478
|
+
* empty parts.
|
|
479
|
+
*
|
|
480
|
+
* @example
|
|
481
|
+
* ```ts
|
|
482
|
+
* enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
|
|
483
|
+
* ```
|
|
484
|
+
*/
|
|
485
|
+
function enumPropName(parentName, propName, enumSuffix) {
|
|
486
|
+
return pascalCase([
|
|
487
|
+
parentName,
|
|
488
|
+
propName,
|
|
489
|
+
enumSuffix
|
|
490
|
+
].filter(Boolean).join(" "));
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Type guard that returns `true` when a schema emits as a plain `string` type.
|
|
494
|
+
*
|
|
495
|
+
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
|
|
496
|
+
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
|
|
497
|
+
*/
|
|
498
|
+
function isStringType(node) {
|
|
499
|
+
if (plainStringTypes.has(node.type)) return true;
|
|
500
|
+
const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
|
|
501
|
+
if (temporal) return temporal.representation !== "date";
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Derives a {@link ParamGroupType} for a query or header group from the resolver.
|
|
506
|
+
*
|
|
507
|
+
* Returns `null` when there is no resolver, no params, or the group name equals the
|
|
508
|
+
* individual param name (so there is no real group to emit).
|
|
509
|
+
*/
|
|
510
|
+
function resolveGroupType({ node, params, group, resolver }) {
|
|
511
|
+
if (!resolver || !params.length) return null;
|
|
512
|
+
const firstParam = params[0];
|
|
513
|
+
const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
|
|
514
|
+
if (groupName === resolver.resolveParamName(node, firstParam)) return null;
|
|
515
|
+
return {
|
|
516
|
+
type: groupName,
|
|
517
|
+
optional: params.every((p) => !p.required)
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
//#endregion
|
|
521
|
+
//#region src/transformers.ts
|
|
522
|
+
/**
|
|
523
|
+
* Replaces a discriminator property's schema with a string enum of allowed values.
|
|
524
|
+
*
|
|
525
|
+
* If `node` is not an object schema, or if the property does not exist, the input
|
|
526
|
+
* node is returned as-is.
|
|
527
|
+
*
|
|
528
|
+
* @example
|
|
529
|
+
* ```ts
|
|
530
|
+
* const schema = createSchema({
|
|
531
|
+
* type: 'object',
|
|
532
|
+
* properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
|
|
533
|
+
* })
|
|
534
|
+
* const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
|
|
535
|
+
* ```
|
|
536
|
+
*/
|
|
537
|
+
function setDiscriminatorEnum({ node, propertyName, values, enumName }) {
|
|
538
|
+
const objectNode = narrowSchema(node, "object");
|
|
539
|
+
if (!objectNode?.properties?.length) return node;
|
|
540
|
+
if (!objectNode.properties.some((prop) => prop.name === propertyName)) return node;
|
|
541
|
+
return createSchema({
|
|
542
|
+
...objectNode,
|
|
543
|
+
properties: objectNode.properties.map((prop) => {
|
|
544
|
+
if (prop.name !== propertyName) return prop;
|
|
545
|
+
return createProperty({
|
|
546
|
+
...prop,
|
|
547
|
+
schema: createSchema({
|
|
548
|
+
type: "enum",
|
|
549
|
+
primitive: "string",
|
|
550
|
+
enumValues: values,
|
|
551
|
+
name: enumName,
|
|
552
|
+
readOnly: prop.schema.readOnly,
|
|
553
|
+
writeOnly: prop.schema.writeOnly
|
|
554
|
+
})
|
|
555
|
+
});
|
|
556
|
+
})
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Merges adjacent anonymous object members into a single anonymous object member.
|
|
561
|
+
*
|
|
562
|
+
* @example
|
|
563
|
+
* ```ts
|
|
564
|
+
* const merged = mergeAdjacentObjects([
|
|
565
|
+
* createSchema({ type: 'object', properties: [createProperty({ name: 'a', schema: createSchema({ type: 'string' }) })] }),
|
|
566
|
+
* createSchema({ type: 'object', properties: [createProperty({ name: 'b', schema: createSchema({ type: 'number' }) })] }),
|
|
567
|
+
* ])
|
|
568
|
+
* ```
|
|
569
|
+
*/
|
|
570
|
+
function* mergeAdjacentObjectsLazy(members) {
|
|
571
|
+
let acc;
|
|
572
|
+
for (const member of members) {
|
|
573
|
+
const objectMember = narrowSchema(member, "object");
|
|
574
|
+
if (objectMember && !objectMember.name && acc !== void 0) {
|
|
575
|
+
const accObject = narrowSchema(acc, "object");
|
|
576
|
+
if (accObject && !accObject.name) {
|
|
577
|
+
acc = createSchema({
|
|
578
|
+
...accObject,
|
|
579
|
+
properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
|
|
580
|
+
});
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (acc !== void 0) yield acc;
|
|
585
|
+
acc = member;
|
|
586
|
+
}
|
|
587
|
+
if (acc !== void 0) yield acc;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Removes enum members that are covered by broader scalar primitives in the same union.
|
|
591
|
+
*
|
|
592
|
+
* @example
|
|
593
|
+
* ```ts
|
|
594
|
+
* const simplified = simplifyUnion([
|
|
595
|
+
* createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
|
|
596
|
+
* createSchema({ type: 'string' }),
|
|
597
|
+
* ])
|
|
598
|
+
* // keeps only string member
|
|
599
|
+
* ```
|
|
600
|
+
*/
|
|
601
|
+
function simplifyUnion(members) {
|
|
602
|
+
const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
|
|
603
|
+
if (!scalarPrimitives.size) return members;
|
|
604
|
+
return members.filter((member) => {
|
|
605
|
+
const enumNode = narrowSchema(member, "enum");
|
|
606
|
+
if (!enumNode) return true;
|
|
607
|
+
const primitive = enumNode.primitive;
|
|
608
|
+
if (!primitive) return true;
|
|
609
|
+
if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
|
|
610
|
+
if (scalarPrimitives.has(primitive)) return false;
|
|
611
|
+
if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
|
|
612
|
+
return true;
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
function setEnumName(propNode, parentName, propName, enumSuffix) {
|
|
616
|
+
const enumNode = narrowSchema(propNode, "enum");
|
|
617
|
+
if (enumNode?.primitive === "boolean") return {
|
|
618
|
+
...propNode,
|
|
619
|
+
name: null
|
|
620
|
+
};
|
|
621
|
+
if (enumNode) return {
|
|
622
|
+
...propNode,
|
|
623
|
+
name: enumPropName(parentName, propName, enumSuffix)
|
|
624
|
+
};
|
|
625
|
+
return propNode;
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
|
|
629
|
+
*
|
|
630
|
+
* Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
|
|
631
|
+
* the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
|
|
632
|
+
*
|
|
633
|
+
* @example
|
|
634
|
+
* ```ts
|
|
635
|
+
* // Ref with description override
|
|
636
|
+
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
|
|
637
|
+
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
|
|
638
|
+
* ```
|
|
639
|
+
*/
|
|
640
|
+
function syncSchemaRef(node) {
|
|
641
|
+
const ref = narrowSchema(node, "ref");
|
|
642
|
+
if (!ref) return node;
|
|
643
|
+
if (!ref.schema) return node;
|
|
644
|
+
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
|
|
645
|
+
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
|
|
646
|
+
return createSchema({
|
|
647
|
+
...ref.schema,
|
|
648
|
+
...definedOverrides
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
//#endregion
|
|
652
|
+
//#region src/utils/strings.ts
|
|
653
|
+
/**
|
|
654
|
+
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
655
|
+
* Returns the string unchanged when no balanced quote pair is found.
|
|
656
|
+
*
|
|
657
|
+
* @example
|
|
658
|
+
* ```ts
|
|
659
|
+
* trimQuotes('"hello"') // 'hello'
|
|
660
|
+
* trimQuotes('hello') // 'hello'
|
|
661
|
+
* ```
|
|
662
|
+
*/
|
|
663
|
+
function trimQuotes(text) {
|
|
664
|
+
if (text.length >= 2) {
|
|
665
|
+
const first = text[0];
|
|
666
|
+
const last = text[text.length - 1];
|
|
667
|
+
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
|
|
668
|
+
}
|
|
669
|
+
return text;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
|
|
673
|
+
*
|
|
674
|
+
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
|
|
675
|
+
* code matches the repo style without a formatter.
|
|
676
|
+
*
|
|
677
|
+
* @example
|
|
678
|
+
* ```ts
|
|
679
|
+
* stringify('hello') // "'hello'"
|
|
680
|
+
* stringify('"hello"') // "'hello'"
|
|
681
|
+
* ```
|
|
682
|
+
*/
|
|
683
|
+
function stringify(value) {
|
|
684
|
+
if (value === void 0 || value === null) return "''";
|
|
685
|
+
return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
|
|
689
|
+
* and the Unicode line terminators U+2028 and U+2029.
|
|
690
|
+
*
|
|
691
|
+
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
692
|
+
*
|
|
693
|
+
* @example
|
|
694
|
+
* ```ts
|
|
695
|
+
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
696
|
+
* ```
|
|
697
|
+
*/
|
|
698
|
+
function jsStringEscape(input) {
|
|
699
|
+
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
|
|
700
|
+
switch (character) {
|
|
701
|
+
case "\"":
|
|
702
|
+
case "'":
|
|
703
|
+
case "\\": return `\\${character}`;
|
|
704
|
+
case "\n": return "\\n";
|
|
705
|
+
case "\r": return "\\r";
|
|
706
|
+
case "\u2028": return "\\u2028";
|
|
707
|
+
case "\u2029": return "\\u2029";
|
|
708
|
+
default: return "";
|
|
709
|
+
}
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
|
|
714
|
+
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
|
|
715
|
+
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
|
|
716
|
+
*
|
|
717
|
+
* @example
|
|
718
|
+
* ```ts
|
|
719
|
+
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
720
|
+
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
721
|
+
* ```
|
|
722
|
+
*/
|
|
723
|
+
function toRegExpString(text, func = "RegExp") {
|
|
724
|
+
const raw = trimQuotes(text);
|
|
725
|
+
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
|
|
726
|
+
const replacementTarget = match?.[1] ?? "";
|
|
727
|
+
const matchedFlags = match?.[2];
|
|
728
|
+
const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
|
|
729
|
+
const { source, flags } = new RegExp(cleaned, matchedFlags);
|
|
730
|
+
if (func === null) return `/${source}/${flags}`;
|
|
731
|
+
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
|
|
735
|
+
* objects recurse with fixed indentation, so the result drops straight into an object literal
|
|
736
|
+
* without re-parsing.
|
|
737
|
+
*
|
|
738
|
+
* @example
|
|
739
|
+
* ```ts
|
|
740
|
+
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
|
|
741
|
+
* // 'foo: bar,\nnested: {\n a: 1\n }'
|
|
742
|
+
* ```
|
|
743
|
+
*/
|
|
744
|
+
function stringifyObject(value) {
|
|
745
|
+
return Object.entries(value).map(([key, val]) => {
|
|
746
|
+
if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
|
|
747
|
+
return `${key}: ${val}`;
|
|
748
|
+
}).filter(Boolean).join(",\n");
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
|
|
752
|
+
* `accessor`. Returns `null` for an empty path.
|
|
753
|
+
*
|
|
754
|
+
* @example
|
|
755
|
+
* ```ts
|
|
756
|
+
* getNestedAccessor('pagination.next.id', 'lastPage')
|
|
757
|
+
* // "lastPage?.['pagination']?.['next']?.['id']"
|
|
758
|
+
* ```
|
|
759
|
+
*/
|
|
760
|
+
function getNestedAccessor(param, accessor) {
|
|
761
|
+
const parts = Array.isArray(param) ? param : param.split(".");
|
|
762
|
+
if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
|
|
763
|
+
return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
|
|
764
|
+
}
|
|
765
|
+
//#endregion
|
|
766
|
+
//#region src/registry.ts
|
|
767
|
+
/**
|
|
768
|
+
* Every node definition. Adding a node means adding its `defineNode` to one
|
|
769
|
+
* `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
|
|
770
|
+
*/
|
|
771
|
+
const nodeDefs = [
|
|
772
|
+
inputDef,
|
|
773
|
+
outputDef,
|
|
774
|
+
operationDef,
|
|
775
|
+
requestBodyDef,
|
|
776
|
+
contentDef,
|
|
777
|
+
responseDef,
|
|
778
|
+
schemaDef,
|
|
779
|
+
propertyDef,
|
|
780
|
+
parameterDef,
|
|
781
|
+
functionParameterDef,
|
|
782
|
+
functionParametersDef,
|
|
783
|
+
typeLiteralDef,
|
|
784
|
+
indexedAccessTypeDef,
|
|
785
|
+
objectBindingPatternDef,
|
|
786
|
+
constDef,
|
|
787
|
+
typeDef,
|
|
788
|
+
functionDef,
|
|
789
|
+
arrowFunctionDef,
|
|
790
|
+
textDef,
|
|
791
|
+
breakDef,
|
|
792
|
+
jsxDef,
|
|
793
|
+
importDef,
|
|
794
|
+
exportDef,
|
|
795
|
+
sourceDef,
|
|
796
|
+
fileDef
|
|
797
|
+
];
|
|
798
|
+
//#endregion
|
|
799
|
+
//#region src/visitor.ts
|
|
800
|
+
/**
|
|
801
|
+
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
|
|
802
|
+
* Derived from each definition's `children`.
|
|
803
|
+
*/
|
|
804
|
+
const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
|
|
805
|
+
/**
|
|
806
|
+
* Maps a node kind to the matching visitor callback name. Derived from each
|
|
807
|
+
* definition's `visitorKey`.
|
|
808
|
+
*/
|
|
809
|
+
const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
|
|
810
|
+
/**
|
|
811
|
+
* Per-kind builders rerun after children are rebuilt. Derived from each
|
|
812
|
+
* definition's `rebuild` flag.
|
|
813
|
+
*/
|
|
814
|
+
const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
|
|
815
|
+
/**
|
|
816
|
+
* Creates a small async concurrency limiter.
|
|
817
|
+
*
|
|
818
|
+
* At most `concurrency` tasks are in flight at once. Extra tasks are queued.
|
|
819
|
+
*
|
|
820
|
+
* @example
|
|
821
|
+
* ```ts
|
|
822
|
+
* const limit = createLimit(2)
|
|
823
|
+
* for (const task of [taskA, taskB, taskC]) {
|
|
824
|
+
* await limit(() => task())
|
|
825
|
+
* }
|
|
826
|
+
* // only 2 tasks run at the same time
|
|
827
|
+
* ```
|
|
828
|
+
*/
|
|
829
|
+
function createLimit(concurrency) {
|
|
830
|
+
let active = 0;
|
|
831
|
+
const queue = [];
|
|
832
|
+
function next() {
|
|
833
|
+
if (active < concurrency && queue.length > 0) {
|
|
834
|
+
active++;
|
|
835
|
+
queue.shift()();
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
return function limit(fn) {
|
|
839
|
+
return new Promise((resolve, reject) => {
|
|
840
|
+
queue.push(() => {
|
|
841
|
+
Promise.resolve(fn()).then(resolve, reject).finally(() => {
|
|
842
|
+
active--;
|
|
843
|
+
next();
|
|
844
|
+
});
|
|
845
|
+
});
|
|
846
|
+
next();
|
|
847
|
+
});
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
const visitorKeysByKind = VISITOR_KEYS;
|
|
851
|
+
/**
|
|
852
|
+
* Returns `true` when `value` is an AST node (an object carrying a `kind`).
|
|
853
|
+
*/
|
|
854
|
+
function isNode(value) {
|
|
855
|
+
return typeof value === "object" && value !== null && "kind" in value;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
|
|
859
|
+
*
|
|
860
|
+
* `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* ```ts
|
|
864
|
+
* const children = getChildren(operationNode, true)
|
|
865
|
+
* // returns parameters, the request body, and responses
|
|
866
|
+
* ```
|
|
867
|
+
*/
|
|
868
|
+
function* getChildren(node, recurse) {
|
|
869
|
+
if (node.kind === "Schema" && !recurse) return;
|
|
870
|
+
const keys = visitorKeysByKind[node.kind];
|
|
871
|
+
if (!keys) return;
|
|
872
|
+
const record = node;
|
|
873
|
+
for (const key of keys) {
|
|
874
|
+
const value = record[key];
|
|
875
|
+
if (Array.isArray(value)) {
|
|
876
|
+
for (const item of value) if (isNode(item)) yield item;
|
|
877
|
+
} else if (isNode(value)) yield value;
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Runs the visitor callback that matches `node.kind` with the traversal
|
|
882
|
+
* context. The result is a replacement node, a collected value, or `undefined`
|
|
883
|
+
* when no callback is registered for the kind.
|
|
884
|
+
*
|
|
885
|
+
* Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
|
|
886
|
+
* in one place. `TResult` is the caller's expected return: the same node type
|
|
887
|
+
* for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
|
|
888
|
+
*/
|
|
889
|
+
function applyVisitor(node, visitor, parent) {
|
|
890
|
+
const key = VISITOR_KEY_BY_KIND[node.kind];
|
|
891
|
+
if (!key) return void 0;
|
|
892
|
+
const fn = visitor[key];
|
|
893
|
+
return fn?.(node, { parent });
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Async depth-first traversal for side effects. Visitor return values are
|
|
897
|
+
* ignored. Use `transform` when you want to rewrite nodes.
|
|
898
|
+
*
|
|
899
|
+
* Sibling nodes at each depth run concurrently up to `options.concurrency`
|
|
900
|
+
* (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
|
|
901
|
+
* work. Lower values reduce memory pressure.
|
|
902
|
+
*
|
|
903
|
+
* @example Log every operation
|
|
904
|
+
* ```ts
|
|
905
|
+
* await walk(root, {
|
|
906
|
+
* operation(node) {
|
|
907
|
+
* console.log(node.operationId)
|
|
908
|
+
* },
|
|
909
|
+
* })
|
|
910
|
+
* ```
|
|
911
|
+
*
|
|
912
|
+
* @example Only visit the root node
|
|
913
|
+
* ```ts
|
|
914
|
+
* await walk(root, { depth: 'shallow', input: () => {} })
|
|
915
|
+
* ```
|
|
916
|
+
*/
|
|
917
|
+
async function walk(node, options) {
|
|
918
|
+
return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
|
|
919
|
+
}
|
|
920
|
+
async function _walk(node, visitor, recurse, limit, parent) {
|
|
921
|
+
await limit(() => applyVisitor(node, visitor, parent));
|
|
922
|
+
const children = Array.from(getChildren(node, recurse));
|
|
923
|
+
if (children.length === 0) return;
|
|
924
|
+
await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
|
|
925
|
+
}
|
|
926
|
+
function transform(node, options) {
|
|
927
|
+
const { depth, parent, ...visitor } = options;
|
|
928
|
+
const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
|
|
929
|
+
const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
|
|
930
|
+
if (rebuilt === node) return node;
|
|
931
|
+
const rebuild = nodeRebuilders[rebuilt.kind];
|
|
932
|
+
return rebuild ? rebuild(rebuilt) : rebuilt;
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
|
|
936
|
+
* each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
|
|
937
|
+
* `Schema` children are skipped in shallow mode.
|
|
938
|
+
*/
|
|
939
|
+
function transformChildren(node, options, recurse) {
|
|
940
|
+
if (node.kind === "Schema" && !recurse) return node;
|
|
941
|
+
const keys = visitorKeysByKind[node.kind];
|
|
942
|
+
if (!keys) return node;
|
|
943
|
+
const record = node;
|
|
944
|
+
const childOptions = {
|
|
945
|
+
...options,
|
|
946
|
+
parent: node
|
|
947
|
+
};
|
|
948
|
+
let updates;
|
|
949
|
+
for (const key of keys) {
|
|
950
|
+
if (!(key in record)) continue;
|
|
951
|
+
const value = record[key];
|
|
952
|
+
if (Array.isArray(value)) {
|
|
953
|
+
let changed = false;
|
|
954
|
+
const mapped = value.map((item) => {
|
|
955
|
+
if (!isNode(item)) return item;
|
|
956
|
+
const next = transform(item, childOptions);
|
|
957
|
+
if (next !== item) changed = true;
|
|
958
|
+
return next;
|
|
959
|
+
});
|
|
960
|
+
if (changed) (updates ??= {})[key] = mapped;
|
|
961
|
+
} else if (isNode(value)) {
|
|
962
|
+
const next = transform(value, childOptions);
|
|
963
|
+
if (next !== value) (updates ??= {})[key] = next;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
return updates ? {
|
|
967
|
+
...node,
|
|
968
|
+
...updates
|
|
969
|
+
} : node;
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Lazy depth-first collection pass. Yields every non-null value returned by
|
|
973
|
+
* the visitor callbacks. Use `collect` for the eager array form.
|
|
974
|
+
*
|
|
975
|
+
* @example Collect every operationId
|
|
976
|
+
* ```ts
|
|
977
|
+
* const ids: string[] = []
|
|
978
|
+
* for (const id of collectLazy<string>(root, {
|
|
979
|
+
* operation(node) {
|
|
980
|
+
* return node.operationId
|
|
981
|
+
* },
|
|
982
|
+
* })) {
|
|
983
|
+
* ids.push(id)
|
|
984
|
+
* }
|
|
985
|
+
* ```
|
|
986
|
+
*/
|
|
987
|
+
function* collectLazy(node, options) {
|
|
988
|
+
const { depth, parent, ...visitor } = options;
|
|
989
|
+
const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
|
|
990
|
+
const v = applyVisitor(node, visitor, parent);
|
|
991
|
+
if (v != null) yield v;
|
|
992
|
+
for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
|
|
993
|
+
...options,
|
|
994
|
+
parent: node
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* Eager depth-first collection pass. Gathers every non-null value the visitor
|
|
999
|
+
* callbacks return into an array.
|
|
1000
|
+
*
|
|
1001
|
+
* @example Collect every operationId
|
|
1002
|
+
* ```ts
|
|
1003
|
+
* const ids = collect<string>(root, {
|
|
1004
|
+
* operation(node) {
|
|
1005
|
+
* return node.operationId
|
|
1006
|
+
* },
|
|
1007
|
+
* })
|
|
1008
|
+
* ```
|
|
1009
|
+
*/
|
|
1010
|
+
function collect(node, options) {
|
|
1011
|
+
return Array.from(collectLazy(node, options));
|
|
1012
|
+
}
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region src/utils/schemaGraph.ts
|
|
1015
|
+
/**
|
|
1016
|
+
* Collects every named schema referenced transitively from a node through its ref edges.
|
|
1017
|
+
*
|
|
1018
|
+
* Refs are followed by name only, so the resolved `node.schema` is never traversed inline.
|
|
1019
|
+
*
|
|
1020
|
+
* @example Collect refs from a single schema
|
|
1021
|
+
* ```ts
|
|
1022
|
+
* const names = collectReferencedSchemaNames(petSchema)
|
|
1023
|
+
* // → Set { 'Category', 'Tag' }
|
|
1024
|
+
* ```
|
|
1025
|
+
*
|
|
1026
|
+
* @example Accumulate refs from multiple schemas into one set
|
|
1027
|
+
* ```ts
|
|
1028
|
+
* const out = new Set<string>()
|
|
1029
|
+
* for (const schema of schemas) {
|
|
1030
|
+
* collectReferencedSchemaNames(schema, out)
|
|
1031
|
+
* }
|
|
1032
|
+
* ```
|
|
1033
|
+
*/
|
|
1034
|
+
const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
|
|
1035
|
+
const refs = /* @__PURE__ */ new Set();
|
|
1036
|
+
collect(node, { schema(child) {
|
|
1037
|
+
if (child.type === "ref") {
|
|
1038
|
+
const name = resolveRefName(child);
|
|
1039
|
+
if (name) refs.add(name);
|
|
1040
|
+
}
|
|
1041
|
+
} });
|
|
1042
|
+
return refs;
|
|
1043
|
+
});
|
|
1044
|
+
function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
|
|
1045
|
+
if (!node) return out;
|
|
1046
|
+
for (const name of collectSchemaRefs(node)) out.add(name);
|
|
1047
|
+
return out;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Collects the names of all top-level schemas transitively used by a set of operations.
|
|
1051
|
+
*
|
|
1052
|
+
* An operation uses a schema when its parameters, request body, or responses reference it, directly
|
|
1053
|
+
* or through other named schemas. The walk is iterative, so reference cycles are safe.
|
|
1054
|
+
*
|
|
1055
|
+
* Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
|
|
1056
|
+
*
|
|
1057
|
+
* @example Only generate schemas referenced by included operations
|
|
1058
|
+
* ```ts
|
|
1059
|
+
* const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
|
|
1060
|
+
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1061
|
+
*
|
|
1062
|
+
* for (const schema of schemas) {
|
|
1063
|
+
* if (schema.name && !allowed.has(schema.name)) continue
|
|
1064
|
+
* // … generate schema
|
|
1065
|
+
* }
|
|
1066
|
+
* ```
|
|
1067
|
+
*/
|
|
1068
|
+
const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
|
|
1069
|
+
function computeUsedSchemaNames(operations, schemas) {
|
|
1070
|
+
const schemaMap = /* @__PURE__ */ new Map();
|
|
1071
|
+
for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
|
|
1072
|
+
const result = /* @__PURE__ */ new Set();
|
|
1073
|
+
function visitSchema(schema) {
|
|
1074
|
+
const directRefs = collectReferencedSchemaNames(schema);
|
|
1075
|
+
for (const name of directRefs) if (!result.has(name)) {
|
|
1076
|
+
result.add(name);
|
|
1077
|
+
const namedSchema = schemaMap.get(name);
|
|
1078
|
+
if (namedSchema) visitSchema(namedSchema);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
for (const op of operations) for (const schema of collectLazy(op, {
|
|
1082
|
+
depth: "shallow",
|
|
1083
|
+
schema: (node) => node
|
|
1084
|
+
})) visitSchema(schema);
|
|
1085
|
+
return result;
|
|
1086
|
+
}
|
|
1087
|
+
function collectUsedSchemaNames(operations, schemas) {
|
|
1088
|
+
return collectUsedSchemaNamesMemo(operations)(schemas);
|
|
1089
|
+
}
|
|
1090
|
+
const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
|
|
1091
|
+
const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
|
|
1092
|
+
const graph = /* @__PURE__ */ new Map();
|
|
1093
|
+
for (const schema of schemas) {
|
|
1094
|
+
if (!schema.name) continue;
|
|
1095
|
+
graph.set(schema.name, collectReferencedSchemaNames(schema));
|
|
1096
|
+
}
|
|
1097
|
+
const circular = /* @__PURE__ */ new Set();
|
|
1098
|
+
for (const start of graph.keys()) {
|
|
1099
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1100
|
+
const stack = [...graph.get(start) ?? []];
|
|
1101
|
+
while (stack.length > 0) {
|
|
1102
|
+
const node = stack.pop();
|
|
1103
|
+
if (node === start) {
|
|
1104
|
+
circular.add(start);
|
|
1105
|
+
break;
|
|
1106
|
+
}
|
|
1107
|
+
if (visited.has(node)) continue;
|
|
1108
|
+
visited.add(node);
|
|
1109
|
+
const next = graph.get(node);
|
|
1110
|
+
if (next) for (const r of next) stack.push(r);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return circular;
|
|
1114
|
+
});
|
|
1115
|
+
/**
|
|
1116
|
+
* Finds every schema that takes part in a circular dependency chain, including direct self-loops.
|
|
1117
|
+
*
|
|
1118
|
+
* Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
|
|
1119
|
+
* the generated code does not recurse forever. Refs are followed by name only, so the walk stays
|
|
1120
|
+
* linear in the size of the schema graph.
|
|
1121
|
+
*
|
|
1122
|
+
* @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
|
|
1123
|
+
*/
|
|
1124
|
+
function findCircularSchemas(schemas) {
|
|
1125
|
+
if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
|
|
1126
|
+
return findCircularSchemasMemo(schemas);
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Returns `true` when a schema, or anything nested inside it, references a circular schema.
|
|
1130
|
+
*
|
|
1131
|
+
* Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
|
|
1132
|
+
* on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
|
|
1133
|
+
*
|
|
1134
|
+
* @note Stops at the first matching circular ref.
|
|
1135
|
+
*/
|
|
1136
|
+
function containsCircularRef(node, { circularSchemas, excludeName }) {
|
|
1137
|
+
if (!node || circularSchemas.size === 0) return false;
|
|
1138
|
+
for (const _ of collectLazy(node, { schema(child) {
|
|
1139
|
+
if (child.type !== "ref") return null;
|
|
1140
|
+
const name = resolveRefName(child);
|
|
1141
|
+
return name && name !== excludeName && circularSchemas.has(name) ? true : null;
|
|
1142
|
+
} })) return true;
|
|
1143
|
+
return false;
|
|
1144
|
+
}
|
|
1145
|
+
//#endregion
|
|
1146
|
+
//#region src/utils/schemaTraversal.ts
|
|
1147
|
+
/**
|
|
1148
|
+
* Maps each property of an object schema to its transformed output. Pairs every result with the
|
|
1149
|
+
* original property so the printer keeps full control over modifiers, getters, and key syntax.
|
|
1150
|
+
*
|
|
1151
|
+
* @example
|
|
1152
|
+
* ```ts
|
|
1153
|
+
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
|
|
1154
|
+
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
|
|
1155
|
+
* ```
|
|
1156
|
+
*/
|
|
1157
|
+
function mapSchemaProperties(node, transform) {
|
|
1158
|
+
return node.properties.map((property) => ({
|
|
1159
|
+
name: property.name,
|
|
1160
|
+
property,
|
|
1161
|
+
output: transform(property.schema)
|
|
1162
|
+
}));
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Maps each member of a union or intersection schema to its transformed output, pairing every
|
|
1166
|
+
* result with the original member.
|
|
1167
|
+
*/
|
|
1168
|
+
function mapSchemaMembers(node, transform) {
|
|
1169
|
+
return (node.members ?? []).map((schema) => ({
|
|
1170
|
+
schema,
|
|
1171
|
+
output: transform(schema)
|
|
1172
|
+
}));
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
|
|
1176
|
+
* the original item.
|
|
1177
|
+
*/
|
|
1178
|
+
function mapSchemaItems(node, transform) {
|
|
1179
|
+
return (node.items ?? []).map((schema) => ({
|
|
1180
|
+
schema,
|
|
1181
|
+
output: transform(schema)
|
|
1182
|
+
}));
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
|
|
1186
|
+
* is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
|
|
1187
|
+
* of a recursive schema until first access.
|
|
1188
|
+
*
|
|
1189
|
+
* @example
|
|
1190
|
+
* ```ts
|
|
1191
|
+
* lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
|
|
1192
|
+
* // "get parent() { return z.lazy(() => Pet) }"
|
|
1193
|
+
* ```
|
|
1194
|
+
*/
|
|
1195
|
+
function lazyGetter({ name, body }) {
|
|
1196
|
+
return `get ${objectKey(name)}() { return ${body} }`;
|
|
1197
|
+
}
|
|
1198
|
+
//#endregion
|
|
1199
|
+
//#region src/utils/operationParams.ts
|
|
1200
|
+
/**
|
|
1201
|
+
* Applies casing rules to parameter names and returns a new array without mutating the input.
|
|
1202
|
+
*
|
|
1203
|
+
* Run it before handing parameters to schema builders so output property keys get the right casing
|
|
1204
|
+
* while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
|
|
1205
|
+
* original array is returned unchanged.
|
|
1206
|
+
*/
|
|
1207
|
+
const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
|
|
1208
|
+
const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
|
|
1209
|
+
return {
|
|
1210
|
+
...param,
|
|
1211
|
+
name: transformed
|
|
1212
|
+
};
|
|
1213
|
+
})));
|
|
1214
|
+
function caseParams(params, casing) {
|
|
1215
|
+
if (!casing) return params;
|
|
1216
|
+
return caseParamsMemo(params)(casing);
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Resolves the {@link TypeExpression} for an individual parameter.
|
|
1220
|
+
*
|
|
1221
|
+
* Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
|
|
1222
|
+
* parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
|
|
1223
|
+
* `GroupParams['petId']`, otherwise the resolved individual name.
|
|
1224
|
+
*/
|
|
1225
|
+
function resolveParamType({ node, param, resolver }) {
|
|
1226
|
+
if (!resolver) return param.schema.primitive ?? "unknown";
|
|
1227
|
+
const individualName = resolver.resolveParamName(node, param);
|
|
1228
|
+
const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
|
|
1229
|
+
const groupResolvers = {
|
|
1230
|
+
path: resolver.resolvePathParamsName,
|
|
1231
|
+
query: resolver.resolveQueryParamsName,
|
|
1232
|
+
header: resolver.resolveHeaderParamsName
|
|
1233
|
+
};
|
|
1234
|
+
const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
|
|
1235
|
+
if (groupName && groupName !== individualName) return createIndexedAccessType({
|
|
1236
|
+
objectType: groupName,
|
|
1237
|
+
indexType: param.name
|
|
1238
|
+
});
|
|
1239
|
+
return individualName;
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Converts an `OperationNode` into function parameters for code generation.
|
|
1243
|
+
*
|
|
1244
|
+
* Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
|
|
1245
|
+
* destructured object parameter (`object`) and separate top-level parameters (`inline`), while
|
|
1246
|
+
* `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
|
|
1247
|
+
* name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
|
|
1248
|
+
*/
|
|
1249
|
+
function createOperationParams(node, options) {
|
|
1250
|
+
const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
|
|
1251
|
+
const dataName = paramNames?.data ?? "data";
|
|
1252
|
+
const paramsName = paramNames?.params ?? "params";
|
|
1253
|
+
const headersName = paramNames?.headers ?? "headers";
|
|
1254
|
+
const pathName = paramNames?.path ?? "pathParams";
|
|
1255
|
+
const wrapType = (type) => typeWrapper ? typeWrapper(type) : type;
|
|
1256
|
+
const wrapTypeExpression = (type) => typeof type === "string" ? wrapType(type) : type;
|
|
1257
|
+
const casedParams = caseParams(node.parameters, paramsCasing);
|
|
1258
|
+
const pathParams = casedParams.filter((p) => p.in === "path");
|
|
1259
|
+
const queryParams = casedParams.filter((p) => p.in === "query");
|
|
1260
|
+
const headerParams = casedParams.filter((p) => p.in === "header");
|
|
1261
|
+
const toProperty = (param) => ({
|
|
1262
|
+
name: param.name,
|
|
1263
|
+
type: wrapTypeExpression(resolveParamType({
|
|
1264
|
+
node,
|
|
1265
|
+
param,
|
|
1266
|
+
resolver
|
|
1267
|
+
})),
|
|
1268
|
+
optional: !param.required
|
|
1269
|
+
});
|
|
1270
|
+
const emptyObjectDefault = (props) => props.every((p) => p.optional) ? "{}" : void 0;
|
|
1271
|
+
const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
|
|
1272
|
+
const bodyProperty = bodyType ? [{
|
|
1273
|
+
name: dataName,
|
|
1274
|
+
type: bodyType,
|
|
1275
|
+
optional: !(node.requestBody?.required ?? false)
|
|
1276
|
+
}] : [];
|
|
1277
|
+
const trailingGroups = [{
|
|
1278
|
+
name: paramsName,
|
|
1279
|
+
node,
|
|
1280
|
+
params: queryParams,
|
|
1281
|
+
groupType: resolveGroupType({
|
|
1282
|
+
node,
|
|
1283
|
+
params: queryParams,
|
|
1284
|
+
group: "query",
|
|
1285
|
+
resolver
|
|
1286
|
+
}),
|
|
1287
|
+
resolver,
|
|
1288
|
+
wrapType
|
|
1289
|
+
}, {
|
|
1290
|
+
name: headersName,
|
|
1291
|
+
node,
|
|
1292
|
+
params: headerParams,
|
|
1293
|
+
groupType: resolveGroupType({
|
|
1294
|
+
node,
|
|
1295
|
+
params: headerParams,
|
|
1296
|
+
group: "header",
|
|
1297
|
+
resolver
|
|
1298
|
+
}),
|
|
1299
|
+
resolver,
|
|
1300
|
+
wrapType
|
|
1301
|
+
}];
|
|
1302
|
+
const params = [];
|
|
1303
|
+
if (paramsType === "object") {
|
|
1304
|
+
const children = [
|
|
1305
|
+
...pathParams.map(toProperty),
|
|
1306
|
+
...bodyProperty,
|
|
1307
|
+
...trailingGroups.flatMap(buildGroupProperty)
|
|
1308
|
+
];
|
|
1309
|
+
if (children.length) params.push(createFunctionParameter({
|
|
1310
|
+
properties: children,
|
|
1311
|
+
default: emptyObjectDefault(children)
|
|
1312
|
+
}));
|
|
1313
|
+
} else {
|
|
1314
|
+
if (pathParamsType === "inlineSpread" && pathParams.length) {
|
|
1315
|
+
const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]);
|
|
1316
|
+
params.push(createFunctionParameter({
|
|
1317
|
+
name: pathName,
|
|
1318
|
+
type: spreadType ? wrapType(spreadType) : void 0,
|
|
1319
|
+
rest: true
|
|
1320
|
+
}));
|
|
1321
|
+
} else if (pathParamsType === "inline") params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))));
|
|
1322
|
+
else if (pathParams.length) {
|
|
1323
|
+
const pathChildren = pathParams.map(toProperty);
|
|
1324
|
+
params.push(createFunctionParameter({
|
|
1325
|
+
properties: pathChildren,
|
|
1326
|
+
default: pathParamsDefault ?? emptyObjectDefault(pathChildren)
|
|
1327
|
+
}));
|
|
1328
|
+
}
|
|
1329
|
+
params.push(...bodyProperty.map((p) => createFunctionParameter(p)));
|
|
1330
|
+
params.push(...trailingGroups.flatMap(buildGroupParam));
|
|
1331
|
+
}
|
|
1332
|
+
params.push(...extraParams);
|
|
1333
|
+
return createFunctionParameters({ params });
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Builds the property descriptor for a query or header group.
|
|
1337
|
+
* Returns an empty array when there are no params to emit.
|
|
1338
|
+
*
|
|
1339
|
+
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
1340
|
+
* {@link TypeLiteralNode} from the individual params.
|
|
1341
|
+
*/
|
|
1342
|
+
function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }) {
|
|
1343
|
+
if (groupType) return [{
|
|
1344
|
+
name,
|
|
1345
|
+
type: typeof groupType.type === "string" ? wrapType(groupType.type) : groupType.type,
|
|
1346
|
+
optional: groupType.optional
|
|
1347
|
+
}];
|
|
1348
|
+
if (params.length) return [{
|
|
1349
|
+
name,
|
|
1350
|
+
type: buildTypeLiteral({
|
|
1351
|
+
node,
|
|
1352
|
+
params,
|
|
1353
|
+
resolver
|
|
1354
|
+
}),
|
|
1355
|
+
optional: params.every((p) => !p.required)
|
|
1356
|
+
}];
|
|
1357
|
+
return [];
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Builds a single {@link FunctionParameterNode} for a query or header group.
|
|
1361
|
+
* Returns an empty array when there are no params to emit.
|
|
1362
|
+
*
|
|
1363
|
+
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
1364
|
+
* {@link TypeLiteralNode} from the individual params.
|
|
1365
|
+
*/
|
|
1366
|
+
function buildGroupParam(args) {
|
|
1367
|
+
return buildGroupProperty(args).map((p) => createFunctionParameter(p));
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
|
|
1371
|
+
*
|
|
1372
|
+
* Used when query or header parameters have no dedicated group type name.
|
|
1373
|
+
* Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
|
|
1374
|
+
*/
|
|
1375
|
+
function buildTypeLiteral({ node, params, resolver }) {
|
|
1376
|
+
return createTypeLiteral({ members: params.map((p) => ({
|
|
1377
|
+
name: p.name,
|
|
1378
|
+
type: resolveParamType({
|
|
1379
|
+
node,
|
|
1380
|
+
param: p,
|
|
1381
|
+
resolver
|
|
1382
|
+
}),
|
|
1383
|
+
optional: !p.required
|
|
1384
|
+
})) });
|
|
1385
|
+
}
|
|
1386
|
+
//#endregion
|
|
1387
|
+
export { enumPropName as A, objectKey as B, trimQuotes as C, simplifyUnion as D, setEnumName as E, isHttpOperationNode as F, httpMethods as H, narrowSchema as I, buildJSDoc as L, isStringType as M, resolveGroupType as N, syncSchemaRef as O, resolveRefName as P, buildList as R, toRegExpString as S, setDiscriminatorEnum as T, schemaTypes as U, isValidVarName as V, nodeDefs as _, resolveParamType as a, stringify as b, mapSchemaMembers as c, containsCircularRef as d, findCircularSchemas as f, walk as g, transform as h, createOperationParams as i, extractRefName as j, childName as k, mapSchemaProperties as l, collectLazy as m, buildTypeLiteral as n, lazyGetter as o, collect as p, caseParams as r, mapSchemaItems as s, buildGroupParam as t, collectUsedSchemaNames as u, getNestedAccessor as v, mergeAdjacentObjectsLazy as w, stringifyObject as x, jsStringEscape as y, buildObject as z };
|
|
1388
|
+
|
|
1389
|
+
//# sourceMappingURL=utils-Dj_KoXMv.js.map
|