UNPKG

@kubb/plugin-ts

Version:

TypeScript code generation plugin for Kubb, transforming OpenAPI schemas into TypeScript interfaces, types, and utility functions.

471 lines (468 loc) 15.6 kB
import { a as createTypeAliasDeclaration, c as createTypeReferenceNode, d as getUnknownType, f as keywordTypeNodes, i as createPropertySignature, l as createUnionDeclaration, n as createIdentifier, o as createTypeLiteralNode, p as modifiers, r as createIndexedAccessTypeNode, s as createTypeOperatorNode, t as Type, u as createUrlTemplateType } from "./components-D8LF7IMj.js"; import path from "node:path"; import { definePlugin, getBarrelFiles, getMode } from "@kubb/core"; import transformers, { camelCase, pascalCase } from "@kubb/core/transformers"; import { OperationGenerator, SchemaGenerator, isKeyword, pluginOasName, schemaKeywords } from "@kubb/plugin-oas"; import { useMode, usePluginManager } from "@kubb/core/hooks"; import { safePrint } from "@kubb/fabric-core/parsers/typescript"; import { createReactGenerator } from "@kubb/plugin-oas/generators"; import { useOas, useOperationManager, useSchemaManager } from "@kubb/plugin-oas/hooks"; import { getBanner, getFooter } from "@kubb/plugin-oas/utils"; import { File } from "@kubb/react-fabric"; import ts from "typescript"; import { Fragment, jsx, jsxs } from "@kubb/react-fabric/jsx-runtime"; //#region src/generators/typeGenerator.tsx function printCombinedSchema({ name, schemas, pluginManager }) { const properties = {}; if (schemas.response) properties["response"] = createUnionDeclaration({ nodes: schemas.responses.map((res) => { const identifier = pluginManager.resolveName({ name: res.name, pluginKey: [pluginTsName], type: "function" }); return createTypeReferenceNode(createIdentifier(identifier), void 0); }) }); if (schemas.request) { const identifier = pluginManager.resolveName({ name: schemas.request.name, pluginKey: [pluginTsName], type: "function" }); properties["request"] = createTypeReferenceNode(createIdentifier(identifier), void 0); } if (schemas.pathParams) { const identifier = pluginManager.resolveName({ name: schemas.pathParams.name, pluginKey: [pluginTsName], type: "function" }); properties["pathParams"] = createTypeReferenceNode(createIdentifier(identifier), void 0); } if (schemas.queryParams) { const identifier = pluginManager.resolveName({ name: schemas.queryParams.name, pluginKey: [pluginTsName], type: "function" }); properties["queryParams"] = createTypeReferenceNode(createIdentifier(identifier), void 0); } if (schemas.headerParams) { const identifier = pluginManager.resolveName({ name: schemas.headerParams.name, pluginKey: [pluginTsName], type: "function" }); properties["headerParams"] = createTypeReferenceNode(createIdentifier(identifier), void 0); } if (schemas.errors) properties["errors"] = createUnionDeclaration({ nodes: schemas.errors.map((error) => { const identifier = pluginManager.resolveName({ name: error.name, pluginKey: [pluginTsName], type: "function" }); return createTypeReferenceNode(createIdentifier(identifier), void 0); }) }); return safePrint(createTypeAliasDeclaration({ name, type: createTypeLiteralNode(Object.keys(properties).map((key) => { const type = properties[key]; if (!type) return; return createPropertySignature({ name: transformers.pascalCase(key), type }); }).filter(Boolean)), modifiers: [modifiers.export] })); } function printRequestSchema({ baseName, operation, schemas, pluginManager }) { const name = pluginManager.resolveName({ name: `${baseName} Request`, pluginKey: [pluginTsName], type: "type" }); const results = []; const dataRequestProperties = []; if (schemas.request) { const identifier = pluginManager.resolveName({ name: schemas.request.name, pluginKey: [pluginTsName], type: "type" }); dataRequestProperties.push(createPropertySignature({ name: "data", questionToken: true, type: createTypeReferenceNode(createIdentifier(identifier), void 0) })); } else dataRequestProperties.push(createPropertySignature({ name: "data", questionToken: true, type: keywordTypeNodes.never })); if (schemas.pathParams) { const identifier = pluginManager.resolveName({ name: schemas.pathParams.name, pluginKey: [pluginTsName], type: "type" }); dataRequestProperties.push(createPropertySignature({ name: "pathParams", type: createTypeReferenceNode(createIdentifier(identifier), void 0) })); } else dataRequestProperties.push(createPropertySignature({ name: "pathParams", questionToken: true, type: keywordTypeNodes.never })); if (schemas.queryParams) { const identifier = pluginManager.resolveName({ name: schemas.queryParams.name, pluginKey: [pluginTsName], type: "type" }); dataRequestProperties.push(createPropertySignature({ name: "queryParams", questionToken: true, type: createTypeReferenceNode(createIdentifier(identifier), void 0) })); } else dataRequestProperties.push(createPropertySignature({ name: "queryParams", questionToken: true, type: keywordTypeNodes.never })); if (schemas.headerParams) { const identifier = pluginManager.resolveName({ name: schemas.headerParams.name, pluginKey: [pluginTsName], type: "type" }); dataRequestProperties.push(createPropertySignature({ name: "headerParams", questionToken: true, type: createTypeReferenceNode(createIdentifier(identifier), void 0) })); } else dataRequestProperties.push(createPropertySignature({ name: "headerParams", questionToken: true, type: keywordTypeNodes.never })); dataRequestProperties.push(createPropertySignature({ name: "url", type: createUrlTemplateType(operation.path) })); const dataRequestNode = createTypeAliasDeclaration({ name, type: createTypeLiteralNode(dataRequestProperties), modifiers: [modifiers.export] }); results.push(safePrint(dataRequestNode)); return results.join("\n\n"); } function printResponseSchema({ baseName, schemas, pluginManager, unknownType }) { const results = []; const name = pluginManager.resolveName({ name: `${baseName} ResponseData`, pluginKey: [pluginTsName], type: "type" }); if (schemas.responses && schemas.responses.length > 0) { const responsesProperties = schemas.responses.map((res) => { const identifier = pluginManager.resolveName({ name: res.name, pluginKey: [pluginTsName], type: "type" }); return createPropertySignature({ name: res.statusCode?.toString() ?? "default", type: createTypeReferenceNode(createIdentifier(identifier), void 0) }); }); const responsesNode = createTypeAliasDeclaration({ name: `${baseName}Responses`, type: createTypeLiteralNode(responsesProperties), modifiers: [modifiers.export] }); results.push(safePrint(responsesNode)); const responseNode = createTypeAliasDeclaration({ name, type: createIndexedAccessTypeNode(createTypeReferenceNode(createIdentifier(`${baseName}Responses`), void 0), createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, createTypeReferenceNode(createIdentifier(`${baseName}Responses`), void 0))), modifiers: [modifiers.export] }); results.push(safePrint(responseNode)); } else { const responseNode = createTypeAliasDeclaration({ name, modifiers: [modifiers.export], type: getUnknownType(unknownType) }); results.push(safePrint(responseNode)); } return results.join("\n\n"); } const typeGenerator = createReactGenerator({ name: "typescript", Operation({ operation, generator, plugin }) { const { options, options: { mapper, enumType, enumKeyCasing, syntaxType, optionalType, arrayType, unknownType } } = plugin; const mode = useMode(); const pluginManager = usePluginManager(); const oas = useOas(); const { getSchemas, getFile, getName, getGroup } = useOperationManager(generator); const schemaManager = useSchemaManager(); const name = getName(operation, { type: "type", pluginKey: [pluginTsName] }); const file = getFile(operation); const schemas = getSchemas(operation); const schemaGenerator = new SchemaGenerator(options, { fabric: generator.context.fabric, oas, events: generator.context.events, plugin, pluginManager, mode, override: options.override }); const operationSchemas = [ schemas.pathParams, schemas.queryParams, schemas.headerParams, schemas.statusCodes, schemas.request, schemas.response ].flat().filter(Boolean); const mapOperationSchema = ({ name: name$1, schema, description, keysToOmit, ...options$1 }) => { const tree = schemaGenerator.parse({ schema, name: name$1, parentName: null }); const imports = schemaManager.getImports(tree); const group = options$1.operation ? getGroup(options$1.operation) : void 0; const type = { name: schemaManager.getName(name$1, { type: "type" }), typedName: schemaManager.getName(name$1, { type: "type" }), file: schemaManager.getFile(options$1.operationName || name$1, { group }) }; return /* @__PURE__ */ jsxs(Fragment, { children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, { root: file.path, path: imp.path, name: imp.name, isTypeOnly: true }, [ name$1, imp.name, imp.path, imp.isTypeOnly ].join("-"))), /* @__PURE__ */ jsx(Type, { name: type.name, typedName: type.typedName, description, tree, schema, mapper, enumType, enumKeyCasing, optionalType, arrayType, keysToOmit, syntaxType })] }); }; const responseName = schemaManager.getName(schemas.response.name, { type: "type" }); const combinedSchemaName = operation.method === "get" ? `${name}Query` : `${name}Mutation`; return /* @__PURE__ */ jsxs(File, { baseName: file.baseName, path: file.path, meta: file.meta, banner: getBanner({ oas, output: plugin.options.output, config: pluginManager.config }), footer: getFooter({ oas, output: plugin.options.output }), children: [operationSchemas.map(mapOperationSchema), generator.context.UNSTABLE_NAMING ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, { name: `${name}Request`, isExportable: true, isIndexable: true, isTypeOnly: true, children: printRequestSchema({ baseName: name, operation, schemas, pluginManager }) }), /* @__PURE__ */ jsx(File.Source, { name: responseName, isExportable: true, isIndexable: true, isTypeOnly: true, children: printResponseSchema({ baseName: name, schemas, pluginManager, unknownType }) })] }) : /* @__PURE__ */ jsx(File.Source, { name: combinedSchemaName, isExportable: true, isIndexable: true, isTypeOnly: true, children: printCombinedSchema({ name: combinedSchemaName, schemas, pluginManager }) })] }); }, Schema({ schema, plugin }) { const { options: { mapper, enumType, enumKeyCasing, syntaxType, optionalType, arrayType, output } } = plugin; const mode = useMode(); const oas = useOas(); const pluginManager = usePluginManager(); const { getName, getImports, getFile } = useSchemaManager(); const imports = getImports(schema.tree); const schemaFromTree = schema.tree.find((item) => item.keyword === schemaKeywords.schema); let typedName = getName(schema.name, { type: "type" }); if (enumType === "asConst" && schemaFromTree && isKeyword(schemaFromTree, schemaKeywords.enum)) typedName = typedName += "Key"; const type = { name: getName(schema.name, { type: "function" }), typedName, file: getFile(schema.name) }; return /* @__PURE__ */ jsxs(File, { baseName: type.file.baseName, path: type.file.path, meta: type.file.meta, banner: getBanner({ oas, output, config: pluginManager.config }), footer: getFooter({ oas, output }), children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, { root: type.file.path, path: imp.path, name: imp.name, isTypeOnly: true }, [ schema.name, imp.path, imp.isTypeOnly ].join("-"))), /* @__PURE__ */ jsx(Type, { name: type.name, typedName: type.typedName, description: schema.value.description, tree: schema.tree, schema: schema.value, mapper, enumType, enumKeyCasing, optionalType, arrayType, syntaxType })] }); } }); //#endregion //#region src/plugin.ts const pluginTsName = "plugin-ts"; const pluginTs = definePlugin((options) => { const { output = { path: "types", barrelType: "named" }, group, exclude = [], include, override = [], enumType = "asConst", enumKeyCasing = "none", enumSuffix = "enum", dateType = "string", unknownType = "any", optionalType = "questionToken", arrayType = "array", emptySchemaType = unknownType, syntaxType = "type", transformers: transformers$1 = {}, mapper = {}, generators = [typeGenerator].filter(Boolean), contentType, UNSTABLE_NAMING } = options; return { name: pluginTsName, options: { output, transformers: transformers$1, dateType, optionalType, arrayType, enumType, enumKeyCasing, enumSuffix, unknownType, emptySchemaType, syntaxType, group, override, mapper, usedEnumNames: {} }, pre: [pluginOasName], resolvePath(baseName, pathMode, options$1) { const root = path.resolve(this.config.root, this.config.output.path); if ((pathMode ?? getMode(path.resolve(root, output.path))) === "single") /** * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend * Other plugins then need to call addOrAppend instead of just add from the fileManager class */ return path.resolve(root, output.path); if (group && (options$1?.group?.path || options$1?.group?.tag)) { const groupName = group?.name ? group.name : (ctx) => { if (group?.type === "path") return `${ctx.group.split("/")[1]}`; return `${camelCase(ctx.group)}Controller`; }; return path.resolve(root, output.path, groupName({ group: group.type === "path" ? options$1.group.path : options$1.group.tag }), baseName); } return path.resolve(root, output.path, baseName); }, resolveName(name, type) { const resolvedName = pascalCase(name, { isFile: type === "file" }); if (type) return transformers$1?.name?.(resolvedName, type) || resolvedName; return resolvedName; }, async install() { const root = path.resolve(this.config.root, this.config.output.path); const mode = getMode(path.resolve(root, output.path)); const oas = await this.getOas(); const schemaFiles = await new SchemaGenerator(this.plugin.options, { fabric: this.fabric, oas, pluginManager: this.pluginManager, events: this.events, plugin: this.plugin, contentType, include: void 0, override, mode, output: output.path }).build(...generators); await this.upsertFile(...schemaFiles); const operationFiles = await new OperationGenerator(this.plugin.options, { fabric: this.fabric, oas, pluginManager: this.pluginManager, events: this.events, plugin: this.plugin, contentType, exclude, include, override, mode, UNSTABLE_NAMING }).build(...generators); await this.upsertFile(...operationFiles); const barrelFiles = await getBarrelFiles(this.fabric.files, { type: output.barrelType ?? "named", root, output, meta: { pluginKey: this.plugin.key } }); await this.upsertFile(...barrelFiles); } }; }); //#endregion export { pluginTsName as n, typeGenerator as r, pluginTs as t }; //# sourceMappingURL=plugin-BrZGmUZ0.js.map