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