@kubb/plugin-ts 5.0.0-alpha.3 → 5.0.0-alpha.30

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.
Files changed (42) hide show
  1. package/dist/index.cjs +1806 -3
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.ts +590 -4
  4. package/dist/index.js +1776 -2
  5. package/dist/index.js.map +1 -0
  6. package/package.json +7 -27
  7. package/src/components/Enum.tsx +82 -0
  8. package/src/components/Type.tsx +29 -162
  9. package/src/constants.ts +39 -0
  10. package/src/factory.ts +134 -49
  11. package/src/generators/typeGenerator.tsx +165 -428
  12. package/src/generators/typeGeneratorLegacy.tsx +349 -0
  13. package/src/index.ts +9 -1
  14. package/src/plugin.ts +98 -176
  15. package/src/presets.ts +28 -0
  16. package/src/printers/functionPrinter.ts +196 -0
  17. package/src/printers/printerTs.ts +310 -0
  18. package/src/resolvers/resolverTs.ts +66 -0
  19. package/src/resolvers/resolverTsLegacy.ts +60 -0
  20. package/src/types.ts +258 -98
  21. package/src/utils.ts +131 -0
  22. package/dist/components-CRjwjdyE.js +0 -725
  23. package/dist/components-CRjwjdyE.js.map +0 -1
  24. package/dist/components-DI0aTIBg.cjs +0 -978
  25. package/dist/components-DI0aTIBg.cjs.map +0 -1
  26. package/dist/components.cjs +0 -3
  27. package/dist/components.d.ts +0 -38
  28. package/dist/components.js +0 -2
  29. package/dist/generators.cjs +0 -4
  30. package/dist/generators.d.ts +0 -503
  31. package/dist/generators.js +0 -2
  32. package/dist/plugin-D5rCK1zO.cjs +0 -992
  33. package/dist/plugin-D5rCK1zO.cjs.map +0 -1
  34. package/dist/plugin-DmwgRHK8.js +0 -944
  35. package/dist/plugin-DmwgRHK8.js.map +0 -1
  36. package/dist/types-BpeKGgCn.d.ts +0 -170
  37. package/src/components/index.ts +0 -1
  38. package/src/components/v2/Type.tsx +0 -165
  39. package/src/generators/index.ts +0 -2
  40. package/src/generators/v2/typeGenerator.tsx +0 -196
  41. package/src/parser.ts +0 -396
  42. package/src/printer.ts +0 -244
