openapi-ts-mock-generator
Version:
typescript mock data generator based openapi
516 lines (506 loc) • 18.3 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/core/types.ts
var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
HttpMethods2["GET"] = "get";
HttpMethods2["PUT"] = "put";
HttpMethods2["POST"] = "post";
HttpMethods2["DELETE"] = "delete";
HttpMethods2["OPTIONS"] = "options";
HttpMethods2["HEAD"] = "head";
HttpMethods2["PATCH"] = "patch";
HttpMethods2["TRACE"] = "trace";
return HttpMethods2;
})(HttpMethods || {});
var isNotNullish = (value) => {
return value !== null && value !== void 0;
};
// src/core/config.ts
import { Faker, ko } from "@faker-js/faker";
var MIN_STRING_LENGTH = 3;
var MAX_STRING_LENGTH = 20;
var MIN_INTEGER = 1;
var MAX_INTEGER = 1e5;
var MIN_NUMBER = 0;
var MAX_NUMBER = 100;
var MIN_WORD_LENGTH = 0;
var MAX_WORD_LENGTH = 3;
var FAKER_SEED = 1;
var faker = new Faker({
locale: [ko]
});
faker.seed(FAKER_SEED);
// src/utils/string-utils.ts
var uuidToB64 = (uuid) => {
const uuidBuffer = Buffer.from(uuid.replace(/-/g, ""), "hex");
const base64Uuid = uuidBuffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
return base64Uuid;
};
// src/utils/code-utils.ts
var toTypeScriptCode = (param, options) => {
const { depth = 0, isStatic } = options;
const prefixSpace = " ".repeat(depth * 2);
if (param === null) {
return "null";
}
if (Array.isArray(param)) {
const results = param.map((elem) => toTypeScriptCode(elem, __spreadProps(__spreadValues({}, options), { depth: depth + 1 }))).join(",\n" + prefixSpace);
return ["[", results, "]"].join("\n" + prefixSpace);
}
if (typeof param === "object") {
const results = Object.entries(param).map(([key, value]) => {
return generateObjectProperty(key, value, options, prefixSpace);
}).join("\n" + prefixSpace);
return ["{", `${results}`, "}"].join("\n" + prefixSpace);
}
if (typeof param === "string") {
if (isStatic === false && (param.startsWith("faker") || param.startsWith("Buffer.from(faker"))) {
return param;
}
if (param.endsWith(" as const")) {
return `"${param.slice(0, -" as const".length)}" as const`;
}
}
return JSON.stringify(param);
};
var shouldApplyNullableExtension = (value, isOptional) => {
if (!isOptional)
return false;
if (value === null)
return true;
if (typeof value === "string" && value.includes(",null")) {
return true;
}
return false;
};
var generateObjectProperty = (key, value, options, prefixSpace) => {
const { isOptional, depth = 0 } = options;
const shouldApplyNullable = shouldApplyNullableExtension(value, isOptional);
const nullableTypeExtensionStart = shouldApplyNullable ? `...(faker.datatype.boolean() ? {
${prefixSpace}` : "";
const nullableTypeExtensionEnd = shouldApplyNullable ? `
${prefixSpace}} : {})` : "";
const propertyValue = toTypeScriptCode(value, __spreadProps(__spreadValues({}, options), {
depth: depth + 1
}));
return `${nullableTypeExtensionStart}${prefixSpace}${key}: ${propertyValue}${nullableTypeExtensionEnd},`;
};
var compressCode = (code) => {
return code.replace(/\n/g, " ").replace(/\s+/g, " ").replace(/\s\./g, ".").trim();
};
// src/utils/array-utils.ts
var getRandomLengthArray = (min = 1, max = 3) => {
const length = faker.number.int({ min, max });
return Array.from({ length }, (_, i) => i);
};
// src/utils/file-utils.ts
import { existsSync, mkdirSync, writeFileSync, rmSync, readdirSync, readFileSync } from "fs";
import * as path from "path";
var readJsonFile = (filePath, defaultValue) => {
if (!existsSync(filePath)) {
return defaultValue;
}
try {
const content = readFileSync(filePath, "utf-8");
return JSON.parse(content);
} catch (error) {
console.warn(`Failed to read JSON file ${filePath}:`, error);
return defaultValue;
}
};
var resolveFilePath = (inputPath, baseDir) => {
if (inputPath.startsWith("http")) {
return inputPath;
}
if (baseDir) {
return path.join(baseDir, inputPath);
}
return inputPath;
};
// src/parsers/openapi-parser.ts
import SwaggerParser from "@apidevtools/swagger-parser";
var getOpenAPIDocsBundle = (path2) => __async(void 0, null, function* () {
const doc = yield SwaggerParser.bundle(path2);
const isOpenApiV3 = "openapi" in doc && doc.openapi.startsWith("3");
if (isOpenApiV3)
return doc;
return void 0;
});
// src/parsers/schema-parser.ts
import { pascalCase } from "change-case-all";
import { isReference } from "oazapfts/generate";
var parseSchema = (schemaValue, specialSchema, options, outputSchema = {}) => {
if (isReference(schemaValue)) {
console.warn("can't parse reference schema", schemaValue, schemaValue.$ref);
return;
}
if (schemaValue.type === "object") {
if (schemaValue.properties === void 0)
return {};
return Object.entries(schemaValue.properties).reduce((acc, [key, field]) => {
acc[key] = parseSchema(field, specialSchema, options, outputSchema);
return acc;
}, {});
} else if (schemaValue.enum !== void 0) {
const enumValue = options.isStatic ? faker.helpers.arrayElement(schemaValue.enum) : `faker.helpers.arrayElement<${schemaValue.enum.map((item) => `"${item}"`).join(" | ")}>(${toTypeScriptCode(schemaValue.enum, __spreadValues({
depth: 0
}, options))})`;
if (options.isStatic && typeof enumValue === "string")
return enumValue + " as const";
return enumValue;
} else if (schemaValue.allOf !== void 0) {
const allOfValue = schemaValue.allOf;
return faker.helpers.arrayElement(
allOfValue.map((field) => {
return parseSchema(field, specialSchema, options, outputSchema);
})
);
} else if (schemaValue.anyOf !== void 0) {
const anyOfValue = schemaValue.anyOf;
return options.isStatic ? faker.helpers.arrayElement(
anyOfValue.map((field) => {
return parseSchema(field, specialSchema, options, outputSchema);
})
) : compressCode(
`
faker.helpers.arrayElement([
${anyOfValue.map(
(field) => toTypeScriptCode(parseSchema(field, specialSchema, options, {}), __spreadValues({
depth: 0
}, options))
)}
])
`
);
} else if (schemaValue.oneOf !== void 0) {
const oneOfValue = schemaValue.oneOf;
return options.isStatic ? faker.helpers.arrayElement(
oneOfValue.map((field) => {
return parseSchema(field, specialSchema, options, outputSchema);
})
) : compressCode(
`
faker.helpers.arrayElement([
${oneOfValue.map(
(field) => toTypeScriptCode(parseSchema(field, specialSchema, options, {}), __spreadValues({
depth: 0
}, options))
)}
])
`
);
} else if (schemaValue.type === "array") {
if ("prefixItems" in schemaValue) {
const length = faker.number.int({
min: schemaValue.minItems,
max: schemaValue.maxItems
});
return schemaValue.prefixItems.slice(0, length).map((field) => parseSchema(field, specialSchema, options, outputSchema));
}
const arrayValue = schemaValue.items;
return getRandomLengthArray(options.arrayMinLength, options.arrayMaxLength).map(
() => parseSchema(arrayValue, specialSchema, options, outputSchema)
);
}
return valueGenerator(schemaValue, specialSchema, options);
};
var valueGenerator = (schemaValue, specialSchema, options) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
const { isStatic } = options;
const { titleSpecial, descriptionSpecial } = specialSchema;
if (schemaValue.title && titleSpecial[schemaValue.title]) {
return titleSpecial[schemaValue.title];
} else if (schemaValue.description && descriptionSpecial[schemaValue.description]) {
return descriptionSpecial[schemaValue.description];
}
if (schemaValue.type === "string" && schemaValue.format === "date-time") {
return isStatic ? faker.date.between({
from: "2020-01-01T00:00:00.000Z",
to: "2030-12-31T23:59:59.999Z"
}).toISOString() : compressCode(
`
faker.date.between({
from: "2020-01-01T00:00:00.000Z",
to: "2030-12-31T23:59:59.999Z",
})
.toISOString()
`
);
} else if (schemaValue.type === "string" && schemaValue.format === "date") {
return isStatic ? faker.date.between({
from: "2020-01-01T00:00:00.000Z",
to: "2030-12-31T23:59:59.999Z"
}).toISOString().split("T")[0] : compressCode(
`
faker.date.between({
from: "2020-01-01T00:00:00.000Z",
to: "2030-12-31T23:59:59.999Z",
})
.toISOString()
.split("T")[0]
`
);
} else if (schemaValue.type === "string" && schemaValue.pattern) {
return isStatic ? faker.helpers.fromRegExp(schemaValue.pattern) : `faker.helpers.fromRegExp(/${schemaValue.pattern}/)`;
} else if (schemaValue.type === "string" && ((_a = schemaValue.title) == null ? void 0 : _a.toLowerCase()) === "b64uuid") {
const baseUuid = faker.string.uuid();
return isStatic ? uuidToB64(baseUuid) : compressCode(
`
Buffer.from(faker.string.uuid().replace(/-/g, ""), "hex")
.toString("base64")
.replace(/\\+/g, "-")
.replace(/\\//g, "_")
.replace(/=/g, "")
`
);
} else if (schemaValue.type === "string") {
const minLength = (_c = schemaValue.minLength) != null ? _c : Math.min(MIN_STRING_LENGTH, (_b = schemaValue.maxLength) != null ? _b : MAX_STRING_LENGTH);
const maxLength = (_e = schemaValue.maxLength) != null ? _e : Math.max(MAX_STRING_LENGTH, (_d = schemaValue.minLength) != null ? _d : MIN_STRING_LENGTH);
return isStatic ? faker.string.alphanumeric({
length: { min: minLength, max: maxLength }
}) : compressCode(
`
faker.string.alphanumeric({
length: { min: ${minLength}, max: ${maxLength} },
})
`
);
} else if (schemaValue.type === "integer") {
return isStatic ? faker.number.int({ min: MIN_INTEGER, max: MAX_INTEGER }) : compressCode(
`
faker.number.int({ min: ${MIN_INTEGER}, max: ${MAX_INTEGER} })
`
);
} else if (schemaValue.type === "number") {
const minNumber = (_g = schemaValue.minimum) != null ? _g : Math.min(MIN_NUMBER, (_f = schemaValue.maximum) != null ? _f : MAX_NUMBER);
const maxNumber = (_i = schemaValue.maximum) != null ? _i : Math.max(MAX_NUMBER, (_h = schemaValue.minimum) != null ? _h : MIN_NUMBER);
return isStatic ? faker.number.float({
min: minNumber,
max: maxNumber,
fractionDigits: 2
}) : compressCode(
`
faker.number.float({
min: ${minNumber},
max: ${maxNumber},
fractionDigits: 2,
})
`
);
} else if (schemaValue.type === "boolean") {
return isStatic ? faker.datatype.boolean() : "faker.datatype.boolean()";
} else if (schemaValue.type === "null") {
return null;
} else if (Object.keys(schemaValue).length === 0) {
return isStatic ? faker.word.words({
count: {
min: MIN_WORD_LENGTH,
max: MAX_WORD_LENGTH
}
}) : compressCode(
`
faker.word.words({
count: {
min: ${MIN_WORD_LENGTH},
max: ${MAX_WORD_LENGTH},
},
})
`
);
}
return isStatic ? faker.word.adjective() : "faker.word.adjective()";
};
// src/parsers/faker-parser.ts
import { join as join2 } from "path";
var specialFakerParser = (options) => {
var _a, _b;
if (options.specialPath === void 0)
return {
titleSpecial: {},
descriptionSpecial: {}
};
const titlePath = join2((_a = options.baseDir) != null ? _a : "", options.specialPath, "titles.json");
const descPath = join2((_b = options.baseDir) != null ? _b : "", options.specialPath, "descriptions.json");
const titleSpecialKey = readJsonFile(titlePath, {});
const descriptionSpecialKey = readJsonFile(descPath, {});
const titleSpecial = Object.entries(titleSpecialKey).reduce((acc, [key, value]) => {
const fakerValue = getFakerValue(value, options);
acc[key] = fakerValue;
return acc;
}, {});
const descriptionSpecial = Object.entries(descriptionSpecialKey).reduce((acc, [key, value]) => {
const fakerValue = getFakerValue(value, options);
acc[key] = fakerValue;
return acc;
}, {});
return { titleSpecial, descriptionSpecial };
};
var getFakerValue = (value, options) => {
if ("value" in value) {
return value.value;
}
if ("module" in value && "type" in value) {
if (options.isStatic === false) {
const fakerOption = "options" in value ? toTypeScriptCode(value.options, __spreadValues({
depth: 0
}, options)) : "";
return `faker.${value.module}.${value.type}(${fakerOption})`;
}
const fakerModule = faker[value.module];
if (fakerModule === void 0) {
console.warn("can't find faker module", fakerModule);
return void 0;
}
const fakerFunc = fakerModule[value.type];
if (fakerFunc === void 0 || typeof fakerFunc !== "function") {
console.warn("can't find faker function", fakerFunc);
return void 0;
}
return "options" in value ? fakerFunc(value.options) : fakerFunc();
}
return void 0;
};
// src/generators/api-generator.ts
import { isReference as isReference2 } from "oazapfts/generate";
var generateAPI = (options) => __async(void 0, null, function* () {
const openapiPath = resolveFilePath(options.path, options.baseDir);
const doc = yield getOpenAPIDocsBundle(openapiPath);
const samplePaths = doc == null ? void 0 : doc.paths;
if (samplePaths === void 0) {
console.warn("No paths found");
return void 0;
}
const specialFakers = specialFakerParser(options);
const normalizedPaths = Object.entries(samplePaths).reduce((acc, [apiName, api]) => {
if (api === void 0)
return acc;
const paths = Object.values(HttpMethods).map((method) => {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (api[method] === void 0)
return void 0;
const responses = Object.entries((_b = (_a = api[method]) == null ? void 0 : _a.responses) != null ? _b : []).map(([statusCode, response]) => {
var _a2, _b2, _c2;
if (isReference2(response))
return void 0;
if (options.includeCodes && !options.includeCodes.includes(parseInt(statusCode)))
return void 0;
const schema = (_c2 = (_b2 = (_a2 = response.content) == null ? void 0 : _a2["application/json"]) == null ? void 0 : _b2.schema) != null ? _c2 : {};
const compositeSchema = createCompositeSchema(schema, specialFakers, options);
return {
statusCode: parseInt(statusCode),
description: response.description,
schema: compositeSchema
};
}).filter(isNotNullish);
return {
pathname: apiName.replace(/{/g, ":").replace(/}/g, ""),
operationId: (_d = (_c = api[method]) == null ? void 0 : _c.operationId) != null ? _d : "",
summary: (_f = (_e = api[method]) == null ? void 0 : _e.summary) != null ? _f : "",
tags: (_h = (_g = api[method]) == null ? void 0 : _g.tags) != null ? _h : ["default"],
method,
responses
};
}).filter(isNotNullish);
return [...acc, ...paths];
}, []);
return normalizedPaths;
});
var createCompositeSchema = (schema, specialFakers, options) => {
if ("oneOf" in schema) {
return {
type: "oneOf",
value: schema
};
}
if ("anyOf" in schema) {
return {
type: "anyOf",
value: schema
};
}
if ("type" in schema && "items" in schema && schema.type === "array") {
return {
type: "array",
value: schema.items
};
}
if (isReference2(schema)) {
return { type: "ref", value: schema };
}
if (Object.keys(schema).length === 0) {
return void 0;
}
return parseSchema(schema != null ? schema : {}, specialFakers, options, {});
};
var extractUniqueTags = (paths) => {
return Array.from(new Set(paths.map((path2) => path2.tags[0])));
};
var filterPathsByTag = (paths, tag) => {
return paths.filter((path2) => path2.tags.includes(tag));
};
var groupPathsByMethod = (paths) => {
return paths.reduce((acc, path2) => {
if (!acc[path2.method]) {
acc[path2.method] = [];
}
acc[path2.method].push(path2);
return acc;
}, {});
};
var extractSchemaReferences = (paths) => {
const refs = /* @__PURE__ */ new Set();
paths.forEach((path2) => {
path2.responses.forEach((response) => {
var _a;
if (((_a = response.schema) == null ? void 0 : _a.type) === "ref") {
refs.add(response.schema.value.$ref);
}
});
});
return Array.from(refs);
};
export {
extractSchemaReferences,
extractUniqueTags,
filterPathsByTag,
generateAPI,
groupPathsByMethod
};
//# sourceMappingURL=api-generator.mjs.map