UNPKG

openapi-ts-mock-generator

Version:
1,067 lines 97.6 kB
#!/usr/bin/env node "use strict"; function _array_like_to_array(arr, len) { if (len == null || len > arr.length) len = arr.length; for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; return arr2; } function _array_with_holes(arr) { if (Array.isArray(arr)) return arr; } function _array_without_holes(arr) { if (Array.isArray(arr)) return _array_like_to_array(arr); } function _assert_this_initialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _class_call_check(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _construct(Parent, args, Class) { if (_is_native_reflect_construct()) { _construct = Reflect.construct; } else { _construct = function construct(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _set_prototype_of(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _defineProperties(target, props) { for(var i = 0; i < props.length; i++){ var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _create_class(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _define_property(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _get_prototype_of(o) { _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _get_prototype_of(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _set_prototype_of(subClass, superClass); } function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } function _is_native_function(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _iterable_to_array(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _iterable_to_array_limit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){ _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally{ try { if (!_n && _i["return"] != null) _i["return"](); } finally{ if (_d) throw _e; } } return _arr; } function _non_iterable_rest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _non_iterable_spread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _object_spread(target) { for(var i = 1; i < arguments.length; i++){ var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _define_property(target, key, source[key]); }); } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function(sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _object_spread_props(target, source) { source = source != null ? source : {}; if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function(key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _possible_constructor_return(self, call) { if (call && (_type_of(call) === "object" || typeof call === "function")) { return call; } return _assert_this_initialized(self); } function _set_prototype_of(o, p) { _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _set_prototype_of(o, p); } function _sliced_to_array(arr, i) { return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest(); } function _to_consumable_array(arr) { return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread(); } function _type_of(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } function _unsupported_iterable_to_array(o, minLen) { if (!o) return; if (typeof o === "string") return _array_like_to_array(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); } function _wrap_native_super(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrap_native_super = function wrapNativeSuper(Class) { if (Class === null || !_is_native_function(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _get_prototype_of(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _set_prototype_of(Wrapper, Class); }; return _wrap_native_super(Class); } function _is_native_reflect_construct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); return true; } catch (e) { return false; } } function _create_super(Derived) { var hasNativeReflectConstruct = _is_native_reflect_construct(); return function _createSuperInternal() { var Super = _get_prototype_of(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _get_prototype_of(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possible_constructor_return(this, result); }; } function _ts_generator(thisArg, body) { var f, y, t, g, _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([ n, v ]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while(_)try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [ op[0] & 2, t.value ]; switch(op[0]){ case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [ 0 ]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [ 6, e ]; y = 0; } finally{ f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = function(to, from, except, desc) { if (from && typeof from === "object" || typeof from === "function") { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { var _loop = function() { var key = _step.value; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: function() { return from[key]; }, enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); }; for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } } } return to; }; var __toESM = function(mod, isNodeMode, target) { return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod); }; // src/defaults.ts var import_faker = require("@faker-js/faker"); var ARRAY_MIN_LENGTH = 1; var ARRAY_MAX_LENGTH = 3; 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 import_faker.Faker({ locale: [ import_faker.ko ] }); faker.seed(FAKER_SEED); var GEN_COMMENT = "/* Do not edit this file. */\n/* This file generated by openapi-ts-mock-generator. */\n\n"; // src/writer.ts var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser")); var import_change_case_all = require("change-case-all"); var import_fs = require("fs"); var import_generate = require("oazapfts/generate"); var path = __toESM(require("path")); var writeHandlers = function(paths, options) { var firstTags = Array.from(new Set(paths.map(function(path3) { return path3.tags[0]; }))); var handlersPerTag = firstTags.reduce(function(acc, tag) { acc[tag] = []; return acc; }, {}); paths.forEach(function(path3) { var codeBaseArray = [ " http.".concat(path3.method, "(`${handlerUrl}").concat(path3.pathname, "`, () => {") ]; if (path3.responses.length === 1) { var _res_schema; var res = path3.responses[0]; if (((_res_schema = res.schema) === null || _res_schema === void 0 ? void 0 : _res_schema.type) === "ref") { var schemaName = (0, import_change_case_all.pascalCase)(res.schema.value.$ref.replace("#/components/schemas/", "")); codeBaseArray.push(" // Schema is ".concat(schemaName)); } var outputResName = "get".concat((0, import_change_case_all.pascalCase)(path3.operationId)).concat(res.statusCode); codeBaseArray.push(" return HttpResponse.json(".concat(outputResName, "(), {")); codeBaseArray.push(" status: ".concat(res.statusCode, ",")); codeBaseArray.push(" })"); } else if (path3.responses.length > 1) { codeBaseArray.push(" const responses = ["); path3.responses.forEach(function(res) { var _res_schema; var schemaName = ((_res_schema = res.schema) === null || _res_schema === void 0 ? void 0 : _res_schema.type) === "ref" ? (0, import_change_case_all.pascalCase)(res.schema.value.$ref.replace("#/components/schemas/", "")) : ""; var schemaComment = schemaName ? " // Schema is ".concat(schemaName) : ""; var outputResName = "get".concat((0, import_change_case_all.pascalCase)(path3.operationId)).concat(res.statusCode); codeBaseArray.push(" [".concat(outputResName, "(), { status: ").concat(res.statusCode, " }],").concat(schemaComment)); return outputResName; }); codeBaseArray.push(" ]"); codeBaseArray.push(" const randomIndex = Math.floor(Math.random() * responses.length)"); codeBaseArray.push(" return HttpResponse.json(...responses[randomIndex])"); } else { codeBaseArray.push(" return HttpResponse.json()"); } codeBaseArray.push(" }),"); var handler = codeBaseArray.join("\n"); handlersPerTag[path3.tags[0]].push(handler); }); Object.entries(handlersPerTag).forEach(function(param) { var _param = _sliced_to_array(param, 2), tag = _param[0], handlers = _param[1]; var importMSW = "import { http, HttpResponse } from 'msw'"; var responseNames = handlers.reduce(function(acc, handler) { var matched = handler.match(/get[A-Z]\w+/g); if (matched === null) return acc; return _to_consumable_array(acc).concat(_to_consumable_array(matched)); }, []).join(", "); var importResponses = responseNames.length > 0 ? "import { ".concat(responseNames, ' } from "../response"\n') : ""; var handlerUrl = 'const handlerUrl = "'.concat(options.handlerUrl, '"'); var handlerName = (0, import_change_case_all.camelCase)(tag); var mockHandlers2 = [ "".concat(importMSW), "".concat(importResponses), "".concat(handlerUrl), "", "export const ".concat(handlerName, "Handlers = ["), "".concat(handlers.join("\n\n")), "]" ].join("\n"); var _options_baseDir; var directory = path.join((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : "", "handlers"); if (!(0, import_fs.existsSync)(directory)) { (0, import_fs.mkdirSync)(directory, { recursive: true }); } else if (options.clear) { (0, import_fs.readdirSync)(directory).forEach(function(file) { (0, import_fs.rmSync)(path.join(directory, file)); }); } var fileName2 = path.join(directory, "".concat(tag, ".ts")); (0, import_fs.writeFileSync)(fileName2, GEN_COMMENT + mockHandlers2); console.log("Generated Handler ".concat(fileName2)); }); var handlersImport = Object.keys(handlersPerTag).map(function(tag) { var handlerName = "".concat((0, import_change_case_all.camelCase)(tag), "Handlers"); return "import { ".concat(handlerName, ' } from "./handlers/').concat(tag, '"'); }).join("\n"); var handlersArrayItem = Object.keys(handlersPerTag).map(function(tag) { var handlerName = "".concat((0, import_change_case_all.camelCase)(tag), "Handlers"); return " ...".concat(handlerName, ","); }).join("\n"); var mockHandlers = [ "".concat(handlersImport), "", "export const handlers = [", "".concat(handlersArrayItem), "]" ].join("\n"); var _options_baseDir; var fileName = path.join((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : "", "mockHandlers.ts"); (0, import_fs.writeFileSync)(fileName, GEN_COMMENT + mockHandlers); console.log("Generated mock handlers ".concat(fileName)); }; var writeResponses = function() { var _ref = _async_to_generator(function(paths, options) { var parser, _options_baseDir, openapiPath, refs, firstTags, codeBasePerTag, specialFakers, _options_baseDir1, directory, importResponses, fileName; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: parser = new import_swagger_parser.default(); openapiPath = options.path.startsWith("http") ? options.path : path.join((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : "", options.path); return [ 4, parser.dereference(openapiPath) ]; case 1: _state.sent(); refs = parser.$refs; firstTags = Array.from(new Set(paths.map(function(path3) { return path3.tags[0]; }))); codeBasePerTag = firstTags.reduce(function(acc, tag) { acc[tag] = []; return acc; }, {}); specialFakers = specialFakerParser(options); paths.forEach(function(path3) { var pathResponses = path3.responses.map(function(res) { var _res_schema, _res_schema1, _res_schema2; var codeBaseArray = [ "export const get".concat((0, import_change_case_all.pascalCase)(path3.operationId)).concat(res.statusCode, " = () => {") ]; if (((_res_schema = res.schema) === null || _res_schema === void 0 ? void 0 : _res_schema.type) === "ref") { var _refSchemaParser = refSchemaParser(res.schema.value.$ref, refs), name = _refSchemaParser.name, value = _refSchemaParser.value; var outputSchema = parseSchema(value, specialFakers, options); codeBaseArray.push(" // Schema is ".concat(name)); codeBaseArray.push(" return ".concat(toUnquotedJSON(outputSchema, { depth: 1, isStatic: options.isStatic }))); } else if (((_res_schema1 = res.schema) === null || _res_schema1 === void 0 ? void 0 : _res_schema1.type) === "array") { if ((0, import_generate.isReference)(res.schema.value)) { var _refSchemaParser1 = refSchemaParser(res.schema.value.$ref, refs), name1 = _refSchemaParser1.name, value1 = _refSchemaParser1.value; var outputSchema1 = getRandomLengthArray(options.arrayMinLength, options.arrayMaxLength).map(function() { return parseSchema(value1, specialFakers, options); }); codeBaseArray.push(" // Schema is ".concat(name1, " array")); codeBaseArray.push(" return ".concat(toUnquotedJSON(outputSchema1, { depth: 1, isStatic: options.isStatic }))); } else { var outputSchema2 = getRandomLengthArray(options.arrayMinLength, options.arrayMaxLength).map(function() { return res.schema && parseSchema(res.schema.value, specialFakers, options); }); codeBaseArray.push(" return ".concat(toUnquotedJSON(outputSchema2, { depth: 1, isStatic: options.isStatic }))); } } else if (((_res_schema2 = res.schema) === null || _res_schema2 === void 0 ? void 0 : _res_schema2.type) === "anyOf") { var _res_schema_value_anyOf; var firstSchema = (_res_schema_value_anyOf = res.schema.value.anyOf) === null || _res_schema_value_anyOf === void 0 ? void 0 : _res_schema_value_anyOf[0]; if ((0, import_generate.isReference)(firstSchema)) { var _refSchemaParser2 = refSchemaParser(firstSchema.$ref, refs), name2 = _refSchemaParser2.name, value2 = _refSchemaParser2.value; var outputSchema3 = parseSchema(value2, specialFakers, options); codeBaseArray.push(" // Schema is ".concat(name2)); codeBaseArray.push(" return ".concat(toUnquotedJSON(outputSchema3, { depth: 1, isStatic: options.isStatic }))); } else { codeBaseArray.push(" return ".concat(res.schema.value)); } } else { var _res_schema3; codeBaseArray.push(" return ".concat((_res_schema3 = res.schema) === null || _res_schema3 === void 0 ? void 0 : _res_schema3.value)); } return _to_consumable_array(codeBaseArray).concat([ "}" ]).join("\n"); }); var pathResponsesWithComment = "// ".concat(path3.operationId, "\n") + pathResponses.join("\n\n"); codeBasePerTag[path3.tags[0]].push(pathResponsesWithComment); }); directory = path.join((_options_baseDir1 = options.baseDir) !== null && _options_baseDir1 !== void 0 ? _options_baseDir1 : "", "response"); if (!(0, import_fs.existsSync)(directory)) { (0, import_fs.mkdirSync)(directory, { recursive: true }); } else if (options.clear) { (0, import_fs.readdirSync)(directory).forEach(function(file) { (0, import_fs.rmSync)(path.join(directory, file)); }); } Object.entries(codeBasePerTag).forEach(function(param) { var _param = _sliced_to_array(param, 2), tag = _param[0], responses = _param[1]; var needImportFaker = responses.some(function(res) { return res.includes("faker."); }); var importFaker = options.isStatic || !needImportFaker ? "" : 'import { faker } from "../fakers"\n\n'; var fileName2 = "".concat(directory, "/").concat(tag, ".ts"); (0, import_fs.writeFileSync)(fileName2, GEN_COMMENT + importFaker + responses.join("\n\n")); console.log("Generated ".concat(fileName2)); }); importResponses = Object.entries(codeBasePerTag).map(function(param) { var _param = _sliced_to_array(param, 2), tag = _param[0], responses = _param[1]; var responseNames = responses.reduce(function(acc, handler) { var matched = handler.match(/get[A-Z]\w+/g); if (matched === null) return acc; return _to_consumable_array(acc).concat(_to_consumable_array(matched)); }, []).join(",\n "); return [ "export {", " " + responseNames, '} from "./' + tag + '"' ].join("\n"); }); fileName = "".concat(directory, "/index.ts"); (0, import_fs.writeFileSync)(fileName, GEN_COMMENT + importResponses.join("\n")); console.log("Generated ".concat(fileName)); return [ 2 ]; } }); }); return function writeResponses(paths, options) { return _ref.apply(this, arguments); }; }(); var writeSchema = function(schemas, options) { var generatedVars = Object.entries(schemas).map(function(param) { var _param = _sliced_to_array(param, 2), varName = _param[0], varValue = _param[1]; return "export const ".concat(varName, "Mock = ").concat(toUnquotedJSON(varValue, { isStatic: options.isStatic })); }).join("\n\n"); var importFaker = options.isStatic ? "" : 'import { faker } from "./fakers"\n\n'; var outputFileName = path.join("".concat(options.baseDir), "schemas.ts"); (0, import_fs.writeFileSync)(outputFileName, GEN_COMMENT + importFaker + generatedVars); console.log("Generated schema ".concat(outputFileName)); }; var writeFaker = function(options) { var _options_baseDir; var directory = path.join((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : ""); if (!(0, import_fs.existsSync)(directory)) { (0, import_fs.mkdirSync)(directory, { recursive: true }); } var localeOption = options.fakerLocale.replace(",", ", "); var importFaker = "import { Faker, ".concat(localeOption, ' } from "@faker-js/faker"\n\n'); var fakerDeclare = [ "export const faker = new Faker({", " locale: [".concat(localeOption, "]"), "})" ].join("\n"); var outputFileName = path.join("".concat(options.baseDir), "fakers.ts"); (0, import_fs.writeFileSync)(outputFileName, GEN_COMMENT + importFaker + fakerDeclare); console.log("Generated fakers ".concat(outputFileName)); }; var toUnquotedJSON = function(param, options) { var _$_object_spread = _object_spread({ depth: 0, isStatic: false, singleLine: false }, options), depth = _$_object_spread.depth, isStatic = _$_object_spread.isStatic, singleLine = _$_object_spread.singleLine; var prefixSpace = " ".repeat(depth * 2); var lineBreak = singleLine ? "" : "\n"; if (param === null) { return "null"; } else if (Array.isArray(param)) { var results = param.map(function(elem) { return toUnquotedJSON(elem, _object_spread_props(_object_spread({}, options), { depth: depth + 1 })); }); var firstElementSpace = singleLine ? "" : " "; return [ "[", firstElementSpace + results.join(", "), "]" ].join(lineBreak + prefixSpace); } else if (typeof param === "object") { var firstElementSpace1 = singleLine ? " " : " "; var lastComma = singleLine ? ", " : ","; var results1 = Object.entries(param).map(function(param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; return "".concat(firstElementSpace1).concat(key, ": ").concat(toUnquotedJSON(value, _object_spread_props(_object_spread({}, options), { depth: depth + 1 }))).concat(lastComma); }).join(lineBreak + prefixSpace); return [ "{", "".concat(results1), "}" ].join(lineBreak + prefixSpace); } else if (typeof param === "string" && isStatic === false && (param.startsWith("faker") || param.startsWith("Buffer.from(faker"))) { return param; } else if (typeof param === "string" && param.endsWith(" as const")) { return '"'.concat(param.slice(0, -" as const".length), '" as const'); } return JSON.stringify(param); }; var multiLineStr = function(str) { return str.replace(/\n/g, " ").replace(/\s+/g, " ").replace(/\s\./g, ".").trim(); }; // src/parser.ts var import_change_case_all2 = require("change-case-all"); var import_fs2 = require("fs"); var import_generate2 = require("oazapfts/generate"); var import_path = require("path"); var parseSchema = function(schemaValue, specialSchema, options) { var outputSchema = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; if ((0, import_generate2.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(function(acc, param) { var _param = _sliced_to_array(param, 2), key = _param[0], field = _param[1]; acc[key] = parseSchema(field, specialSchema, options, outputSchema); return acc; }, {}); } else if (schemaValue.enum !== void 0) { var enumValue = options.isStatic ? faker.helpers.arrayElement(schemaValue.enum) : "faker.helpers.arrayElement<".concat(schemaValue.enum.map(function(item) { return '"'.concat(item, '"'); }).join(" | "), ">(").concat(toUnquotedJSON(schemaValue.enum, { depth: 0, isStatic: options.isStatic, singleLine: true }), ")"); if (options.isStatic && typeof enumValue === "string") return enumValue + " as const"; return enumValue; } else if (schemaValue.allOf !== void 0) { var allOfValue = schemaValue.allOf; return faker.helpers.arrayElement(allOfValue.map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); })); } else if (schemaValue.anyOf !== void 0) { var anyOfValue = schemaValue.anyOf; return options.isStatic ? faker.helpers.arrayElement(anyOfValue.map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); })) : multiLineStr("\n faker.helpers.arrayElement([\n ".concat(anyOfValue.map(function(field) { return toUnquotedJSON(parseSchema(field, specialSchema, options, {}), { depth: 0, isStatic: options.isStatic, singleLine: true }); }), "\n ])\n ")); } else if (schemaValue.oneOf !== void 0) { var oneOfValue = schemaValue.oneOf; return options.isStatic ? faker.helpers.arrayElement(oneOfValue.map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); })) : multiLineStr("\n faker.helpers.arrayElement([\n ".concat(oneOfValue.map(function(field) { return toUnquotedJSON(parseSchema(field, specialSchema, options, {}), { depth: 0, isStatic: options.isStatic, singleLine: true }); }), "\n ])\n ")); } else if (schemaValue.type === "array") { if ("prefixItems" in schemaValue) { var length = faker.number.int({ min: schemaValue.minItems, max: schemaValue.maxItems }); return schemaValue.prefixItems.slice(0, length).map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); }); } var arrayValue = schemaValue.items; return getRandomLengthArray(options.arrayMinLength, options.arrayMaxLength).map(function() { return parseSchema(arrayValue, specialSchema, options, outputSchema); }); } return valueGenerator(schemaValue, specialSchema, options.isStatic); }; var uuidToB64 = function(uuid) { var uuidBuffer = Buffer.from(uuid.replace(/-/g, ""), "hex"); var base64Uuid = uuidBuffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); return base64Uuid; }; var valueGenerator = function(schemaValue, specialSchema, isStatic) { var _schemaValue_title; var titleSpecial = specialSchema.titleSpecial, descriptionSpecial = specialSchema.descriptionSpecial; 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() : multiLineStr('\n faker.date.between({\n from: "2020-01-01T00:00:00.000Z",\n to: "2030-12-31T23:59:59.999Z",\n })\n .toISOString()\n '); } 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] : multiLineStr('\n faker.date.between({\n from: "2020-01-01T00:00:00.000Z",\n to: "2030-12-31T23:59:59.999Z",\n })\n .toISOString()\n .split("T")[0]\n '); } else if (schemaValue.type === "string" && schemaValue.pattern) { return isStatic ? faker.helpers.fromRegExp(schemaValue.pattern) : "faker.helpers.fromRegExp(/".concat(schemaValue.pattern, "/)"); } else if (schemaValue.type === "string" && ((_schemaValue_title = schemaValue.title) === null || _schemaValue_title === void 0 ? void 0 : _schemaValue_title.toLowerCase()) === "b64uuid") { var baseUuid = faker.string.uuid(); return isStatic ? uuidToB64(baseUuid) : multiLineStr('\n Buffer.from(faker.string.uuid().replace(/-/g, ""), "hex")\n .toString("base64")\n .replace(/\\+/g, "-")\n .replace(/\\//g, "_")\n .replace(/=/g, "")\n '); } else if (schemaValue.type === "string") { var _schemaValue_maxLength, _schemaValue_minLength; var minLength = (_schemaValue_minLength = schemaValue.minLength) !== null && _schemaValue_minLength !== void 0 ? _schemaValue_minLength : Math.min(MIN_STRING_LENGTH, (_schemaValue_maxLength = schemaValue.maxLength) !== null && _schemaValue_maxLength !== void 0 ? _schemaValue_maxLength : MAX_STRING_LENGTH); var _schemaValue_minLength1, _schemaValue_maxLength1; var maxLength = (_schemaValue_maxLength1 = schemaValue.maxLength) !== null && _schemaValue_maxLength1 !== void 0 ? _schemaValue_maxLength1 : Math.max(MAX_STRING_LENGTH, (_schemaValue_minLength1 = schemaValue.minLength) !== null && _schemaValue_minLength1 !== void 0 ? _schemaValue_minLength1 : MIN_STRING_LENGTH); return isStatic ? faker.string.alphanumeric({ length: { min: minLength, max: maxLength } }) : multiLineStr("\n faker.string.alphanumeric({\n length: { min: ".concat(minLength, ", max: ").concat(maxLength, " },\n })\n ")); } else if (schemaValue.type === "integer") { return isStatic ? faker.number.int({ min: MIN_INTEGER, max: MAX_INTEGER }) : multiLineStr("\n faker.number.int({ min: ".concat(MIN_INTEGER, ", max: ").concat(MAX_INTEGER, " })\n ")); } else if (schemaValue.type === "number") { var _schemaValue_maximum, _schemaValue_minimum; var minNumber = (_schemaValue_minimum = schemaValue.minimum) !== null && _schemaValue_minimum !== void 0 ? _schemaValue_minimum : Math.min(MIN_NUMBER, (_schemaValue_maximum = schemaValue.maximum) !== null && _schemaValue_maximum !== void 0 ? _schemaValue_maximum : MAX_NUMBER); var _schemaValue_minimum1, _schemaValue_maximum1; var maxNumber = (_schemaValue_maximum1 = schemaValue.maximum) !== null && _schemaValue_maximum1 !== void 0 ? _schemaValue_maximum1 : Math.max(MAX_NUMBER, (_schemaValue_minimum1 = schemaValue.minimum) !== null && _schemaValue_minimum1 !== void 0 ? _schemaValue_minimum1 : MIN_NUMBER); return isStatic ? faker.number.float({ min: minNumber, max: maxNumber, fractionDigits: 2 }) : multiLineStr("\n faker.number.float({\n min: ".concat(minNumber, ",\n max: ").concat(maxNumber, ",\n fractionDigits: 2,\n })\n ")); } 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 } }) : multiLineStr("\n faker.word.words({\n count: {\n min: ".concat(MIN_WORD_LENGTH, ",\n max: ").concat(MAX_WORD_LENGTH, ",\n },\n })\n ")); } return isStatic ? faker.word.adjective() : "faker.word.adjective()"; }; var getRandomLengthArray = function() { var min = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ARRAY_MIN_LENGTH, max = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ARRAY_MAX_LENGTH; var length = faker.number.int({ min: min, max: max }); return Array.from({ length: length }, function(_, i) { return i; }); }; var refSchemaParser = function(ref, refs) { var schemaName = (0, import_change_case_all2.pascalCase)(ref.replace("#/components/schemas/", "")); var schemaValue = refs.get(ref); return { name: schemaName, value: schemaValue }; }; var getFakerValue = function(value, options) { if ("value" in value) { return value.value; } if ("module" in value && "type" in value) { if (options.isStatic === false) { var fakerOption = "options" in value ? toUnquotedJSON(value.options, { depth: 0, isStatic: options.isStatic, singleLine: true }) : ""; return "faker.".concat(value.module, ".").concat(value.type, "(").concat(fakerOption, ")"); } var fakerModule = faker[value.module]; if (fakerModule === void 0) { console.warn("can't find faker module", fakerModule); return void 0; } var 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; }; var specialFakerParser = function(options) { if (options.specialPath === void 0) return { titleSpecial: {}, descriptionSpecial: {} }; var _options_baseDir; var titlePath = (0, import_path.join)((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : "", options.specialPath, "titles.json"); var _options_baseDir1; var descPath = (0, import_path.join)((_options_baseDir1 = options.baseDir) !== null && _options_baseDir1 !== void 0 ? _options_baseDir1 : "", options.specialPath, "descriptions.json"); var titleSpecialKey = (0, import_fs2.existsSync)(titlePath) ? JSON.parse((0, import_fs2.readFileSync)(titlePath, "utf-8")) : {}; var descriptionSpecialKey = (0, import_fs2.existsSync)(descPath) ? JSON.parse((0, import_fs2.readFileSync)(descPath, "utf-8")) : {}; var titleSpecial = Object.entries(titleSpecialKey).reduce(function(acc, param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; var fakerValue = getFakerValue(value, { isStatic: options.isStatic }); acc[key] = fakerValue; return acc; }, {}); var descriptionSpecial = Object.entries(descriptionSpecialKey).reduce(function(acc, param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; var fakerValue = getFakerValue(value, { isStatic: options.isStatic }); acc[key] = fakerValue; return acc; }, {}); return { titleSpecial: titleSpecial, descriptionSpecial: descriptionSpecial }; }; // src/types.ts var HttpMethods = /* @__PURE__ */ function(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 = function(value) { return value !== null && value !== void 0; }; // src/generate.ts var import_swagger_parser2 = __toESM(require("@apidevtools/swagger-parser")); var import_generate3 = require("oazapfts/generate"); var path2 = __toESM(require("path")); var getOpenAPIDocsDeref = function() { var _ref = _async_to_generator(function(path3) { var doc, isOpenApiV3; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: return [ 4, import_swagger_parser2.default.dereference(path3) ]; case 1: doc = _state.sent(); isOpenApiV3 = "openapi" in doc && doc.openapi.startsWith("3"); if (isOpenApiV3) return [ 2, doc ]; return [ 2 ]; } }); }); return function getOpenAPIDocsDeref(path3) { return _ref.apply(this, arguments); }; }(); var getOpenAPIDocsBundle = function() { var _ref = _async_to_generator(function(path3) { var doc, isOpenApiV3; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: return [ 4, import_swagger_parser2.default.bundle(path3) ]; case 1: doc = _state.sent(); isOpenApiV3 = "openapi" in doc && doc.openapi.startsWith("3"); if (isOpenApiV3) return [ 2, doc ]; return [ 2 ]; } }); }); return function getOpenAPIDocsBundle(path3) { return _ref.apply(this, arguments); }; }(); var generateSchema = function() { var _ref = _async_to_generator(function(options) { var _doc_components, _options_baseDir, openapiPath, doc, sampleSchemas, specialFakers; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: openapiPath = options.path.startsWith("http") ? options.path : path2.join((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : "", options.path); return [ 4, getOpenAPIDocsDeref(openapiPath) ]; case 1: doc = _state.sent(); sampleSchemas = doc === null || doc === void 0 ? void 0 : (_doc_components = doc.components) === null || _doc_components === void 0 ? void 0 : _doc_components.schemas; if (sampleSchemas === void 0) { console.warn("No schemas found"); return [ 2 ]; } specialFakers = specialFakerParser(options); return [ 2, Object.entries(sampleSchemas).reduce(function(acc, param) { var _param = _sliced_to_array(param, 2), sch