@kubb/plugin-oas
Version:
Generator swagger
408 lines (403 loc) • 15 kB
JavaScript
;
var chunkDUZZHEQI_cjs = require('./chunk-DUZZHEQI.cjs');
var chunkDEDONPUL_cjs = require('./chunk-DEDONPUL.cjs');
require('./chunk-PADR76WZ.cjs');
var chunkI2LBG5AS_cjs = require('./chunk-I2LBG5AS.cjs');
require('./chunk-B7KP5ZFA.cjs');
require('./chunk-KXB5DUFD.cjs');
var core = require('@kubb/core');
var transformers = require('@kubb/core/transformers');
var path = require('path');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var transformers__default = /*#__PURE__*/_interopDefault(transformers);
var path__default = /*#__PURE__*/_interopDefault(path);
var OperationGenerator = class extends core.BaseGenerator {
#operationsByMethod = {};
get operationsByMethod() {
return this.#operationsByMethod;
}
set operationsByMethod(paths) {
this.#operationsByMethod = paths;
}
#getOptions(operation, method) {
const { override = [] } = this.context;
return override.find(({ pattern, type }) => {
if (type === "tag") {
return !!operation.getTags().some((tag) => tag.name.match(pattern));
}
if (type === "operationId") {
return !!operation.getOperationId({ friendlyCase: true }).match(pattern);
}
if (type === "path") {
return !!operation.path.match(pattern);
}
if (type === "method") {
return !!method.match(pattern);
}
if (type === "contentType") {
return !!operation.getContentType().match(pattern);
}
return false;
})?.options || {};
}
#isExcluded(operation, method) {
const { exclude = [] } = this.context;
let matched = false;
exclude.forEach(({ pattern, type }) => {
if (type === "tag" && !matched) {
matched = !!operation.getTags().some((tag) => tag.name.match(pattern));
}
if (type === "operationId" && !matched) {
matched = !!operation.getOperationId({ friendlyCase: true }).match(pattern);
}
if (type === "path" && !matched) {
matched = !!operation.path.match(pattern);
}
if (type === "method" && !matched) {
matched = !!method.match(pattern);
}
if (type === "contentType" && !matched) {
return !!operation.getContentType().match(pattern);
}
});
return matched;
}
#isIncluded(operation, method) {
const { include = [] } = this.context;
let matched = false;
include.forEach(({ pattern, type }) => {
if (type === "tag" && !matched) {
matched = !!operation.getTags().some((tag) => tag.name.match(pattern));
}
if (type === "operationId" && !matched) {
matched = !!operation.getOperationId({ friendlyCase: true }).match(pattern);
}
if (type === "path" && !matched) {
matched = !!operation.path.match(pattern);
}
if (type === "method" && !matched) {
matched = !!method.match(pattern);
}
if (type === "contentType" && !matched) {
matched = !!operation.getContentType().match(pattern);
}
});
return matched;
}
getSchemas(operation, {
resolveName = (name) => name
} = {}) {
const pathParamsSchema = this.context.oas.getParametersSchema(operation, "path");
const queryParamsSchema = this.context.oas.getParametersSchema(operation, "query");
const headerParamsSchema = this.context.oas.getParametersSchema(operation, "header");
const requestSchema = this.context.oas.getRequestSchema(operation);
const statusCodes = operation.getResponseStatusCodes().map((statusCode) => {
let name = statusCode;
if (name === "default") {
name = "error";
}
const schema = this.context.oas.getResponseSchema(operation, statusCode);
return {
name: resolveName(transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} ${name}`)),
description: operation.getResponseByStatusCode(statusCode)?.description,
schema,
operation,
operationName: transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })}`),
statusCode: name === "error" ? void 0 : Number(statusCode),
keys: schema?.properties ? Object.keys(schema.properties) : void 0,
keysToOmit: schema?.properties ? Object.keys(schema.properties).filter((key) => {
const item = schema.properties?.[key];
return item?.writeOnly;
}) : void 0
};
});
const hasResponses = statusCodes.some((item) => item.statusCode?.toString().startsWith("2"));
return {
pathParams: pathParamsSchema ? {
name: resolveName(transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} PathParams`)),
operation,
operationName: transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })}`),
schema: pathParamsSchema,
keys: pathParamsSchema.properties ? Object.keys(pathParamsSchema.properties) : void 0
} : void 0,
queryParams: queryParamsSchema ? {
name: resolveName(transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} QueryParams`)),
operation,
operationName: transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })}`),
schema: queryParamsSchema,
keys: queryParamsSchema.properties ? Object.keys(queryParamsSchema.properties) : []
} : void 0,
headerParams: headerParamsSchema ? {
name: resolveName(transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} HeaderParams`)),
operation,
operationName: transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })}`),
schema: headerParamsSchema,
keys: headerParamsSchema.properties ? Object.keys(headerParamsSchema.properties) : void 0
} : void 0,
request: requestSchema ? {
name: resolveName(
transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} ${operation.method === "get" ? "queryRequest" : "mutationRequest"}`)
),
description: operation.schema.requestBody?.description,
operation,
operationName: transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })}`),
schema: requestSchema,
keys: requestSchema.properties ? Object.keys(requestSchema.properties) : void 0,
keysToOmit: requestSchema.properties ? Object.keys(requestSchema.properties).filter((key) => {
const item = requestSchema.properties?.[key];
return item?.readOnly;
}) : void 0
} : void 0,
response: {
name: resolveName(
transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} ${operation.method === "get" ? "queryResponse" : "mutationResponse"}`)
),
operation,
operationName: transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })}`),
schema: {
oneOf: hasResponses ? statusCodes.filter((item) => item.statusCode?.toString().startsWith("2")).map((item) => {
return {
...item.schema,
$ref: resolveName(transformers__default.default.pascalCase(`${operation.getOperationId({ friendlyCase: true })} ${item.statusCode}`))
};
}) : void 0
}
},
responses: statusCodes.filter((item) => item.statusCode?.toString().startsWith("2")),
errors: statusCodes.filter((item) => item.statusCode?.toString().startsWith("4") || item.statusCode?.toString().startsWith("5")),
statusCodes
};
}
async build(...generators) {
const { oas } = this.context;
const paths = oas.getPaths();
this.operationsByMethod = Object.entries(paths).reduce((acc, [path2, method]) => {
const methods = Object.keys(method);
methods.forEach((method2) => {
const operation = oas.operation(path2, method2);
if (operation && method2 === operation.method) {
const isExcluded = this.#isExcluded(operation, method2);
const isIncluded = this.context.include ? this.#isIncluded(operation, method2) : true;
if (isIncluded && !isExcluded) {
if (!acc[path2]) {
acc[path2] = {};
}
acc[path2] = {
...acc[path2],
[method2]: {
operation,
schemas: this.getSchemas(operation)
}
};
}
}
});
return acc;
}, {});
const promises = Object.keys(this.operationsByMethod).reduce((acc, path2) => {
const methods = this.operationsByMethod[path2] ? Object.keys(this.operationsByMethod[path2]) : [];
methods.forEach((method) => {
const { operation } = this.operationsByMethod[path2]?.[method];
const options = this.#getOptions(operation, method);
const methodToCall = this[method];
if (typeof methodToCall === "function") {
const promiseMethod = methodToCall?.call(this, operation, {
...this.options,
...options
});
if (promiseMethod) {
acc.push(promiseMethod);
}
}
const promiseOperation = this.operation.call(this, operation, {
...this.options,
...options
});
if (promiseOperation) {
acc.push(promiseOperation);
}
generators?.forEach((generator) => {
const promise = generator.operation?.({
instance: this,
operation,
options: {
...this.options,
...options
}
});
if (promise) {
acc.push(promise);
}
});
});
return acc;
}, []);
const operations = Object.values(this.operationsByMethod).map((item) => Object.values(item).map((item2) => item2.operation));
promises.push(this.all(operations.flat().filter(Boolean), this.operationsByMethod));
generators?.forEach((generator) => {
const promise = generator.operations?.({
instance: this,
operations: operations.flat().filter(Boolean),
operationsByMethod: this.operationsByMethod,
options: this.options
});
if (promise) {
promises.push(promise);
}
});
const files = await Promise.all(promises);
return files.flat().filter(Boolean);
}
/**
* Operation
*/
async operation(_operation, _options) {
return [];
}
/**
* Combination of GET, POST, PATCH, PUT, DELETE
*/
async all(_operations, _paths) {
return [];
}
};
var pluginOasName = "plugin-oas";
var pluginOas = core.createPlugin((options) => {
const {
output = {
path: "schemas"
},
group,
validate = true,
generators = [chunkDUZZHEQI_cjs.jsonGenerator],
serverIndex,
contentType,
oasClass
} = options;
const getOas = async ({ config, logger }) => {
try {
const oas = await chunkDEDONPUL_cjs.parseFromConfig(config, oasClass);
if (validate) {
await oas.valdiate();
}
return oas;
} catch (e) {
const error = e;
logger.emit("warning", error?.message);
return chunkDEDONPUL_cjs.parseFromConfig(config, oasClass);
}
};
return {
name: pluginOasName,
options: {
output,
...options
},
context() {
const { config, logger } = this;
return {
getOas() {
return getOas({ config, logger });
},
async getBaseURL() {
const oasInstance = await this.getOas();
if (serverIndex) {
return oasInstance.api.servers?.at(serverIndex)?.url;
}
return void 0;
}
};
},
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);
},
async buildStart() {
if (!output) {
return;
}
const oas = await getOas({
config: this.config,
logger: this.logger
});
await oas.dereference();
const schemaGenerator = new chunkI2LBG5AS_cjs.SchemaGenerator(
{
unknownType: "unknown",
dateType: "date",
transformers: {},
...this.plugin.options
},
{
oas,
pluginManager: this.pluginManager,
plugin: this.plugin,
contentType,
include: void 0,
override: void 0,
mode: "split",
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: void 0,
include: void 0,
override: void 0,
mode: "split"
});
const operationFiles = await operationGenerator.build(...generators);
await this.addFile(...operationFiles);
}
};
});
Object.defineProperty(exports, "createGenerator", {
enumerable: true,
get: function () { return chunkDUZZHEQI_cjs.createGenerator; }
});
Object.defineProperty(exports, "createReactGenerator", {
enumerable: true,
get: function () { return chunkDUZZHEQI_cjs.createReactGenerator; }
});
Object.defineProperty(exports, "SchemaGenerator", {
enumerable: true,
get: function () { return chunkI2LBG5AS_cjs.SchemaGenerator; }
});
Object.defineProperty(exports, "isKeyword", {
enumerable: true,
get: function () { return chunkI2LBG5AS_cjs.isKeyword; }
});
Object.defineProperty(exports, "schemaKeywords", {
enumerable: true,
get: function () { return chunkI2LBG5AS_cjs.schemaKeywords; }
});
exports.OperationGenerator = OperationGenerator;
exports.pluginOas = pluginOas;
exports.pluginOasName = pluginOasName;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map