@@ -1,725 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { SchemaGenerator, createParser, isKeyword, schemaKeywords } from "@kubb/plugin-oas";
3
- import { safePrint } from "@kubb/fabric-core/parsers/typescript";
4
- import { File } from "@kubb/react-fabric";
5
- import ts from "typescript";
6
- import { isNumber } from "remeda";
7
- import { Fragment, jsx, jsxs } from "@kubb/react-fabric/jsx-runtime";
8
- //#region ../../internals/utils/src/casing.ts
9
- /**
10
- * Shared implementation for camelCase and PascalCase conversion.
11
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
12
- * and capitalizes each word according to `pascal`.
13
- *
14
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
15
- */
16
- function toCamelOrPascal(text, pascal) {
17
- 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) => {
18
- if (word.length > 1 && word === word.toUpperCase()) return word;
19
- if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
20
- return word.charAt(0).toUpperCase() + word.slice(1);
21
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
22
- }
23
- /**
24
- * Splits `text` on `.` and applies `transformPart` to each segment.
25
- * The last segment receives `isLast = true`, all earlier segments receive `false`.
26
- * Segments are joined with `/` to form a file path.
27
- */
28
- function applyToFileParts(text, transformPart) {
29
- const parts = text.split(".");
30
- return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
31
- }
32
- /**
33
- * Converts `text` to camelCase.
34
- * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
35
- *
36
- * @example
37
- * camelCase('hello-world') // 'helloWorld'
38
- * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
39
- */
40
- function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
41
- if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
42
- prefix,
43
- suffix
44
- } : {}));
45
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
46
- }
47
- /**
48
- * Converts `text` to PascalCase.
49
- * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
50
- *
51
- * @example
52
- * pascalCase('hello-world') // 'HelloWorld'
53
- * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
54
- */
55
- function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
56
- if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
57
- prefix,
58
- suffix
59
- }) : camelCase(part));
60
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
61
- }
62
- /**
63
- * Converts `text` to snake_case.
64
- *
65
- * @example
66
- * snakeCase('helloWorld') // 'hello_world'
67
- * snakeCase('Hello-World') // 'hello_world'
68
- */
69
- function snakeCase(text, { prefix = "", suffix = "" } = {}) {
70
- 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("_");
71
- }
72
- /**
73
- * Converts `text` to SCREAMING_SNAKE_CASE.
74
- *
75
- * @example
76
- * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'
77
- */
78
- function screamingSnakeCase(text, { prefix = "", suffix = "" } = {}) {
79
- return snakeCase(text, {
80
- prefix,
81
- suffix
82
- }).toUpperCase();
83
- }
84
- //#endregion
85
- //#region ../../internals/utils/src/string.ts
86
- /**
87
- * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
88
- * Returns the string unchanged when no balanced quote pair is found.
89
- *
90
- * @example
91
- * trimQuotes('"hello"') // 'hello'
92
- * trimQuotes('hello') // 'hello'
93
- */
94
- function trimQuotes(text) {
95
- if (text.length >= 2) {
96
- const first = text[0];
97
- const last = text[text.length - 1];
98
- if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
99
- }
100
- return text;
101
- }
102
- /**
103
- * Escapes characters that are not allowed inside JS string literals.
104
- * Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).
105
- *
106
- * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
107
- */
108
- function jsStringEscape(input) {
109
- return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
110
- switch (character) {
111
- case "\"":
112
- case "'":
113
- case "\\": return `\\${character}`;
114
- case "\n": return "\\n";
115
- case "\r": return "\\r";
116
- case "\u2028": return "\\u2028";
117
- case "\u2029": return "\\u2029";
118
- default: return "";
119
- }
120
- });
121
- }
122
- //#endregion
123
- //#region src/factory.ts
124
- const { SyntaxKind, factory } = ts;
125
- const modifiers = {
126
- async: factory.createModifier(ts.SyntaxKind.AsyncKeyword),
127
- export: factory.createModifier(ts.SyntaxKind.ExportKeyword),
128
- const: factory.createModifier(ts.SyntaxKind.ConstKeyword),
129
- static: factory.createModifier(ts.SyntaxKind.StaticKeyword)
130
- };
131
- const syntaxKind = {
132
- union: SyntaxKind.UnionType,
133
- literalType: SyntaxKind.LiteralType,
134
- stringLiteral: SyntaxKind.StringLiteral
135
- };
136
- function getUnknownType(unknownType) {
137
- if (unknownType === "any") return keywordTypeNodes.any;
138
- if (unknownType === "void") return keywordTypeNodes.void;
139
- return keywordTypeNodes.unknown;
140
- }
141
- function isValidIdentifier(str) {
142
- if (!str.length || str.trim() !== str) return false;
143
- const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
144
- return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
145
- }
146
- function propertyName(name) {
147
- if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
148
- return name;
149
- }
150
- const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
151
- function createQuestionToken(token) {
152
- if (!token) return;
153
- if (token === true) return questionToken;
154
- return token;
155
- }
156
- function createIntersectionDeclaration({ nodes, withParentheses }) {
157
- if (!nodes.length) return null;
158
- if (nodes.length === 1) return nodes[0] || null;
159
- const node = factory.createIntersectionTypeNode(nodes);
160
- if (withParentheses) return factory.createParenthesizedType(node);
161
- return node;
162
- }
163
- function createArrayDeclaration({ nodes, arrayType = "array" }) {
164
- if (!nodes.length) return factory.createTupleTypeNode([]);
165
- if (nodes.length === 1) {
166
- const node = nodes[0];
167
- if (!node) return null;
168
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
169
- return factory.createArrayTypeNode(node);
170
- }
171
- const unionType = factory.createUnionTypeNode(nodes);
172
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
173
- return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
174
- }
175
- /**
176
- * Minimum nodes length of 2
177
- * @example `string | number`
178
- */
179
- function createUnionDeclaration({ nodes, withParentheses }) {
180
- if (!nodes.length) return keywordTypeNodes.any;
181
- if (nodes.length === 1) return nodes[0];
182
- const node = factory.createUnionTypeNode(nodes);
183
- if (withParentheses) return factory.createParenthesizedType(node);
184
- return node;
185
- }
186
- function createPropertySignature({ readOnly, modifiers = [], name, questionToken, type }) {
187
- return factory.createPropertySignature([...modifiers, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken), type);
188
- }
189
- function createParameterSignature(name, { modifiers, dotDotDotToken, questionToken, type, initializer }) {
190
- return factory.createParameterDeclaration(modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer);
191
- }
192
- /**
193
- * @link https://github.com/microsoft/TypeScript/issues/44151
194
- */
195
- function appendJSDocToNode({ node, comments }) {
196
- const filteredComments = comments.filter(Boolean);
197
- if (!filteredComments.length) return node;
198
- const text = filteredComments.reduce((acc = "", comment = "") => {
199
- return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
200
- }, "*");
201
- return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
202
- }
203
- function createIndexSignature(type, { modifiers, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
204
- return factory.createIndexSignature(modifiers, [createParameterSignature(indexName, { type: indexType })], type);
205
- }
206
- function createTypeAliasDeclaration({ modifiers, name, typeParameters, type }) {
207
- return factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
208
- }
209
- function createInterfaceDeclaration({ modifiers, name, typeParameters, members }) {
210
- return factory.createInterfaceDeclaration(modifiers, name, typeParameters, void 0, members);
211
- }
212
- function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
213
- if (syntax === "interface" && "members" in type) return appendJSDocToNode({
214
- node: createInterfaceDeclaration({
215
- members: type.members,
216
- modifiers: isExportable ? [modifiers.export] : [],
217
- name,
218
- typeParameters: void 0
219
- }),
220
- comments
221
- });
222
- return appendJSDocToNode({
223
- node: createTypeAliasDeclaration({
224
- type,
225
- modifiers: isExportable ? [modifiers.export] : [],
226
- name,
227
- typeParameters: void 0
228
- }),
229
- comments
230
- });
231
- }
232
- /**
233
- * Apply casing transformation to enum keys
234
- */
235
- function applyEnumKeyCasing(key, casing = "none") {
236
- if (casing === "none") return key;
237
- if (casing === "screamingSnakeCase") return screamingSnakeCase(key);
238
- if (casing === "snakeCase") return snakeCase(key);
239
- if (casing === "pascalCase") return pascalCase(key);
240
- if (casing === "camelCase") return camelCase(key);
241
- return key;
242
- }
243
- function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
244
- 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]) => {
245
- if (isNumber(value)) {
246
- if (value < 0) return factory.createLiteralTypeNode(factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value))));
247
- return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
248
- }
249
- if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
250
- if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
251
- }).filter(Boolean)))];
252
- 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]) => {
253
- let initializer = factory.createStringLiteral(value?.toString());
254
- 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)));
255
- else initializer = factory.createNumericLiteral(value);
256
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
257
- if (isNumber(Number.parseInt(key.toString(), 10))) {
258
- const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
259
- return factory.createEnumMember(propertyName(casingKey), initializer);
260
- }
261
- if (key) {
262
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
263
- return factory.createEnumMember(propertyName(casingKey), initializer);
264
- }
265
- }).filter(Boolean))];
266
- const identifierName = name;
267
- if (enums.length === 0) return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword))];
268
- 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]) => {
269
- let initializer = factory.createStringLiteral(value?.toString());
270
- if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
271
- else initializer = factory.createNumericLiteral(value);
272
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
273
- if (key) {
274
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
275
- return factory.createPropertyAssignment(propertyName(casingKey), initializer);
276
- }
277
- }).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))))];
278
- }
279
- function createOmitDeclaration({ keys, type, nonNullable }) {
280
- const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
281
- if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
282
- return factory.createLiteralTypeNode(factory.createStringLiteral(key));
283
- }))]);
284
- return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
285
- }
286
- const keywordTypeNodes = {
287
- any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
288
- unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
289
- void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
290
- number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
291
- integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
292
- bigint: factory.createKeywordTypeNode(ts.SyntaxKind.BigIntKeyword),
293
- object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
294
- string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
295
- boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
296
- undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
297
- null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword)),
298
- never: factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
299
- };
300
- /**
301
- * Converts a path like '/pet/{petId}/uploadImage' to a template literal type
302
- * like `/pet/${string}/uploadImage`
303
- */
304
- function createUrlTemplateType(path) {
305
- if (!path.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(path));
306
- const segments = path.split(/(\{[^}]+\})/);
307
- const parts = [];
308
- const parameterIndices = [];
309
- segments.forEach((segment) => {
310
- if (segment.startsWith("{") && segment.endsWith("}")) {
311
- parameterIndices.push(parts.length);
312
- parts.push(segment);
313
- } else if (segment) parts.push(segment);
314
- });
315
- const head = ts.factory.createTemplateHead(parts[0] || "");
316
- const templateSpans = [];
317
- parameterIndices.forEach((paramIndex, i) => {
318
- const isLast = i === parameterIndices.length - 1;
319
- const nextPart = parts[paramIndex + 1] || "";
320
- const literal = isLast ? ts.factory.createTemplateTail(nextPart) : ts.factory.createTemplateMiddle(nextPart);
321
- templateSpans.push(ts.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
322
- });
323
- return ts.factory.createTemplateLiteralType(head, templateSpans);
324
- }
325
- const createTypeLiteralNode = factory.createTypeLiteralNode;
326
- const createTypeReferenceNode = factory.createTypeReferenceNode;
327
- const createNumericLiteral = factory.createNumericLiteral;
328
- const createStringLiteral = factory.createStringLiteral;
329
- const createArrayTypeNode = factory.createArrayTypeNode;
330
- factory.createParenthesizedType;
331
- const createLiteralTypeNode = factory.createLiteralTypeNode;
332
- factory.createNull;
333
- const createIdentifier = factory.createIdentifier;
334
- const createOptionalTypeNode = factory.createOptionalTypeNode;
335
- const createTupleTypeNode = factory.createTupleTypeNode;
336
- const createRestTypeNode = factory.createRestTypeNode;
337
- const createTrue = factory.createTrue;
338
- const createFalse = factory.createFalse;
339
- const createIndexedAccessTypeNode = factory.createIndexedAccessTypeNode;
340
- const createTypeOperatorNode = factory.createTypeOperatorNode;
341
- const createPrefixUnaryExpression = factory.createPrefixUnaryExpression;
342
- //#endregion
343
- //#region src/parser.ts
344
- const typeKeywordMapper = {
345
- any: () => keywordTypeNodes.any,
346
- unknown: () => keywordTypeNodes.unknown,
347
- void: () => keywordTypeNodes.void,
348
- number: () => keywordTypeNodes.number,
349
- integer: () => keywordTypeNodes.number,
350
- bigint: () => keywordTypeNodes.bigint,
351
- object: (nodes) => {
352
- if (!nodes || !nodes.length) return keywordTypeNodes.object;
353
- return createTypeLiteralNode(nodes);
354
- },
355
- string: () => keywordTypeNodes.string,
356
- boolean: () => keywordTypeNodes.boolean,
357
- undefined: () => keywordTypeNodes.undefined,
358
- nullable: void 0,
359
- null: () => keywordTypeNodes.null,
360
- nullish: void 0,
361
- array: (nodes, arrayType) => {
362
- if (!nodes) return;
363
- return createArrayDeclaration({
364
- nodes,
365
- arrayType
366
- });
367
- },
368
- tuple: (nodes, rest, min, max) => {
369
- if (!nodes) return;
370
- if (max) {
371
- nodes = nodes.slice(0, max);
372
- if (nodes.length < max && rest) nodes = [...nodes, ...Array(max - nodes.length).fill(rest)];
373
- }
374
- if (min) nodes = nodes.map((node, index) => index >= min ? createOptionalTypeNode(node) : node);
375
- if (typeof max === "undefined" && rest) nodes.push(createRestTypeNode(createArrayTypeNode(rest)));
376
- return createTupleTypeNode(nodes);
377
- },
378
- enum: (name) => {
379
- if (!name) return;
380
- return createTypeReferenceNode(name, void 0);
381
- },
382
- union: (nodes) => {
383
- if (!nodes) return;
384
- return createUnionDeclaration({
385
- withParentheses: true,
386
- nodes
387
- });
388
- },
389
- const: (name, format) => {
390
- if (name === null || name === void 0 || name === "") return;
391
- if (format === "boolean") {
392
- if (name === true) return createLiteralTypeNode(createTrue());
393
- return createLiteralTypeNode(createFalse());
394
- }
395
- if (format === "number" && typeof name === "number") return createLiteralTypeNode(createNumericLiteral(name));
396
- return createLiteralTypeNode(createStringLiteral(name.toString()));
397
- },
398
- datetime: () => keywordTypeNodes.string,
399
- date: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
400
- time: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
401
- uuid: () => keywordTypeNodes.string,
402
- url: () => keywordTypeNodes.string,
403
- default: void 0,
404
- and: (nodes) => {
405
- if (!nodes) return;
406
- return createIntersectionDeclaration({
407
- withParentheses: true,
408
- nodes
409
- });
410
- },
411
- describe: void 0,
412
- min: void 0,
413
- max: void 0,
414
- optional: void 0,
415
- matches: () => keywordTypeNodes.string,
416
- email: () => keywordTypeNodes.string,
417
- firstName: void 0,
418
- lastName: void 0,
419
- password: void 0,
420
- phone: void 0,
421
- readOnly: void 0,
422
- writeOnly: void 0,
423
- ref: (propertyName) => {
424
- if (!propertyName) return;
425
- return createTypeReferenceNode(propertyName, void 0);
426
- },
427
- blob: () => createTypeReferenceNode("Blob", []),
428
- deprecated: void 0,
429
- example: void 0,
430
- schema: void 0,
431
- catchall: void 0,
432
- name: void 0,
433
- interface: void 0,
434
- exclusiveMaximum: void 0,
435
- exclusiveMinimum: void 0
436
- };
437
- /**
438
- * Recursively parses a schema tree node into a corresponding TypeScript AST node.
439
- *
440
- * Maps OpenAPI schema keywords to TypeScript AST nodes using the `typeKeywordMapper`, handling complex types such as unions, intersections, arrays, tuples (with optional/rest elements and length constraints), enums, constants, references, and objects with property modifiers and documentation annotations.
441
- *
442
- * @param current - The schema node to parse.
443
- * @param siblings - Sibling schema nodes, used for context in certain mappings.
444
- * @param name - The name of the schema or property being parsed.
445
- * @param options - Parsing options controlling output style, property handling, and custom mappers.
446
- * @returns The generated TypeScript AST node, or `undefined` if the schema keyword is not mapped.
447
- */
448
- const parse = createParser({
449
- mapper: typeKeywordMapper,
450
- handlers: {
451
- union(tree, options) {
452
- const { current, schema, name } = tree;
453
- return typeKeywordMapper.union(current.args.map((it) => this.parse({
454
- schema,
455
- parent: current,
456
- name,
457
- current: it,
458
- siblings: []
459
- }, options)).filter(Boolean));
460
- },
461
- and(tree, options) {
462
- const { current, schema, name } = tree;
463
- return typeKeywordMapper.and(current.args.map((it) => this.parse({
464
- schema,
465
- parent: current,
466
- name,
467
- current: it,
468
- siblings: []
469
- }, options)).filter(Boolean));
470
- },
471
- array(tree, options) {
472
- const { current, schema, name } = tree;
473
- return typeKeywordMapper.array(current.args.items.map((it) => this.parse({
474
- schema,
475
- parent: current,
476
- name,
477
- current: it,
478
- siblings: []
479
- }, options)).filter(Boolean), options.arrayType);
480
- },
481
- enum(tree, options) {
482
- const { current } = tree;
483
- if (options.enumType === "inlineLiteral") {
484
- const enumValues = current.args.items.map((item) => item.value).filter((value) => value !== void 0 && value !== null).map((value) => {
485
- const format = typeof value === "number" ? "number" : typeof value === "boolean" ? "boolean" : "string";
486
- return typeKeywordMapper.const(value, format);
487
- }).filter(Boolean);
488
- return typeKeywordMapper.union(enumValues);
489
- }
490
- return typeKeywordMapper.enum(["asConst", "asPascalConst"].includes(options.enumType) ? `${current.args.typeName}Key` : current.args.typeName);
491
- },
492
- ref(tree, _options) {
493
- const { current } = tree;
494
- return typeKeywordMapper.ref(current.args.name);
495
- },
496
- blob() {
497
- return typeKeywordMapper.blob();
498
- },
499
- tuple(tree, options) {
500
- const { current, schema, name } = tree;
501
- return typeKeywordMapper.tuple(current.args.items.map((it) => this.parse({
502
- schema,
503
- parent: current,
504
- name,
505
- current: it,
506
- siblings: []
507
- }, options)).filter(Boolean), current.args.rest && (this.parse({
508
- schema,
509
- parent: current,
510
- name,
511
- current: current.args.rest,
512
- siblings: []
513
- }, options) ?? void 0), current.args.min, current.args.max);
514
- },
515
- const(tree, _options) {
516
- const { current } = tree;
517
- return typeKeywordMapper.const(current.args.name, current.args.format);
518
- },
519
- object(tree, options) {
520
- const { current, schema, name } = tree;
521
- const properties = Object.entries(current.args?.properties || {}).filter((item) => {
522
- const schemas = item[1];
523
- return schemas && typeof schemas.map === "function";
524
- }).map(([name, schemas]) => {
525
- const mappedName = schemas.find((schema) => schema.keyword === schemaKeywords.name)?.args || name;
526
- if (options.mapper && Object.hasOwn(options.mapper, mappedName)) return options.mapper[mappedName];
527
- const isNullish = schemas.some((schema) => schema.keyword === schemaKeywords.nullish);
528
- const isNullable = schemas.some((schema) => schema.keyword === schemaKeywords.nullable);
529
- const isOptional = schemas.some((schema) => schema.keyword === schemaKeywords.optional);
530
- const isReadonly = schemas.some((schema) => schema.keyword === schemaKeywords.readOnly);
531
- const describeSchema = schemas.find((schema) => schema.keyword === schemaKeywords.describe);
532
- const deprecatedSchema = schemas.find((schema) => schema.keyword === schemaKeywords.deprecated);
533
- const defaultSchema = schemas.find((schema) => schema.keyword === schemaKeywords.default);
534
- const exampleSchema = schemas.find((schema) => schema.keyword === schemaKeywords.example);
535
- const schemaSchema = schemas.find((schema) => schema.keyword === schemaKeywords.schema);
536
- const minSchema = schemas.find((schema) => schema.keyword === schemaKeywords.min);
537
- const maxSchema = schemas.find((schema) => schema.keyword === schemaKeywords.max);
538
- const matchesSchema = schemas.find((schema) => schema.keyword === schemaKeywords.matches);
539
- let type = schemas.map((it) => this.parse({
540
- schema,
541
- parent: current,
542
- name,
543
- current: it,
544
- siblings: schemas
545
- }, options)).filter(Boolean)[0];
546
- if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
547
- if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
548
- if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
549
- return appendJSDocToNode({
550
- node: createPropertySignature({
551
- questionToken: isOptional || isNullish ? ["questionToken", "questionTokenAndUndefined"].includes(options.optionalType) : false,
552
- name: mappedName,
553
- type,
554
- readOnly: isReadonly
555
- }),
556
- comments: [
557
- describeSchema ? `@description ${jsStringEscape(describeSchema.args)}` : void 0,
558
- deprecatedSchema ? "@deprecated" : void 0,
559
- minSchema ? `@minLength ${minSchema.args}` : void 0,
560
- maxSchema ? `@maxLength ${maxSchema.args}` : void 0,
561
- matchesSchema ? `@pattern ${matchesSchema.args}` : void 0,
562
- defaultSchema ? `@default ${defaultSchema.args}` : void 0,
563
- exampleSchema ? `@example ${exampleSchema.args}` : void 0,
564
- schemaSchema?.args?.type || schemaSchema?.args?.format ? [`@type ${schemaSchema?.args?.type || "unknown"}${!isOptional ? "" : " | undefined"}`, schemaSchema?.args?.format].filter(Boolean).join(", ") : void 0
565
- ].filter(Boolean)
566
- });
567
- });
568
- let additionalProperties;
569
- if (current.args?.additionalProperties?.length) {
570
- let additionalPropertiesType = current.args.additionalProperties.map((it) => this.parse({
571
- schema,
572
- parent: current,
573
- name,
574
- current: it,
575
- siblings: []
576
- }, options)).filter(Boolean).at(0);
577
- if (current.args?.additionalProperties.some((schema) => isKeyword(schema, schemaKeywords.nullable))) additionalPropertiesType = createUnionDeclaration({ nodes: [additionalPropertiesType, keywordTypeNodes.null] });
578
- additionalProperties = createIndexSignature(properties.length > 0 ? keywordTypeNodes.unknown : additionalPropertiesType);
579
- }
580
- let patternProperties;
581
- if (current.args?.patternProperties) {
582
- const allPatternSchemas = Object.values(current.args.patternProperties).flat();
583
- if (allPatternSchemas.length > 0) {
584
- patternProperties = allPatternSchemas.map((it) => this.parse({
585
- schema,
586
- parent: current,
587
- name,
588
- current: it,
589
- siblings: []
590
- }, options)).filter(Boolean).at(0);
591
- if (allPatternSchemas.some((schema) => isKeyword(schema, schemaKeywords.nullable))) patternProperties = createUnionDeclaration({ nodes: [patternProperties, keywordTypeNodes.null] });
592
- patternProperties = createIndexSignature(patternProperties);
593
- }
594
- }
595
- return typeKeywordMapper.object([
596
- ...properties,
597
- additionalProperties,
598
- patternProperties
599
- ].filter(Boolean));
600
- },
601
- datetime() {
602
- return typeKeywordMapper.datetime();
603
- },
604
- date(tree) {
605
- const { current } = tree;
606
- return typeKeywordMapper.date(current.args.type);
607
- },
608
- time(tree) {
609
- const { current } = tree;
610
- return typeKeywordMapper.time(current.args.type);
611
- }
612
- }
613
- });
614
- //#endregion
615
- //#region src/components/Type.tsx
616
- function Type({ name, typedName, tree, keysToOmit, schema, optionalType, arrayType, syntaxType, enumType, enumKeyCasing, mapper, description }) {
617
- const typeNodes = [];
618
- if (!tree.length) return "";
619
- const schemaFromTree = tree.find((item) => item.keyword === schemaKeywords.schema);
620
- const enumSchemas = SchemaGenerator.deepSearch(tree, schemaKeywords.enum);
621
- let type = tree.map((current, _index, siblings) => parse({
622
- name,
623
- schema,
624
- parent: void 0,
625
- current,
626
- siblings
627
- }, {
628
- optionalType,
629
- arrayType,
630
- enumType,
631
- mapper
632
- })).filter(Boolean).at(0) || typeKeywordMapper.undefined();
633
- if (["asConst", "asPascalConst"].includes(enumType) && enumSchemas.length > 0) {
634
- const isDirectEnum = schema.type === "array" && schema.items !== void 0;
635
- const isEnumOnly = "enum" in schema && schema.enum;
636
- if (isDirectEnum || isEnumOnly) {
637
- type = createTypeReferenceNode(`${enumSchemas[0].args.typeName}Key`);
638
- if (schema.type === "array") if (arrayType === "generic") type = createTypeReferenceNode(createIdentifier("Array"), [type]);
639
- else type = createArrayTypeNode(type);
640
- }
641
- }
642
- if (schemaFromTree && isKeyword(schemaFromTree, schemaKeywords.schema)) {
643
- const isNullish = tree.some((item) => item.keyword === schemaKeywords.nullish);
644
- const isNullable = tree.some((item) => item.keyword === schemaKeywords.nullable);
645
- const isOptional = tree.some((item) => item.keyword === schemaKeywords.optional);
646
- if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
647
- if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
648
- if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
649
- }
650
- const useTypeGeneration = syntaxType === "type" || [syntaxKind.union].includes(type.kind) || !!keysToOmit?.length;
651
- typeNodes.push(createTypeDeclaration({
652
- name,
653
- isExportable: true,
654
- type: keysToOmit?.length ? createOmitDeclaration({
655
- keys: keysToOmit,
656
- type,
657
- nonNullable: true
658
- }) : type,
659
- syntax: useTypeGeneration ? "type" : "interface",
660
- comments: [
661
- schema.title ? `${jsStringEscape(schema.title)}` : void 0,
662
- description ? `@description ${jsStringEscape(description)}` : void 0,
663
- schema.deprecated ? "@deprecated" : void 0,
664
- schema.minLength ? `@minLength ${schema.minLength}` : void 0,
665
- schema.maxLength ? `@maxLength ${schema.maxLength}` : void 0,
666
- schema.pattern ? `@pattern ${schema.pattern}` : void 0,
667
- schema.default ? `@default ${schema.default}` : void 0,
668
- schema.example ? `@example ${schema.example}` : void 0
669
- ]
670
- }));
671
- const enums = [...new Set(enumSchemas)].map((enumSchema) => {
672
- const name = enumType === "asPascalConst" ? pascalCase(enumSchema.args.name) : camelCase(enumSchema.args.name);
673
- const typeName = ["asConst", "asPascalConst"].includes(enumType) ? `${enumSchema.args.typeName}Key` : enumSchema.args.typeName;
674
- const [nameNode, typeNode] = createEnumDeclaration({
675
- name,
676
- typeName,
677
- enums: enumSchema.args.items.map((item) => item.value === void 0 ? void 0 : [trimQuotes(item.name?.toString()), item.value]).filter(Boolean),
678
- type: enumType,
679
- enumKeyCasing
680
- });
681
- return {
682
- nameNode,
683
- typeNode,
684
- name,
685
- typeName
686
- };
687
- });
688
- const shouldExportEnums = enumType !== "inlineLiteral";
689
- const shouldExportType = enumType === "inlineLiteral" || enums.every((item) => item.typeName !== name);
690
- return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ name, nameNode, typeName, typeNode }) => /* @__PURE__ */ jsxs(Fragment, { children: [nameNode && /* @__PURE__ */ jsx(File.Source, {
691
- name,
692
- isExportable: true,
693
- isIndexable: true,
694
- isTypeOnly: false,
695
- children: safePrint(nameNode)
696
- }), /* @__PURE__ */ jsx(File.Source, {
697
- name: typeName,
698
- isIndexable: true,
699
- isExportable: [
700
- "enum",
701
- "asConst",
702
- "asPascalConst",
703
- "constEnum",
704
- "literal",
705
- void 0
706
- ].includes(enumType),
707
- isTypeOnly: [
708
- "asConst",
709
- "asPascalConst",
710
- "literal",
711
- void 0
712
- ].includes(enumType),
713
- children: safePrint(typeNode)
714
- })] })), shouldExportType && /* @__PURE__ */ jsx(File.Source, {
715
- name: typedName,
716
- isTypeOnly: true,
717
- isExportable: true,
718
- isIndexable: true,
719
- children: safePrint(...typeNodes)
720
- })] });
721
- }
722
- //#endregion
723
- export { keywordTypeNodes as A, createTypeDeclaration as C, createUnionDeclaration as D, createTypeReferenceNode as E, camelCase as F, pascalCase as I, syntaxKind as M, jsStringEscape as N, createUrlTemplateType as O, trimQuotes as P, createTypeAliasDeclaration as S, createTypeOperatorNode as T, createPropertySignature as _, createArrayTypeNode as a, createTrue as b, createIdentifier as c, createIntersectionDeclaration as d, createLiteralTypeNode as f, createPrefixUnaryExpression as g, createOptionalTypeNode as h, createArrayDeclaration as i, modifiers as j, getUnknownType as k, createIndexSignature as l, createOmitDeclaration as m, SyntaxKind as n, createEnumDeclaration as o, createNumericLiteral as p, appendJSDocToNode as r, createFalse as s, Type as t, createIndexedAccessTypeNode as u, createRestTypeNode as v, createTypeLiteralNode as w, createTupleTypeNode as x, createStringLiteral as y };
724
-
725
- //# sourceMappingURL=components-CRjwjdyE.js.map