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