UNPKG

@kubb/plugin-ts

Version:

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

358 lines (353 loc) 12.3 kB
import { init_esm_shims, Type, OasType } from './chunk-G37NJ4JQ.js'; import transformers, { pascalCase, camelCase } from '@kubb/core/transformers'; import { print } from '@kubb/parser-ts'; import * as factory from '@kubb/parser-ts/factory'; import { createReactGenerator, pluginOasName, SchemaGenerator, OperationGenerator } from '@kubb/plugin-oas'; import { Oas } from '@kubb/plugin-oas/components'; import { useOas, useSchemaManager, useOperationManager } from '@kubb/plugin-oas/hooks'; import { getFooter, getBanner } from '@kubb/plugin-oas/utils'; import { useApp, File } from '@kubb/react'; import path from 'path'; import { createPlugin, PluginManager, FileManager } from '@kubb/core'; import { jsxs, jsx } from '@kubb/react/jsx-runtime'; // src/generators/index.ts init_esm_shims(); // src/generators/typeGenerator.tsx init_esm_shims(); // src/plugin.ts init_esm_shims(); var pluginTsName = "plugin-ts"; var pluginTs = createPlugin((options) => { const { output = { path: "types", barrelType: "named" }, group, exclude = [], include, override = [], enumType = "asConst", enumSuffix = "enum", dateType = "string", unknownType = "any", optionalType = "questionToken", emptySchemaType = unknownType, syntaxType = "type", transformers: transformers2 = {}, oasType = false, mapper = {}, generators = [typeGenerator, oasType === "infer" ? oasGenerator : void 0].filter(Boolean), contentType } = options; return { name: pluginTsName, options: { output, transformers: transformers2, dateType, optionalType, oasType, enumType, enumSuffix, // keep the used enumnames between SchemaGenerator and OperationGenerator per plugin(pluginKey) usedEnumNames: {}, unknownType, emptySchemaType, syntaxType, group, override, mapper }, pre: [pluginOasName], resolvePath(baseName, pathMode, options2) { const root = path.resolve(this.config.root, this.config.output.path); const mode = pathMode ?? FileManager.getMode(path.resolve(root, output.path)); if (mode === "single") { return path.resolve(root, output.path); } if (group && (options2?.group?.path || options2?.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" ? options2.group.path : options2.group.tag }), baseName ); } return path.resolve(root, output.path, baseName); }, resolveName(name, type) { const resolvedName = pascalCase(name, { isFile: type === "file" }); if (type) { return transformers2?.name?.(resolvedName, type) || resolvedName; } return resolvedName; }, async buildStart() { const [swaggerPlugin] = PluginManager.getDependedPlugins(this.plugins, [pluginOasName]); const oas = await swaggerPlugin.context.getOas(); const root = path.resolve(this.config.root, this.config.output.path); const mode = FileManager.getMode(path.resolve(root, output.path)); const schemaGenerator = new SchemaGenerator(this.plugin.options, { oas, pluginManager: this.pluginManager, plugin: this.plugin, contentType, include: void 0, override, mode, output: output.path }); const schemaFiles = await schemaGenerator.build(...generators); await this.addFile(...schemaFiles); const operationGenerator = new OperationGenerator(this.plugin.options, { oas, pluginManager: this.pluginManager, plugin: this.plugin, contentType, exclude, include, override, mode }); const operationFiles = await operationGenerator.build(...generators); await this.addFile(...operationFiles); const barrelFiles = await this.fileManager.getBarrelFiles({ type: output.barrelType ?? "named", root, output, meta: { pluginKey: this.plugin.key }, logger: this.logger }); await this.addFile(...barrelFiles); } }; }); function printCombinedSchema({ name, schemas, pluginManager }) { const properties = {}; if (schemas.response) { properties["response"] = factory.createUnionDeclaration({ nodes: schemas.responses.map((res) => { const identifier = pluginManager.resolveName({ name: res.name, pluginKey: [pluginTsName], type: "function" }); return factory.createTypeReferenceNode(factory.createIdentifier(identifier), void 0); }) }); } if (schemas.request) { const identifier = pluginManager.resolveName({ name: schemas.request.name, pluginKey: [pluginTsName], type: "function" }); properties["request"] = factory.createTypeReferenceNode(factory.createIdentifier(identifier), void 0); } if (schemas.pathParams) { const identifier = pluginManager.resolveName({ name: schemas.pathParams.name, pluginKey: [pluginTsName], type: "function" }); properties["pathParams"] = factory.createTypeReferenceNode(factory.createIdentifier(identifier), void 0); } if (schemas.queryParams) { const identifier = pluginManager.resolveName({ name: schemas.queryParams.name, pluginKey: [pluginTsName], type: "function" }); properties["queryParams"] = factory.createTypeReferenceNode(factory.createIdentifier(identifier), void 0); } if (schemas.headerParams) { const identifier = pluginManager.resolveName({ name: schemas.headerParams.name, pluginKey: [pluginTsName], type: "function" }); properties["headerParams"] = factory.createTypeReferenceNode(factory.createIdentifier(identifier), void 0); } if (schemas.errors) { properties["errors"] = factory.createUnionDeclaration({ nodes: schemas.errors.map((error) => { const identifier = pluginManager.resolveName({ name: error.name, pluginKey: [pluginTsName], type: "function" }); return factory.createTypeReferenceNode(factory.createIdentifier(identifier), void 0); }) }); } const namespaceNode = factory.createTypeAliasDeclaration({ name, type: factory.createTypeLiteralNode( Object.keys(properties).map((key) => { const type = properties[key]; if (!type) { return void 0; } return factory.createPropertySignature({ name: transformers.pascalCase(key), type }); }).filter(Boolean) ), modifiers: [factory.modifiers.export] }); return print([namespaceNode]); } var typeGenerator = createReactGenerator({ name: "typescript", Operation({ operation, options }) { const { mapper, enumType, syntaxType, optionalType } = options; const { plugin, pluginManager, mode } = useApp(); const oas = useOas(); const { getSchemas, getFile, getName, getGroup } = useOperationManager(); const schemaManager = useSchemaManager(); const file = getFile(operation); const schemas = getSchemas(operation); const type = getName(operation, { type: "function", pluginKey: [pluginTsName] }); const combinedSchemaName = operation.method === "get" ? `${type}Query` : `${type}Mutation`; const schemaGenerator = new SchemaGenerator(options, { oas, 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, schema: schemaObject, description, keysToOmit, ...options2 }, i) => { const tree = schemaGenerator.parse({ schemaObject, name }); const imports = schemaManager.getImports(tree); const group = options2.operation ? getGroup(options2.operation) : void 0; const type2 = { name: schemaManager.getName(name, { type: "type" }), typedName: schemaManager.getName(name, { type: "type" }), file: schemaManager.getFile(options2.operationName || name, { group }) }; return /* @__PURE__ */ jsxs(Oas.Schema, { name, schemaObject, tree, children: [ mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, { root: file.path, path: imp.path, name: imp.name, isTypeOnly: true }, [imp.name, imp.path, imp.isTypeOnly].join("-"))), /* @__PURE__ */ jsx( Type, { name: type2.name, typedName: type2.typedName, description, tree, schema: schemaObject, mapper, enumType, optionalType, keysToOmit, syntaxType } ) ] }, i); }; 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), /* @__PURE__ */ jsx(File.Source, { name: combinedSchemaName, isExportable: true, isIndexable: true, isTypeOnly: true, children: printCombinedSchema({ name: combinedSchemaName, schemas, pluginManager }) }) ] } ); }, Schema({ schema, options }) { const { mapper, enumType, syntaxType, optionalType } = options; const { mode, plugin: { options: { output } }, pluginManager } = useApp(); const oas = useOas(); const { getName, getImports, getFile } = useSchemaManager(); const imports = getImports(schema.tree); if (enumType === "asPascalConst") { console.warn(`enumType '${enumType}' is deprecated`); } const type = { name: getName(schema.name, { type: "function" }), typedName: getName(schema.name, { type: "type" }), 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 }, [imp.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, optionalType, syntaxType } ) ] } ); } }); // src/generators/oasGenerator.tsx init_esm_shims(); var oasGenerator = createReactGenerator({ name: "oas", Operations() { const { pluginManager, plugin: { options: { output }, key: pluginKey } } = useApp(); const oas = useOas(); const file = pluginManager.getFile({ name: "oas", extname: ".ts", pluginKey }); return /* @__PURE__ */ jsxs( File, { baseName: file.baseName, path: file.path, meta: file.meta, banner: getBanner({ oas, output, config: pluginManager.config }), footer: getFooter({ oas, output }), children: [ /* @__PURE__ */ jsx(File.Import, { name: ["Infer"], path: "@kubb/oas", isTypeOnly: true }), /* @__PURE__ */ jsx(OasType, { name: "oas", typeName: "Oas", api: oas.api }) ] } ); } }); export { oasGenerator, pluginTs, pluginTsName, typeGenerator }; //# sourceMappingURL=chunk-AUTKC2ER.js.map //# sourceMappingURL=chunk-AUTKC2ER.js.map