@kubb/plugin-ts
Version:
TypeScript code generation plugin for Kubb, transforming OpenAPI schemas into TypeScript interfaces, types, and utility functions.
387 lines (378 loc) • 13.8 kB
JavaScript
'use strict';
var chunkYB6JHIAR_cjs = require('./chunk-YB6JHIAR.cjs');
var transformers = require('@kubb/core/transformers');
var parserTs = require('@kubb/parser-ts');
var factory = require('@kubb/parser-ts/factory');
var pluginOas = require('@kubb/plugin-oas');
var components = require('@kubb/plugin-oas/components');
var hooks = require('@kubb/plugin-oas/hooks');
var utils = require('@kubb/plugin-oas/utils');
var react = require('@kubb/react');
var path = require('path');
var core = require('@kubb/core');
var jsxRuntime = require('@kubb/react/jsx-runtime');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var transformers__default = /*#__PURE__*/_interopDefault(transformers);
var factory__namespace = /*#__PURE__*/_interopNamespace(factory);
var path__default = /*#__PURE__*/_interopDefault(path);
// src/generators/index.ts
chunkYB6JHIAR_cjs.init_cjs_shims();
// src/generators/typeGenerator.tsx
chunkYB6JHIAR_cjs.init_cjs_shims();
// src/plugin.ts
chunkYB6JHIAR_cjs.init_cjs_shims();
var pluginTsName = "plugin-ts";
var pluginTs = core.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: [pluginOas.pluginOasName],
resolvePath(baseName, pathMode, options2) {
const root = path__default.default.resolve(this.config.root, this.config.output.path);
const mode = pathMode ?? core.FileManager.getMode(path__default.default.resolve(root, output.path));
if (mode === "single") {
return path__default.default.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 `${transformers.camelCase(ctx.group)}Controller`;
};
return path__default.default.resolve(
root,
output.path,
groupName({
group: group.type === "path" ? options2.group.path : options2.group.tag
}),
baseName
);
}
return path__default.default.resolve(root, output.path, baseName);
},
resolveName(name, type) {
const resolvedName = transformers.pascalCase(name, { isFile: type === "file" });
if (type) {
return transformers2?.name?.(resolvedName, type) || resolvedName;
}
return resolvedName;
},
async buildStart() {
const [swaggerPlugin] = core.PluginManager.getDependedPlugins(this.plugins, [pluginOas.pluginOasName]);
const oas = await swaggerPlugin.context.getOas();
const root = path__default.default.resolve(this.config.root, this.config.output.path);
const mode = core.FileManager.getMode(path__default.default.resolve(root, output.path));
const schemaGenerator = new pluginOas.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 pluginOas.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__namespace.createUnionDeclaration({
nodes: schemas.responses.map((res) => {
const identifier = pluginManager.resolveName({
name: res.name,
pluginKey: [pluginTsName],
type: "function"
});
return factory__namespace.createTypeReferenceNode(factory__namespace.createIdentifier(identifier), void 0);
})
});
}
if (schemas.request) {
const identifier = pluginManager.resolveName({
name: schemas.request.name,
pluginKey: [pluginTsName],
type: "function"
});
properties["request"] = factory__namespace.createTypeReferenceNode(factory__namespace.createIdentifier(identifier), void 0);
}
if (schemas.pathParams) {
const identifier = pluginManager.resolveName({
name: schemas.pathParams.name,
pluginKey: [pluginTsName],
type: "function"
});
properties["pathParams"] = factory__namespace.createTypeReferenceNode(factory__namespace.createIdentifier(identifier), void 0);
}
if (schemas.queryParams) {
const identifier = pluginManager.resolveName({
name: schemas.queryParams.name,
pluginKey: [pluginTsName],
type: "function"
});
properties["queryParams"] = factory__namespace.createTypeReferenceNode(factory__namespace.createIdentifier(identifier), void 0);
}
if (schemas.headerParams) {
const identifier = pluginManager.resolveName({
name: schemas.headerParams.name,
pluginKey: [pluginTsName],
type: "function"
});
properties["headerParams"] = factory__namespace.createTypeReferenceNode(factory__namespace.createIdentifier(identifier), void 0);
}
if (schemas.errors) {
properties["errors"] = factory__namespace.createUnionDeclaration({
nodes: schemas.errors.map((error) => {
const identifier = pluginManager.resolveName({
name: error.name,
pluginKey: [pluginTsName],
type: "function"
});
return factory__namespace.createTypeReferenceNode(factory__namespace.createIdentifier(identifier), void 0);
})
});
}
const namespaceNode = factory__namespace.createTypeAliasDeclaration({
name,
type: factory__namespace.createTypeLiteralNode(
Object.keys(properties).map((key) => {
const type = properties[key];
if (!type) {
return void 0;
}
return factory__namespace.createPropertySignature({
name: transformers__default.default.pascalCase(key),
type
});
}).filter(Boolean)
),
modifiers: [factory__namespace.modifiers.export]
});
return parserTs.print([namespaceNode]);
}
var typeGenerator = pluginOas.createReactGenerator({
name: "typescript",
Operation({ operation, options }) {
const { mapper, enumType, syntaxType, optionalType } = options;
const { plugin, pluginManager, mode } = react.useApp();
const oas = hooks.useOas();
const { getSchemas, getFile, getName, getGroup } = hooks.useOperationManager();
const schemaManager = hooks.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 pluginOas.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__ */ jsxRuntime.jsxs(components.Oas.Schema, { name, schemaObject, tree, children: [
mode === "split" && imports.map((imp) => /* @__PURE__ */ jsxRuntime.jsx(react.File.Import, { root: file.path, path: imp.path, name: imp.name, isTypeOnly: true }, [imp.name, imp.path, imp.isTypeOnly].join("-"))),
/* @__PURE__ */ jsxRuntime.jsx(
chunkYB6JHIAR_cjs.Type,
{
name: type2.name,
typedName: type2.typedName,
description,
tree,
schema: schemaObject,
mapper,
enumType,
optionalType,
keysToOmit,
syntaxType
}
)
] }, i);
};
return /* @__PURE__ */ jsxRuntime.jsxs(
react.File,
{
baseName: file.baseName,
path: file.path,
meta: file.meta,
banner: utils.getBanner({ oas, output: plugin.options.output, config: pluginManager.config }),
footer: utils.getFooter({ oas, output: plugin.options.output }),
children: [
operationSchemas.map(mapOperationSchema),
/* @__PURE__ */ jsxRuntime.jsx(react.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
} = react.useApp();
const oas = hooks.useOas();
const { getName, getImports, getFile } = hooks.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__ */ jsxRuntime.jsxs(
react.File,
{
baseName: type.file.baseName,
path: type.file.path,
meta: type.file.meta,
banner: utils.getBanner({ oas, output, config: pluginManager.config }),
footer: utils.getFooter({ oas, output }),
children: [
mode === "split" && imports.map((imp) => /* @__PURE__ */ jsxRuntime.jsx(react.File.Import, { root: type.file.path, path: imp.path, name: imp.name, isTypeOnly: true }, [imp.name, imp.path, imp.isTypeOnly].join("-"))),
/* @__PURE__ */ jsxRuntime.jsx(
chunkYB6JHIAR_cjs.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
chunkYB6JHIAR_cjs.init_cjs_shims();
var oasGenerator = pluginOas.createReactGenerator({
name: "oas",
Operations() {
const {
pluginManager,
plugin: {
options: { output },
key: pluginKey
}
} = react.useApp();
const oas = hooks.useOas();
const file = pluginManager.getFile({ name: "oas", extname: ".ts", pluginKey });
return /* @__PURE__ */ jsxRuntime.jsxs(
react.File,
{
baseName: file.baseName,
path: file.path,
meta: file.meta,
banner: utils.getBanner({ oas, output, config: pluginManager.config }),
footer: utils.getFooter({ oas, output }),
children: [
/* @__PURE__ */ jsxRuntime.jsx(react.File.Import, { name: ["Infer"], path: "@kubb/oas", isTypeOnly: true }),
/* @__PURE__ */ jsxRuntime.jsx(chunkYB6JHIAR_cjs.OasType, { name: "oas", typeName: "Oas", api: oas.api })
]
}
);
}
});
exports.oasGenerator = oasGenerator;
exports.pluginTs = pluginTs;
exports.pluginTsName = pluginTsName;
exports.typeGenerator = typeGenerator;
//# sourceMappingURL=chunk-5LFEQTFW.cjs.map
//# sourceMappingURL=chunk-5LFEQTFW.cjs.map