@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.
Files changed (66) hide show
  1. package/dist/index.cjs +1680 -49
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.ts +529 -4
  4. package/dist/index.js +1653 -52
  5. package/dist/index.js.map +1 -1
  6. package/package.json +3 -42
  7. package/src/components/Enum.tsx +2 -7
  8. package/src/components/Type.tsx +11 -5
  9. package/src/generators/typeGenerator.tsx +36 -24
  10. package/src/generators/typeGeneratorLegacy.tsx +28 -38
  11. package/src/index.ts +13 -1
  12. package/src/plugin.ts +42 -23
  13. package/src/presets.ts +16 -34
  14. package/src/printers/functionPrinter.ts +194 -0
  15. package/src/printers/printerTs.ts +23 -7
  16. package/src/resolvers/resolverTs.ts +10 -47
  17. package/src/resolvers/resolverTsLegacy.ts +4 -31
  18. package/src/types.ts +169 -254
  19. package/src/utils.ts +103 -0
  20. package/dist/Type-Bf8raoQX.cjs +0 -124
  21. package/dist/Type-Bf8raoQX.cjs.map +0 -1
  22. package/dist/Type-BpXxT4l_.js +0 -113
  23. package/dist/Type-BpXxT4l_.js.map +0 -1
  24. package/dist/builderTs-COUg3xtQ.cjs +0 -135
  25. package/dist/builderTs-COUg3xtQ.cjs.map +0 -1
  26. package/dist/builderTs-DPpkJKd1.js +0 -131
  27. package/dist/builderTs-DPpkJKd1.js.map +0 -1
  28. package/dist/builders.cjs +0 -3
  29. package/dist/builders.d.ts +0 -23
  30. package/dist/builders.js +0 -2
  31. package/dist/casing-BJHFg-zZ.js +0 -84
  32. package/dist/casing-BJHFg-zZ.js.map +0 -1
  33. package/dist/casing-DHfdqpLi.cjs +0 -107
  34. package/dist/casing-DHfdqpLi.cjs.map +0 -1
  35. package/dist/chunk-ByKO4r7w.cjs +0 -38
  36. package/dist/components.cjs +0 -4
  37. package/dist/components.d.ts +0 -71
  38. package/dist/components.js +0 -2
  39. package/dist/generators-DFDut8o-.js +0 -555
  40. package/dist/generators-DFDut8o-.js.map +0 -1
  41. package/dist/generators-DKd7MYbx.cjs +0 -567
  42. package/dist/generators-DKd7MYbx.cjs.map +0 -1
  43. package/dist/generators.cjs +0 -4
  44. package/dist/generators.d.ts +0 -12
  45. package/dist/generators.js +0 -2
  46. package/dist/printerTs-BcHudagv.cjs +0 -594
  47. package/dist/printerTs-BcHudagv.cjs.map +0 -1
  48. package/dist/printerTs-CMBCOuqd.js +0 -558
  49. package/dist/printerTs-CMBCOuqd.js.map +0 -1
  50. package/dist/printers.cjs +0 -3
  51. package/dist/printers.d.ts +0 -81
  52. package/dist/printers.js +0 -2
  53. package/dist/resolverTsLegacy-CPiqqsO6.js +0 -185
  54. package/dist/resolverTsLegacy-CPiqqsO6.js.map +0 -1
  55. package/dist/resolverTsLegacy-CuR9XbKk.cjs +0 -196
  56. package/dist/resolverTsLegacy-CuR9XbKk.cjs.map +0 -1
  57. package/dist/resolvers.cjs +0 -4
  58. package/dist/resolvers.d.ts +0 -52
  59. package/dist/resolvers.js +0 -2
  60. package/dist/types-CRtcZOCz.d.ts +0 -374
  61. package/src/builders/builderTs.ts +0 -107
  62. package/src/builders/index.ts +0 -1
  63. package/src/components/index.ts +0 -2
  64. package/src/generators/index.ts +0 -2
  65. package/src/printers/index.ts +0 -1
  66. package/src/resolvers/index.ts +0 -2
