@kubb/ast 5.0.0-beta.58 → 5.0.0-beta.59
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/README.md +10 -0
- package/dist/casing-BE2R1RXg.cjs +88 -0
- package/dist/casing-BE2R1RXg.cjs.map +1 -0
- package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
- package/dist/factory-BmcGBdeg.cjs +1251 -0
- package/dist/factory-BmcGBdeg.cjs.map +1 -0
- package/dist/factory-Du7nEP4B.js +282 -0
- package/dist/factory-Du7nEP4B.js.map +1 -0
- package/dist/factory.cjs +25 -28
- package/dist/factory.d.ts +3 -3
- package/dist/factory.js +3 -3
- package/dist/{ast-ClnJg9BN.d.ts → index-BzjwdK2M.d.ts} +74 -372
- package/dist/index.cjs +445 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +94 -59
- package/dist/index.js +7 -113
- 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/{types-CB2oY8Dw.d.ts → types-olVl9v5p.d.ts} +222 -227
- package/dist/types.d.ts +4 -3
- package/dist/utils-BCtRXfhI.cjs +275 -0
- package/dist/utils-BCtRXfhI.cjs.map +1 -0
- package/dist/{utils-DN4XLVqz.js → utils-SdZU0F3H.js} +472 -1235
- package/dist/utils-SdZU0F3H.js.map +1 -0
- package/dist/utils.cjs +127 -22
- package/dist/utils.d.ts +112 -80
- package/dist/utils.js +3 -2
- package/package.json +1 -1
- package/src/constants.ts +8 -14
- package/src/dedupe.ts +8 -0
- package/src/factory.ts +1 -2
- package/src/guards.ts +1 -1
- package/src/index.ts +4 -13
- package/src/nodes/code.ts +29 -47
- package/src/nodes/content.ts +2 -2
- package/src/nodes/file.ts +28 -23
- package/src/nodes/function.ts +0 -15
- package/src/nodes/input.ts +6 -6
- package/src/nodes/operation.ts +1 -1
- package/src/nodes/parameter.ts +0 -3
- package/src/nodes/property.ts +0 -3
- package/src/nodes/requestBody.ts +3 -6
- package/src/nodes/schema.ts +3 -2
- package/src/printer.ts +1 -1
- package/src/registry.ts +31 -26
- package/src/signature.ts +3 -3
- package/src/transformers.ts +28 -1
- package/src/types.ts +2 -53
- package/src/utils/codegen.ts +104 -0
- package/src/utils/fileMerge.ts +184 -0
- package/src/utils/index.ts +7 -339
- package/src/utils/operationParams.ts +353 -0
- package/src/utils/refs.ts +112 -0
- package/src/utils/schemaGraph.ts +169 -0
- package/src/utils/strings.ts +139 -0
- package/src/visitor.ts +43 -19
- package/dist/extractStringsFromNodes-Bn9cOos9.d.ts +0 -14
- package/dist/factory-C5gHvtLU.js +0 -138
- package/dist/factory-C5gHvtLU.js.map +0 -1
- package/dist/factory-JN-Ylfl6.cjs +0 -155
- package/dist/factory-JN-Ylfl6.cjs.map +0 -1
- package/dist/utils-C8bWAzhv.cjs +0 -2696
- package/dist/utils-C8bWAzhv.cjs.map +0 -1
- package/dist/utils-DN4XLVqz.js.map +0 -1
- package/src/utils/ast.ts +0 -816
|
@@ -1,4 +1,5 @@
|
|
|
1
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";
|
|
2
3
|
//#region src/constants.ts
|
|
3
4
|
const visitorDepths = {
|
|
4
5
|
shallow: "shallow",
|
|
@@ -7,9 +8,8 @@ const visitorDepths = {
|
|
|
7
8
|
/**
|
|
8
9
|
* Schema type discriminators used by all AST schema nodes.
|
|
9
10
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* and format-specific types (`date`, `uuid`, `email`). Use `isScalarPrimitive()` to check for scalar types.
|
|
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
13
|
*/
|
|
14
14
|
const schemaTypes = {
|
|
15
15
|
/**
|
|
@@ -29,7 +29,7 @@ const schemaTypes = {
|
|
|
29
29
|
*/
|
|
30
30
|
bigint: "bigint",
|
|
31
31
|
/**
|
|
32
|
-
* Boolean value
|
|
32
|
+
* Boolean value.
|
|
33
33
|
*/
|
|
34
34
|
boolean: "boolean",
|
|
35
35
|
/**
|
|
@@ -119,8 +119,6 @@ const schemaTypes = {
|
|
|
119
119
|
};
|
|
120
120
|
/**
|
|
121
121
|
* Scalar primitive schema types used for union simplification and type narrowing.
|
|
122
|
-
*
|
|
123
|
-
* Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
|
|
124
122
|
*/
|
|
125
123
|
const SCALAR_PRIMITIVE_TYPES = new Set([
|
|
126
124
|
"string",
|
|
@@ -130,17 +128,14 @@ const SCALAR_PRIMITIVE_TYPES = new Set([
|
|
|
130
128
|
"boolean"
|
|
131
129
|
]);
|
|
132
130
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
|
|
131
|
+
* Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
|
|
132
|
+
* (for example `string | number | boolean`).
|
|
136
133
|
*/
|
|
137
134
|
function isScalarPrimitive(type) {
|
|
138
135
|
return SCALAR_PRIMITIVE_TYPES.has(type);
|
|
139
136
|
}
|
|
140
137
|
/**
|
|
141
138
|
* HTTP method identifiers used by operation nodes.
|
|
142
|
-
*
|
|
143
|
-
* Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
|
|
144
139
|
*/
|
|
145
140
|
const httpMethods = {
|
|
146
141
|
get: "GET",
|
|
@@ -157,170 +152,6 @@ const httpMethods = {
|
|
|
157
152
|
*/
|
|
158
153
|
const INDENT = Array.from({ length: 2 }, () => " ").join("");
|
|
159
154
|
//#endregion
|
|
160
|
-
//#region src/node.ts
|
|
161
|
-
/**
|
|
162
|
-
* Builds a type guard that matches nodes of the given `kind`.
|
|
163
|
-
*/
|
|
164
|
-
function isKind(kind) {
|
|
165
|
-
return (node) => node.kind === kind;
|
|
166
|
-
}
|
|
167
|
-
/**
|
|
168
|
-
* Updates a schema's `optional` and `nullish` flags from a parent's `required`
|
|
169
|
-
* value and the schema's own `nullable`. Mirrors how OpenAPI parameters and
|
|
170
|
-
* object properties combine "required" and "nullable" into a single AST.
|
|
171
|
-
*
|
|
172
|
-
* - Non-required + non-nullable → `optional: true`.
|
|
173
|
-
* - Non-required + nullable → `nullish: true`.
|
|
174
|
-
* - Required → both flags cleared.
|
|
175
|
-
*/
|
|
176
|
-
function syncOptionality(schema, required) {
|
|
177
|
-
const nullable = schema.nullable ?? false;
|
|
178
|
-
return {
|
|
179
|
-
...schema,
|
|
180
|
-
optional: !required && !nullable ? true : void 0,
|
|
181
|
-
nullish: !required && nullable ? true : void 0
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Defines a node once and derives its `create` builder, `is` guard, and traversal
|
|
186
|
-
* metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
|
|
187
|
-
* `kind`, so node construction lives in one place without scattered `as` casts.
|
|
188
|
-
*
|
|
189
|
-
* Set `rebuild: true` when the `build` hook derives fields from children. After a
|
|
190
|
-
* transform rewrites those children, the registry reruns `create` so the derived
|
|
191
|
-
* fields stay correct.
|
|
192
|
-
*
|
|
193
|
-
* @example Simple node
|
|
194
|
-
* ```ts
|
|
195
|
-
* const importDef = defineNode<ImportNode>({ kind: 'Import' })
|
|
196
|
-
* const createImport = importDef.create
|
|
197
|
-
* ```
|
|
198
|
-
*
|
|
199
|
-
* @example Node with a build hook that is rerun on transform
|
|
200
|
-
* ```ts
|
|
201
|
-
* const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
|
|
202
|
-
* kind: 'Property',
|
|
203
|
-
* build: (props) => ({ ...props, required: props.required ?? false }),
|
|
204
|
-
* children: ['schema'],
|
|
205
|
-
* visitorKey: 'property',
|
|
206
|
-
* rebuild: true,
|
|
207
|
-
* })
|
|
208
|
-
* ```
|
|
209
|
-
*/
|
|
210
|
-
function defineNode(config) {
|
|
211
|
-
const { kind, defaults, build, children, visitorKey, rebuild } = config;
|
|
212
|
-
function create(input) {
|
|
213
|
-
const base = build ? build(input) : input;
|
|
214
|
-
return {
|
|
215
|
-
...defaults,
|
|
216
|
-
...base,
|
|
217
|
-
kind
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
return {
|
|
221
|
-
kind,
|
|
222
|
-
create,
|
|
223
|
-
is: isKind(kind),
|
|
224
|
-
children,
|
|
225
|
-
visitorKey,
|
|
226
|
-
rebuild
|
|
227
|
-
};
|
|
228
|
-
}
|
|
229
|
-
//#endregion
|
|
230
|
-
//#region src/nodes/schema.ts
|
|
231
|
-
/**
|
|
232
|
-
* Maps schema `type` to its underlying `primitive`.
|
|
233
|
-
* Primitive types map to themselves. Special string formats map to `'string'`.
|
|
234
|
-
* Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
|
|
235
|
-
*/
|
|
236
|
-
const TYPE_TO_PRIMITIVE = {
|
|
237
|
-
string: "string",
|
|
238
|
-
number: "number",
|
|
239
|
-
integer: "integer",
|
|
240
|
-
bigint: "bigint",
|
|
241
|
-
boolean: "boolean",
|
|
242
|
-
null: "null",
|
|
243
|
-
any: "any",
|
|
244
|
-
unknown: "unknown",
|
|
245
|
-
void: "void",
|
|
246
|
-
never: "never",
|
|
247
|
-
object: "object",
|
|
248
|
-
array: "array",
|
|
249
|
-
date: "date",
|
|
250
|
-
uuid: "string",
|
|
251
|
-
email: "string",
|
|
252
|
-
url: "string",
|
|
253
|
-
datetime: "string",
|
|
254
|
-
time: "string"
|
|
255
|
-
};
|
|
256
|
-
/**
|
|
257
|
-
* Definition for the {@link SchemaNode}. Object schemas default `properties` to an
|
|
258
|
-
* empty array, and `primitive` is inferred from `type` when not explicitly provided.
|
|
259
|
-
*/
|
|
260
|
-
const schemaDef = defineNode({
|
|
261
|
-
kind: "Schema",
|
|
262
|
-
build: (props) => {
|
|
263
|
-
if (props.type === "object") return {
|
|
264
|
-
properties: [],
|
|
265
|
-
primitive: "object",
|
|
266
|
-
...props
|
|
267
|
-
};
|
|
268
|
-
return {
|
|
269
|
-
primitive: TYPE_TO_PRIMITIVE[props.type],
|
|
270
|
-
...props
|
|
271
|
-
};
|
|
272
|
-
},
|
|
273
|
-
children: [
|
|
274
|
-
"properties",
|
|
275
|
-
"items",
|
|
276
|
-
"members",
|
|
277
|
-
"additionalProperties"
|
|
278
|
-
],
|
|
279
|
-
visitorKey: "schema"
|
|
280
|
-
});
|
|
281
|
-
function createSchema(props) {
|
|
282
|
-
return schemaDef.create(props);
|
|
283
|
-
}
|
|
284
|
-
//#endregion
|
|
285
|
-
//#region ../../internals/utils/src/casing.ts
|
|
286
|
-
/**
|
|
287
|
-
* Shared implementation for camelCase and PascalCase conversion.
|
|
288
|
-
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
289
|
-
* and capitalizes each word according to `pascal`.
|
|
290
|
-
*
|
|
291
|
-
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
292
|
-
*/
|
|
293
|
-
function toCamelOrPascal(text, pascal) {
|
|
294
|
-
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
|
|
295
|
-
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
296
|
-
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
|
|
297
|
-
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Converts `text` to camelCase.
|
|
301
|
-
*
|
|
302
|
-
* @example Word boundaries
|
|
303
|
-
* `camelCase('hello-world') // 'helloWorld'`
|
|
304
|
-
*
|
|
305
|
-
* @example With a prefix
|
|
306
|
-
* `camelCase('tag', { prefix: 'create' }) // 'createTag'`
|
|
307
|
-
*/
|
|
308
|
-
function camelCase(text, { prefix = "", suffix = "" } = {}) {
|
|
309
|
-
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
310
|
-
}
|
|
311
|
-
/**
|
|
312
|
-
* Converts `text` to PascalCase.
|
|
313
|
-
*
|
|
314
|
-
* @example Word boundaries
|
|
315
|
-
* `pascalCase('hello-world') // 'HelloWorld'`
|
|
316
|
-
*
|
|
317
|
-
* @example With a suffix
|
|
318
|
-
* `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
|
|
319
|
-
*/
|
|
320
|
-
function pascalCase(text, { prefix = "", suffix = "" } = {}) {
|
|
321
|
-
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
322
|
-
}
|
|
323
|
-
//#endregion
|
|
324
155
|
//#region ../../internals/utils/src/promise.ts
|
|
325
156
|
/**
|
|
326
157
|
* Wraps `factory` with a keyed cache backed by the provided store.
|
|
@@ -496,29 +327,75 @@ function singleQuote(value) {
|
|
|
496
327
|
return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
497
328
|
}
|
|
498
329
|
//#endregion
|
|
499
|
-
//#region src/utils/
|
|
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
|
+
}
|
|
500
382
|
/**
|
|
501
|
-
*
|
|
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.
|
|
502
387
|
*
|
|
503
|
-
*
|
|
504
|
-
*
|
|
388
|
+
* @example
|
|
389
|
+
* ```ts
|
|
390
|
+
* buildList(['z.string()', 'z.number()'])
|
|
391
|
+
* // '[z.string(), z.number()]'
|
|
392
|
+
* ```
|
|
505
393
|
*/
|
|
506
|
-
function
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
if (node.kind === "Break") return "";
|
|
512
|
-
if (node.kind === "Jsx") return node.value;
|
|
513
|
-
const parts = [];
|
|
514
|
-
if ("params" in node && node.params) parts.push(node.params);
|
|
515
|
-
if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
|
|
516
|
-
if ("returnType" in node && node.returnType) parts.push(node.returnType);
|
|
517
|
-
if ("type" in node && typeof node.type === "string") parts.push(node.type);
|
|
518
|
-
const nested = extractStringsFromNodes(node.nodes);
|
|
519
|
-
if (nested) parts.push(nested);
|
|
520
|
-
return parts.join("\n");
|
|
521
|
-
}).filter(Boolean).join("\n");
|
|
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}`;
|
|
522
399
|
}
|
|
523
400
|
//#endregion
|
|
524
401
|
//#region src/guards.ts
|
|
@@ -535,7 +412,7 @@ function narrowSchema(node, type) {
|
|
|
535
412
|
return node?.type === type ? node : null;
|
|
536
413
|
}
|
|
537
414
|
/**
|
|
538
|
-
* Narrows an `OperationNode` to an `HttpOperationNode
|
|
415
|
+
* Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
|
|
539
416
|
*
|
|
540
417
|
* @example
|
|
541
418
|
* ```ts
|
|
@@ -548,500 +425,348 @@ function isHttpOperationNode(node) {
|
|
|
548
425
|
return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
|
|
549
426
|
}
|
|
550
427
|
//#endregion
|
|
551
|
-
//#region src/
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
428
|
+
//#region src/utils/refs.ts
|
|
429
|
+
const plainStringTypes = new Set([
|
|
430
|
+
"string",
|
|
431
|
+
"uuid",
|
|
432
|
+
"email",
|
|
433
|
+
"url",
|
|
434
|
+
"datetime"
|
|
435
|
+
]);
|
|
556
436
|
/**
|
|
557
|
-
*
|
|
437
|
+
* Returns the last path segment of a reference string.
|
|
558
438
|
*
|
|
559
439
|
* @example
|
|
560
440
|
* ```ts
|
|
561
|
-
*
|
|
562
|
-
* // { petId: string }
|
|
441
|
+
* extractRefName('#/components/schemas/Pet') // 'Pet'
|
|
563
442
|
* ```
|
|
564
443
|
*/
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
*/
|
|
569
|
-
const indexedAccessTypeDef = defineNode({ kind: "IndexedAccessType" });
|
|
444
|
+
function extractRefName(ref) {
|
|
445
|
+
return ref.split("/").at(-1) ?? ref;
|
|
446
|
+
}
|
|
570
447
|
/**
|
|
571
|
-
*
|
|
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.
|
|
572
451
|
*
|
|
573
452
|
* @example
|
|
574
453
|
* ```ts
|
|
575
|
-
*
|
|
576
|
-
* //
|
|
454
|
+
* resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
|
|
455
|
+
* // => 'Pet'
|
|
577
456
|
* ```
|
|
578
457
|
*/
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
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
|
+
}
|
|
584
463
|
/**
|
|
585
|
-
*
|
|
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.
|
|
586
466
|
*
|
|
587
467
|
* @example
|
|
588
468
|
* ```ts
|
|
589
|
-
*
|
|
590
|
-
*
|
|
469
|
+
* childName('Order', 'shipping_address') // 'OrderShippingAddress'
|
|
470
|
+
* childName(undefined, 'params') // null
|
|
591
471
|
* ```
|
|
592
472
|
*/
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
* Passing `properties` builds a destructured group: an {@link ObjectBindingPatternNode} name
|
|
597
|
-
* paired with a {@link TypeLiteralNode} type.
|
|
598
|
-
*/
|
|
599
|
-
const functionParameterDef = defineNode({
|
|
600
|
-
kind: "FunctionParameter",
|
|
601
|
-
build: (input) => {
|
|
602
|
-
if ("properties" in input) return {
|
|
603
|
-
name: createObjectBindingPattern({ elements: input.properties.map((p) => ({ name: p.name })) }),
|
|
604
|
-
type: createTypeLiteral({ members: input.properties.map((p) => ({
|
|
605
|
-
name: p.name,
|
|
606
|
-
type: p.type,
|
|
607
|
-
optional: p.optional ?? false
|
|
608
|
-
})) }),
|
|
609
|
-
optional: input.optional ?? false,
|
|
610
|
-
...input.default !== void 0 ? { default: input.default } : {}
|
|
611
|
-
};
|
|
612
|
-
return {
|
|
613
|
-
optional: false,
|
|
614
|
-
...input
|
|
615
|
-
};
|
|
616
|
-
}
|
|
617
|
-
});
|
|
473
|
+
function childName(parentName, propName) {
|
|
474
|
+
return parentName ? pascalCase([parentName, propName].join(" ")) : null;
|
|
475
|
+
}
|
|
618
476
|
/**
|
|
619
|
-
*
|
|
620
|
-
*
|
|
621
|
-
* @example Optional param
|
|
622
|
-
* ```ts
|
|
623
|
-
* createFunctionParameter({ name: 'params', type: 'QueryParams', optional: true })
|
|
624
|
-
* // → params?: QueryParams
|
|
625
|
-
* ```
|
|
477
|
+
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
|
|
478
|
+
* empty parts.
|
|
626
479
|
*
|
|
627
|
-
* @example
|
|
480
|
+
* @example
|
|
628
481
|
* ```ts
|
|
629
|
-
*
|
|
630
|
-
* // → { id, name }: { id: string; name?: string } = {}
|
|
482
|
+
* enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
|
|
631
483
|
* ```
|
|
632
484
|
*/
|
|
633
|
-
|
|
485
|
+
function enumPropName(parentName, propName, enumSuffix) {
|
|
486
|
+
return pascalCase([
|
|
487
|
+
parentName,
|
|
488
|
+
propName,
|
|
489
|
+
enumSuffix
|
|
490
|
+
].filter(Boolean).join(" "));
|
|
491
|
+
}
|
|
634
492
|
/**
|
|
635
|
-
*
|
|
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'`.
|
|
636
497
|
*/
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
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
|
+
}
|
|
641
504
|
/**
|
|
642
|
-
*
|
|
505
|
+
* Derives a {@link ParamGroupType} for a query or header group from the resolver.
|
|
643
506
|
*
|
|
644
|
-
*
|
|
645
|
-
*
|
|
646
|
-
* const empty = createFunctionParameters()
|
|
647
|
-
* // { kind: 'FunctionParameters', params: [] }
|
|
648
|
-
* ```
|
|
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).
|
|
649
509
|
*/
|
|
650
|
-
function
|
|
651
|
-
|
|
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
|
+
};
|
|
652
519
|
}
|
|
653
520
|
//#endregion
|
|
654
|
-
//#region src/
|
|
655
|
-
/**
|
|
656
|
-
* Definition for the {@link PropertyNode}. `required` defaults to `false` and the
|
|
657
|
-
* schema's `optional`/`nullish` flags are kept in sync with it.
|
|
658
|
-
*/
|
|
659
|
-
const propertyDef = defineNode({
|
|
660
|
-
kind: "Property",
|
|
661
|
-
build: (props) => {
|
|
662
|
-
const required = props.required ?? false;
|
|
663
|
-
return {
|
|
664
|
-
...props,
|
|
665
|
-
required,
|
|
666
|
-
schema: syncOptionality(props.schema, required)
|
|
667
|
-
};
|
|
668
|
-
},
|
|
669
|
-
children: ["schema"],
|
|
670
|
-
visitorKey: "property",
|
|
671
|
-
rebuild: true
|
|
672
|
-
});
|
|
521
|
+
//#region src/transformers.ts
|
|
673
522
|
/**
|
|
674
|
-
*
|
|
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.
|
|
675
527
|
*
|
|
676
528
|
* @example
|
|
677
529
|
* ```ts
|
|
678
|
-
* const
|
|
679
|
-
*
|
|
680
|
-
* required: true,
|
|
681
|
-
* schema: createSchema({ type: 'string', nullable: true }),
|
|
530
|
+
* const schema = createSchema({
|
|
531
|
+
* type: 'object',
|
|
532
|
+
* properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
|
|
682
533
|
* })
|
|
683
|
-
*
|
|
534
|
+
* const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
|
|
684
535
|
* ```
|
|
685
536
|
*/
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
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
|
+
}
|
|
693
559
|
/**
|
|
694
|
-
*
|
|
560
|
+
* Merges adjacent anonymous object members into a single anonymous object member.
|
|
695
561
|
*
|
|
696
|
-
* @example
|
|
562
|
+
* @example
|
|
697
563
|
* ```ts
|
|
698
|
-
*
|
|
699
|
-
*
|
|
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
|
+
* ])
|
|
700
568
|
* ```
|
|
701
569
|
*/
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
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
|
+
}
|
|
707
589
|
/**
|
|
708
|
-
*
|
|
590
|
+
* Removes enum members that are covered by broader scalar primitives in the same union.
|
|
709
591
|
*
|
|
710
592
|
* @example
|
|
711
593
|
* ```ts
|
|
712
|
-
*
|
|
713
|
-
*
|
|
594
|
+
* const simplified = simplifyUnion([
|
|
595
|
+
* createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
|
|
596
|
+
* createSchema({ type: 'string' }),
|
|
597
|
+
* ])
|
|
598
|
+
* // keeps only string member
|
|
714
599
|
* ```
|
|
715
600
|
*/
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
const
|
|
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
|
+
}
|
|
721
627
|
/**
|
|
722
|
-
*
|
|
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.
|
|
723
632
|
*
|
|
724
633
|
* @example
|
|
725
634
|
* ```ts
|
|
726
|
-
*
|
|
727
|
-
*
|
|
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
|
|
728
638
|
* ```
|
|
729
639
|
*/
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
const
|
|
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
|
|
735
653
|
/**
|
|
736
|
-
*
|
|
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.
|
|
737
656
|
*
|
|
738
657
|
* @example
|
|
739
658
|
* ```ts
|
|
740
|
-
*
|
|
741
|
-
*
|
|
659
|
+
* trimQuotes('"hello"') // 'hello'
|
|
660
|
+
* trimQuotes('hello') // 'hello'
|
|
742
661
|
* ```
|
|
743
662
|
*/
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
}
|
|
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
|
+
}
|
|
752
671
|
/**
|
|
753
|
-
*
|
|
672
|
+
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
|
|
754
673
|
*
|
|
755
|
-
*
|
|
756
|
-
*
|
|
757
|
-
* createText('return fetch(id)')
|
|
758
|
-
* // { kind: 'Text', value: 'return fetch(id)' }
|
|
759
|
-
* ```
|
|
760
|
-
*/
|
|
761
|
-
const createText = textDef.create;
|
|
762
|
-
/**
|
|
763
|
-
* Definition for the {@link BreakNode}.
|
|
764
|
-
*/
|
|
765
|
-
const breakDef = defineNode({
|
|
766
|
-
kind: "Break",
|
|
767
|
-
build: () => ({})
|
|
768
|
-
});
|
|
769
|
-
/**
|
|
770
|
-
* Creates a {@link BreakNode} representing a line break in the source output.
|
|
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.
|
|
771
676
|
*
|
|
772
677
|
* @example
|
|
773
678
|
* ```ts
|
|
774
|
-
*
|
|
775
|
-
* //
|
|
679
|
+
* stringify('hello') // "'hello'"
|
|
680
|
+
* stringify('"hello"') // "'hello'"
|
|
776
681
|
* ```
|
|
777
682
|
*/
|
|
778
|
-
function
|
|
779
|
-
|
|
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, "\\'")}'`;
|
|
780
686
|
}
|
|
781
687
|
/**
|
|
782
|
-
*
|
|
783
|
-
|
|
784
|
-
const jsxDef = defineNode({
|
|
785
|
-
kind: "Jsx",
|
|
786
|
-
build: (value) => ({ value })
|
|
787
|
-
});
|
|
788
|
-
/**
|
|
789
|
-
* Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
|
|
790
|
-
*
|
|
791
|
-
* @example
|
|
792
|
-
* ```ts
|
|
793
|
-
* createJsx('<>\n <a href={href}>Open</a>\n</>')
|
|
794
|
-
* // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
|
|
795
|
-
* ```
|
|
796
|
-
*/
|
|
797
|
-
const createJsx = jsxDef.create;
|
|
798
|
-
//#endregion
|
|
799
|
-
//#region src/nodes/content.ts
|
|
800
|
-
/**
|
|
801
|
-
* Definition for the {@link ContentNode}.
|
|
802
|
-
*/
|
|
803
|
-
const contentDef = defineNode({
|
|
804
|
-
kind: "Content",
|
|
805
|
-
children: ["schema"]
|
|
806
|
-
});
|
|
807
|
-
/**
|
|
808
|
-
* Creates a `ContentNode` for a single request-body or response content type.
|
|
809
|
-
*/
|
|
810
|
-
const createContent = contentDef.create;
|
|
811
|
-
//#endregion
|
|
812
|
-
//#region src/nodes/file.ts
|
|
813
|
-
/**
|
|
814
|
-
* Definition for the {@link ImportNode}.
|
|
815
|
-
*/
|
|
816
|
-
const importDef = defineNode({ kind: "Import" });
|
|
817
|
-
/**
|
|
818
|
-
* Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
|
|
819
|
-
*
|
|
820
|
-
* @example Named import
|
|
821
|
-
* ```ts
|
|
822
|
-
* createImport({ name: ['useState'], path: 'react' })
|
|
823
|
-
* // import { useState } from 'react'
|
|
824
|
-
* ```
|
|
825
|
-
*/
|
|
826
|
-
const createImport = importDef.create;
|
|
827
|
-
/**
|
|
828
|
-
* Definition for the {@link ExportNode}.
|
|
829
|
-
*/
|
|
830
|
-
const exportDef = defineNode({ kind: "Export" });
|
|
831
|
-
/**
|
|
832
|
-
* Creates an `ExportNode` representing a language-agnostic export/public API declaration.
|
|
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.
|
|
833
690
|
*
|
|
834
|
-
* @
|
|
835
|
-
* ```ts
|
|
836
|
-
* createExport({ name: ['Pet'], path: './Pet' })
|
|
837
|
-
* // export { Pet } from './Pet'
|
|
838
|
-
* ```
|
|
839
|
-
*/
|
|
840
|
-
const createExport = exportDef.create;
|
|
841
|
-
/**
|
|
842
|
-
* Definition for the {@link SourceNode}.
|
|
843
|
-
*/
|
|
844
|
-
const sourceDef = defineNode({ kind: "Source" });
|
|
845
|
-
/**
|
|
846
|
-
* Creates a `SourceNode` representing a fragment of source code within a file.
|
|
691
|
+
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
847
692
|
*
|
|
848
693
|
* @example
|
|
849
694
|
* ```ts
|
|
850
|
-
*
|
|
695
|
+
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
851
696
|
* ```
|
|
852
697
|
*/
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
const inputDef = defineNode({
|
|
865
|
-
kind: "Input",
|
|
866
|
-
defaults: {
|
|
867
|
-
schemas: [],
|
|
868
|
-
operations: [],
|
|
869
|
-
meta: {
|
|
870
|
-
circularNames: [],
|
|
871
|
-
enumNames: []
|
|
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 "";
|
|
872
709
|
}
|
|
873
|
-
}
|
|
874
|
-
children: ["schemas", "operations"],
|
|
875
|
-
visitorKey: "input"
|
|
876
|
-
});
|
|
877
|
-
/**
|
|
878
|
-
* Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
|
|
879
|
-
* `operations` are `AsyncIterable` sources and whose `meta` is optional. Otherwise it builds the
|
|
880
|
-
* eager variant with array `schemas`/`operations` and the defaulted `meta`.
|
|
881
|
-
*
|
|
882
|
-
* @example Eager
|
|
883
|
-
* ```ts
|
|
884
|
-
* const input = createInput()
|
|
885
|
-
* // { kind: 'Input', schemas: [], operations: [] }
|
|
886
|
-
* ```
|
|
887
|
-
*
|
|
888
|
-
* @example Streaming
|
|
889
|
-
* ```ts
|
|
890
|
-
* const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
|
|
891
|
-
* ```
|
|
892
|
-
*/
|
|
893
|
-
function createInput(options = {}) {
|
|
894
|
-
const { stream, ...overrides } = options;
|
|
895
|
-
if (stream) return {
|
|
896
|
-
kind: "Input",
|
|
897
|
-
...overrides
|
|
898
|
-
};
|
|
899
|
-
return inputDef.create(overrides);
|
|
900
|
-
}
|
|
901
|
-
//#endregion
|
|
902
|
-
//#region src/nodes/requestBody.ts
|
|
903
|
-
/**
|
|
904
|
-
* Definition for the {@link RequestBodyNode}, normalizing each content entry into a `ContentNode`.
|
|
905
|
-
*/
|
|
906
|
-
const requestBodyDef = defineNode({
|
|
907
|
-
kind: "RequestBody",
|
|
908
|
-
build: (props) => ({
|
|
909
|
-
...props,
|
|
910
|
-
content: props.content?.map(createContent)
|
|
911
|
-
}),
|
|
912
|
-
children: ["content"]
|
|
913
|
-
});
|
|
914
|
-
/**
|
|
915
|
-
* Creates a `RequestBodyNode`, normalizing each content entry into a `ContentNode`.
|
|
916
|
-
*/
|
|
917
|
-
const createRequestBody = requestBodyDef.create;
|
|
918
|
-
//#endregion
|
|
919
|
-
//#region src/nodes/operation.ts
|
|
920
|
-
/**
|
|
921
|
-
* Definition for the {@link OperationNode}. HTTP operations (those carrying both
|
|
922
|
-
* `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
|
|
923
|
-
* normalized into a `RequestBodyNode`.
|
|
924
|
-
*/
|
|
925
|
-
const operationDef = defineNode({
|
|
926
|
-
kind: "Operation",
|
|
927
|
-
build: (props) => {
|
|
928
|
-
const { requestBody, ...rest } = props;
|
|
929
|
-
const isHttp = rest.method !== void 0 && rest.path !== void 0;
|
|
930
|
-
return {
|
|
931
|
-
tags: [],
|
|
932
|
-
parameters: [],
|
|
933
|
-
responses: [],
|
|
934
|
-
...rest,
|
|
935
|
-
...isHttp ? { protocol: "http" } : {},
|
|
936
|
-
requestBody: requestBody ? createRequestBody(requestBody) : void 0
|
|
937
|
-
};
|
|
938
|
-
},
|
|
939
|
-
children: [
|
|
940
|
-
"parameters",
|
|
941
|
-
"requestBody",
|
|
942
|
-
"responses"
|
|
943
|
-
],
|
|
944
|
-
visitorKey: "operation"
|
|
945
|
-
});
|
|
946
|
-
function createOperation(props) {
|
|
947
|
-
return operationDef.create(props);
|
|
710
|
+
});
|
|
948
711
|
}
|
|
949
|
-
//#endregion
|
|
950
|
-
//#region src/nodes/output.ts
|
|
951
712
|
/**
|
|
952
|
-
*
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
kind: "Output",
|
|
956
|
-
defaults: { files: [] },
|
|
957
|
-
visitorKey: "output"
|
|
958
|
-
});
|
|
959
|
-
/**
|
|
960
|
-
* Creates an `OutputNode` with a stable default for `files`.
|
|
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.
|
|
961
716
|
*
|
|
962
717
|
* @example
|
|
963
718
|
* ```ts
|
|
964
|
-
*
|
|
965
|
-
*
|
|
719
|
+
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
720
|
+
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
966
721
|
* ```
|
|
967
722
|
*/
|
|
968
|
-
function
|
|
969
|
-
|
|
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)}` : ""})`;
|
|
970
732
|
}
|
|
971
|
-
//#endregion
|
|
972
|
-
//#region src/nodes/parameter.ts
|
|
973
|
-
/**
|
|
974
|
-
* Definition for the {@link ParameterNode}. `required` defaults to `false` and the
|
|
975
|
-
* schema's `optional`/`nullish` flags are kept in sync with it.
|
|
976
|
-
*/
|
|
977
|
-
const parameterDef = defineNode({
|
|
978
|
-
kind: "Parameter",
|
|
979
|
-
build: (props) => {
|
|
980
|
-
const required = props.required ?? false;
|
|
981
|
-
return {
|
|
982
|
-
...props,
|
|
983
|
-
required,
|
|
984
|
-
schema: syncOptionality(props.schema, required)
|
|
985
|
-
};
|
|
986
|
-
},
|
|
987
|
-
children: ["schema"],
|
|
988
|
-
visitorKey: "parameter",
|
|
989
|
-
rebuild: true
|
|
990
|
-
});
|
|
991
733
|
/**
|
|
992
|
-
*
|
|
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.
|
|
993
737
|
*
|
|
994
738
|
* @example
|
|
995
739
|
* ```ts
|
|
996
|
-
*
|
|
997
|
-
*
|
|
998
|
-
* in: 'path',
|
|
999
|
-
* required: true,
|
|
1000
|
-
* schema: createSchema({ type: 'string' }),
|
|
1001
|
-
* })
|
|
740
|
+
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
|
|
741
|
+
* // 'foo: bar,\nnested: {\n a: 1\n }'
|
|
1002
742
|
* ```
|
|
1003
743
|
*/
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
*/
|
|
1011
|
-
const responseDef = defineNode({
|
|
1012
|
-
kind: "Response",
|
|
1013
|
-
build: (props) => {
|
|
1014
|
-
const { schema, mediaType, keysToOmit, content, ...rest } = props;
|
|
1015
|
-
const entries = content ?? (schema ? [{
|
|
1016
|
-
contentType: mediaType ?? "application/json",
|
|
1017
|
-
schema,
|
|
1018
|
-
keysToOmit: keysToOmit ?? null
|
|
1019
|
-
}] : void 0);
|
|
1020
|
-
return {
|
|
1021
|
-
...rest,
|
|
1022
|
-
content: entries?.map(createContent)
|
|
1023
|
-
};
|
|
1024
|
-
},
|
|
1025
|
-
children: ["content"],
|
|
1026
|
-
visitorKey: "response"
|
|
1027
|
-
});
|
|
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
|
+
}
|
|
1028
750
|
/**
|
|
1029
|
-
*
|
|
751
|
+
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
|
|
752
|
+
* `accessor`. Returns `null` for an empty path.
|
|
1030
753
|
*
|
|
1031
754
|
* @example
|
|
1032
755
|
* ```ts
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1035
|
-
* content: [{ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) }],
|
|
1036
|
-
* })
|
|
756
|
+
* getNestedAccessor('pagination.next.id', 'lastPage')
|
|
757
|
+
* // "lastPage?.['pagination']?.['next']?.['id']"
|
|
1037
758
|
* ```
|
|
1038
759
|
*/
|
|
1039
|
-
|
|
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
|
+
}
|
|
1040
765
|
//#endregion
|
|
1041
766
|
//#region src/registry.ts
|
|
1042
767
|
/**
|
|
1043
768
|
* Every node definition. Adding a node means adding its `defineNode` to one
|
|
1044
|
-
* `nodes/*.ts` file and listing it here. The visitor tables
|
|
769
|
+
* `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
|
|
1045
770
|
*/
|
|
1046
771
|
const nodeDefs = [
|
|
1047
772
|
inputDef,
|
|
@@ -1070,6 +795,8 @@ const nodeDefs = [
|
|
|
1070
795
|
sourceDef,
|
|
1071
796
|
fileDef
|
|
1072
797
|
];
|
|
798
|
+
//#endregion
|
|
799
|
+
//#region src/visitor.ts
|
|
1073
800
|
/**
|
|
1074
801
|
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
|
|
1075
802
|
* Derived from each definition's `children`.
|
|
@@ -1085,8 +812,6 @@ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.vis
|
|
|
1085
812
|
* definition's `rebuild` flag.
|
|
1086
813
|
*/
|
|
1087
814
|
const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
|
|
1088
|
-
//#endregion
|
|
1089
|
-
//#region src/visitor.ts
|
|
1090
815
|
/**
|
|
1091
816
|
* Creates a small async concurrency limiter.
|
|
1092
817
|
*
|
|
@@ -1153,9 +878,9 @@ function* getChildren(node, recurse) {
|
|
|
1153
878
|
}
|
|
1154
879
|
}
|
|
1155
880
|
/**
|
|
1156
|
-
*
|
|
1157
|
-
* context.
|
|
1158
|
-
*
|
|
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.
|
|
1159
884
|
*
|
|
1160
885
|
* Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
|
|
1161
886
|
* in one place. `TResult` is the caller's expected return: the same node type
|
|
@@ -1270,8 +995,8 @@ function* collectLazy(node, options) {
|
|
|
1270
995
|
});
|
|
1271
996
|
}
|
|
1272
997
|
/**
|
|
1273
|
-
* Eager depth-first collection pass.
|
|
1274
|
-
*
|
|
998
|
+
* Eager depth-first collection pass. Gathers every non-null value the visitor
|
|
999
|
+
* callbacks return into an array.
|
|
1275
1000
|
*
|
|
1276
1001
|
* @example Collect every operationId
|
|
1277
1002
|
* ```ts
|
|
@@ -1286,104 +1011,169 @@ function collect(node, options) {
|
|
|
1286
1011
|
return Array.from(collectLazy(node, options));
|
|
1287
1012
|
}
|
|
1288
1013
|
//#endregion
|
|
1289
|
-
//#region src/utils/
|
|
1290
|
-
const plainStringTypes = new Set([
|
|
1291
|
-
"string",
|
|
1292
|
-
"uuid",
|
|
1293
|
-
"email",
|
|
1294
|
-
"url",
|
|
1295
|
-
"datetime"
|
|
1296
|
-
]);
|
|
1014
|
+
//#region src/utils/schemaGraph.ts
|
|
1297
1015
|
/**
|
|
1298
|
-
*
|
|
1016
|
+
* Collects every named schema referenced transitively from a node through its ref edges.
|
|
1299
1017
|
*
|
|
1300
|
-
*
|
|
1301
|
-
* override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
|
|
1018
|
+
* Refs are followed by name only, so the resolved `node.schema` is never traversed inline.
|
|
1302
1019
|
*
|
|
1303
|
-
* @example
|
|
1020
|
+
* @example Collect refs from a single schema
|
|
1304
1021
|
* ```ts
|
|
1305
|
-
*
|
|
1306
|
-
*
|
|
1307
|
-
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
|
|
1022
|
+
* const names = collectReferencedSchemaNames(petSchema)
|
|
1023
|
+
* // → Set { 'Category', 'Tag' }
|
|
1308
1024
|
* ```
|
|
1309
|
-
*/
|
|
1310
|
-
function syncSchemaRef(node) {
|
|
1311
|
-
const ref = narrowSchema(node, "ref");
|
|
1312
|
-
if (!ref) return node;
|
|
1313
|
-
if (!ref.schema) return node;
|
|
1314
|
-
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
|
|
1315
|
-
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
|
|
1316
|
-
return createSchema({
|
|
1317
|
-
...ref.schema,
|
|
1318
|
-
...definedOverrides
|
|
1319
|
-
});
|
|
1320
|
-
}
|
|
1321
|
-
/**
|
|
1322
|
-
* Type guard that returns `true` when a schema emits as a plain `string` type.
|
|
1323
1025
|
*
|
|
1324
|
-
*
|
|
1325
|
-
*
|
|
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
|
+
* ```
|
|
1326
1033
|
*/
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
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;
|
|
1332
1048
|
}
|
|
1333
1049
|
/**
|
|
1334
|
-
*
|
|
1050
|
+
* Collects the names of all top-level schemas transitively used by a set of operations.
|
|
1335
1051
|
*
|
|
1336
|
-
*
|
|
1337
|
-
*
|
|
1338
|
-
* The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
|
|
1339
|
-
*/
|
|
1340
|
-
const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
|
|
1341
|
-
const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
|
|
1342
|
-
return {
|
|
1343
|
-
...param,
|
|
1344
|
-
name: transformed
|
|
1345
|
-
};
|
|
1346
|
-
})));
|
|
1347
|
-
function caseParams(params, casing) {
|
|
1348
|
-
if (!casing) return params;
|
|
1349
|
-
return caseParamsMemo(params)(casing);
|
|
1350
|
-
}
|
|
1351
|
-
/**
|
|
1352
|
-
* Creates a single-property object schema used as a discriminator literal.
|
|
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.
|
|
1353
1054
|
*
|
|
1354
|
-
*
|
|
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
|
|
1355
1058
|
* ```ts
|
|
1356
|
-
*
|
|
1357
|
-
*
|
|
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
|
+
* }
|
|
1358
1066
|
* ```
|
|
1359
1067
|
*/
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
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;
|
|
1374
1086
|
}
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
const
|
|
1386
|
-
const
|
|
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/operationParams.ts
|
|
1147
|
+
/**
|
|
1148
|
+
* Applies casing rules to parameter names and returns a new array without mutating the input.
|
|
1149
|
+
*
|
|
1150
|
+
* Run it before handing parameters to schema builders so output property keys get the right casing
|
|
1151
|
+
* while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
|
|
1152
|
+
* original array is returned unchanged.
|
|
1153
|
+
*/
|
|
1154
|
+
const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
|
|
1155
|
+
const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
|
|
1156
|
+
return {
|
|
1157
|
+
...param,
|
|
1158
|
+
name: transformed
|
|
1159
|
+
};
|
|
1160
|
+
})));
|
|
1161
|
+
function caseParams(params, casing) {
|
|
1162
|
+
if (!casing) return params;
|
|
1163
|
+
return caseParamsMemo(params)(casing);
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Resolves the {@link TypeExpression} for an individual parameter.
|
|
1167
|
+
*
|
|
1168
|
+
* Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
|
|
1169
|
+
* parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
|
|
1170
|
+
* `GroupParams['petId']`, otherwise the resolved individual name.
|
|
1171
|
+
*/
|
|
1172
|
+
function resolveParamType({ node, param, resolver }) {
|
|
1173
|
+
if (!resolver) return param.schema.primitive ?? "unknown";
|
|
1174
|
+
const individualName = resolver.resolveParamName(node, param);
|
|
1175
|
+
const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
|
|
1176
|
+
const groupResolvers = {
|
|
1387
1177
|
path: resolver.resolvePathParamsName,
|
|
1388
1178
|
query: resolver.resolveQueryParamsName,
|
|
1389
1179
|
header: resolver.resolveHeaderParamsName
|
|
@@ -1540,560 +1330,7 @@ function buildTypeLiteral({ node, params, resolver }) {
|
|
|
1540
1330
|
optional: !p.required
|
|
1541
1331
|
})) });
|
|
1542
1332
|
}
|
|
1543
|
-
function sourceKey(source) {
|
|
1544
|
-
return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
|
|
1545
|
-
}
|
|
1546
|
-
function pathTypeKey(path, isTypeOnly) {
|
|
1547
|
-
return `${path}:${isTypeOnly ?? false}`;
|
|
1548
|
-
}
|
|
1549
|
-
function exportKey(path, name, isTypeOnly, asAlias) {
|
|
1550
|
-
return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
|
|
1551
|
-
}
|
|
1552
|
-
function importKey(path, name, isTypeOnly) {
|
|
1553
|
-
return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
|
|
1554
|
-
}
|
|
1555
|
-
/**
|
|
1556
|
-
* Computes a multi-level sort key for exports and imports:
|
|
1557
|
-
* non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
|
|
1558
|
-
*/
|
|
1559
|
-
function sortKey(node) {
|
|
1560
|
-
const isArray = Array.isArray(node.name) ? "1" : "0";
|
|
1561
|
-
const typeOnly = node.isTypeOnly ? "0" : "1";
|
|
1562
|
-
const hasName = node.name != null ? "1" : "0";
|
|
1563
|
-
const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
|
|
1564
|
-
return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
|
|
1565
|
-
}
|
|
1566
|
-
/**
|
|
1567
|
-
* Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
|
|
1568
|
-
*
|
|
1569
|
-
* Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
|
|
1570
|
-
*/
|
|
1571
|
-
function combineSources(sources) {
|
|
1572
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1573
|
-
for (const source of sources) {
|
|
1574
|
-
const key = sourceKey(source);
|
|
1575
|
-
if (!seen.has(key)) seen.set(key, source);
|
|
1576
|
-
}
|
|
1577
|
-
return [...seen.values()];
|
|
1578
|
-
}
|
|
1579
|
-
/**
|
|
1580
|
-
* Merges `incoming` names into `existing`, preserving order and dropping duplicates.
|
|
1581
|
-
*
|
|
1582
|
-
* Shared by `combineExports` and `combineImports` for the same-path name-merge case.
|
|
1583
|
-
*/
|
|
1584
|
-
function mergeNameArrays(existing, incoming) {
|
|
1585
|
-
const merged = new Set(existing);
|
|
1586
|
-
for (const name of incoming) merged.add(name);
|
|
1587
|
-
return [...merged];
|
|
1588
|
-
}
|
|
1589
|
-
/**
|
|
1590
|
-
* Deduplicates and merges `ExportNode` objects by path and type.
|
|
1591
|
-
*
|
|
1592
|
-
* Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
|
|
1593
|
-
* Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
|
|
1594
|
-
*/
|
|
1595
|
-
function combineExports(exports) {
|
|
1596
|
-
const result = [];
|
|
1597
|
-
const namedByPath = /* @__PURE__ */ new Map();
|
|
1598
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1599
|
-
const keyed = exports.map((node) => ({
|
|
1600
|
-
node,
|
|
1601
|
-
key: sortKey(node)
|
|
1602
|
-
}));
|
|
1603
|
-
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
1604
|
-
for (const { node: curr } of keyed) {
|
|
1605
|
-
const { name, path, isTypeOnly, asAlias } = curr;
|
|
1606
|
-
if (Array.isArray(name)) {
|
|
1607
|
-
if (!name.length) continue;
|
|
1608
|
-
const key = pathTypeKey(path, isTypeOnly);
|
|
1609
|
-
const existing = namedByPath.get(key);
|
|
1610
|
-
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
|
|
1611
|
-
else {
|
|
1612
|
-
const newItem = {
|
|
1613
|
-
...curr,
|
|
1614
|
-
name: [...new Set(name)]
|
|
1615
|
-
};
|
|
1616
|
-
result.push(newItem);
|
|
1617
|
-
namedByPath.set(key, newItem);
|
|
1618
|
-
}
|
|
1619
|
-
} else {
|
|
1620
|
-
const key = exportKey(path, name, isTypeOnly, asAlias);
|
|
1621
|
-
if (!seen.has(key)) {
|
|
1622
|
-
result.push(curr);
|
|
1623
|
-
seen.add(key);
|
|
1624
|
-
}
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
return result;
|
|
1628
|
-
}
|
|
1629
|
-
/**
|
|
1630
|
-
* Deduplicates and merges `ImportNode` objects, filtering out unused imports.
|
|
1631
|
-
*
|
|
1632
|
-
* Retains imports that are referenced in `source` or re-exported. Imports with the same path and
|
|
1633
|
-
* `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
|
|
1634
|
-
*
|
|
1635
|
-
* @note Use this when combining imports from multiple files to avoid duplicate declarations.
|
|
1636
|
-
*/
|
|
1637
|
-
function combineImports(imports, exports, source) {
|
|
1638
|
-
const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
|
|
1639
|
-
const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
|
|
1640
|
-
const importNameMemo = /* @__PURE__ */ new Map();
|
|
1641
|
-
const canonicalizeName = (n) => {
|
|
1642
|
-
if (typeof n === "string") return n;
|
|
1643
|
-
const key = `${n.propertyName}:${n.name ?? ""}`;
|
|
1644
|
-
if (!importNameMemo.has(key)) importNameMemo.set(key, n);
|
|
1645
|
-
return importNameMemo.get(key);
|
|
1646
|
-
};
|
|
1647
|
-
const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
|
|
1648
|
-
for (const node of imports) {
|
|
1649
|
-
if (!Array.isArray(node.name)) continue;
|
|
1650
|
-
if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
|
|
1651
|
-
}
|
|
1652
|
-
const result = [];
|
|
1653
|
-
const namedByPath = /* @__PURE__ */ new Map();
|
|
1654
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1655
|
-
const keyed = imports.map((node) => ({
|
|
1656
|
-
node,
|
|
1657
|
-
key: sortKey(node)
|
|
1658
|
-
}));
|
|
1659
|
-
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
1660
|
-
for (const { node: curr } of keyed) {
|
|
1661
|
-
if (curr.path === curr.root) continue;
|
|
1662
|
-
const { path, isTypeOnly } = curr;
|
|
1663
|
-
let { name } = curr;
|
|
1664
|
-
if (Array.isArray(name)) {
|
|
1665
|
-
name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
|
|
1666
|
-
if (!name.length) continue;
|
|
1667
|
-
const key = pathTypeKey(path, isTypeOnly);
|
|
1668
|
-
const existing = namedByPath.get(key);
|
|
1669
|
-
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
|
|
1670
|
-
else {
|
|
1671
|
-
const newItem = {
|
|
1672
|
-
...curr,
|
|
1673
|
-
name
|
|
1674
|
-
};
|
|
1675
|
-
result.push(newItem);
|
|
1676
|
-
namedByPath.set(key, newItem);
|
|
1677
|
-
}
|
|
1678
|
-
} else {
|
|
1679
|
-
if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
|
|
1680
|
-
const key = importKey(path, name, isTypeOnly);
|
|
1681
|
-
if (!seen.has(key)) {
|
|
1682
|
-
result.push(curr);
|
|
1683
|
-
seen.add(key);
|
|
1684
|
-
}
|
|
1685
|
-
}
|
|
1686
|
-
}
|
|
1687
|
-
return result;
|
|
1688
|
-
}
|
|
1689
|
-
/**
|
|
1690
|
-
* Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
|
|
1691
|
-
*
|
|
1692
|
-
* Returns `null` for non-ref nodes or when no name can be resolved. Use this to get a schema's
|
|
1693
|
-
* identifier for type definitions or error messages.
|
|
1694
|
-
*
|
|
1695
|
-
* @example
|
|
1696
|
-
* ```ts
|
|
1697
|
-
* resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
|
|
1698
|
-
* // => 'Pet'
|
|
1699
|
-
* ```
|
|
1700
|
-
*/
|
|
1701
|
-
function resolveRefName(node) {
|
|
1702
|
-
if (!node || node.type !== "ref") return null;
|
|
1703
|
-
if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
|
|
1704
|
-
return node.name ?? node.schema?.name ?? null;
|
|
1705
|
-
}
|
|
1706
|
-
/**
|
|
1707
|
-
* Collects every named schema referenced (transitively) from a node via ref edges.
|
|
1708
|
-
*
|
|
1709
|
-
* Refs are followed by name only, the resolved `node.schema` is not traversed inline.
|
|
1710
|
-
* Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
|
|
1711
|
-
*
|
|
1712
|
-
* @example Collect refs from a single schema
|
|
1713
|
-
* ```ts
|
|
1714
|
-
* const names = collectReferencedSchemaNames(petSchema)
|
|
1715
|
-
* // → Set { 'Category', 'Tag' }
|
|
1716
|
-
* ```
|
|
1717
|
-
*
|
|
1718
|
-
* @example Accumulate refs from multiple schemas into one set
|
|
1719
|
-
* ```ts
|
|
1720
|
-
* const out = new Set<string>()
|
|
1721
|
-
* for (const schema of schemas) {
|
|
1722
|
-
* collectReferencedSchemaNames(schema, out)
|
|
1723
|
-
* }
|
|
1724
|
-
* ```
|
|
1725
|
-
*/
|
|
1726
|
-
const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
|
|
1727
|
-
const refs = /* @__PURE__ */ new Set();
|
|
1728
|
-
collect(node, { schema(child) {
|
|
1729
|
-
if (child.type === "ref") {
|
|
1730
|
-
const name = resolveRefName(child);
|
|
1731
|
-
if (name) refs.add(name);
|
|
1732
|
-
}
|
|
1733
|
-
} });
|
|
1734
|
-
return refs;
|
|
1735
|
-
});
|
|
1736
|
-
function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
|
|
1737
|
-
if (!node) return out;
|
|
1738
|
-
for (const name of collectSchemaRefs(node)) out.add(name);
|
|
1739
|
-
return out;
|
|
1740
|
-
}
|
|
1741
|
-
/**
|
|
1742
|
-
* Collects the names of all top-level schemas transitively used by a set of operations.
|
|
1743
|
-
*
|
|
1744
|
-
* An operation uses a schema when any of its parameters, request body content, or responses
|
|
1745
|
-
* reference it, directly or indirectly through other named schemas.
|
|
1746
|
-
* The walk is iterative and safe against reference cycles.
|
|
1747
|
-
*
|
|
1748
|
-
* Use this together with `include` filters to determine which schemas from `components/schemas`
|
|
1749
|
-
* are reachable from the allowed operations, so that schemas used only by excluded operations
|
|
1750
|
-
* are not generated.
|
|
1751
|
-
*
|
|
1752
|
-
* @example Only generate schemas referenced by included operations
|
|
1753
|
-
* ```ts
|
|
1754
|
-
* const includedOps = operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
|
|
1755
|
-
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1756
|
-
*
|
|
1757
|
-
* for (const schema of schemas) {
|
|
1758
|
-
* if (schema.name && !allowed.has(schema.name)) continue
|
|
1759
|
-
* // … generate schema
|
|
1760
|
-
* }
|
|
1761
|
-
* ```
|
|
1762
|
-
*
|
|
1763
|
-
* @example Check whether a specific schema is needed
|
|
1764
|
-
* ```ts
|
|
1765
|
-
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1766
|
-
* allowed.has('OrderStatus') // false when no included operation references OrderStatus
|
|
1767
|
-
* ```
|
|
1768
|
-
*/
|
|
1769
|
-
const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
|
|
1770
|
-
function computeUsedSchemaNames(operations, schemas) {
|
|
1771
|
-
const schemaMap = /* @__PURE__ */ new Map();
|
|
1772
|
-
for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
|
|
1773
|
-
const result = /* @__PURE__ */ new Set();
|
|
1774
|
-
function visitSchema(schema) {
|
|
1775
|
-
const directRefs = collectReferencedSchemaNames(schema);
|
|
1776
|
-
for (const name of directRefs) if (!result.has(name)) {
|
|
1777
|
-
result.add(name);
|
|
1778
|
-
const namedSchema = schemaMap.get(name);
|
|
1779
|
-
if (namedSchema) visitSchema(namedSchema);
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
for (const op of operations) for (const schema of collectLazy(op, {
|
|
1783
|
-
depth: "shallow",
|
|
1784
|
-
schema: (node) => node
|
|
1785
|
-
})) visitSchema(schema);
|
|
1786
|
-
return result;
|
|
1787
|
-
}
|
|
1788
|
-
function collectUsedSchemaNames(operations, schemas) {
|
|
1789
|
-
return collectUsedSchemaNamesMemo(operations)(schemas);
|
|
1790
|
-
}
|
|
1791
|
-
const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
|
|
1792
|
-
const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
|
|
1793
|
-
const graph = /* @__PURE__ */ new Map();
|
|
1794
|
-
for (const schema of schemas) {
|
|
1795
|
-
if (!schema.name) continue;
|
|
1796
|
-
graph.set(schema.name, collectReferencedSchemaNames(schema));
|
|
1797
|
-
}
|
|
1798
|
-
const circular = /* @__PURE__ */ new Set();
|
|
1799
|
-
for (const start of graph.keys()) {
|
|
1800
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1801
|
-
const stack = [...graph.get(start) ?? []];
|
|
1802
|
-
while (stack.length > 0) {
|
|
1803
|
-
const node = stack.pop();
|
|
1804
|
-
if (node === start) {
|
|
1805
|
-
circular.add(start);
|
|
1806
|
-
break;
|
|
1807
|
-
}
|
|
1808
|
-
if (visited.has(node)) continue;
|
|
1809
|
-
visited.add(node);
|
|
1810
|
-
const next = graph.get(node);
|
|
1811
|
-
if (next) for (const r of next) stack.push(r);
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
return circular;
|
|
1815
|
-
});
|
|
1816
|
-
/**
|
|
1817
|
-
* Identifies all schemas that participate in circular dependency chains, including direct self-loops.
|
|
1818
|
-
*
|
|
1819
|
-
* Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
|
|
1820
|
-
* in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
|
|
1821
|
-
* Refs are followed by name only, keeping the algorithm linear in the schema graph size.
|
|
1822
|
-
*
|
|
1823
|
-
* @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
|
|
1824
|
-
*/
|
|
1825
|
-
function findCircularSchemas(schemas) {
|
|
1826
|
-
if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
|
|
1827
|
-
return findCircularSchemasMemo(schemas);
|
|
1828
|
-
}
|
|
1829
|
-
/**
|
|
1830
|
-
* Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
|
|
1831
|
-
*
|
|
1832
|
-
* Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
|
|
1833
|
-
* Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
|
|
1834
|
-
*
|
|
1835
|
-
* @note Returns `true` for the first matching circular ref found. Use for fast dependency checks.
|
|
1836
|
-
*/
|
|
1837
|
-
function containsCircularRef(node, { circularSchemas, excludeName }) {
|
|
1838
|
-
if (!node || circularSchemas.size === 0) return false;
|
|
1839
|
-
for (const _ of collectLazy(node, { schema(child) {
|
|
1840
|
-
if (child.type !== "ref") return null;
|
|
1841
|
-
const name = resolveRefName(child);
|
|
1842
|
-
return name && name !== excludeName && circularSchemas.has(name) ? true : null;
|
|
1843
|
-
} })) return true;
|
|
1844
|
-
return false;
|
|
1845
|
-
}
|
|
1846
|
-
//#endregion
|
|
1847
|
-
//#region src/utils/index.ts
|
|
1848
|
-
/**
|
|
1849
|
-
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
1850
|
-
* Returns the string unchanged when no balanced quote pair is found.
|
|
1851
|
-
*
|
|
1852
|
-
* @example
|
|
1853
|
-
* ```ts
|
|
1854
|
-
* trimQuotes('"hello"') // 'hello'
|
|
1855
|
-
* trimQuotes('hello') // 'hello'
|
|
1856
|
-
* ```
|
|
1857
|
-
*/
|
|
1858
|
-
function trimQuotes(text) {
|
|
1859
|
-
if (text.length >= 2) {
|
|
1860
|
-
const first = text[0];
|
|
1861
|
-
const last = text[text.length - 1];
|
|
1862
|
-
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
|
|
1863
|
-
}
|
|
1864
|
-
return text;
|
|
1865
|
-
}
|
|
1866
|
-
/**
|
|
1867
|
-
* Serializes a primitive value to a single-quoted string literal, stripping any surrounding quote
|
|
1868
|
-
* characters first. Escaping comes from `JSON.stringify`, then the quote style switches to single
|
|
1869
|
-
* quotes so generated code matches the repo style without a formatter.
|
|
1870
|
-
*
|
|
1871
|
-
* @example
|
|
1872
|
-
* ```ts
|
|
1873
|
-
* stringify('hello') // "'hello'"
|
|
1874
|
-
* stringify('"hello"') // "'hello'"
|
|
1875
|
-
* ```
|
|
1876
|
-
*/
|
|
1877
|
-
function stringify(value) {
|
|
1878
|
-
if (value === void 0 || value === null) return "''";
|
|
1879
|
-
return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
|
|
1880
|
-
}
|
|
1881
|
-
/**
|
|
1882
|
-
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
|
|
1883
|
-
* and the Unicode line terminators U+2028 and U+2029.
|
|
1884
|
-
*
|
|
1885
|
-
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
1886
|
-
*
|
|
1887
|
-
* @example
|
|
1888
|
-
* ```ts
|
|
1889
|
-
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
1890
|
-
* ```
|
|
1891
|
-
*/
|
|
1892
|
-
function jsStringEscape(input) {
|
|
1893
|
-
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
|
|
1894
|
-
switch (character) {
|
|
1895
|
-
case "\"":
|
|
1896
|
-
case "'":
|
|
1897
|
-
case "\\": return `\\${character}`;
|
|
1898
|
-
case "\n": return "\\n";
|
|
1899
|
-
case "\r": return "\\r";
|
|
1900
|
-
case "\u2028": return "\\u2028";
|
|
1901
|
-
case "\u2029": return "\\u2029";
|
|
1902
|
-
default: return "";
|
|
1903
|
-
}
|
|
1904
|
-
});
|
|
1905
|
-
}
|
|
1906
|
-
/**
|
|
1907
|
-
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
|
|
1908
|
-
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
|
|
1909
|
-
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
|
|
1910
|
-
*
|
|
1911
|
-
* @example
|
|
1912
|
-
* ```ts
|
|
1913
|
-
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
1914
|
-
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
1915
|
-
* ```
|
|
1916
|
-
*/
|
|
1917
|
-
function toRegExpString(text, func = "RegExp") {
|
|
1918
|
-
const raw = trimQuotes(text);
|
|
1919
|
-
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
|
|
1920
|
-
const replacementTarget = match?.[1] ?? "";
|
|
1921
|
-
const matchedFlags = match?.[2];
|
|
1922
|
-
const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
|
|
1923
|
-
const { source, flags } = new RegExp(cleaned, matchedFlags);
|
|
1924
|
-
if (func === null) return `/${source}/${flags}`;
|
|
1925
|
-
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
|
|
1926
|
-
}
|
|
1927
|
-
/**
|
|
1928
|
-
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
|
|
1929
|
-
* objects recurse with fixed indentation, so the result drops straight into an object literal
|
|
1930
|
-
* without re-parsing.
|
|
1931
|
-
*
|
|
1932
|
-
* @example
|
|
1933
|
-
* ```ts
|
|
1934
|
-
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
|
|
1935
|
-
* // 'foo: bar,\nnested: {\n a: 1\n }'
|
|
1936
|
-
* ```
|
|
1937
|
-
*/
|
|
1938
|
-
function stringifyObject(value) {
|
|
1939
|
-
return Object.entries(value).map(([key, val]) => {
|
|
1940
|
-
if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
|
|
1941
|
-
return `${key}: ${val}`;
|
|
1942
|
-
}).filter(Boolean).join(",\n");
|
|
1943
|
-
}
|
|
1944
|
-
/**
|
|
1945
|
-
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
|
|
1946
|
-
* `accessor`. Returns `null` for an empty path.
|
|
1947
|
-
*
|
|
1948
|
-
* @example
|
|
1949
|
-
* ```ts
|
|
1950
|
-
* getNestedAccessor('pagination.next.id', 'lastPage')
|
|
1951
|
-
* // "lastPage?.['pagination']?.['next']?.['id']"
|
|
1952
|
-
* ```
|
|
1953
|
-
*/
|
|
1954
|
-
function getNestedAccessor(param, accessor) {
|
|
1955
|
-
const parts = Array.isArray(param) ? param : param.split(".");
|
|
1956
|
-
if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
|
|
1957
|
-
return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
|
|
1958
|
-
}
|
|
1959
|
-
/**
|
|
1960
|
-
* Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
|
|
1961
|
-
* comments so callers always get a usable string.
|
|
1962
|
-
*
|
|
1963
|
-
* @example
|
|
1964
|
-
* ```ts
|
|
1965
|
-
* buildJSDoc(['@type string', '@example hello'])
|
|
1966
|
-
* // '/**\n * @type string\n * @example hello\n *\/\n '
|
|
1967
|
-
* ```
|
|
1968
|
-
*/
|
|
1969
|
-
function buildJSDoc(comments, options = {}) {
|
|
1970
|
-
const { indent = " * ", suffix = "\n ", fallback = " " } = options;
|
|
1971
|
-
if (comments.length === 0) return fallback;
|
|
1972
|
-
return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
|
|
1973
|
-
}
|
|
1974
|
-
/**
|
|
1975
|
-
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
|
|
1976
|
-
*/
|
|
1977
|
-
function indentLines(text) {
|
|
1978
|
-
if (!text) return "";
|
|
1979
|
-
return text.split("\n").map((line) => line.trim() ? `${INDENT}${line}` : "").join("\n");
|
|
1980
|
-
}
|
|
1981
|
-
/**
|
|
1982
|
-
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
|
|
1983
|
-
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
|
|
1984
|
-
*
|
|
1985
|
-
* @example
|
|
1986
|
-
* ```ts
|
|
1987
|
-
* objectKey('name') // 'name'
|
|
1988
|
-
* objectKey('x-total') // "'x-total'"
|
|
1989
|
-
* ```
|
|
1990
|
-
*/
|
|
1991
|
-
function objectKey(name) {
|
|
1992
|
-
return isIdentifier(name) ? name : singleQuote(name);
|
|
1993
|
-
}
|
|
1994
|
-
/**
|
|
1995
|
-
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
1996
|
-
* level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
|
|
1997
|
-
* so callers never re-parse the generated code. A trailing comma is added per entry to match the
|
|
1998
|
-
* formatter's multi-line style.
|
|
1999
|
-
*
|
|
2000
|
-
* @example
|
|
2001
|
-
* ```ts
|
|
2002
|
-
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
2003
|
-
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
2004
|
-
* ```
|
|
2005
|
-
*/
|
|
2006
|
-
function buildObject(entries) {
|
|
2007
|
-
if (entries.length === 0) return "{}";
|
|
2008
|
-
return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
|
|
2009
|
-
}
|
|
2010
|
-
/**
|
|
2011
|
-
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
2012
|
-
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
2013
|
-
* one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
|
|
2014
|
-
* `z.array([…])`, and similar member lists so objects inside them nest correctly.
|
|
2015
|
-
*
|
|
2016
|
-
* @example
|
|
2017
|
-
* ```ts
|
|
2018
|
-
* buildList(['z.string()', 'z.number()'])
|
|
2019
|
-
* // '[z.string(), z.number()]'
|
|
2020
|
-
* ```
|
|
2021
|
-
*/
|
|
2022
|
-
function buildList(items, brackets = ["[", "]"]) {
|
|
2023
|
-
const [open, close] = brackets;
|
|
2024
|
-
if (items.length === 0) return `${open}${close}`;
|
|
2025
|
-
if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
|
|
2026
|
-
return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
|
|
2027
|
-
}
|
|
2028
|
-
/**
|
|
2029
|
-
* Returns the last path segment of a reference string.
|
|
2030
|
-
*
|
|
2031
|
-
* @example
|
|
2032
|
-
* ```ts
|
|
2033
|
-
* extractRefName('#/components/schemas/Pet') // 'Pet'
|
|
2034
|
-
* ```
|
|
2035
|
-
*/
|
|
2036
|
-
function extractRefName(ref) {
|
|
2037
|
-
return ref.split("/").at(-1) ?? ref;
|
|
2038
|
-
}
|
|
2039
|
-
/**
|
|
2040
|
-
* Builds a PascalCase child schema name by joining a parent name and property name.
|
|
2041
|
-
* Returns `null` when there is no parent to nest under.
|
|
2042
|
-
*
|
|
2043
|
-
* @example
|
|
2044
|
-
* ```ts
|
|
2045
|
-
* childName('Order', 'shipping_address') // 'OrderShippingAddress'
|
|
2046
|
-
* childName(undefined, 'params') // null
|
|
2047
|
-
* ```
|
|
2048
|
-
*/
|
|
2049
|
-
function childName(parentName, propName) {
|
|
2050
|
-
return parentName ? pascalCase([parentName, propName].join(" ")) : null;
|
|
2051
|
-
}
|
|
2052
|
-
/**
|
|
2053
|
-
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
|
|
2054
|
-
* empty parts.
|
|
2055
|
-
*
|
|
2056
|
-
* @example
|
|
2057
|
-
* ```ts
|
|
2058
|
-
* enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
|
|
2059
|
-
* ```
|
|
2060
|
-
*/
|
|
2061
|
-
function enumPropName(parentName, propName, enumSuffix) {
|
|
2062
|
-
return pascalCase([
|
|
2063
|
-
parentName,
|
|
2064
|
-
propName,
|
|
2065
|
-
enumSuffix
|
|
2066
|
-
].filter(Boolean).join(" "));
|
|
2067
|
-
}
|
|
2068
|
-
/**
|
|
2069
|
-
* Returns the discriminator key whose mapping value matches `ref`, or `null` when there is no match.
|
|
2070
|
-
*
|
|
2071
|
-
* @example
|
|
2072
|
-
* ```ts
|
|
2073
|
-
* findDiscriminator({ dog: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // 'dog'
|
|
2074
|
-
* ```
|
|
2075
|
-
*/
|
|
2076
|
-
function findDiscriminator(mapping, ref) {
|
|
2077
|
-
if (!mapping || !ref) return null;
|
|
2078
|
-
return Object.entries(mapping).find(([, value]) => value === ref)?.[0] ?? null;
|
|
2079
|
-
}
|
|
2080
|
-
/**
|
|
2081
|
-
* Derives a {@link ParamGroupType} for a query or header group from the resolver.
|
|
2082
|
-
*
|
|
2083
|
-
* Returns `null` when there is no resolver, no params, or the group name equals the
|
|
2084
|
-
* individual param name (so there is no real group to emit).
|
|
2085
|
-
*/
|
|
2086
|
-
function resolveGroupType({ node, params, group, resolver }) {
|
|
2087
|
-
if (!resolver || !params.length) return null;
|
|
2088
|
-
const firstParam = params[0];
|
|
2089
|
-
const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
|
|
2090
|
-
if (groupName === resolver.resolveParamName(node, firstParam)) return null;
|
|
2091
|
-
return {
|
|
2092
|
-
type: groupName,
|
|
2093
|
-
optional: params.every((p) => !p.required)
|
|
2094
|
-
};
|
|
2095
|
-
}
|
|
2096
1333
|
//#endregion
|
|
2097
|
-
export {
|
|
1334
|
+
export { isHttpOperationNode as A, simplifyUnion as C, extractRefName as D, enumPropName as E, objectKey as F, isValidVarName as I, httpMethods as L, buildJSDoc as M, buildList as N, isStringType as O, buildObject as P, schemaTypes as R, setEnumName as S, childName as T, stringifyObject as _, resolveParamType as a, mergeAdjacentObjectsLazy as b, findCircularSchemas as c, transform as d, walk as f, stringify as g, jsStringEscape as h, createOperationParams as i, narrowSchema as j, resolveGroupType as k, collect as l, getNestedAccessor as m, buildTypeLiteral as n, collectUsedSchemaNames as o, nodeDefs as p, caseParams as r, containsCircularRef as s, buildGroupParam as t, collectLazy as u, toRegExpString as v, syncSchemaRef as w, setDiscriminatorEnum as x, trimQuotes as y };
|
|
2098
1335
|
|
|
2099
|
-
//# sourceMappingURL=utils-
|
|
1336
|
+
//# sourceMappingURL=utils-SdZU0F3H.js.map
|