@kubb/plugin-ts 5.0.0-alpha.3 → 5.0.0-alpha.31
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/dist/index.cjs +1806 -3
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +590 -4
- package/dist/index.js +1776 -2
- package/dist/index.js.map +1 -0
- package/package.json +7 -27
- package/src/components/Enum.tsx +82 -0
- package/src/components/Type.tsx +29 -162
- package/src/constants.ts +39 -0
- package/src/factory.ts +134 -49
- package/src/generators/typeGenerator.tsx +165 -428
- package/src/generators/typeGeneratorLegacy.tsx +349 -0
- package/src/index.ts +9 -1
- package/src/plugin.ts +98 -176
- package/src/presets.ts +28 -0
- package/src/printers/functionPrinter.ts +196 -0
- package/src/printers/printerTs.ts +310 -0
- package/src/resolvers/resolverTs.ts +66 -0
- package/src/resolvers/resolverTsLegacy.ts +60 -0
- package/src/types.ts +258 -98
- package/src/utils.ts +131 -0
- package/dist/components-CRjwjdyE.js +0 -725
- package/dist/components-CRjwjdyE.js.map +0 -1
- package/dist/components-DI0aTIBg.cjs +0 -978
- package/dist/components-DI0aTIBg.cjs.map +0 -1
- package/dist/components.cjs +0 -3
- package/dist/components.d.ts +0 -38
- package/dist/components.js +0 -2
- package/dist/generators.cjs +0 -4
- package/dist/generators.d.ts +0 -503
- package/dist/generators.js +0 -2
- package/dist/plugin-D5rCK1zO.cjs +0 -992
- package/dist/plugin-D5rCK1zO.cjs.map +0 -1
- package/dist/plugin-DmwgRHK8.js +0 -944
- package/dist/plugin-DmwgRHK8.js.map +0 -1
- package/dist/types-BpeKGgCn.d.ts +0 -170
- package/src/components/index.ts +0 -1
- package/src/components/v2/Type.tsx +0 -165
- package/src/generators/index.ts +0 -2
- package/src/generators/v2/typeGenerator.tsx +0 -196
- package/src/parser.ts +0 -396
- package/src/printer.ts +0 -244
package/dist/index.js
CHANGED
|
@@ -1,2 +1,1776 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import "./chunk--u3MIqq1.js";
|
|
2
|
+
import { safePrint } from "@kubb/fabric-core/parsers/typescript";
|
|
3
|
+
import { File } from "@kubb/react-fabric";
|
|
4
|
+
import { caseParams, collect, createPrinterFactory, createProperty, createSchema, extractRefName, isStringType, narrowSchema, schemaTypes, syncSchemaRef, transform } from "@kubb/ast";
|
|
5
|
+
import { isNumber } from "remeda";
|
|
6
|
+
import ts from "typescript";
|
|
7
|
+
import { Fragment, jsx, jsxs } from "@kubb/react-fabric/jsx-runtime";
|
|
8
|
+
import { createPlugin, defineGenerator, definePresets, definePrinter, defineResolver, getPreset, mergeGenerators } from "@kubb/core";
|
|
9
|
+
//#region ../../internals/utils/src/casing.ts
|
|
10
|
+
/**
|
|
11
|
+
* Shared implementation for camelCase and PascalCase conversion.
|
|
12
|
+
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
13
|
+
* and capitalizes each word according to `pascal`.
|
|
14
|
+
*
|
|
15
|
+
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
16
|
+
*/
|
|
17
|
+
function toCamelOrPascal(text, pascal) {
|
|
18
|
+
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) => {
|
|
19
|
+
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
20
|
+
if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
|
|
21
|
+
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
22
|
+
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Splits `text` on `.` and applies `transformPart` to each segment.
|
|
26
|
+
* The last segment receives `isLast = true`, all earlier segments receive `false`.
|
|
27
|
+
* Segments are joined with `/` to form a file path.
|
|
28
|
+
*
|
|
29
|
+
* Only splits on dots followed by a letter so that version numbers
|
|
30
|
+
* embedded in operationIds (e.g. `v2025.0`) are kept intact.
|
|
31
|
+
*/
|
|
32
|
+
function applyToFileParts(text, transformPart) {
|
|
33
|
+
const parts = text.split(/\.(?=[a-zA-Z])/);
|
|
34
|
+
return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Converts `text` to camelCase.
|
|
38
|
+
* When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* camelCase('hello-world') // 'helloWorld'
|
|
42
|
+
* camelCase('pet.petId', { isFile: true }) // 'pet/petId'
|
|
43
|
+
*/
|
|
44
|
+
function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
|
|
45
|
+
if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
|
|
46
|
+
prefix,
|
|
47
|
+
suffix
|
|
48
|
+
} : {}));
|
|
49
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Converts `text` to PascalCase.
|
|
53
|
+
* When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* pascalCase('hello-world') // 'HelloWorld'
|
|
57
|
+
* pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
|
|
58
|
+
*/
|
|
59
|
+
function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
|
|
60
|
+
if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
|
|
61
|
+
prefix,
|
|
62
|
+
suffix
|
|
63
|
+
}) : camelCase(part));
|
|
64
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Converts `text` to snake_case.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* snakeCase('helloWorld') // 'hello_world'
|
|
71
|
+
* snakeCase('Hello-World') // 'hello_world'
|
|
72
|
+
*/
|
|
73
|
+
function snakeCase(text, { prefix = "", suffix = "" } = {}) {
|
|
74
|
+
return `${prefix} ${text} ${suffix}`.trim().replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s\-.]+/g, "_").replace(/[^a-zA-Z0-9_]/g, "").toLowerCase().split("_").filter(Boolean).join("_");
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Converts `text` to SCREAMING_SNAKE_CASE.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* screamingSnakeCase('helloWorld') // 'HELLO_WORLD'
|
|
81
|
+
*/
|
|
82
|
+
function screamingSnakeCase(text, { prefix = "", suffix = "" } = {}) {
|
|
83
|
+
return snakeCase(text, {
|
|
84
|
+
prefix,
|
|
85
|
+
suffix
|
|
86
|
+
}).toUpperCase();
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region ../../internals/utils/src/string.ts
|
|
90
|
+
/**
|
|
91
|
+
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
92
|
+
* Returns the string unchanged when no balanced quote pair is found.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* trimQuotes('"hello"') // 'hello'
|
|
96
|
+
* trimQuotes('hello') // 'hello'
|
|
97
|
+
*/
|
|
98
|
+
function trimQuotes(text) {
|
|
99
|
+
if (text.length >= 2) {
|
|
100
|
+
const first = text[0];
|
|
101
|
+
const last = text[text.length - 1];
|
|
102
|
+
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
|
|
103
|
+
}
|
|
104
|
+
return text;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Escapes characters that are not allowed inside JS string literals.
|
|
108
|
+
* Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).
|
|
109
|
+
*
|
|
110
|
+
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
function jsStringEscape(input) {
|
|
118
|
+
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
|
|
119
|
+
switch (character) {
|
|
120
|
+
case "\"":
|
|
121
|
+
case "'":
|
|
122
|
+
case "\\": return `\\${character}`;
|
|
123
|
+
case "\n": return "\\n";
|
|
124
|
+
case "\r": return "\\r";
|
|
125
|
+
case "\u2028": return "\\u2028";
|
|
126
|
+
case "\u2029": return "\\u2029";
|
|
127
|
+
default: return "";
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region ../../internals/utils/src/object.ts
|
|
133
|
+
/**
|
|
134
|
+
* Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* stringify('hello') // '"hello"'
|
|
138
|
+
* stringify('"hello"') // '"hello"'
|
|
139
|
+
*/
|
|
140
|
+
function stringify(value) {
|
|
141
|
+
if (value === void 0 || value === null) return "\"\"";
|
|
142
|
+
return JSON.stringify(trimQuotes(value.toString()));
|
|
143
|
+
}
|
|
144
|
+
//#endregion
|
|
145
|
+
//#region src/constants.ts
|
|
146
|
+
/**
|
|
147
|
+
* `optionalType` values that cause a property's type to include `| undefined`.
|
|
148
|
+
*/
|
|
149
|
+
const OPTIONAL_ADDS_UNDEFINED = new Set(["undefined", "questionTokenAndUndefined"]);
|
|
150
|
+
/**
|
|
151
|
+
* `optionalType` values that render the property key with a `?` token.
|
|
152
|
+
*/
|
|
153
|
+
const OPTIONAL_ADDS_QUESTION_TOKEN = new Set(["questionToken", "questionTokenAndUndefined"]);
|
|
154
|
+
/**
|
|
155
|
+
* `enumType` values that append a `Key` suffix to the generated enum type alias.
|
|
156
|
+
*/
|
|
157
|
+
const ENUM_TYPES_WITH_KEY_SUFFIX = new Set(["asConst", "asPascalConst"]);
|
|
158
|
+
/**
|
|
159
|
+
* `enumType` values that require a runtime value declaration (object, enum, or literal).
|
|
160
|
+
*/
|
|
161
|
+
const ENUM_TYPES_WITH_RUNTIME_VALUE = new Set([
|
|
162
|
+
"enum",
|
|
163
|
+
"asConst",
|
|
164
|
+
"asPascalConst",
|
|
165
|
+
"constEnum",
|
|
166
|
+
"literal",
|
|
167
|
+
void 0
|
|
168
|
+
]);
|
|
169
|
+
/**
|
|
170
|
+
* `enumType` values whose type declaration is type-only (no runtime value emitted for the type alias).
|
|
171
|
+
*/
|
|
172
|
+
const ENUM_TYPES_WITH_TYPE_ONLY = new Set([
|
|
173
|
+
"asConst",
|
|
174
|
+
"asPascalConst",
|
|
175
|
+
"literal",
|
|
176
|
+
void 0
|
|
177
|
+
]);
|
|
178
|
+
/**
|
|
179
|
+
* Ordering priority for function parameters: lower = sorted earlier.
|
|
180
|
+
*/
|
|
181
|
+
const PARAM_RANK = {
|
|
182
|
+
required: 0,
|
|
183
|
+
optional: 1,
|
|
184
|
+
withDefault: 2,
|
|
185
|
+
rest: 3
|
|
186
|
+
};
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region src/factory.ts
|
|
189
|
+
const { SyntaxKind, factory } = ts;
|
|
190
|
+
const modifiers = {
|
|
191
|
+
async: factory.createModifier(ts.SyntaxKind.AsyncKeyword),
|
|
192
|
+
export: factory.createModifier(ts.SyntaxKind.ExportKeyword),
|
|
193
|
+
const: factory.createModifier(ts.SyntaxKind.ConstKeyword),
|
|
194
|
+
static: factory.createModifier(ts.SyntaxKind.StaticKeyword)
|
|
195
|
+
};
|
|
196
|
+
const syntaxKind = {
|
|
197
|
+
union: SyntaxKind.UnionType,
|
|
198
|
+
literalType: SyntaxKind.LiteralType,
|
|
199
|
+
stringLiteral: SyntaxKind.StringLiteral
|
|
200
|
+
};
|
|
201
|
+
function isValidIdentifier(str) {
|
|
202
|
+
if (!str.length || str.trim() !== str) return false;
|
|
203
|
+
const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
|
|
204
|
+
return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
|
|
205
|
+
}
|
|
206
|
+
function propertyName(name) {
|
|
207
|
+
if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
|
|
208
|
+
return name;
|
|
209
|
+
}
|
|
210
|
+
const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
|
|
211
|
+
function createQuestionToken(token) {
|
|
212
|
+
if (!token) return;
|
|
213
|
+
if (token === true) return questionToken;
|
|
214
|
+
return token;
|
|
215
|
+
}
|
|
216
|
+
function createIntersectionDeclaration({ nodes, withParentheses }) {
|
|
217
|
+
if (!nodes.length) return null;
|
|
218
|
+
if (nodes.length === 1) return nodes[0] || null;
|
|
219
|
+
const node = factory.createIntersectionTypeNode(nodes);
|
|
220
|
+
if (withParentheses) return factory.createParenthesizedType(node);
|
|
221
|
+
return node;
|
|
222
|
+
}
|
|
223
|
+
function createArrayDeclaration({ nodes, arrayType = "array" }) {
|
|
224
|
+
if (!nodes.length) return factory.createTupleTypeNode([]);
|
|
225
|
+
if (nodes.length === 1) {
|
|
226
|
+
const node = nodes[0];
|
|
227
|
+
if (!node) return null;
|
|
228
|
+
if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
|
|
229
|
+
return factory.createArrayTypeNode(node);
|
|
230
|
+
}
|
|
231
|
+
const unionType = factory.createUnionTypeNode(nodes);
|
|
232
|
+
if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
|
|
233
|
+
return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Minimum nodes length of 2
|
|
237
|
+
* @example `string | number`
|
|
238
|
+
*/
|
|
239
|
+
function createUnionDeclaration({ nodes, withParentheses }) {
|
|
240
|
+
if (!nodes.length) return keywordTypeNodes.any;
|
|
241
|
+
if (nodes.length === 1) return nodes[0];
|
|
242
|
+
const node = factory.createUnionTypeNode(nodes);
|
|
243
|
+
if (withParentheses) return factory.createParenthesizedType(node);
|
|
244
|
+
return node;
|
|
245
|
+
}
|
|
246
|
+
function createPropertySignature({ readOnly, modifiers = [], name, questionToken, type }) {
|
|
247
|
+
return factory.createPropertySignature([...modifiers, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken), type);
|
|
248
|
+
}
|
|
249
|
+
function createParameterSignature(name, { modifiers, dotDotDotToken, questionToken, type, initializer }) {
|
|
250
|
+
return factory.createParameterDeclaration(modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* @link https://github.com/microsoft/TypeScript/issues/44151
|
|
254
|
+
*/
|
|
255
|
+
function appendJSDocToNode({ node, comments }) {
|
|
256
|
+
const filteredComments = comments.filter(Boolean);
|
|
257
|
+
if (!filteredComments.length) return node;
|
|
258
|
+
const text = filteredComments.reduce((acc = "", comment = "") => {
|
|
259
|
+
return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
|
|
260
|
+
}, "*");
|
|
261
|
+
return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
|
|
262
|
+
}
|
|
263
|
+
function createIndexSignature(type, { modifiers, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
|
|
264
|
+
return factory.createIndexSignature(modifiers, [createParameterSignature(indexName, { type: indexType })], type);
|
|
265
|
+
}
|
|
266
|
+
function createTypeAliasDeclaration({ modifiers, name, typeParameters, type }) {
|
|
267
|
+
return factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
|
|
268
|
+
}
|
|
269
|
+
function createInterfaceDeclaration({ modifiers, name, typeParameters, members }) {
|
|
270
|
+
return factory.createInterfaceDeclaration(modifiers, name, typeParameters, void 0, members);
|
|
271
|
+
}
|
|
272
|
+
function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
|
|
273
|
+
if (syntax === "interface" && "members" in type) return appendJSDocToNode({
|
|
274
|
+
node: createInterfaceDeclaration({
|
|
275
|
+
members: [...type.members],
|
|
276
|
+
modifiers: isExportable ? [modifiers.export] : [],
|
|
277
|
+
name,
|
|
278
|
+
typeParameters: void 0
|
|
279
|
+
}),
|
|
280
|
+
comments
|
|
281
|
+
});
|
|
282
|
+
return appendJSDocToNode({
|
|
283
|
+
node: createTypeAliasDeclaration({
|
|
284
|
+
type,
|
|
285
|
+
modifiers: isExportable ? [modifiers.export] : [],
|
|
286
|
+
name,
|
|
287
|
+
typeParameters: void 0
|
|
288
|
+
}),
|
|
289
|
+
comments
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Apply casing transformation to enum keys
|
|
294
|
+
*/
|
|
295
|
+
function applyEnumKeyCasing(key, casing = "none") {
|
|
296
|
+
if (casing === "none") return key;
|
|
297
|
+
if (casing === "screamingSnakeCase") return screamingSnakeCase(key);
|
|
298
|
+
if (casing === "snakeCase") return snakeCase(key);
|
|
299
|
+
if (casing === "pascalCase") return pascalCase(key);
|
|
300
|
+
if (casing === "camelCase") return camelCase(key);
|
|
301
|
+
return key;
|
|
302
|
+
}
|
|
303
|
+
function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
|
|
304
|
+
if (type === "literal" || type === "inlineLiteral") return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createUnionTypeNode(enums.map(([_key, value]) => {
|
|
305
|
+
if (isNumber(value)) {
|
|
306
|
+
if (value < 0) return factory.createLiteralTypeNode(factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value))));
|
|
307
|
+
return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
|
|
308
|
+
}
|
|
309
|
+
if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
|
|
310
|
+
if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
|
|
311
|
+
}).filter(Boolean)))];
|
|
312
|
+
if (type === "enum" || type === "constEnum") return [void 0, factory.createEnumDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword), type === "constEnum" ? factory.createToken(ts.SyntaxKind.ConstKeyword) : void 0].filter(Boolean), factory.createIdentifier(typeName), enums.map(([key, value]) => {
|
|
313
|
+
let initializer = factory.createStringLiteral(value?.toString());
|
|
314
|
+
if (Number.parseInt(value.toString(), 10) === value && isNumber(Number.parseInt(value.toString(), 10))) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
|
|
315
|
+
else initializer = factory.createNumericLiteral(value);
|
|
316
|
+
if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
|
|
317
|
+
if (isNumber(Number.parseInt(key.toString(), 10))) {
|
|
318
|
+
const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
|
|
319
|
+
return factory.createEnumMember(propertyName(casingKey), initializer);
|
|
320
|
+
}
|
|
321
|
+
if (key) {
|
|
322
|
+
const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
|
|
323
|
+
return factory.createEnumMember(propertyName(casingKey), initializer);
|
|
324
|
+
}
|
|
325
|
+
}).filter(Boolean))];
|
|
326
|
+
const identifierName = name;
|
|
327
|
+
if (enums.length === 0) return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword))];
|
|
328
|
+
return [factory.createVariableStatement([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(identifierName), void 0, void 0, factory.createAsExpression(factory.createObjectLiteralExpression(enums.map(([key, value]) => {
|
|
329
|
+
let initializer = factory.createStringLiteral(value?.toString());
|
|
330
|
+
if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
|
|
331
|
+
else initializer = factory.createNumericLiteral(value);
|
|
332
|
+
if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
|
|
333
|
+
if (key) {
|
|
334
|
+
const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
|
|
335
|
+
return factory.createPropertyAssignment(propertyName(casingKey), initializer);
|
|
336
|
+
}
|
|
337
|
+
}).filter(Boolean), true), factory.createTypeReferenceNode(factory.createIdentifier("const"), void 0)))], ts.NodeFlags.Const)), factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0)), factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0))))];
|
|
338
|
+
}
|
|
339
|
+
function createOmitDeclaration({ keys, type, nonNullable }) {
|
|
340
|
+
const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
|
|
341
|
+
if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
|
|
342
|
+
return factory.createLiteralTypeNode(factory.createStringLiteral(key));
|
|
343
|
+
}))]);
|
|
344
|
+
return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
|
|
345
|
+
}
|
|
346
|
+
const keywordTypeNodes = {
|
|
347
|
+
any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
|
|
348
|
+
unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
|
|
349
|
+
void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
|
|
350
|
+
number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
|
|
351
|
+
integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
|
|
352
|
+
bigint: factory.createKeywordTypeNode(ts.SyntaxKind.BigIntKeyword),
|
|
353
|
+
object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
|
|
354
|
+
string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
|
|
355
|
+
boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
|
|
356
|
+
undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
|
|
357
|
+
null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword)),
|
|
358
|
+
never: factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
|
|
359
|
+
};
|
|
360
|
+
/**
|
|
361
|
+
* Converts a path like '/pet/{petId}/uploadImage' to a template literal type
|
|
362
|
+
* like `/pet/${string}/uploadImage`
|
|
363
|
+
*/
|
|
364
|
+
/**
|
|
365
|
+
* Converts an OAS-style path (e.g. `/pets/{petId}`) or an Express-style path
|
|
366
|
+
* (e.g. `/pets/:petId`) to a TypeScript template literal type
|
|
367
|
+
* like `` `/pets/${string}` ``.
|
|
368
|
+
*/
|
|
369
|
+
function createUrlTemplateType(path) {
|
|
370
|
+
const normalized = path.replace(/:([^/]+)/g, "{$1}");
|
|
371
|
+
if (!normalized.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(normalized));
|
|
372
|
+
const segments = normalized.split(/(\{[^}]+\})/);
|
|
373
|
+
const parts = [];
|
|
374
|
+
const parameterIndices = [];
|
|
375
|
+
segments.forEach((segment) => {
|
|
376
|
+
if (segment.startsWith("{") && segment.endsWith("}")) {
|
|
377
|
+
parameterIndices.push(parts.length);
|
|
378
|
+
parts.push(segment);
|
|
379
|
+
} else if (segment) parts.push(segment);
|
|
380
|
+
});
|
|
381
|
+
const head = ts.factory.createTemplateHead(parts[0] || "");
|
|
382
|
+
const templateSpans = [];
|
|
383
|
+
parameterIndices.forEach((paramIndex, i) => {
|
|
384
|
+
const isLast = i === parameterIndices.length - 1;
|
|
385
|
+
const nextPart = parts[paramIndex + 1] || "";
|
|
386
|
+
const literal = isLast ? ts.factory.createTemplateTail(nextPart) : ts.factory.createTemplateMiddle(nextPart);
|
|
387
|
+
templateSpans.push(ts.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
|
|
388
|
+
});
|
|
389
|
+
return ts.factory.createTemplateLiteralType(head, templateSpans);
|
|
390
|
+
}
|
|
391
|
+
const createTypeLiteralNode = factory.createTypeLiteralNode;
|
|
392
|
+
const createTypeReferenceNode = factory.createTypeReferenceNode;
|
|
393
|
+
const createNumericLiteral = factory.createNumericLiteral;
|
|
394
|
+
const createStringLiteral = factory.createStringLiteral;
|
|
395
|
+
const createArrayTypeNode = factory.createArrayTypeNode;
|
|
396
|
+
factory.createParenthesizedType;
|
|
397
|
+
const createLiteralTypeNode = factory.createLiteralTypeNode;
|
|
398
|
+
factory.createNull;
|
|
399
|
+
const createIdentifier = factory.createIdentifier;
|
|
400
|
+
const createOptionalTypeNode = factory.createOptionalTypeNode;
|
|
401
|
+
const createTupleTypeNode = factory.createTupleTypeNode;
|
|
402
|
+
const createRestTypeNode = factory.createRestTypeNode;
|
|
403
|
+
const createTrue = factory.createTrue;
|
|
404
|
+
const createFalse = factory.createFalse;
|
|
405
|
+
factory.createIndexedAccessTypeNode;
|
|
406
|
+
factory.createTypeOperatorNode;
|
|
407
|
+
const createPrefixUnaryExpression = factory.createPrefixUnaryExpression;
|
|
408
|
+
/**
|
|
409
|
+
* Converts a primitive const value to a TypeScript literal type node.
|
|
410
|
+
* Handles negative numbers via a prefix unary expression.
|
|
411
|
+
*/
|
|
412
|
+
function constToTypeNode(value, format) {
|
|
413
|
+
if (format === "boolean") return createLiteralTypeNode(value === true ? createTrue() : createFalse());
|
|
414
|
+
if (format === "number" && typeof value === "number") {
|
|
415
|
+
if (value < 0) return createLiteralTypeNode(createPrefixUnaryExpression(SyntaxKind.MinusToken, createNumericLiteral(Math.abs(value))));
|
|
416
|
+
return createLiteralTypeNode(createNumericLiteral(value));
|
|
417
|
+
}
|
|
418
|
+
return createLiteralTypeNode(createStringLiteral(String(value)));
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Returns a `Date` reference type node when `representation` is `'date'`, otherwise falls back to `string`.
|
|
422
|
+
*/
|
|
423
|
+
function dateOrStringNode(node) {
|
|
424
|
+
return node.representation === "date" ? createTypeReferenceNode(createIdentifier("Date")) : keywordTypeNodes.string;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Maps an array of `SchemaNode`s through the printer, filtering out `null` and `undefined` results.
|
|
428
|
+
*/
|
|
429
|
+
function buildMemberNodes(members, print) {
|
|
430
|
+
return (members ?? []).map(print).filter(Boolean);
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Builds a TypeScript tuple type node from an array schema's `items`,
|
|
434
|
+
* applying min/max slice and optional/rest element rules.
|
|
435
|
+
*/
|
|
436
|
+
function buildTupleNode(node, print) {
|
|
437
|
+
let items = (node.items ?? []).map(print).filter(Boolean);
|
|
438
|
+
const restNode = node.rest ? print(node.rest) ?? void 0 : void 0;
|
|
439
|
+
const { min, max } = node;
|
|
440
|
+
if (max !== void 0) {
|
|
441
|
+
items = items.slice(0, max);
|
|
442
|
+
if (items.length < max && restNode) items = [...items, ...Array(max - items.length).fill(restNode)];
|
|
443
|
+
}
|
|
444
|
+
if (min !== void 0) items = items.map((item, i) => i >= min ? createOptionalTypeNode(item) : item);
|
|
445
|
+
if (max === void 0 && restNode) items.push(createRestTypeNode(createArrayTypeNode(restNode)));
|
|
446
|
+
return createTupleTypeNode(items);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Applies `nullable` and optional/nullish `| undefined` union modifiers to a property's resolved base type.
|
|
450
|
+
*/
|
|
451
|
+
function buildPropertyType(schema, baseType, optionalType) {
|
|
452
|
+
const addsUndefined = OPTIONAL_ADDS_UNDEFINED.has(optionalType);
|
|
453
|
+
const meta = syncSchemaRef(schema);
|
|
454
|
+
let type = baseType;
|
|
455
|
+
if (meta.nullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
|
|
456
|
+
if ((meta.nullish || meta.optional) && addsUndefined) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
|
|
457
|
+
return type;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Creates TypeScript index signatures for `additionalProperties` and `patternProperties` on an object schema node.
|
|
461
|
+
*/
|
|
462
|
+
function buildIndexSignatures(node, propertyCount, print) {
|
|
463
|
+
const elements = [];
|
|
464
|
+
if (node.additionalProperties && node.additionalProperties !== true) {
|
|
465
|
+
const additionalType = print(node.additionalProperties) ?? keywordTypeNodes.unknown;
|
|
466
|
+
elements.push(createIndexSignature(propertyCount > 0 ? keywordTypeNodes.unknown : additionalType));
|
|
467
|
+
} else if (node.additionalProperties === true) elements.push(createIndexSignature(keywordTypeNodes.unknown));
|
|
468
|
+
if (node.patternProperties) {
|
|
469
|
+
const first = Object.values(node.patternProperties)[0];
|
|
470
|
+
if (first) {
|
|
471
|
+
let patternType = print(first) ?? keywordTypeNodes.unknown;
|
|
472
|
+
if (first.nullable) patternType = createUnionDeclaration({ nodes: [patternType, keywordTypeNodes.null] });
|
|
473
|
+
elements.push(createIndexSignature(patternType));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return elements;
|
|
477
|
+
}
|
|
478
|
+
//#endregion
|
|
479
|
+
//#region src/components/Enum.tsx
|
|
480
|
+
/**
|
|
481
|
+
* Resolves the runtime identifier name and the TypeScript type name for an enum schema node.
|
|
482
|
+
*
|
|
483
|
+
* The raw `node.name` may be a YAML key such as `"enumNames.Type"` which is not a
|
|
484
|
+
* valid TypeScript identifier. The resolver normalizes it; for inline enum
|
|
485
|
+
* properties the adapter already emits a PascalCase+suffix name so resolution is typically a no-op.
|
|
486
|
+
*/
|
|
487
|
+
function getEnumNames({ node, enumType, enumTypeSuffix, resolver }) {
|
|
488
|
+
const resolved = resolver.default(node.name, "type");
|
|
489
|
+
return {
|
|
490
|
+
enumName: enumType === "asPascalConst" ? resolved : camelCase(node.name),
|
|
491
|
+
typeName: ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) ? resolver.resolveEnumKeyName(node, enumTypeSuffix) : resolved
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Renders the enum declaration(s) for a single named `EnumSchemaNode`.
|
|
496
|
+
*
|
|
497
|
+
* Depending on `enumType` this may emit:
|
|
498
|
+
* - A runtime object (`asConst` / `asPascalConst`) plus a `typeof` type alias
|
|
499
|
+
* - A `const enum` or plain `enum` declaration (`constEnum` / `enum`)
|
|
500
|
+
* - A union literal type alias (`literal`)
|
|
501
|
+
*
|
|
502
|
+
* The emitted `File.Source` nodes carry the resolved names so that the barrel
|
|
503
|
+
* index picks up the correct export identifiers.
|
|
504
|
+
*/
|
|
505
|
+
function Enum({ node, enumType, enumTypeSuffix, enumKeyCasing, resolver }) {
|
|
506
|
+
const { enumName, typeName } = getEnumNames({
|
|
507
|
+
node,
|
|
508
|
+
enumType,
|
|
509
|
+
enumTypeSuffix,
|
|
510
|
+
resolver
|
|
511
|
+
});
|
|
512
|
+
const [nameNode, typeNode] = createEnumDeclaration({
|
|
513
|
+
name: enumName,
|
|
514
|
+
typeName,
|
|
515
|
+
enums: node.namedEnumValues?.map((v) => [trimQuotes(v.name.toString()), v.value]) ?? node.enumValues?.filter((v) => v !== null && v !== void 0).map((v) => [trimQuotes(v.toString()), v]) ?? [],
|
|
516
|
+
type: enumType,
|
|
517
|
+
enumKeyCasing
|
|
518
|
+
});
|
|
519
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [nameNode && /* @__PURE__ */ jsx(File.Source, {
|
|
520
|
+
name: enumName,
|
|
521
|
+
isExportable: true,
|
|
522
|
+
isIndexable: true,
|
|
523
|
+
isTypeOnly: false,
|
|
524
|
+
children: safePrint(nameNode)
|
|
525
|
+
}), /* @__PURE__ */ jsx(File.Source, {
|
|
526
|
+
name: typeName,
|
|
527
|
+
isIndexable: true,
|
|
528
|
+
isExportable: ENUM_TYPES_WITH_RUNTIME_VALUE.has(enumType),
|
|
529
|
+
isTypeOnly: ENUM_TYPES_WITH_TYPE_ONLY.has(enumType),
|
|
530
|
+
children: safePrint(typeNode)
|
|
531
|
+
})] });
|
|
532
|
+
}
|
|
533
|
+
//#endregion
|
|
534
|
+
//#region src/components/Type.tsx
|
|
535
|
+
function Type({ name, node, printer, enumType, enumTypeSuffix, enumKeyCasing, resolver }) {
|
|
536
|
+
const enumSchemaNodes = collect(node, { schema(n) {
|
|
537
|
+
const enumNode = narrowSchema(n, schemaTypes.enum);
|
|
538
|
+
if (enumNode?.name) return enumNode;
|
|
539
|
+
} });
|
|
540
|
+
const output = printer.print(node);
|
|
541
|
+
if (!output) return;
|
|
542
|
+
const enums = [...new Map(enumSchemaNodes.map((n) => [n.name, n])).values()].map((node) => {
|
|
543
|
+
return {
|
|
544
|
+
node,
|
|
545
|
+
...getEnumNames({
|
|
546
|
+
node,
|
|
547
|
+
enumType,
|
|
548
|
+
enumTypeSuffix,
|
|
549
|
+
resolver
|
|
550
|
+
})
|
|
551
|
+
};
|
|
552
|
+
});
|
|
553
|
+
const shouldExportEnums = enumType !== "inlineLiteral";
|
|
554
|
+
const shouldExportType = enumType === "inlineLiteral" || enums.every((item) => item.typeName !== name);
|
|
555
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ node }) => /* @__PURE__ */ jsx(Enum, {
|
|
556
|
+
node,
|
|
557
|
+
enumType,
|
|
558
|
+
enumTypeSuffix,
|
|
559
|
+
enumKeyCasing,
|
|
560
|
+
resolver
|
|
561
|
+
})), shouldExportType && /* @__PURE__ */ jsx(File.Source, {
|
|
562
|
+
name,
|
|
563
|
+
isTypeOnly: true,
|
|
564
|
+
isExportable: true,
|
|
565
|
+
isIndexable: true,
|
|
566
|
+
children: output
|
|
567
|
+
})] });
|
|
568
|
+
}
|
|
569
|
+
//#endregion
|
|
570
|
+
//#region src/utils.ts
|
|
571
|
+
/**
|
|
572
|
+
* Collects JSDoc annotation strings for a schema node.
|
|
573
|
+
*
|
|
574
|
+
* Only uses official JSDoc tags from https://jsdoc.app/: `@description`, `@deprecated`, `@default`, `@example`, `@type`.
|
|
575
|
+
* Constraint metadata (min/max length, pattern, multipleOf, min/maxProperties) is emitted as plain-text lines.
|
|
576
|
+
|
|
577
|
+
*/
|
|
578
|
+
function buildPropertyJSDocComments(schema) {
|
|
579
|
+
const meta = syncSchemaRef(schema);
|
|
580
|
+
const isArray = meta?.primitive === "array";
|
|
581
|
+
return [
|
|
582
|
+
meta && "description" in meta && meta.description ? `@description ${jsStringEscape(meta.description)}` : void 0,
|
|
583
|
+
meta && "deprecated" in meta && meta.deprecated ? "@deprecated" : void 0,
|
|
584
|
+
!isArray && meta && "min" in meta && meta.min !== void 0 ? `@minLength ${meta.min}` : void 0,
|
|
585
|
+
!isArray && meta && "max" in meta && meta.max !== void 0 ? `@maxLength ${meta.max}` : void 0,
|
|
586
|
+
meta && "pattern" in meta && meta.pattern ? `@pattern ${meta.pattern}` : void 0,
|
|
587
|
+
meta && "default" in meta && meta.default !== void 0 ? `@default ${"primitive" in meta && meta.primitive === "string" ? stringify(meta.default) : meta.default}` : void 0,
|
|
588
|
+
meta && "example" in meta && meta.example !== void 0 ? `@example ${meta.example}` : void 0,
|
|
589
|
+
meta && "primitive" in meta && meta.primitive ? [`@type ${meta.primitive}`, "optional" in schema && schema.optional ? " | undefined" : void 0].filter(Boolean).join("") : void 0
|
|
590
|
+
].filter(Boolean);
|
|
591
|
+
}
|
|
592
|
+
function buildParams(node, { params, resolver }) {
|
|
593
|
+
return createSchema({
|
|
594
|
+
type: "object",
|
|
595
|
+
properties: params.map((param) => createProperty({
|
|
596
|
+
name: param.name,
|
|
597
|
+
required: param.required,
|
|
598
|
+
schema: createSchema({
|
|
599
|
+
type: "ref",
|
|
600
|
+
name: resolver.resolveParamName(node, param)
|
|
601
|
+
})
|
|
602
|
+
}))
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
function buildData(node, { resolver }) {
|
|
606
|
+
const pathParams = node.parameters.filter((p) => p.in === "path");
|
|
607
|
+
const queryParams = node.parameters.filter((p) => p.in === "query");
|
|
608
|
+
const headerParams = node.parameters.filter((p) => p.in === "header");
|
|
609
|
+
return createSchema({
|
|
610
|
+
type: "object",
|
|
611
|
+
deprecated: node.deprecated,
|
|
612
|
+
properties: [
|
|
613
|
+
createProperty({
|
|
614
|
+
name: "data",
|
|
615
|
+
schema: node.requestBody?.schema ? createSchema({
|
|
616
|
+
type: "ref",
|
|
617
|
+
name: resolver.resolveDataName(node),
|
|
618
|
+
optional: true
|
|
619
|
+
}) : createSchema({
|
|
620
|
+
type: "never",
|
|
621
|
+
primitive: void 0,
|
|
622
|
+
optional: true
|
|
623
|
+
})
|
|
624
|
+
}),
|
|
625
|
+
createProperty({
|
|
626
|
+
name: "pathParams",
|
|
627
|
+
required: pathParams.length > 0,
|
|
628
|
+
schema: pathParams.length > 0 ? buildParams(node, {
|
|
629
|
+
params: pathParams,
|
|
630
|
+
resolver
|
|
631
|
+
}) : createSchema({
|
|
632
|
+
type: "never",
|
|
633
|
+
primitive: void 0
|
|
634
|
+
})
|
|
635
|
+
}),
|
|
636
|
+
createProperty({
|
|
637
|
+
name: "queryParams",
|
|
638
|
+
schema: queryParams.length > 0 ? createSchema({
|
|
639
|
+
...buildParams(node, {
|
|
640
|
+
params: queryParams,
|
|
641
|
+
resolver
|
|
642
|
+
}),
|
|
643
|
+
optional: true
|
|
644
|
+
}) : createSchema({
|
|
645
|
+
type: "never",
|
|
646
|
+
primitive: void 0,
|
|
647
|
+
optional: true
|
|
648
|
+
})
|
|
649
|
+
}),
|
|
650
|
+
createProperty({
|
|
651
|
+
name: "headerParams",
|
|
652
|
+
schema: headerParams.length > 0 ? createSchema({
|
|
653
|
+
...buildParams(node, {
|
|
654
|
+
params: headerParams,
|
|
655
|
+
resolver
|
|
656
|
+
}),
|
|
657
|
+
optional: true
|
|
658
|
+
}) : createSchema({
|
|
659
|
+
type: "never",
|
|
660
|
+
primitive: void 0,
|
|
661
|
+
optional: true
|
|
662
|
+
})
|
|
663
|
+
}),
|
|
664
|
+
createProperty({
|
|
665
|
+
name: "url",
|
|
666
|
+
required: true,
|
|
667
|
+
schema: createSchema({
|
|
668
|
+
type: "url",
|
|
669
|
+
path: node.path
|
|
670
|
+
})
|
|
671
|
+
})
|
|
672
|
+
]
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
function buildResponses(node, { resolver }) {
|
|
676
|
+
if (node.responses.length === 0) return null;
|
|
677
|
+
return createSchema({
|
|
678
|
+
type: "object",
|
|
679
|
+
properties: node.responses.map((res) => createProperty({
|
|
680
|
+
name: String(res.statusCode),
|
|
681
|
+
required: true,
|
|
682
|
+
schema: createSchema({
|
|
683
|
+
type: "ref",
|
|
684
|
+
name: resolver.resolveResponseStatusName(node, res.statusCode)
|
|
685
|
+
})
|
|
686
|
+
}))
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
function buildResponseUnion(node, { resolver }) {
|
|
690
|
+
const responsesWithSchema = node.responses.filter((res) => res.schema);
|
|
691
|
+
if (responsesWithSchema.length === 0) return null;
|
|
692
|
+
return createSchema({
|
|
693
|
+
type: "union",
|
|
694
|
+
members: responsesWithSchema.map((res) => createSchema({
|
|
695
|
+
type: "ref",
|
|
696
|
+
name: resolver.resolveResponseStatusName(node, res.statusCode)
|
|
697
|
+
}))
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
//#endregion
|
|
701
|
+
//#region src/printers/printerTs.ts
|
|
702
|
+
/**
|
|
703
|
+
* TypeScript type printer built with `definePrinter`.
|
|
704
|
+
*
|
|
705
|
+
* Converts a `SchemaNode` AST node into a TypeScript AST node:
|
|
706
|
+
* - **`printer.print(node)`** — when `options.typeName` is set, returns a full
|
|
707
|
+
* `type Name = …` or `interface Name { … }` declaration (`ts.Node`).
|
|
708
|
+
* Without `typeName`, returns the raw `ts.TypeNode` for the schema.
|
|
709
|
+
*
|
|
710
|
+
* Dispatches on `node.type` to the appropriate handler in `nodes`. Options are closed
|
|
711
|
+
* over per printer instance, so each call to `printerTs(options)` produces an independent printer.
|
|
712
|
+
*
|
|
713
|
+
* @example Raw type node (no `typeName`)
|
|
714
|
+
* ```ts
|
|
715
|
+
* const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enumType: 'inlineLiteral' })
|
|
716
|
+
* const typeNode = printer.print(schemaNode) // ts.TypeNode
|
|
717
|
+
* ```
|
|
718
|
+
*
|
|
719
|
+
* @example Full declaration (with `typeName`)
|
|
720
|
+
* ```ts
|
|
721
|
+
* const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enumType: 'inlineLiteral', typeName: 'MyType' })
|
|
722
|
+
* const declaration = printer.print(schemaNode) // ts.TypeAliasDeclaration | ts.InterfaceDeclaration
|
|
723
|
+
* ```
|
|
724
|
+
*/
|
|
725
|
+
const printerTs = definePrinter((options) => {
|
|
726
|
+
const addsUndefined = OPTIONAL_ADDS_UNDEFINED.has(options.optionalType);
|
|
727
|
+
return {
|
|
728
|
+
name: "typescript",
|
|
729
|
+
options,
|
|
730
|
+
nodes: {
|
|
731
|
+
any: () => keywordTypeNodes.any,
|
|
732
|
+
unknown: () => keywordTypeNodes.unknown,
|
|
733
|
+
void: () => keywordTypeNodes.void,
|
|
734
|
+
never: () => keywordTypeNodes.never,
|
|
735
|
+
boolean: () => keywordTypeNodes.boolean,
|
|
736
|
+
null: () => keywordTypeNodes.null,
|
|
737
|
+
blob: () => createTypeReferenceNode("Blob", []),
|
|
738
|
+
string: () => keywordTypeNodes.string,
|
|
739
|
+
uuid: () => keywordTypeNodes.string,
|
|
740
|
+
email: () => keywordTypeNodes.string,
|
|
741
|
+
url: (node) => {
|
|
742
|
+
if (node.path) return createUrlTemplateType(node.path);
|
|
743
|
+
return keywordTypeNodes.string;
|
|
744
|
+
},
|
|
745
|
+
ipv4: () => keywordTypeNodes.string,
|
|
746
|
+
ipv6: () => keywordTypeNodes.string,
|
|
747
|
+
datetime: () => keywordTypeNodes.string,
|
|
748
|
+
number: () => keywordTypeNodes.number,
|
|
749
|
+
integer: () => keywordTypeNodes.number,
|
|
750
|
+
bigint: () => keywordTypeNodes.bigint,
|
|
751
|
+
date: dateOrStringNode,
|
|
752
|
+
time: dateOrStringNode,
|
|
753
|
+
ref(node) {
|
|
754
|
+
if (!node.name) return;
|
|
755
|
+
const refName = node.ref ? extractRefName(node.ref) ?? node.name : node.name;
|
|
756
|
+
return createTypeReferenceNode(node.ref && ENUM_TYPES_WITH_KEY_SUFFIX.has(this.options.enumType) && this.options.enumTypeSuffix && this.options.enumSchemaNames?.has(refName) ? this.options.resolver.resolveEnumKeyName({ name: refName }, this.options.enumTypeSuffix) : node.ref ? this.options.resolver.default(refName, "type") : refName, void 0);
|
|
757
|
+
},
|
|
758
|
+
enum(node) {
|
|
759
|
+
const values = node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? [];
|
|
760
|
+
if (this.options.enumType === "inlineLiteral" || !node.name) return createUnionDeclaration({
|
|
761
|
+
withParentheses: true,
|
|
762
|
+
nodes: values.filter((v) => v !== null && v !== void 0).map((value) => constToTypeNode(value, typeof value)).filter(Boolean)
|
|
763
|
+
}) ?? void 0;
|
|
764
|
+
return createTypeReferenceNode(ENUM_TYPES_WITH_KEY_SUFFIX.has(this.options.enumType) && this.options.enumTypeSuffix ? this.options.resolver.resolveEnumKeyName(node, this.options.enumTypeSuffix) : this.options.resolver.default(node.name, "type"), void 0);
|
|
765
|
+
},
|
|
766
|
+
union(node) {
|
|
767
|
+
const members = node.members ?? [];
|
|
768
|
+
const hasStringLiteral = members.some((m) => {
|
|
769
|
+
return narrowSchema(m, schemaTypes.enum)?.primitive === "string";
|
|
770
|
+
});
|
|
771
|
+
const hasPlainString = members.some((m) => isStringType(m));
|
|
772
|
+
if (hasStringLiteral && hasPlainString) return createUnionDeclaration({
|
|
773
|
+
withParentheses: true,
|
|
774
|
+
nodes: members.map((m) => {
|
|
775
|
+
if (isStringType(m)) return createIntersectionDeclaration({
|
|
776
|
+
nodes: [keywordTypeNodes.string, createTypeLiteralNode([])],
|
|
777
|
+
withParentheses: true
|
|
778
|
+
});
|
|
779
|
+
return this.transform(m);
|
|
780
|
+
}).filter(Boolean)
|
|
781
|
+
}) ?? void 0;
|
|
782
|
+
return createUnionDeclaration({
|
|
783
|
+
withParentheses: true,
|
|
784
|
+
nodes: buildMemberNodes(members, this.transform)
|
|
785
|
+
}) ?? void 0;
|
|
786
|
+
},
|
|
787
|
+
intersection(node) {
|
|
788
|
+
return createIntersectionDeclaration({
|
|
789
|
+
withParentheses: true,
|
|
790
|
+
nodes: buildMemberNodes(node.members, this.transform)
|
|
791
|
+
}) ?? void 0;
|
|
792
|
+
},
|
|
793
|
+
array(node) {
|
|
794
|
+
return createArrayDeclaration({
|
|
795
|
+
nodes: (node.items ?? []).map((item) => this.transform(item)).filter(Boolean),
|
|
796
|
+
arrayType: this.options.arrayType
|
|
797
|
+
}) ?? void 0;
|
|
798
|
+
},
|
|
799
|
+
tuple(node) {
|
|
800
|
+
return buildTupleNode(node, this.transform);
|
|
801
|
+
},
|
|
802
|
+
object(node) {
|
|
803
|
+
const { transform, options } = this;
|
|
804
|
+
const addsQuestionToken = OPTIONAL_ADDS_QUESTION_TOKEN.has(options.optionalType);
|
|
805
|
+
const propertyNodes = node.properties.map((prop) => {
|
|
806
|
+
const baseType = transform(prop.schema) ?? keywordTypeNodes.unknown;
|
|
807
|
+
const type = buildPropertyType(prop.schema, baseType, options.optionalType);
|
|
808
|
+
const propMeta = syncSchemaRef(prop.schema);
|
|
809
|
+
return appendJSDocToNode({
|
|
810
|
+
node: createPropertySignature({
|
|
811
|
+
questionToken: prop.schema.optional || prop.schema.nullish ? addsQuestionToken : false,
|
|
812
|
+
name: prop.name,
|
|
813
|
+
type,
|
|
814
|
+
readOnly: propMeta?.readOnly
|
|
815
|
+
}),
|
|
816
|
+
comments: buildPropertyJSDocComments(prop.schema)
|
|
817
|
+
});
|
|
818
|
+
});
|
|
819
|
+
const allElements = [...propertyNodes, ...buildIndexSignatures(node, propertyNodes.length, transform)];
|
|
820
|
+
if (!allElements.length) return keywordTypeNodes.object;
|
|
821
|
+
return createTypeLiteralNode(allElements);
|
|
822
|
+
},
|
|
823
|
+
...options.nodes
|
|
824
|
+
},
|
|
825
|
+
print(node) {
|
|
826
|
+
const { name, syntaxType = "type", description, keysToOmit } = this.options;
|
|
827
|
+
let base = this.transform(node);
|
|
828
|
+
if (!base) return null;
|
|
829
|
+
const meta = syncSchemaRef(node);
|
|
830
|
+
if (!name) {
|
|
831
|
+
if (meta.nullable) base = createUnionDeclaration({ nodes: [base, keywordTypeNodes.null] });
|
|
832
|
+
if ((meta.nullish || meta.optional) && addsUndefined) base = createUnionDeclaration({ nodes: [base, keywordTypeNodes.undefined] });
|
|
833
|
+
return safePrint(base);
|
|
834
|
+
}
|
|
835
|
+
let inner = keysToOmit?.length ? createOmitDeclaration({
|
|
836
|
+
keys: keysToOmit,
|
|
837
|
+
type: base,
|
|
838
|
+
nonNullable: true
|
|
839
|
+
}) : base;
|
|
840
|
+
if (meta.nullable) inner = createUnionDeclaration({ nodes: [inner, keywordTypeNodes.null] });
|
|
841
|
+
if (meta.nullish || meta.optional) inner = createUnionDeclaration({ nodes: [inner, keywordTypeNodes.undefined] });
|
|
842
|
+
const useTypeGeneration = syntaxType === "type" || inner.kind === syntaxKind.union || !!keysToOmit?.length;
|
|
843
|
+
return safePrint(createTypeDeclaration({
|
|
844
|
+
name,
|
|
845
|
+
isExportable: true,
|
|
846
|
+
type: inner,
|
|
847
|
+
syntax: useTypeGeneration ? "type" : "interface",
|
|
848
|
+
comments: buildPropertyJSDocComments({
|
|
849
|
+
...meta,
|
|
850
|
+
description
|
|
851
|
+
})
|
|
852
|
+
}));
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
});
|
|
856
|
+
//#endregion
|
|
857
|
+
//#region src/generators/typeGenerator.tsx
|
|
858
|
+
const typeGenerator = defineGenerator({
|
|
859
|
+
name: "typescript",
|
|
860
|
+
schema(node, options) {
|
|
861
|
+
const { enumType, enumTypeSuffix, enumKeyCasing, syntaxType, optionalType, arrayType, output, group, printer } = options;
|
|
862
|
+
const { adapter, config, resolver, root } = this;
|
|
863
|
+
if (!node.name) return;
|
|
864
|
+
const mode = this.getMode(output);
|
|
865
|
+
const enumSchemaNames = new Set((adapter.rootNode?.schemas ?? []).filter((s) => narrowSchema(s, schemaTypes.enum) && s.name).map((s) => s.name));
|
|
866
|
+
function resolveImportName(schemaName) {
|
|
867
|
+
if (ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) && enumTypeSuffix && enumSchemaNames.has(schemaName)) return resolver.resolveEnumKeyName({ name: schemaName }, enumTypeSuffix);
|
|
868
|
+
return resolver.resolveTypeName(schemaName);
|
|
869
|
+
}
|
|
870
|
+
const imports = adapter.getImports(node, (schemaName) => ({
|
|
871
|
+
name: resolveImportName(schemaName),
|
|
872
|
+
path: resolver.resolveFile({
|
|
873
|
+
name: schemaName,
|
|
874
|
+
extname: ".ts"
|
|
875
|
+
}, {
|
|
876
|
+
root,
|
|
877
|
+
output,
|
|
878
|
+
group
|
|
879
|
+
}).path
|
|
880
|
+
}));
|
|
881
|
+
const isEnumSchema = !!narrowSchema(node, schemaTypes.enum);
|
|
882
|
+
const meta = {
|
|
883
|
+
name: ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) && isEnumSchema ? resolver.resolveEnumKeyName(node, enumTypeSuffix) : resolver.resolveTypeName(node.name),
|
|
884
|
+
file: resolver.resolveFile({
|
|
885
|
+
name: node.name,
|
|
886
|
+
extname: ".ts"
|
|
887
|
+
}, {
|
|
888
|
+
root,
|
|
889
|
+
output,
|
|
890
|
+
group
|
|
891
|
+
})
|
|
892
|
+
};
|
|
893
|
+
const schemaPrinter = printerTs({
|
|
894
|
+
optionalType,
|
|
895
|
+
arrayType,
|
|
896
|
+
enumType,
|
|
897
|
+
enumTypeSuffix,
|
|
898
|
+
name: meta.name,
|
|
899
|
+
syntaxType,
|
|
900
|
+
description: node.description,
|
|
901
|
+
resolver,
|
|
902
|
+
enumSchemaNames,
|
|
903
|
+
nodes: printer?.nodes
|
|
904
|
+
});
|
|
905
|
+
return /* @__PURE__ */ jsxs(File, {
|
|
906
|
+
baseName: meta.file.baseName,
|
|
907
|
+
path: meta.file.path,
|
|
908
|
+
meta: meta.file.meta,
|
|
909
|
+
banner: resolver.resolveBanner(adapter.rootNode, {
|
|
910
|
+
output,
|
|
911
|
+
config
|
|
912
|
+
}),
|
|
913
|
+
footer: resolver.resolveFooter(adapter.rootNode, {
|
|
914
|
+
output,
|
|
915
|
+
config
|
|
916
|
+
}),
|
|
917
|
+
children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, {
|
|
918
|
+
root: meta.file.path,
|
|
919
|
+
path: imp.path,
|
|
920
|
+
name: imp.name,
|
|
921
|
+
isTypeOnly: true
|
|
922
|
+
}, [
|
|
923
|
+
node.name,
|
|
924
|
+
imp.path,
|
|
925
|
+
imp.isTypeOnly
|
|
926
|
+
].join("-"))), /* @__PURE__ */ jsx(Type, {
|
|
927
|
+
name: meta.name,
|
|
928
|
+
node,
|
|
929
|
+
enumType,
|
|
930
|
+
enumTypeSuffix,
|
|
931
|
+
enumKeyCasing,
|
|
932
|
+
resolver,
|
|
933
|
+
printer: schemaPrinter
|
|
934
|
+
})]
|
|
935
|
+
});
|
|
936
|
+
},
|
|
937
|
+
operation(node, options) {
|
|
938
|
+
const { enumType, enumTypeSuffix, enumKeyCasing, optionalType, arrayType, syntaxType, paramsCasing, group, output, printer } = options;
|
|
939
|
+
const { adapter, config, resolver, root } = this;
|
|
940
|
+
const mode = this.getMode(output);
|
|
941
|
+
const params = caseParams(node.parameters, paramsCasing);
|
|
942
|
+
const meta = { file: resolver.resolveFile({
|
|
943
|
+
name: node.operationId,
|
|
944
|
+
extname: ".ts",
|
|
945
|
+
tag: node.tags[0] ?? "default",
|
|
946
|
+
path: node.path
|
|
947
|
+
}, {
|
|
948
|
+
root,
|
|
949
|
+
output,
|
|
950
|
+
group
|
|
951
|
+
}) };
|
|
952
|
+
const enumSchemaNames = new Set((adapter.rootNode?.schemas ?? []).filter((s) => narrowSchema(s, schemaTypes.enum) && s.name).map((s) => s.name));
|
|
953
|
+
function resolveImportName(schemaName) {
|
|
954
|
+
if (ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) && enumTypeSuffix && enumSchemaNames.has(schemaName)) return resolver.resolveEnumKeyName({ name: schemaName }, enumTypeSuffix);
|
|
955
|
+
return resolver.resolveTypeName(schemaName);
|
|
956
|
+
}
|
|
957
|
+
function renderSchemaType({ schema, name, keysToOmit }) {
|
|
958
|
+
if (!schema) return null;
|
|
959
|
+
const imports = adapter.getImports(schema, (schemaName) => ({
|
|
960
|
+
name: resolveImportName(schemaName),
|
|
961
|
+
path: resolver.resolveFile({
|
|
962
|
+
name: schemaName,
|
|
963
|
+
extname: ".ts"
|
|
964
|
+
}, {
|
|
965
|
+
root,
|
|
966
|
+
output,
|
|
967
|
+
group
|
|
968
|
+
}).path
|
|
969
|
+
}));
|
|
970
|
+
const schemaPrinter = printerTs({
|
|
971
|
+
optionalType,
|
|
972
|
+
arrayType,
|
|
973
|
+
enumType,
|
|
974
|
+
enumTypeSuffix,
|
|
975
|
+
name,
|
|
976
|
+
syntaxType,
|
|
977
|
+
description: schema.description,
|
|
978
|
+
keysToOmit,
|
|
979
|
+
resolver,
|
|
980
|
+
enumSchemaNames,
|
|
981
|
+
nodes: printer?.nodes
|
|
982
|
+
});
|
|
983
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, {
|
|
984
|
+
root: meta.file.path,
|
|
985
|
+
path: imp.path,
|
|
986
|
+
name: imp.name,
|
|
987
|
+
isTypeOnly: true
|
|
988
|
+
}, [
|
|
989
|
+
name,
|
|
990
|
+
imp.path,
|
|
991
|
+
imp.isTypeOnly
|
|
992
|
+
].join("-"))), /* @__PURE__ */ jsx(Type, {
|
|
993
|
+
name,
|
|
994
|
+
node: schema,
|
|
995
|
+
enumType,
|
|
996
|
+
enumTypeSuffix,
|
|
997
|
+
enumKeyCasing,
|
|
998
|
+
resolver,
|
|
999
|
+
printer: schemaPrinter
|
|
1000
|
+
})] });
|
|
1001
|
+
}
|
|
1002
|
+
const paramTypes = params.map((param) => renderSchemaType({
|
|
1003
|
+
schema: param.schema,
|
|
1004
|
+
name: resolver.resolveParamName(node, param)
|
|
1005
|
+
}));
|
|
1006
|
+
const requestType = node.requestBody?.schema ? renderSchemaType({
|
|
1007
|
+
schema: {
|
|
1008
|
+
...node.requestBody.schema,
|
|
1009
|
+
description: node.requestBody.description ?? node.requestBody.schema.description
|
|
1010
|
+
},
|
|
1011
|
+
name: resolver.resolveDataName(node),
|
|
1012
|
+
keysToOmit: node.requestBody.keysToOmit
|
|
1013
|
+
}) : null;
|
|
1014
|
+
const responseTypes = node.responses.map((res) => renderSchemaType({
|
|
1015
|
+
schema: res.schema,
|
|
1016
|
+
name: resolver.resolveResponseStatusName(node, res.statusCode),
|
|
1017
|
+
keysToOmit: res.keysToOmit
|
|
1018
|
+
}));
|
|
1019
|
+
const dataType = renderSchemaType({
|
|
1020
|
+
schema: buildData({
|
|
1021
|
+
...node,
|
|
1022
|
+
parameters: params
|
|
1023
|
+
}, { resolver }),
|
|
1024
|
+
name: resolver.resolveRequestConfigName(node)
|
|
1025
|
+
});
|
|
1026
|
+
const responsesType = renderSchemaType({
|
|
1027
|
+
schema: buildResponses(node, { resolver }),
|
|
1028
|
+
name: resolver.resolveResponsesName(node)
|
|
1029
|
+
});
|
|
1030
|
+
const responseType = renderSchemaType({
|
|
1031
|
+
schema: node.responses.some((res) => res.schema) ? {
|
|
1032
|
+
...buildResponseUnion(node, { resolver }),
|
|
1033
|
+
description: "Union of all possible responses"
|
|
1034
|
+
} : null,
|
|
1035
|
+
name: resolver.resolveResponseName(node)
|
|
1036
|
+
});
|
|
1037
|
+
return /* @__PURE__ */ jsxs(File, {
|
|
1038
|
+
baseName: meta.file.baseName,
|
|
1039
|
+
path: meta.file.path,
|
|
1040
|
+
meta: meta.file.meta,
|
|
1041
|
+
banner: resolver.resolveBanner(adapter.rootNode, {
|
|
1042
|
+
output,
|
|
1043
|
+
config
|
|
1044
|
+
}),
|
|
1045
|
+
footer: resolver.resolveFooter(adapter.rootNode, {
|
|
1046
|
+
output,
|
|
1047
|
+
config
|
|
1048
|
+
}),
|
|
1049
|
+
children: [
|
|
1050
|
+
paramTypes,
|
|
1051
|
+
responseTypes,
|
|
1052
|
+
requestType,
|
|
1053
|
+
dataType,
|
|
1054
|
+
responsesType,
|
|
1055
|
+
responseType
|
|
1056
|
+
]
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
});
|
|
1060
|
+
//#endregion
|
|
1061
|
+
//#region package.json
|
|
1062
|
+
var version = "5.0.0-alpha.31";
|
|
1063
|
+
//#endregion
|
|
1064
|
+
//#region src/resolvers/resolverTs.ts
|
|
1065
|
+
/**
|
|
1066
|
+
* Resolver for `@kubb/plugin-ts` that provides the default naming and path-resolution
|
|
1067
|
+
* helpers used by the plugin. Import this in other plugins to resolve the exact names and
|
|
1068
|
+
* paths that `plugin-ts` generates without hardcoding the conventions.
|
|
1069
|
+
*
|
|
1070
|
+
* The `default` method is automatically injected by `defineResolver` — it uses `camelCase`
|
|
1071
|
+
* for identifiers/files and `pascalCase` for type names.
|
|
1072
|
+
*
|
|
1073
|
+
* @example
|
|
1074
|
+
* ```ts
|
|
1075
|
+
* import { resolver } from '@kubb/plugin-ts'
|
|
1076
|
+
*
|
|
1077
|
+
* resolver.default('list pets', 'type') // → 'ListPets'
|
|
1078
|
+
* resolver.resolveName('list pets status 200') // → 'ListPetsStatus200'
|
|
1079
|
+
* resolver.resolvePathName('list pets', 'file') // → 'listPets'
|
|
1080
|
+
* ```
|
|
1081
|
+
*/
|
|
1082
|
+
const resolverTs = defineResolver(() => {
|
|
1083
|
+
return {
|
|
1084
|
+
name: "default",
|
|
1085
|
+
pluginName: "plugin-ts",
|
|
1086
|
+
default(name, type) {
|
|
1087
|
+
return pascalCase(name, { isFile: type === "file" });
|
|
1088
|
+
},
|
|
1089
|
+
resolveTypeName(name) {
|
|
1090
|
+
return pascalCase(name);
|
|
1091
|
+
},
|
|
1092
|
+
resolvePathName(name, type) {
|
|
1093
|
+
return pascalCase(name, { isFile: type === "file" });
|
|
1094
|
+
},
|
|
1095
|
+
resolveParamName(node, param) {
|
|
1096
|
+
return this.resolveTypeName(`${node.operationId} ${param.in} ${param.name}`);
|
|
1097
|
+
},
|
|
1098
|
+
resolveResponseStatusName(node, statusCode) {
|
|
1099
|
+
return this.resolveTypeName(`${node.operationId} Status ${statusCode}`);
|
|
1100
|
+
},
|
|
1101
|
+
resolveDataName(node) {
|
|
1102
|
+
return this.resolveTypeName(`${node.operationId} Data`);
|
|
1103
|
+
},
|
|
1104
|
+
resolveRequestConfigName(node) {
|
|
1105
|
+
return this.resolveTypeName(`${node.operationId} RequestConfig`);
|
|
1106
|
+
},
|
|
1107
|
+
resolveResponsesName(node) {
|
|
1108
|
+
return this.resolveTypeName(`${node.operationId} Responses`);
|
|
1109
|
+
},
|
|
1110
|
+
resolveResponseName(node) {
|
|
1111
|
+
return this.resolveTypeName(`${node.operationId} Response`);
|
|
1112
|
+
},
|
|
1113
|
+
resolveEnumKeyName(node, enumTypeSuffix = "key") {
|
|
1114
|
+
return `${this.resolveTypeName(node.name ?? "")}${enumTypeSuffix}`;
|
|
1115
|
+
},
|
|
1116
|
+
resolvePathParamsName(node, param) {
|
|
1117
|
+
return this.resolveParamName(node, param);
|
|
1118
|
+
},
|
|
1119
|
+
resolveQueryParamsName(node, param) {
|
|
1120
|
+
return this.resolveParamName(node, param);
|
|
1121
|
+
},
|
|
1122
|
+
resolveHeaderParamsName(node, param) {
|
|
1123
|
+
return this.resolveParamName(node, param);
|
|
1124
|
+
}
|
|
1125
|
+
};
|
|
1126
|
+
});
|
|
1127
|
+
//#endregion
|
|
1128
|
+
//#region src/resolvers/resolverTsLegacy.ts
|
|
1129
|
+
/**
|
|
1130
|
+
* Legacy resolver for `@kubb/plugin-ts` that reproduces the naming conventions
|
|
1131
|
+
* used before the v2 resolver refactor. Enable via `compatibilityPreset: 'kubbV4'`
|
|
1132
|
+
* (or by composing this resolver manually).
|
|
1133
|
+
*
|
|
1134
|
+
* Key differences from the default resolver:
|
|
1135
|
+
* - Response status types: `<OperationId><StatusCode>` (e.g. `CreatePets201`) instead of `<OperationId>Status201`
|
|
1136
|
+
* - Default/error responses: `<OperationId>Error` instead of `<OperationId>StatusDefault`
|
|
1137
|
+
* - Request body: `<OperationId>MutationRequest` (non-GET) / `<OperationId>QueryRequest` (GET)
|
|
1138
|
+
* - Combined responses type: `<OperationId>Mutation` / `<OperationId>Query`
|
|
1139
|
+
* - Response union: `<OperationId>MutationResponse` / `<OperationId>QueryResponse`
|
|
1140
|
+
*
|
|
1141
|
+
* @example
|
|
1142
|
+
* ```ts
|
|
1143
|
+
* import { resolverTsLegacy } from '@kubb/plugin-ts'
|
|
1144
|
+
*
|
|
1145
|
+
* resolverTsLegacy.resolveResponseStatusTypedName(node, 201) // → 'CreatePets201'
|
|
1146
|
+
* resolverTsLegacy.resolveResponseStatusTypedName(node, 'default') // → 'CreatePetsError'
|
|
1147
|
+
* resolverTsLegacy.resolveDataTypedName(node) // → 'CreatePetsMutationRequest' (POST)
|
|
1148
|
+
* resolverTsLegacy.resolveResponsesTypedName(node) // → 'CreatePetsMutation' (POST)
|
|
1149
|
+
* resolverTsLegacy.resolveResponseTypedName(node) // → 'CreatePetsMutationResponse' (POST)
|
|
1150
|
+
* ```
|
|
1151
|
+
*/
|
|
1152
|
+
const resolverTsLegacy = defineResolver(() => {
|
|
1153
|
+
return {
|
|
1154
|
+
...resolverTs,
|
|
1155
|
+
pluginName: "plugin-ts",
|
|
1156
|
+
resolveResponseStatusName(node, statusCode) {
|
|
1157
|
+
if (statusCode === "default") return this.resolveTypeName(`${node.operationId} Error`);
|
|
1158
|
+
return this.resolveTypeName(`${node.operationId} ${statusCode}`);
|
|
1159
|
+
},
|
|
1160
|
+
resolveDataName(node) {
|
|
1161
|
+
const suffix = node.method === "GET" ? "QueryRequest" : "MutationRequest";
|
|
1162
|
+
return this.resolveTypeName(`${node.operationId} ${suffix}`);
|
|
1163
|
+
},
|
|
1164
|
+
resolveResponsesName(node) {
|
|
1165
|
+
const suffix = node.method === "GET" ? "Query" : "Mutation";
|
|
1166
|
+
return this.resolveTypeName(`${node.operationId} ${suffix}`);
|
|
1167
|
+
},
|
|
1168
|
+
resolveResponseName(node) {
|
|
1169
|
+
const suffix = node.method === "GET" ? "QueryResponse" : "MutationResponse";
|
|
1170
|
+
return this.resolveTypeName(`${node.operationId} ${suffix}`);
|
|
1171
|
+
},
|
|
1172
|
+
resolvePathParamsName(node, _param) {
|
|
1173
|
+
return this.resolveTypeName(`${node.operationId} PathParams`);
|
|
1174
|
+
},
|
|
1175
|
+
resolveQueryParamsName(node, _param) {
|
|
1176
|
+
return this.resolveTypeName(`${node.operationId} QueryParams`);
|
|
1177
|
+
},
|
|
1178
|
+
resolveHeaderParamsName(node, _param) {
|
|
1179
|
+
return this.resolveTypeName(`${node.operationId} HeaderParams`);
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
});
|
|
1183
|
+
//#endregion
|
|
1184
|
+
//#region src/generators/typeGeneratorLegacy.tsx
|
|
1185
|
+
function buildGroupedParamsSchema({ params, parentName }) {
|
|
1186
|
+
return createSchema({
|
|
1187
|
+
type: "object",
|
|
1188
|
+
properties: params.map((param) => {
|
|
1189
|
+
let schema = param.schema;
|
|
1190
|
+
if (narrowSchema(schema, "enum") && !schema.name && parentName) schema = {
|
|
1191
|
+
...schema,
|
|
1192
|
+
name: pascalCase([
|
|
1193
|
+
parentName,
|
|
1194
|
+
param.name,
|
|
1195
|
+
"enum"
|
|
1196
|
+
].join(" "))
|
|
1197
|
+
};
|
|
1198
|
+
return createProperty({
|
|
1199
|
+
name: param.name,
|
|
1200
|
+
required: param.required,
|
|
1201
|
+
schema
|
|
1202
|
+
});
|
|
1203
|
+
})
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
function buildLegacyResponsesSchemaNode(node, { resolver }) {
|
|
1207
|
+
const isGet = node.method.toLowerCase() === "get";
|
|
1208
|
+
const successResponses = node.responses.filter((res) => {
|
|
1209
|
+
const code = Number(res.statusCode);
|
|
1210
|
+
return !Number.isNaN(code) && code >= 200 && code < 300;
|
|
1211
|
+
});
|
|
1212
|
+
const errorResponses = node.responses.filter((res) => res.statusCode === "default" || Number(res.statusCode) >= 400);
|
|
1213
|
+
const responseSchema = successResponses.length > 0 ? successResponses.length === 1 ? createSchema({
|
|
1214
|
+
type: "ref",
|
|
1215
|
+
name: resolver.resolveResponseStatusName(node, successResponses[0].statusCode)
|
|
1216
|
+
}) : createSchema({
|
|
1217
|
+
type: "union",
|
|
1218
|
+
members: successResponses.map((res) => createSchema({
|
|
1219
|
+
type: "ref",
|
|
1220
|
+
name: resolver.resolveResponseStatusName(node, res.statusCode)
|
|
1221
|
+
}))
|
|
1222
|
+
}) : createSchema({
|
|
1223
|
+
type: "any",
|
|
1224
|
+
primitive: void 0
|
|
1225
|
+
});
|
|
1226
|
+
const errorsSchema = errorResponses.length > 0 ? errorResponses.length === 1 ? createSchema({
|
|
1227
|
+
type: "ref",
|
|
1228
|
+
name: resolver.resolveResponseStatusName(node, errorResponses[0].statusCode)
|
|
1229
|
+
}) : createSchema({
|
|
1230
|
+
type: "union",
|
|
1231
|
+
members: errorResponses.map((res) => createSchema({
|
|
1232
|
+
type: "ref",
|
|
1233
|
+
name: resolver.resolveResponseStatusName(node, res.statusCode)
|
|
1234
|
+
}))
|
|
1235
|
+
}) : createSchema({
|
|
1236
|
+
type: "any",
|
|
1237
|
+
primitive: void 0
|
|
1238
|
+
});
|
|
1239
|
+
const properties = [createProperty({
|
|
1240
|
+
name: "Response",
|
|
1241
|
+
required: true,
|
|
1242
|
+
schema: responseSchema
|
|
1243
|
+
})];
|
|
1244
|
+
if (!isGet && node.requestBody?.schema) properties.push(createProperty({
|
|
1245
|
+
name: "Request",
|
|
1246
|
+
required: true,
|
|
1247
|
+
schema: createSchema({
|
|
1248
|
+
type: "ref",
|
|
1249
|
+
name: resolver.resolveDataName(node)
|
|
1250
|
+
})
|
|
1251
|
+
}));
|
|
1252
|
+
const queryParam = node.parameters.find((p) => p.in === "query");
|
|
1253
|
+
if (queryParam) properties.push(createProperty({
|
|
1254
|
+
name: "QueryParams",
|
|
1255
|
+
required: true,
|
|
1256
|
+
schema: createSchema({
|
|
1257
|
+
type: "ref",
|
|
1258
|
+
name: resolver.resolveQueryParamsName(node, queryParam)
|
|
1259
|
+
})
|
|
1260
|
+
}));
|
|
1261
|
+
const pathParam = node.parameters.find((p) => p.in === "path");
|
|
1262
|
+
if (pathParam) properties.push(createProperty({
|
|
1263
|
+
name: "PathParams",
|
|
1264
|
+
required: true,
|
|
1265
|
+
schema: createSchema({
|
|
1266
|
+
type: "ref",
|
|
1267
|
+
name: resolver.resolvePathParamsName(node, pathParam)
|
|
1268
|
+
})
|
|
1269
|
+
}));
|
|
1270
|
+
const headerParam = node.parameters.find((p) => p.in === "header");
|
|
1271
|
+
if (headerParam) properties.push(createProperty({
|
|
1272
|
+
name: "HeaderParams",
|
|
1273
|
+
required: true,
|
|
1274
|
+
schema: createSchema({
|
|
1275
|
+
type: "ref",
|
|
1276
|
+
name: resolver.resolveHeaderParamsName(node, headerParam)
|
|
1277
|
+
})
|
|
1278
|
+
}));
|
|
1279
|
+
properties.push(createProperty({
|
|
1280
|
+
name: "Errors",
|
|
1281
|
+
required: true,
|
|
1282
|
+
schema: errorsSchema
|
|
1283
|
+
}));
|
|
1284
|
+
return createSchema({
|
|
1285
|
+
type: "object",
|
|
1286
|
+
properties
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
function buildLegacyResponseUnionSchemaNode(node, { resolver }) {
|
|
1290
|
+
const successResponses = node.responses.filter((res) => {
|
|
1291
|
+
const code = Number(res.statusCode);
|
|
1292
|
+
return !Number.isNaN(code) && code >= 200 && code < 300;
|
|
1293
|
+
});
|
|
1294
|
+
if (successResponses.length === 0) return createSchema({
|
|
1295
|
+
type: "any",
|
|
1296
|
+
primitive: void 0
|
|
1297
|
+
});
|
|
1298
|
+
if (successResponses.length === 1) return createSchema({
|
|
1299
|
+
type: "ref",
|
|
1300
|
+
name: resolver.resolveResponseStatusName(node, successResponses[0].statusCode)
|
|
1301
|
+
});
|
|
1302
|
+
return createSchema({
|
|
1303
|
+
type: "union",
|
|
1304
|
+
members: successResponses.map((res) => createSchema({
|
|
1305
|
+
type: "ref",
|
|
1306
|
+
name: resolver.resolveResponseStatusName(node, res.statusCode)
|
|
1307
|
+
}))
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
function nameUnnamedEnums(node, parentName) {
|
|
1311
|
+
return transform(node, {
|
|
1312
|
+
schema(n) {
|
|
1313
|
+
const enumNode = narrowSchema(n, "enum");
|
|
1314
|
+
if (enumNode && !enumNode.name) return {
|
|
1315
|
+
...enumNode,
|
|
1316
|
+
name: pascalCase([parentName, "enum"].join(" "))
|
|
1317
|
+
};
|
|
1318
|
+
},
|
|
1319
|
+
property(p) {
|
|
1320
|
+
const enumNode = narrowSchema(p.schema, "enum");
|
|
1321
|
+
if (enumNode && !enumNode.name) return {
|
|
1322
|
+
...p,
|
|
1323
|
+
schema: {
|
|
1324
|
+
...enumNode,
|
|
1325
|
+
name: pascalCase([
|
|
1326
|
+
parentName,
|
|
1327
|
+
p.name,
|
|
1328
|
+
"enum"
|
|
1329
|
+
].join(" "))
|
|
1330
|
+
}
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
const typeGeneratorLegacy = defineGenerator({
|
|
1336
|
+
name: "typescript-legacy",
|
|
1337
|
+
schema(node, options) {
|
|
1338
|
+
const { enumType, enumTypeSuffix, enumKeyCasing, syntaxType, optionalType, arrayType, output, group } = options;
|
|
1339
|
+
const { adapter, config, resolver, root } = this;
|
|
1340
|
+
if (!node.name) return;
|
|
1341
|
+
const mode = this.getMode(output);
|
|
1342
|
+
const imports = adapter.getImports(node, (schemaName) => ({
|
|
1343
|
+
name: resolver.resolveTypeName(schemaName),
|
|
1344
|
+
path: resolver.resolveFile({
|
|
1345
|
+
name: schemaName,
|
|
1346
|
+
extname: ".ts"
|
|
1347
|
+
}, {
|
|
1348
|
+
root,
|
|
1349
|
+
output,
|
|
1350
|
+
group
|
|
1351
|
+
}).path
|
|
1352
|
+
}));
|
|
1353
|
+
const isEnumSchema = !!narrowSchema(node, schemaTypes.enum);
|
|
1354
|
+
const meta = {
|
|
1355
|
+
name: ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) && isEnumSchema ? resolver.resolveEnumKeyName(node, enumTypeSuffix) : resolver.resolveTypeName(node.name),
|
|
1356
|
+
file: resolver.resolveFile({
|
|
1357
|
+
name: node.name,
|
|
1358
|
+
extname: ".ts"
|
|
1359
|
+
}, {
|
|
1360
|
+
root,
|
|
1361
|
+
output,
|
|
1362
|
+
group
|
|
1363
|
+
})
|
|
1364
|
+
};
|
|
1365
|
+
const schemaPrinter = printerTs({
|
|
1366
|
+
optionalType,
|
|
1367
|
+
arrayType,
|
|
1368
|
+
enumType,
|
|
1369
|
+
enumTypeSuffix,
|
|
1370
|
+
name: meta.name,
|
|
1371
|
+
syntaxType,
|
|
1372
|
+
description: node.description,
|
|
1373
|
+
resolver
|
|
1374
|
+
});
|
|
1375
|
+
return /* @__PURE__ */ jsxs(File, {
|
|
1376
|
+
baseName: meta.file.baseName,
|
|
1377
|
+
path: meta.file.path,
|
|
1378
|
+
meta: meta.file.meta,
|
|
1379
|
+
banner: resolver.resolveBanner(adapter.rootNode, {
|
|
1380
|
+
output,
|
|
1381
|
+
config
|
|
1382
|
+
}),
|
|
1383
|
+
footer: resolver.resolveFooter(adapter.rootNode, {
|
|
1384
|
+
output,
|
|
1385
|
+
config
|
|
1386
|
+
}),
|
|
1387
|
+
children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, {
|
|
1388
|
+
root: meta.file.path,
|
|
1389
|
+
path: imp.path,
|
|
1390
|
+
name: imp.name,
|
|
1391
|
+
isTypeOnly: true
|
|
1392
|
+
}, [
|
|
1393
|
+
node.name,
|
|
1394
|
+
imp.path,
|
|
1395
|
+
imp.isTypeOnly
|
|
1396
|
+
].join("-"))), /* @__PURE__ */ jsx(Type, {
|
|
1397
|
+
name: meta.name,
|
|
1398
|
+
node,
|
|
1399
|
+
enumType,
|
|
1400
|
+
enumTypeSuffix,
|
|
1401
|
+
enumKeyCasing,
|
|
1402
|
+
resolver,
|
|
1403
|
+
printer: schemaPrinter
|
|
1404
|
+
})]
|
|
1405
|
+
});
|
|
1406
|
+
},
|
|
1407
|
+
operation(node, options) {
|
|
1408
|
+
const { enumType, enumTypeSuffix, enumKeyCasing, optionalType, arrayType, syntaxType, paramsCasing, group, output } = options;
|
|
1409
|
+
const { adapter, config, resolver, root } = this;
|
|
1410
|
+
const mode = this.getMode(output);
|
|
1411
|
+
const params = caseParams(node.parameters, paramsCasing);
|
|
1412
|
+
const meta = { file: resolver.resolveFile({
|
|
1413
|
+
name: node.operationId,
|
|
1414
|
+
extname: ".ts",
|
|
1415
|
+
tag: node.tags[0] ?? "default",
|
|
1416
|
+
path: node.path
|
|
1417
|
+
}, {
|
|
1418
|
+
root,
|
|
1419
|
+
output,
|
|
1420
|
+
group
|
|
1421
|
+
}) };
|
|
1422
|
+
function renderSchemaType({ schema, name, description, keysToOmit }) {
|
|
1423
|
+
if (!schema) return null;
|
|
1424
|
+
const imports = adapter.getImports(schema, (schemaName) => ({
|
|
1425
|
+
name: resolver.resolveTypeName(schemaName),
|
|
1426
|
+
path: resolver.resolveFile({
|
|
1427
|
+
name: schemaName,
|
|
1428
|
+
extname: ".ts"
|
|
1429
|
+
}, {
|
|
1430
|
+
root,
|
|
1431
|
+
output,
|
|
1432
|
+
group
|
|
1433
|
+
}).path
|
|
1434
|
+
}));
|
|
1435
|
+
const opPrinter = printerTs({
|
|
1436
|
+
optionalType,
|
|
1437
|
+
arrayType,
|
|
1438
|
+
enumType,
|
|
1439
|
+
enumTypeSuffix,
|
|
1440
|
+
name,
|
|
1441
|
+
syntaxType,
|
|
1442
|
+
description,
|
|
1443
|
+
keysToOmit,
|
|
1444
|
+
resolver
|
|
1445
|
+
});
|
|
1446
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, {
|
|
1447
|
+
root: meta.file.path,
|
|
1448
|
+
path: imp.path,
|
|
1449
|
+
name: imp.name,
|
|
1450
|
+
isTypeOnly: true
|
|
1451
|
+
}, [
|
|
1452
|
+
name,
|
|
1453
|
+
imp.path,
|
|
1454
|
+
imp.isTypeOnly
|
|
1455
|
+
].join("-"))), /* @__PURE__ */ jsx(Type, {
|
|
1456
|
+
name,
|
|
1457
|
+
node: schema,
|
|
1458
|
+
enumType,
|
|
1459
|
+
enumTypeSuffix,
|
|
1460
|
+
enumKeyCasing,
|
|
1461
|
+
resolver,
|
|
1462
|
+
printer: opPrinter
|
|
1463
|
+
})] });
|
|
1464
|
+
}
|
|
1465
|
+
const pathParams = params.filter((p) => p.in === "path");
|
|
1466
|
+
const queryParams = params.filter((p) => p.in === "query");
|
|
1467
|
+
const headerParams = params.filter((p) => p.in === "header");
|
|
1468
|
+
const responseTypes = node.responses.map((res) => {
|
|
1469
|
+
const responseName = resolver.resolveResponseStatusName(node, res.statusCode);
|
|
1470
|
+
const baseResponseName = resolverTsLegacy.resolveResponseStatusName(node, res.statusCode);
|
|
1471
|
+
return renderSchemaType({
|
|
1472
|
+
schema: res.schema ? nameUnnamedEnums(res.schema, baseResponseName) : res.schema,
|
|
1473
|
+
name: responseName,
|
|
1474
|
+
description: res.description,
|
|
1475
|
+
keysToOmit: res.keysToOmit
|
|
1476
|
+
});
|
|
1477
|
+
});
|
|
1478
|
+
const requestType = node.requestBody?.schema ? renderSchemaType({
|
|
1479
|
+
schema: nameUnnamedEnums(node.requestBody.schema, resolverTsLegacy.resolveDataName(node)),
|
|
1480
|
+
name: resolver.resolveDataName(node),
|
|
1481
|
+
description: node.requestBody.description ?? node.requestBody.schema.description,
|
|
1482
|
+
keysToOmit: node.requestBody.keysToOmit
|
|
1483
|
+
}) : null;
|
|
1484
|
+
const legacyParamTypes = [
|
|
1485
|
+
pathParams.length > 0 ? renderSchemaType({
|
|
1486
|
+
schema: buildGroupedParamsSchema({
|
|
1487
|
+
params: pathParams,
|
|
1488
|
+
parentName: resolverTsLegacy.resolvePathParamsName(node, pathParams[0])
|
|
1489
|
+
}),
|
|
1490
|
+
name: resolver.resolvePathParamsName(node, pathParams[0])
|
|
1491
|
+
}) : null,
|
|
1492
|
+
queryParams.length > 0 ? renderSchemaType({
|
|
1493
|
+
schema: buildGroupedParamsSchema({
|
|
1494
|
+
params: queryParams,
|
|
1495
|
+
parentName: resolverTsLegacy.resolveQueryParamsName(node, queryParams[0])
|
|
1496
|
+
}),
|
|
1497
|
+
name: resolver.resolveQueryParamsName(node, queryParams[0])
|
|
1498
|
+
}) : null,
|
|
1499
|
+
headerParams.length > 0 ? renderSchemaType({
|
|
1500
|
+
schema: buildGroupedParamsSchema({
|
|
1501
|
+
params: headerParams,
|
|
1502
|
+
parentName: resolverTsLegacy.resolveHeaderParamsName(node, headerParams[0])
|
|
1503
|
+
}),
|
|
1504
|
+
name: resolver.resolveHeaderParamsName(node, headerParams[0])
|
|
1505
|
+
}) : null
|
|
1506
|
+
];
|
|
1507
|
+
const legacyResponsesType = renderSchemaType({
|
|
1508
|
+
schema: buildLegacyResponsesSchemaNode(node, { resolver }),
|
|
1509
|
+
name: resolver.resolveResponsesName(node)
|
|
1510
|
+
});
|
|
1511
|
+
const legacyResponseType = renderSchemaType({
|
|
1512
|
+
schema: buildLegacyResponseUnionSchemaNode(node, { resolver }),
|
|
1513
|
+
name: resolver.resolveResponseName(node)
|
|
1514
|
+
});
|
|
1515
|
+
return /* @__PURE__ */ jsxs(File, {
|
|
1516
|
+
baseName: meta.file.baseName,
|
|
1517
|
+
path: meta.file.path,
|
|
1518
|
+
meta: meta.file.meta,
|
|
1519
|
+
banner: resolver.resolveBanner(adapter.rootNode, {
|
|
1520
|
+
output,
|
|
1521
|
+
config
|
|
1522
|
+
}),
|
|
1523
|
+
footer: resolver.resolveFooter(adapter.rootNode, {
|
|
1524
|
+
output,
|
|
1525
|
+
config
|
|
1526
|
+
}),
|
|
1527
|
+
children: [
|
|
1528
|
+
legacyParamTypes,
|
|
1529
|
+
responseTypes,
|
|
1530
|
+
requestType,
|
|
1531
|
+
legacyResponseType,
|
|
1532
|
+
legacyResponsesType
|
|
1533
|
+
]
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
});
|
|
1537
|
+
//#endregion
|
|
1538
|
+
//#region src/presets.ts
|
|
1539
|
+
/**
|
|
1540
|
+
* Built-in preset registry for `@kubb/plugin-ts`.
|
|
1541
|
+
*
|
|
1542
|
+
* - `default` — uses `resolverTs` and `typeGenerator` (current naming conventions).
|
|
1543
|
+
* - `kubbV4` — uses `resolverTsLegacy` and `typeGeneratorLegacy` (Kubb v4 naming conventions).
|
|
1544
|
+
*/
|
|
1545
|
+
const presets = definePresets({
|
|
1546
|
+
default: {
|
|
1547
|
+
name: "default",
|
|
1548
|
+
resolver: resolverTs,
|
|
1549
|
+
generators: [typeGenerator],
|
|
1550
|
+
printer: printerTs
|
|
1551
|
+
},
|
|
1552
|
+
kubbV4: {
|
|
1553
|
+
name: "kubbV4",
|
|
1554
|
+
resolver: resolverTsLegacy,
|
|
1555
|
+
generators: [typeGeneratorLegacy],
|
|
1556
|
+
printer: printerTs
|
|
1557
|
+
}
|
|
1558
|
+
});
|
|
1559
|
+
//#endregion
|
|
1560
|
+
//#region src/plugin.ts
|
|
1561
|
+
/**
|
|
1562
|
+
* Canonical plugin name for `@kubb/plugin-ts`, used to identify the plugin in driver lookups and warnings.
|
|
1563
|
+
*/
|
|
1564
|
+
const pluginTsName = "plugin-ts";
|
|
1565
|
+
/**
|
|
1566
|
+
* The `@kubb/plugin-ts` plugin factory.
|
|
1567
|
+
*
|
|
1568
|
+
* Generates TypeScript type declarations from an OpenAPI/AST `RootNode`.
|
|
1569
|
+
* Walks schemas and operations, delegates rendering to the active generators,
|
|
1570
|
+
* and writes barrel files based on `output.barrelType`.
|
|
1571
|
+
*
|
|
1572
|
+
* @example
|
|
1573
|
+
* ```ts
|
|
1574
|
+
* import { pluginTs } from '@kubb/plugin-ts'
|
|
1575
|
+
*
|
|
1576
|
+
* export default defineConfig({
|
|
1577
|
+
* plugins: [pluginTs({ output: { path: 'types' }, enumType: 'asConst' })],
|
|
1578
|
+
* })
|
|
1579
|
+
* ```
|
|
1580
|
+
*/
|
|
1581
|
+
const pluginTs = createPlugin((options) => {
|
|
1582
|
+
const { output = {
|
|
1583
|
+
path: "types",
|
|
1584
|
+
barrelType: "named"
|
|
1585
|
+
}, group, exclude = [], include, override = [], enumType = "asConst", enumTypeSuffix = "Key", enumKeyCasing = "none", optionalType = "questionToken", arrayType = "array", syntaxType = "type", paramsCasing, printer, compatibilityPreset = "default", resolver: userResolver, transformer: userTransformer, generators: userGenerators = [] } = options;
|
|
1586
|
+
const preset = getPreset({
|
|
1587
|
+
preset: compatibilityPreset,
|
|
1588
|
+
presets,
|
|
1589
|
+
resolver: userResolver,
|
|
1590
|
+
transformer: userTransformer,
|
|
1591
|
+
generators: userGenerators
|
|
1592
|
+
});
|
|
1593
|
+
const mergedGenerator = mergeGenerators(preset.generators ?? []);
|
|
1594
|
+
let resolveNameWarning = false;
|
|
1595
|
+
let resolvePathWarning = false;
|
|
1596
|
+
return {
|
|
1597
|
+
name: pluginTsName,
|
|
1598
|
+
version,
|
|
1599
|
+
get resolver() {
|
|
1600
|
+
return preset.resolver;
|
|
1601
|
+
},
|
|
1602
|
+
get transformer() {
|
|
1603
|
+
return preset.transformer;
|
|
1604
|
+
},
|
|
1605
|
+
get options() {
|
|
1606
|
+
return {
|
|
1607
|
+
output,
|
|
1608
|
+
exclude,
|
|
1609
|
+
include,
|
|
1610
|
+
override,
|
|
1611
|
+
optionalType,
|
|
1612
|
+
group: group ? {
|
|
1613
|
+
...group,
|
|
1614
|
+
name: (ctx) => {
|
|
1615
|
+
if (group.type === "path") return `${ctx.group.split("/")[1]}`;
|
|
1616
|
+
return `${camelCase(ctx.group)}Controller`;
|
|
1617
|
+
}
|
|
1618
|
+
} : void 0,
|
|
1619
|
+
arrayType,
|
|
1620
|
+
enumType,
|
|
1621
|
+
enumTypeSuffix,
|
|
1622
|
+
enumKeyCasing,
|
|
1623
|
+
syntaxType,
|
|
1624
|
+
paramsCasing,
|
|
1625
|
+
printer
|
|
1626
|
+
};
|
|
1627
|
+
},
|
|
1628
|
+
resolvePath(baseName, pathMode, options) {
|
|
1629
|
+
if (!resolvePathWarning) {
|
|
1630
|
+
this.warn("Do not use resolvePath for pluginTs, use resolverTs.resolvePath instead");
|
|
1631
|
+
resolvePathWarning = true;
|
|
1632
|
+
}
|
|
1633
|
+
return this.plugin.resolver.resolvePath({
|
|
1634
|
+
baseName,
|
|
1635
|
+
pathMode,
|
|
1636
|
+
tag: options?.group?.tag,
|
|
1637
|
+
path: options?.group?.path
|
|
1638
|
+
}, {
|
|
1639
|
+
root: this.root,
|
|
1640
|
+
output,
|
|
1641
|
+
group: this.plugin.options.group
|
|
1642
|
+
});
|
|
1643
|
+
},
|
|
1644
|
+
resolveName(name, type) {
|
|
1645
|
+
if (!resolveNameWarning) {
|
|
1646
|
+
this.warn("Do not use resolveName for pluginTs, use resolverTs.default instead");
|
|
1647
|
+
resolveNameWarning = true;
|
|
1648
|
+
}
|
|
1649
|
+
return this.plugin.resolver.default(name, type);
|
|
1650
|
+
},
|
|
1651
|
+
async schema(node, options) {
|
|
1652
|
+
return mergedGenerator.schema?.call(this, node, options);
|
|
1653
|
+
},
|
|
1654
|
+
async operation(node, options) {
|
|
1655
|
+
return mergedGenerator.operation?.call(this, node, options);
|
|
1656
|
+
},
|
|
1657
|
+
async operations(nodes, options) {
|
|
1658
|
+
return mergedGenerator.operations?.call(this, nodes, options);
|
|
1659
|
+
},
|
|
1660
|
+
async buildStart() {
|
|
1661
|
+
await this.openInStudio({ ast: true });
|
|
1662
|
+
}
|
|
1663
|
+
};
|
|
1664
|
+
});
|
|
1665
|
+
//#endregion
|
|
1666
|
+
//#region src/printers/functionPrinter.ts
|
|
1667
|
+
const kindToHandlerKey = {
|
|
1668
|
+
FunctionParameter: "functionParameter",
|
|
1669
|
+
ParameterGroup: "parameterGroup",
|
|
1670
|
+
FunctionParameters: "functionParameters",
|
|
1671
|
+
Type: "type"
|
|
1672
|
+
};
|
|
1673
|
+
/**
|
|
1674
|
+
* Creates a function-parameter printer factory.
|
|
1675
|
+
*
|
|
1676
|
+
* Uses `createPrinterFactory` and dispatches handlers by `node.kind`
|
|
1677
|
+
* (for function nodes) rather than by `node.type` (for schema nodes).
|
|
1678
|
+
*/
|
|
1679
|
+
const defineFunctionPrinter = createPrinterFactory((node) => kindToHandlerKey[node.kind]);
|
|
1680
|
+
function rank(param) {
|
|
1681
|
+
if (param.kind === "ParameterGroup") {
|
|
1682
|
+
if (param.default) return PARAM_RANK.withDefault;
|
|
1683
|
+
return param.optional ?? param.properties.every((p) => p.optional || p.default !== void 0) ? PARAM_RANK.optional : PARAM_RANK.required;
|
|
1684
|
+
}
|
|
1685
|
+
if (param.rest) return PARAM_RANK.rest;
|
|
1686
|
+
if (param.default) return PARAM_RANK.withDefault;
|
|
1687
|
+
return param.optional ? PARAM_RANK.optional : PARAM_RANK.required;
|
|
1688
|
+
}
|
|
1689
|
+
function sortParams(params) {
|
|
1690
|
+
return [...params].sort((a, b) => rank(a) - rank(b));
|
|
1691
|
+
}
|
|
1692
|
+
function sortChildParams(params) {
|
|
1693
|
+
return [...params].sort((a, b) => rank(a) - rank(b));
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Default function-signature printer.
|
|
1697
|
+
* Covers the four standard output modes used across Kubb plugins.
|
|
1698
|
+
*
|
|
1699
|
+
* @example
|
|
1700
|
+
* ```ts
|
|
1701
|
+
* const printer = functionPrinter({ mode: 'declaration' })
|
|
1702
|
+
*
|
|
1703
|
+
* const sig = createFunctionParameters({
|
|
1704
|
+
* params: [
|
|
1705
|
+
* createFunctionParameter({ name: 'petId', type: 'string', optional: false }),
|
|
1706
|
+
* createFunctionParameter({ name: 'config', type: 'Config', optional: false, default: '{}' }),
|
|
1707
|
+
* ],
|
|
1708
|
+
* })
|
|
1709
|
+
*
|
|
1710
|
+
* printer.print(sig) // → "petId: string, config: Config = {}"
|
|
1711
|
+
* ```
|
|
1712
|
+
*/
|
|
1713
|
+
const functionPrinter = defineFunctionPrinter((options) => ({
|
|
1714
|
+
name: "functionParameters",
|
|
1715
|
+
options,
|
|
1716
|
+
nodes: {
|
|
1717
|
+
type(node) {
|
|
1718
|
+
if (node.variant === "member") return `${node.base}['${node.key}']`;
|
|
1719
|
+
if (node.variant === "struct") return `{ ${node.properties.map((p) => {
|
|
1720
|
+
const typeStr = this.transform(p.type);
|
|
1721
|
+
const key = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(p.name) ? p.name : JSON.stringify(p.name);
|
|
1722
|
+
return p.optional ? `${key}?: ${typeStr}` : `${key}: ${typeStr}`;
|
|
1723
|
+
}).join("; ")} }`;
|
|
1724
|
+
if (node.variant === "reference") return node.name;
|
|
1725
|
+
return null;
|
|
1726
|
+
},
|
|
1727
|
+
functionParameter(node) {
|
|
1728
|
+
const { mode, transformName, transformType } = this.options;
|
|
1729
|
+
const name = transformName ? transformName(node.name) : node.name;
|
|
1730
|
+
const rawType = node.type ? this.transform(node.type) : void 0;
|
|
1731
|
+
const type = rawType != null && transformType ? transformType(rawType) : rawType;
|
|
1732
|
+
if (mode === "keys" || mode === "values") return node.rest ? `...${name}` : name;
|
|
1733
|
+
if (mode === "call") return node.rest ? `...${name}` : name;
|
|
1734
|
+
if (node.rest) return type ? `...${name}: ${type}` : `...${name}`;
|
|
1735
|
+
if (type) {
|
|
1736
|
+
if (node.optional) return `${name}?: ${type}`;
|
|
1737
|
+
return node.default ? `${name}: ${type} = ${node.default}` : `${name}: ${type}`;
|
|
1738
|
+
}
|
|
1739
|
+
return node.default ? `${name} = ${node.default}` : name;
|
|
1740
|
+
},
|
|
1741
|
+
parameterGroup(node) {
|
|
1742
|
+
const { mode, transformName, transformType } = this.options;
|
|
1743
|
+
const sorted = sortChildParams(node.properties);
|
|
1744
|
+
const isOptional = node.optional ?? sorted.every((p) => p.optional || p.default !== void 0);
|
|
1745
|
+
if (node.inline) return sorted.map((p) => this.transform(p)).filter(Boolean).join(", ");
|
|
1746
|
+
if (mode === "keys" || mode === "values") return `{ ${sorted.map((p) => p.name).join(", ")} }`;
|
|
1747
|
+
if (mode === "call") return `{ ${sorted.map((p) => p.name).join(", ")} }`;
|
|
1748
|
+
const names = sorted.map((p) => {
|
|
1749
|
+
return transformName ? transformName(p.name) : p.name;
|
|
1750
|
+
});
|
|
1751
|
+
const nameStr = names.length ? `{ ${names.join(", ")} }` : void 0;
|
|
1752
|
+
if (!nameStr) return null;
|
|
1753
|
+
let typeAnnotation = node.type ? this.transform(node.type) ?? void 0 : void 0;
|
|
1754
|
+
if (!typeAnnotation) {
|
|
1755
|
+
const typeParts = sorted.filter((p) => p.type).map((p) => {
|
|
1756
|
+
const rawT = p.type ? this.transform(p.type) : void 0;
|
|
1757
|
+
const t = rawT != null && transformType ? transformType(rawT) : rawT;
|
|
1758
|
+
return p.optional || p.default !== void 0 ? `${p.name}?: ${t}` : `${p.name}: ${t}`;
|
|
1759
|
+
});
|
|
1760
|
+
typeAnnotation = typeParts.length ? `{ ${typeParts.join("; ")} }` : void 0;
|
|
1761
|
+
}
|
|
1762
|
+
if (typeAnnotation) {
|
|
1763
|
+
if (isOptional) return `${nameStr}: ${typeAnnotation} = ${node.default ?? "{}"}`;
|
|
1764
|
+
return node.default ? `${nameStr}: ${typeAnnotation} = ${node.default}` : `${nameStr}: ${typeAnnotation}`;
|
|
1765
|
+
}
|
|
1766
|
+
return node.default ? `${nameStr} = ${node.default}` : nameStr;
|
|
1767
|
+
},
|
|
1768
|
+
functionParameters(node) {
|
|
1769
|
+
return sortParams(node.params).map((p) => this.transform(p)).filter(Boolean).join(", ");
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
}));
|
|
1773
|
+
//#endregion
|
|
1774
|
+
export { Enum, Type, functionPrinter, pluginTs, pluginTsName, printerTs, resolverTs, resolverTsLegacy, typeGenerator };
|
|
1775
|
+
|
|
1776
|
+
//# sourceMappingURL=index.js.map
|