UNPKG

@alexop/openapi-zod-client

Version:

[![Screenshot 2022-11-12 at 18 52 25](https://user-images.githubusercontent.com/47224540/201487856-ffc4c862-6f31-4de1-8ef1-3981fabf3416.png)](https://openapi-zod-client.vercel.app/)

1,510 lines (1,456 loc) 100 kB
'use strict'; var path = require('node:path'); var server = require('pastable/server'); var tsPattern = require('ts-pattern'); var handlebars = require('handlebars'); var prettier = require('prettier'); var parserTypescript = require('prettier/parser-typescript'); var tanu = require('tanu'); var whence = require('whence'); 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 path__default = /*#__PURE__*/_interopDefault(path); var prettier__default = /*#__PURE__*/_interopDefault(prettier); var parserTypescript__default = /*#__PURE__*/_interopDefault(parserTypescript); function _regeneratorRuntime() { _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } 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 _asyncToGenerator(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 _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _arrayLikeToArray(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 _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } var getHandlebars = function getHandlebars() { var instance = handlebars.create(); instance.registerHelper("ifeq", function (a, b, options) { if (a === b) { // @ts-expect-error return options.fn(this); } // @ts-expect-error return options.inverse(this); }); instance.registerHelper("ifNotEmptyObj", function (obj, options) { if (_typeof(obj) === "object" && Object.keys(obj).length > 0) { // @ts-expect-error return options.fn(this); } // @ts-expect-error return options.inverse(this); }); instance.registerHelper("toCamelCase", function (input) { // Check if input string is already in camelCase if (/^[a-z][a-zA-Z0-9]*$/.test(input)) { return input; } var words = input.split(/[\s_-]/); return words.map(function (word, index) { if (index === 0) { return word.toLowerCase(); } return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }).join(""); }); return instance; }; /** @see https://github.dev/stephenh/ts-poet/blob/5ea0dbb3c9f1f4b0ee51a54abb2d758102eda4a2/src/Code.ts#L231 */ function maybePretty(input, options) { try { return prettier__default["default"].format(input.trim(), _objectSpread2({ parser: "typescript", plugins: [parserTypescript__default["default"]] }, options)); } catch (_unused) { return input; // assume it's invalid syntax and ignore } } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _nonIterableRest() { 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } // taken from // https://github.dev/metadevpro/openapi3-ts/blob/a62ff445207af599f591532ef776e671c456cc37/src/model/OpenApi.ts#L261-L269 // to avoid the runtime dependency on `openapi3-ts` // which itself depends on `yaml` import (which use CJS `require` and thus can't be imported in a ESM module) /** * A type guard to check if the given value is a `ReferenceObject`. * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types * * @param obj The value to check. */ function isReferenceObject(obj) { return obj != null && Object.prototype.hasOwnProperty.call(obj, "$ref"); } var getOpenApiDependencyGraph = function getOpenApiDependencyGraph(schemaRef, getSchemaByRef) { var visitedsRefs = {}; var refsDependencyGraph = {}; var visit = function visit(schema, fromRef) { if (!schema) return; if (isReferenceObject(schema)) { if (!refsDependencyGraph[fromRef]) { refsDependencyGraph[fromRef] = new Set(); } refsDependencyGraph[fromRef].add(schema.$ref); if (visitedsRefs[schema.$ref]) return; visitedsRefs[fromRef] = true; visit(getSchemaByRef(schema.$ref), schema.$ref); return; } if (schema.allOf) { var _iterator = _createForOfIteratorHelper(schema.allOf), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var allOf = _step.value; visit(allOf, fromRef); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return; } if (schema.oneOf) { var _iterator2 = _createForOfIteratorHelper(schema.oneOf), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var oneOf = _step2.value; visit(oneOf, fromRef); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return; } if (schema.anyOf) { var _iterator3 = _createForOfIteratorHelper(schema.anyOf), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var anyOf = _step3.value; visit(anyOf, fromRef); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return; } if (schema.type === "array") { if (!schema.items) return; return void visit(schema.items, fromRef); } if (schema.type === "object" || schema.properties || schema.additionalProperties) { if (schema.properties) { for (var property in schema.properties) { visit(schema.properties[property], fromRef); } } if (schema.additionalProperties && _typeof(schema.additionalProperties) === "object") { visit(schema.additionalProperties, fromRef); } } }; schemaRef.forEach(function (ref) { return visit(getSchemaByRef(ref), ref); }); var deepDependencyGraph = {}; var visitedsDeepRefs = {}; schemaRef.forEach(function (ref) { var deps = refsDependencyGraph[ref]; if (!deps) return; if (!deepDependencyGraph[ref]) { deepDependencyGraph[ref] = new Set(); } var visit = function visit(dep) { deepDependencyGraph[ref].add(dep); if (refsDependencyGraph[dep] && ref !== dep) { refsDependencyGraph[dep].forEach(function (transitive) { if (visitedsDeepRefs[ref + "__" + transitive]) return; visitedsDeepRefs[ref + "__" + transitive] = true; visit(transitive); }); } }; deps.forEach(function (dep) { return visit(dep); }); }); return { refsDependencyGraph: refsDependencyGraph, deepDependencyGraph: deepDependencyGraph }; }; var asComponentSchema = function asComponentSchema(name) { return "#/components/schemas/".concat(name); }; function normalizeString(text) { var prefixed = prefixStringStartingWithNumberIfNeeded(text); return prefixed.normalize("NFKD") // The normalize() using NFKD method returns the Unicode Normalization Form of a given string. .trim() // Remove whitespace from both sides of a string (optional) .replace(/\s+/g, "_") // Replace spaces with _ .replace(/-+/g, "_") // Replace - with _ .replace(/[^\w\-]+/g, "_") // Remove all non-word chars .replace(/--+/g, "-"); // Replace multiple - with single - } var wrapWithQuotesIfNeeded = function wrapWithQuotesIfNeeded(str) { if (/^\w+$/.test(str)) { return str; } return "\"".concat(str, "\""); }; var prefixStringStartingWithNumberIfNeeded = function prefixStringStartingWithNumberIfNeeded(str) { var firstAsNumber = Number(str[0]); if (typeof firstAsNumber === "number" && !Number.isNaN(firstAsNumber)) { return "_" + str; } return str; }; var pathParamWithBracketsRegex = /({\w+})/g; var wordPrecededByNonWordCharacter = /[^\w\-]+/g; var pathParamToVariableName = function pathParamToVariableName(name) { // Replace all underscores with # to preserve them when doing snakeToCamel var preserveUnderscore = name.replaceAll("_", "#"); return server.snakeToCamel(preserveUnderscore.replaceAll("-", "_")).replaceAll("#", "_"); }; var matcherRegex = /{(\b\w+(?:-\w+)*\b)}/g; var replaceHyphenatedPath = function replaceHyphenatedPath(path) { var matches = path.match(matcherRegex); if (matches === null) { return path.replaceAll(matcherRegex, ":$1"); } matches.forEach(function (match) { var replacement = pathParamToVariableName(match.replaceAll(matcherRegex, ":$1")); path = path.replaceAll(match, replacement); }); return path; }; /** @example turns `/media-objects/{id}` into `MediaObjectsId` */ var pathToVariableName = function pathToVariableName(path) { return server.capitalize(server.kebabToCamel(path).replaceAll("/", "")) // /media-objects/{id} -> MediaObjects{id} .replace(pathParamWithBracketsRegex, function (group) { return server.capitalize(group.slice(1, -1)); }) // {id} -> Id .replace(wordPrecededByNonWordCharacter, "_"); }; // "/robots.txt" -> "/robots_txt" var isPrimitiveType$1 = function isPrimitiveType(type) { return primitiveTypeList$1.includes(type); }; var primitiveTypeList$1 = ["string", "number", "integer", "boolean", "null"]; var escapeControlCharacters = function escapeControlCharacters(str) { return str.replace(/\t/g, "\\t") // U+0009 .replace(/\n/g, "\\n") // U+000A .replace(/\r/g, "\\r") // U+000D .replace(/([\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uFFFE\uFFFF])/g, function (_m, p1) { var dec = p1.codePointAt(); var hex = dec.toString(16); // eslint-disable-next-line sonarjs/no-nested-template-literals if (dec <= 0xff) return "\\x".concat("00".concat(hex).slice(-2)); // eslint-disable-next-line sonarjs/no-nested-template-literals return "\\u".concat("0000".concat(hex).slice(-4)); }); }; var autocorrectRef = function autocorrectRef(ref) { return ref[1] === "/" ? ref : "#/" + ref.slice(1); }; var makeSchemaResolver = function makeSchemaResolver(doc) { // both used for debugging purpose // eslint-disable-next-line sonarjs/no-unused-collection var nameByRef = new Map(); // eslint-disable-next-line sonarjs/no-unused-collection var refByName = new Map(); var byRef = new Map(); var byNormalized = new Map(); var getSchemaByRef = function getSchemaByRef(ref) { var _get; // #components -> #/components var correctRef = autocorrectRef(ref); var split = correctRef.split("/"); // "#/components/schemas/Something.jsonld" -> #/components/schemas var path = split.slice(1, -1).join("/"); var map = (_get = server.get(doc, path.replace("#/", "").replace("#", "").replaceAll("/", "."))) !== null && _get !== void 0 ? _get : {}; // "#/components/schemas/Something.jsonld" -> "Something.jsonld" var name = split[split.length - 1]; var normalized = normalizeString(name); nameByRef.set(correctRef, normalized); refByName.set(normalized, correctRef); var infos = { ref: correctRef, name: name, normalized: normalized }; byRef.set(infos.ref, infos); byNormalized.set(infos.normalized, infos); // doc.components.schemas["Something.jsonld"] return map[name]; }; return { getSchemaByRef: getSchemaByRef, resolveRef: function resolveRef(ref) { return byRef.get(autocorrectRef(ref)); }, resolveSchemaName: function resolveSchemaName(normalized) { return byNormalized.get(normalized); } }; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var complexityByType = function complexityByType(schema) { var type = schema.type; if (!type) return 0; return tsPattern.match(type)["with"]("string", function () { return 1; })["with"]("number", function () { return 1; })["with"]("integer", function () { return 1; })["with"]("boolean", function () { return 1; })["with"]("null", function () { return 1; }).otherwise(function () { return 0; }); }; var complexityByComposite = function complexityByComposite(from) { if (!from) return 0; return tsPattern.match(from)["with"]("oneOf", function () { return 2; })["with"]("anyOf", function () { return 3; })["with"]("allOf", function () { return 2; })["with"]("enum", function () { return 1; })["with"]("array", function () { return 1; })["with"]("record", function () { return 1; })["with"]("empty-object", function () { return 1; })["with"]("object", function () { return 2; }).otherwise(function () { return 0; }); }; function getSchemaComplexity(_ref) { var current = _ref.current, schema = _ref.schema; if (!schema) return current; if (isReferenceObject(schema)) return current + 2; if (Array.isArray(schema.type)) { if (schema.type.length === 1) { return complexityByComposite("oneOf") + getSchemaComplexity({ current: current, schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: schema.type[0] }) }); } return current + complexityByComposite("oneOf") + server.getSum(schema.type.map(function (prop) { return getSchemaComplexity({ current: 0, schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: prop }) }); })); } if (schema.type === "null") { return current + complexityByType(_objectSpread2(_objectSpread2({}, schema), {}, { type: "null" })); } if (schema.oneOf) { if (schema.oneOf.length === 1) { return complexityByComposite("oneOf") + getSchemaComplexity({ current: current, schema: schema.oneOf[0] }); } return current + complexityByComposite("oneOf") + server.getSum(schema.oneOf.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } // anyOf = oneOf but with 1 or more = `T extends oneOf ? T | T[] : never` if (schema.anyOf) { if (schema.anyOf.length === 1) { return complexityByComposite("anyOf") + getSchemaComplexity({ current: current, schema: schema.anyOf[0] }); } return current + complexityByComposite("anyOf") + server.getSum(schema.anyOf.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } if (schema.allOf) { if (schema.allOf.length === 1) { return complexityByComposite("allOf") + getSchemaComplexity({ current: current, schema: schema.allOf[0] }); } return current + complexityByComposite("allOf") + server.getSum(schema.allOf.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } if (!schema.type) return current; if (isPrimitiveType$1(schema.type)) { if (schema["enum"]) { return current + complexityByType(schema) + complexityByComposite("enum") + server.getSum(schema["enum"].map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } return current + complexityByType(schema); } if (schema.type === "array") { if (schema.items) { return complexityByComposite("array") + getSchemaComplexity({ current: current, schema: schema.items }); } return complexityByComposite("array") + getSchemaComplexity({ current: current, schema: undefined }); } if (schema.type === "object" || schema.properties || schema.additionalProperties) { if (schema.additionalProperties) { if (schema.additionalProperties === true) { return complexityByComposite("record") + getSchemaComplexity({ current: current, schema: undefined }); } return complexityByComposite("record") + getSchemaComplexity({ current: current, schema: schema.additionalProperties }); } if (schema.properties) { var props = Object.values(schema.properties); return current + complexityByComposite("object") + server.getSum(props.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } return complexityByComposite("empty-object") + getSchemaComplexity({ current: current, schema: undefined }); } return current; } var CodeMeta = /*#__PURE__*/function () { function CodeMeta(schema, ctx) { var _meta$referencedBy; var meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _classCallCheck(this, CodeMeta); _defineProperty(this, "children", []); this.schema = schema; this.ctx = ctx; if (isReferenceObject(schema)) { this.ref = schema.$ref; } // @ts-expect-error this.meta = _objectSpread2({}, meta); this.meta.referencedBy = _toConsumableArray((_meta$referencedBy = meta === null || meta === void 0 ? void 0 : meta.referencedBy) !== null && _meta$referencedBy !== void 0 ? _meta$referencedBy : []); if (this.ref) { this.meta.referencedBy.push(this); } } _createClass(CodeMeta, [{ key: "codeString", get: function get() { if (this.code) return this.code; return this.ctx ? this.ctx.resolver.resolveRef(this.ref).normalized : this.ref; } }, { key: "complexity", get: function get() { return getSchemaComplexity({ current: 0, schema: this.schema }); } }, { key: "assign", value: function assign(code) { this.code = code; return this; } }, { key: "inherit", value: function inherit(parent) { if (parent) { parent.children.push(this); } return this; } }, { key: "toString", value: function toString() { return this.codeString; } }, { key: "toJSON", value: function toJSON() { return this.codeString; } }]); return CodeMeta; }(); /** * @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject * @see https://github.com/colinhacks/zod */ // eslint-disable-next-line sonarjs/cognitive-complexity function getZodSchema(_ref) { var schema = _ref.schema, ctx = _ref.ctx, inheritedMeta = _ref.meta, options = _ref.options; if (!schema) { throw new Error("Schema is required"); } var code = new CodeMeta(schema, ctx, inheritedMeta); var meta = { parent: code.inherit(inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.parent), referencedBy: _toConsumableArray(code.meta.referencedBy) }; var refsPath = code.meta.referencedBy.slice(0, -1).map(function (prev) { return ctx ? ctx.resolver.resolveRef(prev.ref).normalized : prev.ref; }); if (isReferenceObject(schema)) { var _ctx$resolver$resolve; if (!ctx) throw new Error("Context is required"); var schemaName = (_ctx$resolver$resolve = ctx.resolver.resolveRef(schema.$ref)) === null || _ctx$resolver$resolve === void 0 ? void 0 : _ctx$resolver$resolve.normalized; // circular(=recursive) reference if (refsPath.length > 1 && refsPath.includes(schemaName)) { return code.assign(ctx.zodSchemaByName[code.ref]); } var result = ctx.zodSchemaByName[schema.$ref]; if (!result) { var actualSchema = ctx.resolver.getSchemaByRef(schema.$ref); if (!actualSchema) { throw new Error("Schema ".concat(schema.$ref, " not found")); } result = getZodSchema({ schema: actualSchema, ctx: ctx, meta: meta, options: options }).toString(); } if (ctx.zodSchemaByName[schemaName]) { return code; } ctx.zodSchemaByName[schemaName] = result; return code; } if (Array.isArray(schema.type)) { if (schema.type.length === 1) { return getZodSchema({ schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: schema.type[0] }), ctx: ctx, meta: meta, options: options }); } return code.assign("z.union([".concat(schema.type.map(function (prop) { return getZodSchema({ schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: prop }), ctx: ctx, meta: meta, options: options }); }).join(", "), "])")); } if (schema.type === "null") { return code.assign("z.null()"); } if (schema.oneOf) { if (schema.oneOf.length === 1) { var _type = getZodSchema({ schema: schema.oneOf[0], ctx: ctx, meta: meta, options: options }); return code.assign(_type.toString()); } if (schema.discriminator) { var propertyName = schema.discriminator.propertyName; return code.assign("\n z.discriminatedUnion(\"".concat(propertyName, "\", [").concat(schema.oneOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }).join(", "), "])\n ")); } return code.assign("z.union([".concat(schema.oneOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }).join(", "), "])")); } // anyOf = oneOf but with 1 or more = `T extends oneOf ? T | T[] : never` if (schema.anyOf) { if (schema.anyOf.length === 1) { var _type2 = getZodSchema({ schema: schema.anyOf[0], ctx: ctx, meta: meta, options: options }); return code.assign(_type2.toString()); } var types = schema.anyOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }).map(function (type) { if ("type" in type.schema) { if (Array.isArray(type.schema.type)) ; else { var _schemaType = type.schema.type.toLowerCase(); !isPrimitiveType$1(_schemaType); } } return type.toString(); }).join(", "); return code.assign("z.union([".concat(types, "])")); } if (schema.allOf) { if (schema.allOf.length === 1) { var _type3 = getZodSchema({ schema: schema.allOf[0], ctx: ctx, meta: meta, options: options }); return code.assign(_type3.toString()); } var _types = schema.allOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }); var first = _types.at(0); var rest = _types.slice(1).map(function (type) { return "and(".concat(type.toString(), ")"); }).join("."); return code.assign("".concat(first.toString(), ".").concat(rest)); } var schemaType = schema.type ? schema.type.toLowerCase() : undefined; if (schemaType && isPrimitiveType$1(schemaType)) { if (schema["enum"]) { if (schemaType === "string") { if (schema["enum"].length === 1) { var value = schema["enum"][0]; var valueString = value === null ? "null" : "\"".concat(value, "\""); return code.assign("z.literal(".concat(valueString, ")")); } // eslint-disable-next-line sonarjs/no-nested-template-literals return code.assign("z.enum([".concat(schema["enum"].map(function (value) { return "\"".concat(value, "\""); }).join(", "), "])")); } if (schema["enum"].some(function (e) { return typeof e === "string"; })) { return code.assign("z.never()"); } if (schema["enum"].length === 1) { var _value = schema["enum"][0]; return code.assign("z.literal(".concat(_value === null ? "null" : _value, ")")); } return code.assign( // eslint-disable-next-line sonarjs/no-nested-template-literals "z.union([".concat(schema["enum"].map(function (value) { return "z.literal(".concat(value === null ? "null" : value, ")"); }).join(", "), "])")); } return code.assign(tsPattern.match(schemaType)["with"]("integer", function () { return "z.number()"; })["with"]("string", function () { return tsPattern.match(schema.format)["with"]("binary", function () { return "z.instanceof(File)"; }).otherwise(function () { return "z.string()"; }); }).otherwise(function (type) { return "z.".concat(type, "()"); })); } var readonly = options !== null && options !== void 0 && options.allReadonly ? ".readonly()" : ""; if (schemaType === "array") { if (schema.items) { return code.assign("z.array(".concat(getZodSchema({ schema: schema.items, ctx: ctx, meta: meta, options: options }).toString(), ")").concat(readonly)); } return code.assign("z.array(z.any())".concat(readonly)); } if (schemaType === "object" || schema.properties || schema.additionalProperties) { var _schema$required; // additional properties are allowed by default unless explicitly opting out var additionalProps = schema.additionalProperties === false ? "" : ".passthrough()"; if (_typeof(schema.additionalProperties) === "object" && Object.keys(schema.additionalProperties).length > 0) { return code.assign("z.record(".concat((getZodSchema({ schema: schema.additionalProperties, ctx: ctx, meta: meta, options: options }) + getZodChain({ schema: schema.additionalProperties, meta: _objectSpread2(_objectSpread2({}, meta), {}, { isRequired: true }), options: options })).toString(), ")")); } var hasRequiredArray = schema.required && schema.required.length > 0; var isPartial = options !== null && options !== void 0 && options.withImplicitRequiredProps ? false : !((_schema$required = schema.required) !== null && _schema$required !== void 0 && _schema$required.length); var properties = "{}"; if (schema.properties) { var propsMap = Object.entries(schema.properties).map(function (_ref2) { var _schema$required2; var _ref3 = _slicedToArray(_ref2, 2), prop = _ref3[0], propSchema = _ref3[1]; var propMetadata = _objectSpread2(_objectSpread2({}, meta), {}, { isRequired: isPartial ? true : hasRequiredArray ? (_schema$required2 = schema.required) === null || _schema$required2 === void 0 ? void 0 : _schema$required2.includes(prop) : options === null || options === void 0 ? void 0 : options.withImplicitRequiredProps, name: prop }); var propActualSchema = propSchema; if (isReferenceObject(propSchema) && ctx !== null && ctx !== void 0 && ctx.resolver) { propActualSchema = ctx.resolver.getSchemaByRef(propSchema.$ref); if (!propActualSchema) { throw new Error("Schema ".concat(propSchema.$ref, " not found")); } } var propCode = getZodSchema({ schema: propSchema, ctx: ctx, meta: propMetadata, options: options }) + getZodChain({ schema: propActualSchema, meta: propMetadata, options: options }); return [prop, propCode.toString()]; }); properties = "{ " + propsMap.map(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 2), prop = _ref5[0], propSchema = _ref5[1]; return "".concat(wrapWithQuotesIfNeeded(prop), ": ").concat(propSchema); }).join(", ") + " }"; } var partial = isPartial ? ".partial()" : ""; return code.assign("z.object(".concat(properties, ")").concat(partial).concat(additionalProps).concat(readonly)); } if (!schemaType) return code.assign("z.unknown()"); // eslint-disable-next-line @typescript-eslint/restrict-template-expressions throw new Error("Unsupported schema type: ".concat(schemaType)); } var getZodChain = function getZodChain(_ref6) { var schema = _ref6.schema, meta = _ref6.meta, options = _ref6.options; var chains = []; tsPattern.match(schema.type)["with"]("string", function () { return chains.push(getZodChainableStringValidations(schema)); })["with"]("number", "integer", function () { return chains.push(getZodChainableNumberValidations(schema)); })["with"]("array", function () { return chains.push(getZodChainableArrayValidations(schema)); }).otherwise(function () { return void 0; }); if (typeof schema.description === "string" && schema.description !== "" && options !== null && options !== void 0 && options.withDescription) { chains.push("describe(\"".concat(schema.description, "\")")); } var output = chains.concat(getZodChainablePresence(schema, meta), (options === null || options === void 0 ? void 0 : options.withDefaultValues) !== false ? getZodChainableDefault(schema) : []).filter(Boolean).join("."); return output ? ".".concat(output) : ""; }; var getZodChainablePresence = function getZodChainablePresence(schema, meta) { if (schema.nullable && !(meta !== null && meta !== void 0 && meta.isRequired)) { return "nullish()"; } if (schema.nullable) { return "nullable()"; } if (!(meta !== null && meta !== void 0 && meta.isRequired)) { return "optional()"; } return ""; }; // TODO OA prefixItems -> z.tuple var unwrapQuotesIfNeeded = function unwrapQuotesIfNeeded(value) { if (typeof value === "string" && value.startsWith('"') && value.endsWith('"')) { return value.slice(1, -1); } return value; }; var getZodChainableDefault = function getZodChainableDefault(schema) { if (schema["default"]) { var value = tsPattern.match(schema.type)["with"]("number", "integer", function () { return unwrapQuotesIfNeeded(schema["default"]); }).otherwise(function () { return JSON.stringify(schema["default"]); }); return "default(".concat(value, ")"); } return ""; }; var formatPatternIfNeeded = function formatPatternIfNeeded(pattern) { if (pattern.startsWith("/") && pattern.endsWith("/")) { pattern = pattern.slice(1, -1); } pattern = escapeControlCharacters(pattern); return "/".concat(pattern, "/"); }; var getZodChainableStringValidations = function getZodChainableStringValidations(schema) { var validations = []; if (!schema["enum"]) { if (schema.minLength !== undefined) { validations.push("min(".concat(schema.minLength, ")")); } if (schema.maxLength !== undefined) { validations.push("max(".concat(schema.maxLength, ")")); } } if (schema.pattern) { validations.push("regex(".concat(formatPatternIfNeeded(schema.pattern), ")")); } if (schema.format) { var chain = tsPattern.match(schema.format)["with"]("email", function () { return "email()"; })["with"]("hostname", function () { return "url()"; })["with"]("uri", function () { return "url()"; })["with"]("uuid", function () { return "uuid()"; })["with"]("date-time", function () { return "datetime({ offset: true })"; }).otherwise(function () { return ""; }); if (chain) { validations.push(chain); } } return validations.join("."); }; var getZodChainableNumberValidations = function getZodChainableNumberValidations(schema) { var validations = []; // none of the chains are valid for enums if (schema["enum"]) { return ""; } if (schema.type === "integer") { validations.push("int()"); } if (schema.minimum !== undefined) { if (schema.exclusiveMinimum === true) { validations.push("gt(".concat(schema.minimum, ")")); } else { validations.push("gte(".concat(schema.minimum, ")")); } } else if (typeof schema.exclusiveMinimum === "number") { validations.push("gt(".concat(schema.exclusiveMinimum, ")")); } if (schema.maximum !== undefined) { if (schema.exclusiveMaximum === true) { validations.push("lt(".concat(schema.maximum, ")")); } else { validations.push("lte(".concat(schema.maximum, ")")); } } else if (typeof schema.exclusiveMaximum === "number") { validations.push("lt(".concat(schema.exclusiveMaximum, ")")); } if (schema.multipleOf) { validations.push("multipleOf(".concat(schema.multipleOf, ")")); } return validations.join("."); }; var getZodChainableArrayValidations = function getZodChainableArrayValidations(schema) { var validations = []; if (schema.minItems) { validations.push("min(".concat(schema.minItems, ")")); } if (schema.maxItems) { validations.push("max(".concat(schema.maxItems, ")")); } return validations.join("."); }; var voidSchema = "z.void()"; // eslint-disable-next-line sonarjs/cognitive-complexity var getZodiosEndpointDefinitionList = function getZodiosEndpointDefinitionList(doc, options) { var _doc$components$schem, _doc$componen