@kubb/plugin-ts
Version:
TypeScript code generation plugin for Kubb, transforming OpenAPI schemas into TypeScript interfaces, types, and utility functions.
601 lines (597 loc) • 28 kB
JavaScript
import transformers from "@kubb/core/transformers";
import { SchemaGenerator, createParser, isKeyword, schemaKeywords } from "@kubb/plugin-oas";
import { safePrint } from "@kubb/fabric-core/parsers/typescript";
import { File } from "@kubb/react-fabric";
import ts from "typescript";
import "natural-orderby";
import { isNumber } from "remeda";
import { Fragment, jsx, jsxs } from "@kubb/react-fabric/jsx-runtime";
//#region src/factory.ts
const { SyntaxKind, factory } = ts;
const modifiers = {
async: factory.createModifier(ts.SyntaxKind.AsyncKeyword),
export: factory.createModifier(ts.SyntaxKind.ExportKeyword),
const: factory.createModifier(ts.SyntaxKind.ConstKeyword),
static: factory.createModifier(ts.SyntaxKind.StaticKeyword)
};
const syntaxKind = { union: SyntaxKind.UnionType };
function getUnknownType(unknownType) {
if (unknownType === "any") return keywordTypeNodes.any;
if (unknownType === "void") return keywordTypeNodes.void;
return keywordTypeNodes.unknown;
}
function isValidIdentifier(str) {
if (!str.length || str.trim() !== str) return false;
const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
}
function propertyName(name) {
if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
return name;
}
const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
function createQuestionToken(token) {
if (!token) return;
if (token === true) return questionToken;
return token;
}
function createIntersectionDeclaration({ nodes, withParentheses }) {
if (!nodes.length) return null;
if (nodes.length === 1) return nodes[0] || null;
const node = factory.createIntersectionTypeNode(nodes);
if (withParentheses) return factory.createParenthesizedType(node);
return node;
}
function createArrayDeclaration({ nodes, arrayType = "array" }) {
if (!nodes.length) return factory.createTupleTypeNode([]);
if (nodes.length === 1) {
const node = nodes[0];
if (!node) return null;
if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
return factory.createArrayTypeNode(node);
}
const unionType = factory.createUnionTypeNode(nodes);
if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
}
/**
* Minimum nodes length of 2
* @example `string | number`
*/
function createUnionDeclaration({ nodes, withParentheses }) {
if (!nodes.length) return keywordTypeNodes.any;
if (nodes.length === 1) return nodes[0];
const node = factory.createUnionTypeNode(nodes);
if (withParentheses) return factory.createParenthesizedType(node);
return node;
}
function createPropertySignature({ readOnly, modifiers: modifiers$1 = [], name, questionToken: questionToken$1, type }) {
return factory.createPropertySignature([...modifiers$1, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken$1), type);
}
function createParameterSignature(name, { modifiers: modifiers$1, dotDotDotToken, questionToken: questionToken$1, type, initializer }) {
return factory.createParameterDeclaration(modifiers$1, dotDotDotToken, name, createQuestionToken(questionToken$1), type, initializer);
}
/**
* @link https://github.com/microsoft/TypeScript/issues/44151
*/
function appendJSDocToNode({ node, comments }) {
const filteredComments = comments.filter(Boolean);
if (!filteredComments.length) return node;
const text = filteredComments.reduce((acc = "", comment = "") => {
return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
}, "*");
return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
}
function createIndexSignature(type, { modifiers: modifiers$1, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
return factory.createIndexSignature(modifiers$1, [createParameterSignature(indexName, { type: indexType })], type);
}
function createTypeAliasDeclaration({ modifiers: modifiers$1, name, typeParameters, type }) {
return factory.createTypeAliasDeclaration(modifiers$1, name, typeParameters, type);
}
function createInterfaceDeclaration({ modifiers: modifiers$1, name, typeParameters, members }) {
return factory.createInterfaceDeclaration(modifiers$1, name, typeParameters, void 0, members);
}
function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
if (syntax === "interface" && "members" in type) return appendJSDocToNode({
node: createInterfaceDeclaration({
members: type.members,
modifiers: isExportable ? [modifiers.export] : [],
name,
typeParameters: void 0
}),
comments
});
return appendJSDocToNode({
node: createTypeAliasDeclaration({
type,
modifiers: isExportable ? [modifiers.export] : [],
name,
typeParameters: void 0
}),
comments
});
}
/**
* Apply casing transformation to enum keys
*/
function applyEnumKeyCasing(key, casing = "none") {
if (casing === "none") return key;
if (casing === "screamingSnakeCase") return transformers.screamingSnakeCase(key);
if (casing === "snakeCase") return transformers.snakeCase(key);
if (casing === "pascalCase") return transformers.pascalCase(key);
if (casing === "camelCase") return transformers.camelCase(key);
return key;
}
function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
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]) => {
if (isNumber(value)) return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
}).filter(Boolean)))];
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]) => {
let initializer = factory.createStringLiteral(value?.toString());
if (Number.parseInt(value.toString(), 10) === value && isNumber(Number.parseInt(value.toString(), 10))) initializer = factory.createNumericLiteral(value);
if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
if (isNumber(Number.parseInt(key.toString(), 10))) {
const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
return factory.createEnumMember(propertyName(casingKey), initializer);
}
if (key) {
const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
return factory.createEnumMember(propertyName(casingKey), initializer);
}
}).filter(Boolean))];
const identifierName = type === "asPascalConst" ? typeName : name;
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]) => {
let initializer = factory.createStringLiteral(value?.toString());
if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
else initializer = factory.createNumericLiteral(value);
if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
if (key) {
const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
return factory.createPropertyAssignment(propertyName(casingKey), initializer);
}
}).filter(Boolean), true), factory.createTypeReferenceNode(factory.createIdentifier("const"), void 0)))], ts.NodeFlags.Const)), factory.createTypeAliasDeclaration(type === "asPascalConst" ? [] : [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))))];
}
function createOmitDeclaration({ keys, type, nonNullable }) {
const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
return factory.createLiteralTypeNode(factory.createStringLiteral(key));
}))]);
return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
}
const keywordTypeNodes = {
any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword)),
never: factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
};
/**
* Converts a path like '/pet/{petId}/uploadImage' to a template literal type
* like `/pet/${string}/uploadImage`
*/
function createUrlTemplateType(path) {
if (!path.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(path));
const segments = path.split(/(\{[^}]+\})/);
const parts = [];
const parameterIndices = [];
segments.forEach((segment) => {
if (segment.startsWith("{") && segment.endsWith("}")) {
parameterIndices.push(parts.length);
parts.push(segment);
} else if (segment) parts.push(segment);
});
const head = ts.factory.createTemplateHead(parts[0] || "");
const templateSpans = [];
parameterIndices.forEach((paramIndex, i) => {
const isLast = i === parameterIndices.length - 1;
const nextPart = parts[paramIndex + 1] || "";
const literal = isLast ? ts.factory.createTemplateTail(nextPart) : ts.factory.createTemplateMiddle(nextPart);
templateSpans.push(ts.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
});
return ts.factory.createTemplateLiteralType(head, templateSpans);
}
const createTypeLiteralNode = factory.createTypeLiteralNode;
const createTypeReferenceNode = factory.createTypeReferenceNode;
const createNumericLiteral = factory.createNumericLiteral;
const createStringLiteral = factory.createStringLiteral;
const createArrayTypeNode = factory.createArrayTypeNode;
const createParenthesizedType = factory.createParenthesizedType;
const createLiteralTypeNode = factory.createLiteralTypeNode;
const createNull = factory.createNull;
const createIdentifier = factory.createIdentifier;
const createOptionalTypeNode = factory.createOptionalTypeNode;
const createTupleTypeNode = factory.createTupleTypeNode;
const createRestTypeNode = factory.createRestTypeNode;
const createTrue = factory.createTrue;
const createFalse = factory.createFalse;
const createIndexedAccessTypeNode = factory.createIndexedAccessTypeNode;
const createTypeOperatorNode = factory.createTypeOperatorNode;
//#endregion
//#region src/parser.ts
const typeKeywordMapper = {
any: () => keywordTypeNodes.any,
unknown: () => keywordTypeNodes.unknown,
void: () => keywordTypeNodes.void,
number: () => keywordTypeNodes.number,
integer: () => keywordTypeNodes.number,
object: (nodes) => {
if (!nodes || !nodes.length) return keywordTypeNodes.object;
return createTypeLiteralNode(nodes);
},
string: () => keywordTypeNodes.string,
boolean: () => keywordTypeNodes.boolean,
undefined: () => keywordTypeNodes.undefined,
nullable: void 0,
null: () => keywordTypeNodes.null,
nullish: void 0,
array: (nodes, arrayType) => {
if (!nodes) return;
return createArrayDeclaration({
nodes,
arrayType
});
},
tuple: (nodes, rest, min, max) => {
if (!nodes) return;
if (max) {
nodes = nodes.slice(0, max);
if (nodes.length < max && rest) nodes = [...nodes, ...Array(max - nodes.length).fill(rest)];
}
if (min) nodes = nodes.map((node, index) => index >= min ? createOptionalTypeNode(node) : node);
if (typeof max === "undefined" && rest) nodes.push(createRestTypeNode(createArrayTypeNode(rest)));
return createTupleTypeNode(nodes);
},
enum: (name) => {
if (!name) return;
return createTypeReferenceNode(name, void 0);
},
union: (nodes) => {
if (!nodes) return;
return createUnionDeclaration({
withParentheses: true,
nodes
});
},
const: (name, format) => {
if (name === null || name === void 0 || name === "") return;
if (format === "boolean") {
if (name === true) return createLiteralTypeNode(createTrue());
return createLiteralTypeNode(createFalse());
}
if (format === "number" && typeof name === "number") return createLiteralTypeNode(createNumericLiteral(name));
return createLiteralTypeNode(createStringLiteral(name.toString()));
},
datetime: () => keywordTypeNodes.string,
date: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
time: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
uuid: () => keywordTypeNodes.string,
url: () => keywordTypeNodes.string,
default: void 0,
and: (nodes) => {
if (!nodes) return;
return createIntersectionDeclaration({
withParentheses: true,
nodes
});
},
describe: void 0,
min: void 0,
max: void 0,
optional: void 0,
matches: () => keywordTypeNodes.string,
email: () => keywordTypeNodes.string,
firstName: void 0,
lastName: void 0,
password: void 0,
phone: void 0,
readOnly: void 0,
writeOnly: void 0,
ref: (propertyName$1) => {
if (!propertyName$1) return;
return createTypeReferenceNode(propertyName$1, void 0);
},
blob: () => createTypeReferenceNode("Blob", []),
deprecated: void 0,
example: void 0,
schema: void 0,
catchall: void 0,
name: void 0,
interface: void 0,
exclusiveMaximum: void 0,
exclusiveMinimum: void 0
};
/**
* Recursively parses a schema tree node into a corresponding TypeScript AST node.
*
* 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.
*
* @param current - The schema node to parse.
* @param siblings - Sibling schema nodes, used for context in certain mappings.
* @param name - The name of the schema or property being parsed.
* @param options - Parsing options controlling output style, property handling, and custom mappers.
* @returns The generated TypeScript AST node, or `undefined` if the schema keyword is not mapped.
*/
const parse = createParser({
mapper: typeKeywordMapper,
handlers: {
union(tree, options) {
const { current, schema, name } = tree;
return typeKeywordMapper.union(current.args.map((it) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: []
}, options)).filter(Boolean));
},
and(tree, options) {
const { current, schema, name } = tree;
return typeKeywordMapper.and(current.args.map((it) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: []
}, options)).filter(Boolean));
},
array(tree, options) {
const { current, schema, name } = tree;
return typeKeywordMapper.array(current.args.items.map((it) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: []
}, options)).filter(Boolean), options.arrayType);
},
enum(tree, options) {
const { current } = tree;
if (options.enumType === "inlineLiteral") {
const enumValues = current.args.items.map((item) => item.value).filter((value) => value !== void 0 && value !== null).map((value) => {
const format = typeof value === "number" ? "number" : typeof value === "boolean" ? "boolean" : "string";
return typeKeywordMapper.const(value, format);
}).filter(Boolean);
return typeKeywordMapper.union(enumValues);
}
return typeKeywordMapper.enum(options.enumType === "asConst" ? `${current.args.typeName}Key` : current.args.typeName);
},
ref(tree, _options) {
const { current } = tree;
return typeKeywordMapper.ref(current.args.name);
},
blob() {
return typeKeywordMapper.blob();
},
tuple(tree, options) {
const { current, schema, name } = tree;
return typeKeywordMapper.tuple(current.args.items.map((it) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: []
}, options)).filter(Boolean), current.args.rest && (this.parse({
schema,
parent: current,
name,
current: current.args.rest,
siblings: []
}, options) ?? void 0), current.args.min, current.args.max);
},
const(tree, _options) {
const { current } = tree;
return typeKeywordMapper.const(current.args.name, current.args.format);
},
object(tree, options) {
const { current, schema, name } = tree;
const properties = Object.entries(current.args?.properties || {}).filter((item) => {
const schemas = item[1];
return schemas && typeof schemas.map === "function";
}).map(([name$1, schemas]) => {
const mappedName = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.name)?.args || name$1;
if (options.mapper && Object.hasOwn(options.mapper, mappedName)) return options.mapper[mappedName];
const isNullish = schemas.some((schema$1) => schema$1.keyword === schemaKeywords.nullish);
const isNullable = schemas.some((schema$1) => schema$1.keyword === schemaKeywords.nullable);
const isOptional = schemas.some((schema$1) => schema$1.keyword === schemaKeywords.optional);
const isReadonly = schemas.some((schema$1) => schema$1.keyword === schemaKeywords.readOnly);
const describeSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.describe);
const deprecatedSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.deprecated);
const defaultSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.default);
const exampleSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.example);
const schemaSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.schema);
const minSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.min);
const maxSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.max);
const matchesSchema = schemas.find((schema$1) => schema$1.keyword === schemaKeywords.matches);
let type = schemas.map((it) => this.parse({
schema,
parent: current,
name: name$1,
current: it,
siblings: schemas
}, options)).filter(Boolean)[0];
if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
const propertyNode = createPropertySignature({
questionToken: isOptional || isNullish ? ["questionToken", "questionTokenAndUndefined"].includes(options.optionalType) : false,
name: mappedName,
type,
readOnly: isReadonly
});
return appendJSDocToNode({
node: propertyNode,
comments: [
describeSchema ? `@description ${transformers.jsStringEscape(describeSchema.args)}` : void 0,
deprecatedSchema ? "@deprecated" : void 0,
minSchema ? `@minLength ${minSchema.args}` : void 0,
maxSchema ? `@maxLength ${maxSchema.args}` : void 0,
matchesSchema ? `@pattern ${matchesSchema.args}` : void 0,
defaultSchema ? `@default ${defaultSchema.args}` : void 0,
exampleSchema ? `@example ${exampleSchema.args}` : void 0,
schemaSchema?.args?.type || schemaSchema?.args?.format ? [`@type ${schemaSchema?.args?.type || "unknown"}${!isOptional ? "" : " | undefined"}`, schemaSchema?.args?.format].filter(Boolean).join(", ") : void 0
].filter(Boolean)
});
});
let additionalProperties;
if (current.args?.additionalProperties?.length) {
let additionalPropertiesType = current.args.additionalProperties.map((it) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: []
}, options)).filter(Boolean).at(0);
if (current.args?.additionalProperties.some((schema$1) => isKeyword(schema$1, schemaKeywords.nullable))) additionalPropertiesType = createUnionDeclaration({ nodes: [additionalPropertiesType, keywordTypeNodes.null] });
const indexSignatureType = properties.length > 0 ? keywordTypeNodes.unknown : additionalPropertiesType;
additionalProperties = createIndexSignature(indexSignatureType);
}
let patternProperties;
if (current.args?.patternProperties) {
const allPatternSchemas = Object.values(current.args.patternProperties).flat();
if (allPatternSchemas.length > 0) {
patternProperties = allPatternSchemas.map((it) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: []
}, options)).filter(Boolean).at(0);
if (allPatternSchemas.some((schema$1) => isKeyword(schema$1, schemaKeywords.nullable))) patternProperties = createUnionDeclaration({ nodes: [patternProperties, keywordTypeNodes.null] });
patternProperties = createIndexSignature(patternProperties);
}
}
return typeKeywordMapper.object([
...properties,
additionalProperties,
patternProperties
].filter(Boolean));
},
datetime() {
return typeKeywordMapper.datetime();
},
date(tree) {
const { current } = tree;
return typeKeywordMapper.date(current.args.type);
},
time(tree) {
const { current } = tree;
return typeKeywordMapper.time(current.args.type);
}
}
});
//#endregion
//#region src/components/Type.tsx
function Type({ name, typedName, tree, keysToOmit, schema, optionalType, arrayType, syntaxType, enumType, enumKeyCasing, mapper, description }) {
const typeNodes = [];
if (!tree.length) return "";
const schemaFromTree = tree.find((item) => item.keyword === schemaKeywords.schema);
const enumSchemas = SchemaGenerator.deepSearch(tree, schemaKeywords.enum);
let type = tree.map((current, _index, siblings) => parse({
name,
schema,
parent: void 0,
current,
siblings
}, {
optionalType,
arrayType,
enumType,
mapper
})).filter(Boolean).at(0) || typeKeywordMapper.undefined();
if (enumType === "asConst" && enumSchemas.length > 0) {
const isDirectEnum = schema.type === "array" && schema.items !== void 0;
const isEnumOnly = "enum" in schema && schema.enum;
if (isDirectEnum || isEnumOnly) {
const typeNameWithKey = `${enumSchemas[0].args.typeName}Key`;
type = createTypeReferenceNode(typeNameWithKey);
if (schema.type === "array") if (arrayType === "generic") type = createTypeReferenceNode(createIdentifier("Array"), [type]);
else type = createArrayTypeNode(type);
}
}
if (schemaFromTree && isKeyword(schemaFromTree, schemaKeywords.schema)) {
const isNullish = tree.some((item) => item.keyword === schemaKeywords.nullish);
const isNullable = tree.some((item) => item.keyword === schemaKeywords.nullable);
const isOptional = tree.some((item) => item.keyword === schemaKeywords.optional);
if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
}
const useTypeGeneration = syntaxType === "type" || [syntaxKind.union].includes(type.kind) || !!keysToOmit?.length;
typeNodes.push(createTypeDeclaration({
name,
isExportable: true,
type: keysToOmit?.length ? createOmitDeclaration({
keys: keysToOmit,
type,
nonNullable: true
}) : type,
syntax: useTypeGeneration ? "type" : "interface",
comments: [
description ? `@description ${transformers.jsStringEscape(description)}` : void 0,
schema.deprecated ? "@deprecated" : void 0,
schema.minLength ? `@minLength ${schema.minLength}` : void 0,
schema.maxLength ? `@maxLength ${schema.maxLength}` : void 0,
schema.pattern ? `@pattern ${schema.pattern}` : void 0,
schema.default ? `@default ${schema.default}` : void 0,
schema.example ? `@example ${schema.example}` : void 0
]
}));
const enums = [...new Set(enumSchemas)].map((enumSchema) => {
const name$1 = enumType === "asPascalConst" ? transformers.pascalCase(enumSchema.args.name) : transformers.camelCase(enumSchema.args.name);
const typeName = enumType === "asConst" ? `${enumSchema.args.typeName}Key` : enumSchema.args.typeName;
const [nameNode, typeNode] = createEnumDeclaration({
name: name$1,
typeName,
enums: enumSchema.args.items.map((item) => item.value === void 0 ? void 0 : [transformers.trimQuotes(item.name?.toString()), item.value]).filter(Boolean),
type: enumType,
enumKeyCasing
});
return {
nameNode,
typeNode,
name: name$1,
typeName
};
});
const shouldExportEnums = enumType !== "inlineLiteral";
const shouldExportType = enumType === "inlineLiteral" || enums.every((item) => item.typeName !== name);
return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ name: name$1, nameNode, typeName, typeNode }) => /* @__PURE__ */ jsxs(Fragment, { children: [nameNode && /* @__PURE__ */ jsx(File.Source, {
name: name$1,
isExportable: true,
isIndexable: true,
children: safePrint(nameNode)
}), /* @__PURE__ */ jsx(File.Source, {
name: typeName,
isIndexable: true,
isExportable: [
"enum",
"asConst",
"constEnum",
"literal",
void 0
].includes(enumType),
isTypeOnly: [
"asConst",
"literal",
void 0
].includes(enumType),
children: safePrint(typeNode)
})] })), shouldExportType && /* @__PURE__ */ jsx(File.Source, {
name: typedName,
isTypeOnly: true,
isExportable: true,
isIndexable: true,
children: safePrint(...typeNodes)
})] });
}
//#endregion
export { createTypeAliasDeclaration as a, createTypeReferenceNode as c, getUnknownType as d, keywordTypeNodes as f, createPropertySignature as i, createUnionDeclaration as l, createIdentifier as n, createTypeLiteralNode as o, modifiers as p, createIndexedAccessTypeNode as r, createTypeOperatorNode as s, Type as t, createUrlTemplateType as u };
//# sourceMappingURL=components-D8LF7IMj.js.map