@@ -1,558 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { i as snakeCase, n as pascalCase, r as screamingSnakeCase, t as camelCase } from "./casing-BJHFg-zZ.js";
3
- import { isStringType, narrowSchema, schemaTypes } from "@kubb/ast";
4
- import { definePrinter } from "@kubb/core";
5
- import { safePrint } from "@kubb/fabric-core/parsers/typescript";
6
- import { isNumber } from "remeda";
7
- import ts from "typescript";
8
- //#region ../../internals/utils/src/string.ts
9
- /**
10
- * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
11
- * Returns the string unchanged when no balanced quote pair is found.
12
- *
13
- * @example
14
- * trimQuotes('"hello"') // 'hello'
15
- * trimQuotes('hello') // 'hello'
16
- */
17
- function trimQuotes(text) {
18
- if (text.length >= 2) {
19
- const first = text[0];
20
- const last = text[text.length - 1];
21
- if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
22
- }
23
- return text;
24
- }
25
- /**
26
- * Escapes characters that are not allowed inside JS string literals.
27
- * Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).
28
- *
29
- * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
30
- *
31
- * @example
32
- * ```ts
33
- * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
34
- * ```
35
- */
36
- function jsStringEscape(input) {
37
- return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
38
- switch (character) {
39
- case "\"":
40
- case "'":
41
- case "\\": return `\\${character}`;
42
- case "\n": return "\\n";
43
- case "\r": return "\\r";
44
- case "\u2028": return "\\u2028";
45
- case "\u2029": return "\\u2029";
46
- default: return "";
47
- }
48
- });
49
- }
50
- //#endregion
51
- //#region ../../internals/utils/src/object.ts
52
- /**
53
- * Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.
54
- *
55
- * @example
56
- * stringify('hello') // '"hello"'
57
- * stringify('"hello"') // '"hello"'
58
- */
59
- function stringify(value) {
60
- if (value === void 0 || value === null) return "\"\"";
61
- return JSON.stringify(trimQuotes(value.toString()));
62
- }
63
- //#endregion
64
- //#region src/constants.ts
65
- /**
66
- * `optionalType` values that cause a property's type to include `| undefined`.
67
- */
68
- const OPTIONAL_ADDS_UNDEFINED = new Set(["undefined", "questionTokenAndUndefined"]);
69
- /**
70
- * `optionalType` values that render the property key with a `?` token.
71
- */
72
- const OPTIONAL_ADDS_QUESTION_TOKEN = new Set(["questionToken", "questionTokenAndUndefined"]);
73
- /**
74
- * `enumType` values that append a `Key` suffix to the generated enum type alias.
75
- */
76
- const ENUM_TYPES_WITH_KEY_SUFFIX = new Set(["asConst", "asPascalConst"]);
77
- /**
78
- * `enumType` values that require a runtime value declaration (object, enum, or literal).
79
- */
80
- const ENUM_TYPES_WITH_RUNTIME_VALUE = new Set([
81
- "enum",
82
- "asConst",
83
- "asPascalConst",
84
- "constEnum",
85
- "literal",
86
- void 0
87
- ]);
88
- /**
89
- * `enumType` values whose type declaration is type-only (no runtime value emitted for the type alias).
90
- */
91
- const ENUM_TYPES_WITH_TYPE_ONLY = new Set([
92
- "asConst",
93
- "asPascalConst",
94
- "literal",
95
- void 0
96
- ]);
97
- //#endregion
98
- //#region src/factory.ts
99
- const { SyntaxKind, factory } = ts;
100
- const modifiers = {
101
- async: factory.createModifier(ts.SyntaxKind.AsyncKeyword),
102
- export: factory.createModifier(ts.SyntaxKind.ExportKeyword),
103
- const: factory.createModifier(ts.SyntaxKind.ConstKeyword),
104
- static: factory.createModifier(ts.SyntaxKind.StaticKeyword)
105
- };
106
- const syntaxKind = {
107
- union: SyntaxKind.UnionType,
108
- literalType: SyntaxKind.LiteralType,
109
- stringLiteral: SyntaxKind.StringLiteral
110
- };
111
- function isValidIdentifier(str) {
112
- if (!str.length || str.trim() !== str) return false;
113
- const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
114
- return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
115
- }
116
- function propertyName(name) {
117
- if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
118
- return name;
119
- }
120
- const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
121
- function createQuestionToken(token) {
122
- if (!token) return;
123
- if (token === true) return questionToken;
124
- return token;
125
- }
126
- function createIntersectionDeclaration({ nodes, withParentheses }) {
127
- if (!nodes.length) return null;
128
- if (nodes.length === 1) return nodes[0] || null;
129
- const node = factory.createIntersectionTypeNode(nodes);
130
- if (withParentheses) return factory.createParenthesizedType(node);
131
- return node;
132
- }
133
- function createArrayDeclaration({ nodes, arrayType = "array" }) {
134
- if (!nodes.length) return factory.createTupleTypeNode([]);
135
- if (nodes.length === 1) {
136
- const node = nodes[0];
137
- if (!node) return null;
138
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
139
- return factory.createArrayTypeNode(node);
140
- }
141
- const unionType = factory.createUnionTypeNode(nodes);
142
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
143
- return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
144
- }
145
- /**
146
- * Minimum nodes length of 2
147
- * @example `string | number`
148
- */
149
- function createUnionDeclaration({ nodes, withParentheses }) {
150
- if (!nodes.length) return keywordTypeNodes.any;
151
- if (nodes.length === 1) return nodes[0];
152
- const node = factory.createUnionTypeNode(nodes);
153
- if (withParentheses) return factory.createParenthesizedType(node);
154
- return node;
155
- }
156
- function createPropertySignature({ readOnly, modifiers = [], name, questionToken, type }) {
157
- return factory.createPropertySignature([...modifiers, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken), type);
158
- }
159
- function createParameterSignature(name, { modifiers, dotDotDotToken, questionToken, type, initializer }) {
160
- return factory.createParameterDeclaration(modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer);
161
- }
162
- /**
163
- * @link https://github.com/microsoft/TypeScript/issues/44151
164
- */
165
- function appendJSDocToNode({ node, comments }) {
166
- const filteredComments = comments.filter(Boolean);
167
- if (!filteredComments.length) return node;
168
- const text = filteredComments.reduce((acc = "", comment = "") => {
169
- return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
170
- }, "*");
171
- return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
172
- }
173
- function createIndexSignature(type, { modifiers, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
174
- return factory.createIndexSignature(modifiers, [createParameterSignature(indexName, { type: indexType })], type);
175
- }
176
- function createTypeAliasDeclaration({ modifiers, name, typeParameters, type }) {
177
- return factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
178
- }
179
- function createInterfaceDeclaration({ modifiers, name, typeParameters, members }) {
180
- return factory.createInterfaceDeclaration(modifiers, name, typeParameters, void 0, members);
181
- }
182
- function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
183
- if (syntax === "interface" && "members" in type) return appendJSDocToNode({
184
- node: createInterfaceDeclaration({
185
- members: type.members,
186
- modifiers: isExportable ? [modifiers.export] : [],
187
- name,
188
- typeParameters: void 0
189
- }),
190
- comments
191
- });
192
- return appendJSDocToNode({
193
- node: createTypeAliasDeclaration({
194
- type,
195
- modifiers: isExportable ? [modifiers.export] : [],
196
- name,
197
- typeParameters: void 0
198
- }),
199
- comments
200
- });
201
- }
202
- /**
203
- * Apply casing transformation to enum keys
204
- */
205
- function applyEnumKeyCasing(key, casing = "none") {
206
- if (casing === "none") return key;
207
- if (casing === "screamingSnakeCase") return screamingSnakeCase(key);
208
- if (casing === "snakeCase") return snakeCase(key);
209
- if (casing === "pascalCase") return pascalCase(key);
210
- if (casing === "camelCase") return camelCase(key);
211
- return key;
212
- }
213
- function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
214
- 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]) => {
215
- if (isNumber(value)) {
216
- if (value < 0) return factory.createLiteralTypeNode(factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value))));
217
- return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
218
- }
219
- if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
220
- if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
221
- }).filter(Boolean)))];
222
- 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]) => {
223
- let initializer = factory.createStringLiteral(value?.toString());
224
- 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)));
225
- else initializer = factory.createNumericLiteral(value);
226
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
227
- if (isNumber(Number.parseInt(key.toString(), 10))) {
228
- const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
229
- return factory.createEnumMember(propertyName(casingKey), initializer);
230
- }
231
- if (key) {
232
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
233
- return factory.createEnumMember(propertyName(casingKey), initializer);
234
- }
235
- }).filter(Boolean))];
236
- const identifierName = name;
237
- if (enums.length === 0) return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword))];
238
- 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]) => {
239
- let initializer = factory.createStringLiteral(value?.toString());
240
- if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
241
- else initializer = factory.createNumericLiteral(value);
242
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
243
- if (key) {
244
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
245
- return factory.createPropertyAssignment(propertyName(casingKey), initializer);
246
- }
247
- }).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))))];
248
- }
249
- function createOmitDeclaration({ keys, type, nonNullable }) {
250
- const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
251
- if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
252
- return factory.createLiteralTypeNode(factory.createStringLiteral(key));
253
- }))]);
254
- return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
255
- }
256
- const keywordTypeNodes = {
257
- any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
258
- unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
259
- void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
260
- number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
261
- integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
262
- bigint: factory.createKeywordTypeNode(ts.SyntaxKind.BigIntKeyword),
263
- object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
264
- string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
265
- boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
266
- undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
267
- null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword)),
268
- never: factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
269
- };
270
- /**
271
- * Converts a path like '/pet/{petId}/uploadImage' to a template literal type
272
- * like `/pet/${string}/uploadImage`
273
- */
274
- /**
275
- * Converts an OAS-style path (e.g. `/pets/{petId}`) or an Express-style path
276
- * (e.g. `/pets/:petId`) to a TypeScript template literal type
277
- * like `` `/pets/${string}` ``.
278
- */
279
- function createUrlTemplateType(path) {
280
- const normalized = path.replace(/:([^/]+)/g, "{$1}");
281
- if (!normalized.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(normalized));
282
- const segments = normalized.split(/(\{[^}]+\})/);
283
- const parts = [];
284
- const parameterIndices = [];
285
- segments.forEach((segment) => {
286
- if (segment.startsWith("{") && segment.endsWith("}")) {
287
- parameterIndices.push(parts.length);
288
- parts.push(segment);
289
- } else if (segment) parts.push(segment);
290
- });
291
- const head = ts.factory.createTemplateHead(parts[0] || "");
292
- const templateSpans = [];
293
- parameterIndices.forEach((paramIndex, i) => {
294
- const isLast = i === parameterIndices.length - 1;
295
- const nextPart = parts[paramIndex + 1] || "";
296
- const literal = isLast ? ts.factory.createTemplateTail(nextPart) : ts.factory.createTemplateMiddle(nextPart);
297
- templateSpans.push(ts.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
298
- });
299
- return ts.factory.createTemplateLiteralType(head, templateSpans);
300
- }
301
- const createTypeLiteralNode = factory.createTypeLiteralNode;
302
- const createTypeReferenceNode = factory.createTypeReferenceNode;
303
- const createNumericLiteral = factory.createNumericLiteral;
304
- const createStringLiteral = factory.createStringLiteral;
305
- const createArrayTypeNode = factory.createArrayTypeNode;
306
- factory.createParenthesizedType;
307
- const createLiteralTypeNode = factory.createLiteralTypeNode;
308
- factory.createNull;
309
- const createIdentifier = factory.createIdentifier;
310
- const createOptionalTypeNode = factory.createOptionalTypeNode;
311
- const createTupleTypeNode = factory.createTupleTypeNode;
312
- const createRestTypeNode = factory.createRestTypeNode;
313
- const createTrue = factory.createTrue;
314
- const createFalse = factory.createFalse;
315
- factory.createIndexedAccessTypeNode;
316
- factory.createTypeOperatorNode;
317
- const createPrefixUnaryExpression = factory.createPrefixUnaryExpression;
318
- //#endregion
319
- //#region src/printers/printerTs.ts
320
- /**
321
- * Converts a primitive const value to a TypeScript literal type node.
322
- * Handles negative numbers via a prefix unary expression.
323
- */
324
- function constToTypeNode(value, format) {
325
- if (format === "boolean") return createLiteralTypeNode(value === true ? createTrue() : createFalse());
326
- if (format === "number" && typeof value === "number") {
327
- if (value < 0) return createLiteralTypeNode(createPrefixUnaryExpression(SyntaxKind.MinusToken, createNumericLiteral(Math.abs(value))));
328
- return createLiteralTypeNode(createNumericLiteral(value));
329
- }
330
- return createLiteralTypeNode(createStringLiteral(String(value)));
331
- }
332
- /**
333
- * Returns a `Date` reference type node when `representation` is `'date'`, otherwise falls back to `string`.
334
- */
335
- function dateOrStringNode(node) {
336
- return node.representation === "date" ? createTypeReferenceNode(createIdentifier("Date")) : keywordTypeNodes.string;
337
- }
338
- /**
339
- * Maps an array of `SchemaNode`s through the printer, filtering out `null` and `undefined` results.
340
- */
341
- function buildMemberNodes(members, print) {
342
- return (members ?? []).map(print).filter(Boolean);
343
- }
344
- /**
345
- * Builds a TypeScript tuple type node from an array schema's `items`,
346
- * applying min/max slice and optional/rest element rules.
347
- */
348
- function buildTupleNode(node, print) {
349
- let items = (node.items ?? []).map(print).filter(Boolean);
350
- const restNode = node.rest ? print(node.rest) ?? void 0 : void 0;
351
- const { min, max } = node;
352
- if (max !== void 0) {
353
- items = items.slice(0, max);
354
- if (items.length < max && restNode) items = [...items, ...Array(max - items.length).fill(restNode)];
355
- }
356
- if (min !== void 0) items = items.map((item, i) => i >= min ? createOptionalTypeNode(item) : item);
357
- if (max === void 0 && restNode) items.push(createRestTypeNode(createArrayTypeNode(restNode)));
358
- return createTupleTypeNode(items);
359
- }
360
- /**
361
- * Applies `nullable` and optional/nullish `| undefined` union modifiers to a property's resolved base type.
362
- */
363
- function buildPropertyType(schema, baseType, optionalType) {
364
- const addsUndefined = OPTIONAL_ADDS_UNDEFINED.has(optionalType);
365
- let type = baseType;
366
- if (schema.nullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
367
- if ((schema.nullish || schema.optional) && addsUndefined) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
368
- return type;
369
- }
370
- /**
371
- * Collects JSDoc annotation strings (description, deprecated, min/max, pattern, default, example, type) for a schema node.
372
- */
373
- function buildPropertyJSDocComments(schema) {
374
- const isArray = schema.type === "array";
375
- return [
376
- "description" in schema && schema.description ? `@description ${jsStringEscape(schema.description)}` : void 0,
377
- "deprecated" in schema && schema.deprecated ? "@deprecated" : void 0,
378
- !isArray && "min" in schema && schema.min !== void 0 ? `@minLength ${schema.min}` : void 0,
379
- !isArray && "max" in schema && schema.max !== void 0 ? `@maxLength ${schema.max}` : void 0,
380
- "pattern" in schema && schema.pattern ? `@pattern ${schema.pattern}` : void 0,
381
- "default" in schema && schema.default !== void 0 ? `@default ${"primitive" in schema && schema.primitive === "string" ? stringify(schema.default) : schema.default}` : void 0,
382
- "example" in schema && schema.example !== void 0 ? `@example ${schema.example}` : void 0,
383
- "primitive" in schema && schema.primitive ? [`@type ${schema.primitive || "unknown"}`, "optional" in schema && schema.optional ? " | undefined" : void 0].filter(Boolean).join("") : void 0
384
- ];
385
- }
386
- /**
387
- * Creates TypeScript index signatures for `additionalProperties` and `patternProperties` on an object schema node.
388
- */
389
- function buildIndexSignatures(node, propertyCount, print) {
390
- const elements = [];
391
- if (node.additionalProperties && node.additionalProperties !== true) {
392
- const additionalType = print(node.additionalProperties) ?? keywordTypeNodes.unknown;
393
- elements.push(createIndexSignature(propertyCount > 0 ? keywordTypeNodes.unknown : additionalType));
394
- } else if (node.additionalProperties === true) elements.push(createIndexSignature(keywordTypeNodes.unknown));
395
- if (node.patternProperties) {
396
- const first = Object.values(node.patternProperties)[0];
397
- if (first) {
398
- let patternType = print(first) ?? keywordTypeNodes.unknown;
399
- if (first.nullable) patternType = createUnionDeclaration({ nodes: [patternType, keywordTypeNodes.null] });
400
- elements.push(createIndexSignature(patternType));
401
- }
402
- }
403
- return elements;
404
- }
405
- /**
406
- * TypeScript type printer built with `definePrinter`.
407
- *
408
- * Converts a `SchemaNode` AST node into a TypeScript AST node:
409
- * - **`printer.print(node)`** — when `options.typeName` is set, returns a full
410
- * `type Name = …` or `interface Name { … }` declaration (`ts.Node`).
411
- * Without `typeName`, returns the raw `ts.TypeNode` for the schema.
412
- *
413
- * Dispatches on `node.type` to the appropriate handler in `nodes`. Options are closed
414
- * over per printer instance, so each call to `printerTs(options)` produces an independent printer.
415
- *
416
- * @example Raw type node (no `typeName`)
417
- * ```ts
418
- * const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enumType: 'inlineLiteral' })
419
- * const typeNode = printer.print(schemaNode) // ts.TypeNode
420
- * ```
421
- *
422
- * @example Full declaration (with `typeName`)
423
- * ```ts
424
- * const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enumType: 'inlineLiteral', typeName: 'MyType' })
425
- * const declaration = printer.print(schemaNode) // ts.TypeAliasDeclaration | ts.InterfaceDeclaration
426
- * ```
427
- */
428
- const printerTs = definePrinter((options) => {
429
- const addsUndefined = OPTIONAL_ADDS_UNDEFINED.has(options.optionalType);
430
- return {
431
- name: "typescript",
432
- options,
433
- nodes: {
434
- any: () => keywordTypeNodes.any,
435
- unknown: () => keywordTypeNodes.unknown,
436
- void: () => keywordTypeNodes.void,
437
- never: () => keywordTypeNodes.never,
438
- boolean: () => keywordTypeNodes.boolean,
439
- null: () => keywordTypeNodes.null,
440
- blob: () => createTypeReferenceNode("Blob", []),
441
- string: () => keywordTypeNodes.string,
442
- uuid: () => keywordTypeNodes.string,
443
- email: () => keywordTypeNodes.string,
444
- url: (node) => {
445
- if (node.path) return createUrlTemplateType(node.path);
446
- return keywordTypeNodes.string;
447
- },
448
- datetime: () => keywordTypeNodes.string,
449
- number: () => keywordTypeNodes.number,
450
- integer: () => keywordTypeNodes.number,
451
- bigint: () => keywordTypeNodes.bigint,
452
- date: dateOrStringNode,
453
- time: dateOrStringNode,
454
- ref(node) {
455
- if (!node.name) return;
456
- const refName = node.ref ? node.ref.split("/").at(-1) ?? node.name : node.name;
457
- return createTypeReferenceNode(node.ref ? this.options.resolver.default(refName, "type") : refName, void 0);
458
- },
459
- enum(node) {
460
- const values = node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? [];
461
- if (this.options.enumType === "inlineLiteral" || !node.name) return createUnionDeclaration({
462
- withParentheses: true,
463
- nodes: values.filter((v) => v !== null).map((value) => constToTypeNode(value, typeof value)).filter(Boolean)
464
- }) ?? void 0;
465
- return createTypeReferenceNode(ENUM_TYPES_WITH_KEY_SUFFIX.has(this.options.enumType) && this.options.enumTypeSuffix ? this.options.resolver.resolveEnumKeyTypedName(node, this.options.enumTypeSuffix) : this.options.resolver.default(node.name, "type"), void 0);
466
- },
467
- union(node) {
468
- const members = node.members ?? [];
469
- const hasStringLiteral = members.some((m) => {
470
- return narrowSchema(m, schemaTypes.enum)?.primitive === "string";
471
- });
472
- const hasPlainString = members.some((m) => isStringType(m));
473
- if (hasStringLiteral && hasPlainString) return createUnionDeclaration({
474
- withParentheses: true,
475
- nodes: members.map((m) => {
476
- if (isStringType(m)) return createIntersectionDeclaration({
477
- nodes: [keywordTypeNodes.string, createTypeLiteralNode([])],
478
- withParentheses: true
479
- });
480
- return this.transform(m);
481
- }).filter(Boolean)
482
- }) ?? void 0;
483
- return createUnionDeclaration({
484
- withParentheses: true,
485
- nodes: buildMemberNodes(members, this.transform)
486
- }) ?? void 0;
487
- },
488
- intersection(node) {
489
- return createIntersectionDeclaration({
490
- withParentheses: true,
491
- nodes: buildMemberNodes(node.members, this.transform)
492
- }) ?? void 0;
493
- },
494
- array(node) {
495
- return createArrayDeclaration({
496
- nodes: (node.items ?? []).map((item) => this.transform(item)).filter(Boolean),
497
- arrayType: this.options.arrayType
498
- }) ?? void 0;
499
- },
500
- tuple(node) {
501
- return buildTupleNode(node, this.transform);
502
- },
503
- object(node) {
504
- const { transform, options } = this;
505
- const addsQuestionToken = OPTIONAL_ADDS_QUESTION_TOKEN.has(options.optionalType);
506
- const propertyNodes = node.properties.map((prop) => {
507
- const baseType = transform(prop.schema) ?? keywordTypeNodes.unknown;
508
- const type = buildPropertyType(prop.schema, baseType, options.optionalType);
509
- return appendJSDocToNode({
510
- node: createPropertySignature({
511
- questionToken: prop.schema.optional || prop.schema.nullish ? addsQuestionToken : false,
512
- name: prop.name,
513
- type,
514
- readOnly: prop.schema.readOnly
515
- }),
516
- comments: buildPropertyJSDocComments(prop.schema)
517
- });
518
- });
519
- const allElements = [...propertyNodes, ...buildIndexSignatures(node, propertyNodes.length, transform)];
520
- if (!allElements.length) return keywordTypeNodes.object;
521
- return createTypeLiteralNode(allElements);
522
- }
523
- },
524
- print(node) {
525
- let type = this.transform(node);
526
- if (!type) return null;
527
- if (node.nullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
528
- if ((node.nullish || node.optional) && addsUndefined) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
529
- const { typeName, syntaxType = "type", description, keysToOmit } = this.options;
530
- if (!typeName) return safePrint(type);
531
- const useTypeGeneration = syntaxType === "type" || type.kind === syntaxKind.union || !!keysToOmit?.length;
532
- return safePrint(createTypeDeclaration({
533
- name: typeName,
534
- isExportable: true,
535
- type: keysToOmit?.length ? createOmitDeclaration({
536
- keys: keysToOmit,
537
- type,
538
- nonNullable: true
539
- }) : type,
540
- syntax: useTypeGeneration ? "type" : "interface",
541
- comments: [
542
- node?.title ? jsStringEscape(node.title) : void 0,
543
- description ? `@description ${jsStringEscape(description)}` : void 0,
544
- node?.deprecated ? "@deprecated" : void 0,
545
- node && "min" in node && node.min !== void 0 ? `@minLength ${node.min}` : void 0,
546
- node && "max" in node && node.max !== void 0 ? `@maxLength ${node.max}` : void 0,
547
- node && "pattern" in node && node.pattern ? `@pattern ${node.pattern}` : void 0,
548
- node?.default ? `@default ${node.default}` : void 0,
549
- node?.example ? `@example ${node.example}` : void 0
550
- ]
551
- }));
552
- }
553
- };
554
- });
555
- //#endregion
556
- export { ENUM_TYPES_WITH_TYPE_ONLY as a, ENUM_TYPES_WITH_RUNTIME_VALUE as i, createEnumDeclaration as n, trimQuotes as o, ENUM_TYPES_WITH_KEY_SUFFIX as r, printerTs as t };
557
-
558
- //# sourceMappingURL=printerTs-CMBCOuqd.js.map