var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __hasOwnProp = Object.prototype.hasOwnProperty; var __moduleCache = /* @__PURE__ */ new WeakMap; var __toCommonJS = (from) => { var entry = __moduleCache.get(from), desc; if (entry) return entry; entry = __defProp({}, "__esModule", { value: true }); if (from && typeof from === "object" || typeof from === "function") __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })); __moduleCache.set(from, entry); return entry; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, set: (newValue) => all[name] = () => newValue }); }; // src/index.ts var exports_src = {}; __export(exports_src, { default: () => Plato, PlatoSession: () => PlatoSession }); module.exports = __toCommonJS(exports_src); // node_modules/axios/lib/helpers/bind.js function bind(fn, thisArg) { return function wrap() { return fn.apply(thisArg, arguments); }; } // node_modules/axios/lib/utils.js function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); } function isArrayBufferView(val) { let result; if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { result = ArrayBuffer.isView(val); } else { result = val && val.buffer && isArrayBuffer(val.buffer); } return result; } function forEach(obj, fn, { allOwnKeys = false } = {}) { if (obj === null || typeof obj === "undefined") { return; } let i; let l; if (typeof obj !== "object") { obj = [obj]; } if (isArray(obj)) { for (i = 0, l = obj.length;i < l; i++) { fn.call(null, obj[i], i, obj); } } else { const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); const len = keys.length; let key; for (i = 0;i < len; i++) { key = keys[i]; fn.call(null, obj[key], key, obj); } } } function findKey(obj, key) { key = key.toLowerCase(); const keys = Object.keys(obj); let i = keys.length; let _key; while (i-- > 0) { _key = keys[i]; if (key === _key.toLowerCase()) { return _key; } } return null; } function merge() { const { caseless } = isContextDefined(this) && this || {}; const result = {}; const assignValue = (val, key) => { const targetKey = caseless && findKey(result, key) || key; if (isPlainObject(result[targetKey]) && isPlainObject(val)) { result[targetKey] = merge(result[targetKey], val); } else if (isPlainObject(val)) { result[targetKey] = merge({}, val); } else if (isArray(val)) { result[targetKey] = val.slice(); } else { result[targetKey] = val; } }; for (let i = 0, l = arguments.length;i < l; i++) { arguments[i] && forEach(arguments[i], assignValue); } return result; } function isSpecCompliantForm(thing) { return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); } var { toString } = Object.prototype; var { getPrototypeOf } = Object; var kindOf = ((cache) => (thing) => { const str = toString.call(thing); return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); })(Object.create(null)); var kindOfTest = (type) => { type = type.toLowerCase(); return (thing) => kindOf(thing) === type; }; var typeOfTest = (type) => (thing) => typeof thing === type; var { isArray } = Array; var isUndefined = typeOfTest("undefined"); var isArrayBuffer = kindOfTest("ArrayBuffer"); var isString = typeOfTest("string"); var isFunction = typeOfTest("function"); var isNumber = typeOfTest("number"); var isObject = (thing) => thing !== null && typeof thing === "object"; var isBoolean = (thing) => thing === true || thing === false; var isPlainObject = (val) => { if (kindOf(val) !== "object") { return false; } const prototype = getPrototypeOf(val); return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); }; var isDate = kindOfTest("Date"); var isFile = kindOfTest("File"); var isBlob = kindOfTest("Blob"); var isFileList = kindOfTest("FileList"); var isStream = (val) => isObject(val) && isFunction(val.pipe); var isFormData = (thing) => { let kind; return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); }; var isURLSearchParams = kindOfTest("URLSearchParams"); var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest); var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); var _global = (() => { if (typeof globalThis !== "undefined") return globalThis; return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; })(); var isContextDefined = (context) => !isUndefined(context) && context !== _global; var extend = (a, b, thisArg, { allOwnKeys } = {}) => { forEach(b, (val, key) => { if (thisArg && isFunction(val)) { a[key] = bind(val, thisArg); } else { a[key] = val; } }, { allOwnKeys }); return a; }; var stripBOM = (content) => { if (content.charCodeAt(0) === 65279) { content = content.slice(1); } return content; }; var inherits = (constructor, superConstructor, props, descriptors) => { constructor.prototype = Object.create(superConstructor.prototype, descriptors); constructor.prototype.constructor = constructor; Object.defineProperty(constructor, "super", { value: superConstructor.prototype }); props && Object.assign(constructor.prototype, props); }; var toFlatObject = (sourceObj, destObj, filter, propFilter) => { let props; let i; let prop; const merged = {}; destObj = destObj || {}; if (sourceObj == null) return destObj; do { props = Object.getOwnPropertyNames(sourceObj); i = props.length; while (i-- > 0) { prop = props[i]; if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = filter !== false && getPrototypeOf(sourceObj); } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); return destObj; }; var endsWith = (str, searchString, position) => { str = String(str); if (position === undefined || position > str.length) { position = str.length; } position -= searchString.length; const lastIndex = str.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; var toArray = (thing) => { if (!thing) return null; if (isArray(thing)) return thing; let i = thing.length; if (!isNumber(i)) return null; const arr = new Array(i); while (i-- > 0) { arr[i] = thing[i]; } return arr; }; var isTypedArray = ((TypedArray) => { return (thing) => { return TypedArray && thing instanceof TypedArray; }; })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); var forEachEntry = (obj, fn) => { const generator = obj && obj[Symbol.iterator]; const iterator = generator.call(obj); let result; while ((result = iterator.next()) && !result.done) { const pair = result.value; fn.call(obj, pair[0], pair[1]); } }; var matchAll = (regExp, str) => { let matches; const arr = []; while ((matches = regExp.exec(str)) !== null) { arr.push(matches); } return arr; }; var isHTMLForm = kindOfTest("HTMLFormElement"); var toCamelCase = (str) => { return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { return p1.toUpperCase() + p2; }); }; var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); var isRegExp = kindOfTest("RegExp"); var reduceDescriptors = (obj, reducer) => { const descriptors = Object.getOwnPropertyDescriptors(obj); const reducedDescriptors = {}; forEach(descriptors, (descriptor, name) => { let ret; if ((ret = reducer(descriptor, name, obj)) !== false) { reducedDescriptors[name] = ret || descriptor; } }); Object.defineProperties(obj, reducedDescriptors); }; var freezeMethods = (obj) => { reduceDescriptors(obj, (descriptor, name) => { if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { return false; } const value = obj[name]; if (!isFunction(value)) return; descriptor.enumerable = false; if ("writable" in descriptor) { descriptor.writable = false; return; } if (!descriptor.set) { descriptor.set = () => { throw Error("Can not rewrite read-only method \'" + name + "\'"); }; } }); }; var toObjectSet = (arrayOrString, delimiter) => { const obj = {}; const define = (arr) => { arr.forEach((value) => { obj[value] = true; }); }; isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); return obj; }; var noop = () => { }; var toFiniteNumber = (value, defaultValue) => { return value != null && Number.isFinite(value = +value) ? value : defaultValue; }; var ALPHA = "abcdefghijklmnopqrstuvwxyz"; var DIGIT = "0123456789"; var ALPHABET = { DIGIT, ALPHA, ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT }; var generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { let str = ""; const { length } = alphabet; while (size--) { str += alphabet[Math.random() * length | 0]; } return str; }; var toJSONObject = (obj) => { const stack = new Array(10); const visit = (source, i) => { if (isObject(source)) { if (stack.indexOf(source) >= 0) { return; } if (!("toJSON" in source)) { stack[i] = source; const target = isArray(source) ? [] : {}; forEach(source, (value, key) => { const reducedValue = visit(value, i + 1); !isUndefined(reducedValue) && (target[key] = reducedValue); }); stack[i] = undefined; return target; } } return source; }; return visit(obj, 0); }; var isAsyncFn = kindOfTest("AsyncFunction"); var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); var _setImmediate = ((setImmediateSupported, postMessageSupported) => { if (setImmediateSupported) { return setImmediate; } return postMessageSupported ? ((token, callbacks) => { _global.addEventListener("message", ({ source, data }) => { if (source === _global && data === token) { callbacks.length && callbacks.shift()(); } }, false); return (cb) => { callbacks.push(cb); _global.postMessage(token, "*"); }; })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); })(typeof setImmediate === "function", isFunction(_global.postMessage)); var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate; var utils_default = { isArray, isArrayBuffer, isBuffer, isFormData, isArrayBufferView, isString, isNumber, isBoolean, isObject, isPlainObject, isReadableStream, isRequest, isResponse, isHeaders, isUndefined, isDate, isFile, isBlob, isRegExp, isFunction, isStream, isURLSearchParams, isTypedArray, isFileList, forEach, merge, extend, trim, stripBOM, inherits, toFlatObject, kindOf, kindOfTest, endsWith, toArray, forEachEntry, matchAll, isHTMLForm, hasOwnProperty, hasOwnProp: hasOwnProperty, reduceDescriptors, freezeMethods, toObjectSet, toCamelCase, noop, toFiniteNumber, findKey, global: _global, isContextDefined, ALPHABET, generateString, isSpecCompliantForm, toJSONObject, isAsyncFn, isThenable, setImmediate: _setImmediate, asap }; // node_modules/axios/lib/core/AxiosError.js function AxiosError(message, code, config, request, response) { Error.call(this); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack; } this.message = message; this.name = "AxiosError"; code && (this.code = code); config && (this.config = config); request && (this.request = request); if (response) { this.response = response; this.status = response.status ? response.status : null; } } utils_default.inherits(AxiosError, Error, { toJSON: function toJSON() { return { message: this.message, name: this.name, description: this.description, number: this.number, fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, config: utils_default.toJSONObject(this.config), code: this.code, status: this.status }; } }); var prototype = AxiosError.prototype; var descriptors = {}; [ "ERR_BAD_OPTION_VALUE", "ERR_BAD_OPTION", "ECONNABORTED", "ETIMEDOUT", "ERR_NETWORK", "ERR_FR_TOO_MANY_REDIRECTS", "ERR_DEPRECATED", "ERR_BAD_RESPONSE", "ERR_BAD_REQUEST", "ERR_CANCELED", "ERR_NOT_SUPPORT", "ERR_INVALID_URL" ].forEach((code) => { descriptors[code] = { value: code }; }); Object.defineProperties(AxiosError, descriptors); Object.defineProperty(prototype, "isAxiosError", { value: true }); AxiosError.from = (error, code, config, request, response, customProps) => { const axiosError = Object.create(prototype); utils_default.toFlatObject(error, axiosError, function filter(obj) { return obj !== Error.prototype; }, (prop) => { return prop !== "isAxiosError"; }); AxiosError.call(axiosError, error.message, code, config, request, response); axiosError.cause = error; axiosError.name = error.name; customProps && Object.assign(axiosError, customProps); return axiosError; }; var AxiosError_default = AxiosError; // node_modules/axios/lib/helpers/null.js var null_default = null; // node_modules/axios/lib/helpers/toFormData.js function isVisitable(thing) { return utils_default.isPlainObject(thing) || utils_default.isArray(thing); } function removeBrackets(key) { return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; } function renderKey(path, key, dots) { if (!path) return key; return path.concat(key).map(function each(token, i) { token = removeBrackets(token); return !dots && i ? "[" + token + "]" : token; }).join(dots ? "." : ""); } function isFlatArray(arr) { return utils_default.isArray(arr) && !arr.some(isVisitable); } function toFormData(obj, formData, options) { if (!utils_default.isObject(obj)) { throw new TypeError("target must be an object"); } formData = formData || new (null_default || FormData); options = utils_default.toFlatObject(options, { metaTokens: true, dots: false, indexes: false }, false, function defined(option, source) { return !utils_default.isUndefined(source[option]); }); const metaTokens = options.metaTokens; const visitor = options.visitor || defaultVisitor; const dots = options.dots; const indexes = options.indexes; const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); if (!utils_default.isFunction(visitor)) { throw new TypeError("visitor must be a function"); } function convertValue(value) { if (value === null) return ""; if (utils_default.isDate(value)) { return value.toISOString(); } if (!useBlob && utils_default.isBlob(value)) { throw new AxiosError_default("Blob is not supported. Use a Buffer instead."); } if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); } return value; } function defaultVisitor(value, key, path) { let arr = value; if (value && !path && typeof value === "object") { if (utils_default.endsWith(key, "{}")) { key = metaTokens ? key : key.slice(0, -2); value = JSON.stringify(value); } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { key = removeBrackets(key); arr.forEach(function each(el, index) { !(utils_default.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", convertValue(el)); }); return false; } } if (isVisitable(value)) { return true; } formData.append(renderKey(path, key, dots), convertValue(value)); return false; } const stack = []; const exposedHelpers = Object.assign(predicates, { defaultVisitor, convertValue, isVisitable }); function build(value, path) { if (utils_default.isUndefined(value)) return; if (stack.indexOf(value) !== -1) { throw Error("Circular reference detected in " + path.join(".")); } stack.push(value); utils_default.forEach(value, function each(el, key) { const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path, exposedHelpers); if (result === true) { build(el, path ? path.concat(key) : [key]); } }); stack.pop(); } if (!utils_default.isObject(obj)) { throw new TypeError("data must be an object"); } build(obj); return formData; } var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { return /^is[A-Z]/.test(prop); }); var toFormData_default = toFormData; // node_modules/axios/lib/helpers/AxiosURLSearchParams.js function encode(str) { const charMap = { "!": "%21", "'": "%27", "(": "%28", ")": "%29", "~": "%7E", "%20": "+", "%00": "\0" }; return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { return charMap[match]; }); } function AxiosURLSearchParams(params, options) { this._pairs = []; params && toFormData_default(params, this, options); } var prototype2 = AxiosURLSearchParams.prototype; prototype2.append = function append(name, value) { this._pairs.push([name, value]); }; prototype2.toString = function toString2(encoder) { const _encode = encoder ? function(value) { return encoder.call(this, value, encode); } : encode; return this._pairs.map(function each(pair) { return _encode(pair[0]) + "=" + _encode(pair[1]); }, "").join("&"); }; var AxiosURLSearchParams_default = AxiosURLSearchParams; // node_modules/axios/lib/helpers/buildURL.js function encode2(val) { return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); } function buildURL(url, params, options) { if (!params) { return url; } const _encode = options && options.encode || encode2; const serializeFn = options && options.serialize; let serializedParams; if (serializeFn) { serializedParams = serializeFn(params, options); } else { serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode); } if (serializedParams) { const hashmarkIndex = url.indexOf("#"); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; } return url; } // node_modules/axios/lib/core/InterceptorManager.js class InterceptorManager { constructor() { this.handlers = []; } use(fulfilled, rejected, options) { this.handlers.push({ fulfilled, rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; } eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } } clear() { if (this.handlers) { this.handlers = []; } } forEach(fn) { utils_default.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); } } var InterceptorManager_default = InterceptorManager; // node_modules/axios/lib/defaults/transitional.js var transitional_default = { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }; // node_modules/axios/lib/platform/browser/classes/URLSearchParams.js var URLSearchParams_default = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams_default; // node_modules/axios/lib/platform/browser/classes/FormData.js var FormData_default = typeof FormData !== "undefined" ? FormData : null; // node_modules/axios/lib/platform/browser/classes/Blob.js var Blob_default = typeof Blob !== "undefined" ? Blob : null; // node_modules/axios/lib/platform/browser/index.js var browser_default = { isBrowser: true, classes: { URLSearchParams: URLSearchParams_default, FormData: FormData_default, Blob: Blob_default }, protocols: ["http", "https", "file", "blob", "url", "data"] }; // node_modules/axios/lib/platform/common/utils.js var exports_utils = {}; __export(exports_utils, { origin: () => origin, navigator: () => _navigator, hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv, hasStandardBrowserEnv: () => hasStandardBrowserEnv, hasBrowserEnv: () => hasBrowserEnv }); var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; var _navigator = typeof navigator === "object" && navigator || undefined; var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0); var hasStandardBrowserWebWorkerEnv = (() => { return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; })(); var origin = hasBrowserEnv && window.location.href || "http://localhost"; // node_modules/axios/lib/platform/index.js var platform_default = { ...exports_utils, ...browser_default }; // node_modules/axios/lib/helpers/toURLEncodedForm.js function toURLEncodedForm(data, options) { return toFormData_default(data, new platform_default.classes.URLSearchParams, Object.assign({ visitor: function(value, key, path, helpers) { if (platform_default.isNode && utils_default.isBuffer(value)) { this.append(key, value.toString("base64")); return false; } return helpers.defaultVisitor.apply(this, arguments); } }, options)); } // node_modules/axios/lib/helpers/formDataToJSON.js function parsePropPath(name) { return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { return match[0] === "[]" ? "" : match[1] || match[0]; }); } function arrayToObject(arr) { const obj = {}; const keys = Object.keys(arr); let i; const len = keys.length; let key; for (i = 0;i < len; i++) { key = keys[i]; obj[key] = arr[key]; } return obj; } function formDataToJSON(formData) { function buildPath(path, value, target, index) { let name = path[index++]; if (name === "__proto__") return true; const isNumericKey = Number.isFinite(+name); const isLast = index >= path.length; name = !name && utils_default.isArray(target) ? target.length : name; if (isLast) { if (utils_default.hasOwnProp(target, name)) { target[name] = [target[name], value]; } else { target[name] = value; } return !isNumericKey; } if (!target[name] || !utils_default.isObject(target[name])) { target[name] = []; } const result = buildPath(path, value, target[name], index); if (result && utils_default.isArray(target[name])) { target[name] = arrayToObject(target[name]); } return !isNumericKey; } if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { const obj = {}; utils_default.forEachEntry(formData, (name, value) => { buildPath(parsePropPath(name), value, obj, 0); }); return obj; } return null; } var formDataToJSON_default = formDataToJSON; // node_modules/axios/lib/defaults/index.js function stringifySafely(rawValue, parser, encoder) { if (utils_default.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); return utils_default.trim(rawValue); } catch (e) { if (e.name !== "SyntaxError") { throw e; } } } return (encoder || JSON.stringify)(rawValue); } var defaults = { transitional: transitional_default, adapter: ["xhr", "http", "fetch"], transformRequest: [function transformRequest(data, headers) { const contentType = headers.getContentType() || ""; const hasJSONContentType = contentType.indexOf("application/json") > -1; const isObjectPayload = utils_default.isObject(data); if (isObjectPayload && utils_default.isHTMLForm(data)) { data = new FormData(data); } const isFormData2 = utils_default.isFormData(data); if (isFormData2) { return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data; } if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) { return data; } if (utils_default.isArrayBufferView(data)) { return data.buffer; } if (utils_default.isURLSearchParams(data)) { headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); return data.toString(); } let isFileList2; if (isObjectPayload) { if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { return toURLEncodedForm(data, this.formSerializer).toString(); } if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { const _FormData = this.env && this.env.FormData; return toFormData_default(isFileList2 ? { "files[]": data } : data, _FormData && new _FormData, this.formSerializer); } } if (isObjectPayload || hasJSONContentType) { headers.setContentType("application/json", false); return stringifySafely(data); } return data; }], transformResponse: [function transformResponse(data) { const transitional = this.transitional || defaults.transitional; const forcedJSONParsing = transitional && transitional.forcedJSONParsing; const JSONRequested = this.responseType === "json"; if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) { return data; } if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { const silentJSONParsing = transitional && transitional.silentJSONParsing; const strictJSONParsing = !silentJSONParsing && JSONRequested; try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === "SyntaxError") { throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } } } return data; }], timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", maxContentLength: -1, maxBodyLength: -1, env: { FormData: platform_default.classes.FormData, Blob: platform_default.classes.Blob }, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; }, headers: { common: { Accept: "application/json, text/plain, */*", "Content-Type": undefined } } }; utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { defaults.headers[method] = {}; }); var defaults_default = defaults; // node_modules/axios/lib/helpers/parseHeaders.js var ignoreDuplicateOf = utils_default.toObjectSet([ "age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent" ]); var parseHeaders_default = (rawHeaders) => { const parsed = {}; let key; let val; let i; rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { i = line.indexOf(":"); key = line.substring(0, i).trim().toLowerCase(); val = line.substring(i + 1).trim(); if (!key || parsed[key] && ignoreDuplicateOf[key]) { return; } if (key === "set-cookie") { if (parsed[key]) { parsed[key].push(val); } else { parsed[key] = [val]; } } else { parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; } }); return parsed; }; // node_modules/axios/lib/core/AxiosHeaders.js function normalizeHeader(header) { return header && String(header).trim().toLowerCase(); } function normalizeValue(value) { if (value === false || value == null) { return value; } return utils_default.isArray(value) ? value.map(normalizeValue) : String(value); } function parseTokens(str) { const tokens = Object.create(null); const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; let match; while (match = tokensRE.exec(str)) { tokens[match[1]] = match[2]; } return tokens; } function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { if (utils_default.isFunction(filter2)) { return filter2.call(this, value, header); } if (isHeaderNameFilter) { value = header; } if (!utils_default.isString(value)) return; if (utils_default.isString(filter2)) { return value.indexOf(filter2) !== -1; } if (utils_default.isRegExp(filter2)) { return filter2.test(value); } } function formatHeader(header) { return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { return char.toUpperCase() + str; }); } function buildAccessors(obj, header) { const accessorName = utils_default.toCamelCase(" " + header); ["get", "set", "has"].forEach((methodName) => { Object.defineProperty(obj, methodName + accessorName, { value: function(arg1, arg2, arg3) { return this[methodName].call(this, header, arg1, arg2, arg3); }, configurable: true }); }); } var $internals = Symbol("internals"); var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); class AxiosHeaders { constructor(headers) { headers && this.set(headers); } set(header, valueOrRewrite, rewrite) { const self2 = this; function setHeader(_value, _header, _rewrite) { const lHeader = normalizeHeader(_header); if (!lHeader) { throw new Error("header name must be a non-empty string"); } const key = utils_default.findKey(self2, lHeader); if (!key || self2[key] === undefined || _rewrite === true || _rewrite === undefined && self2[key] !== false) { self2[key || _header] = normalizeValue(_value); } } const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); if (utils_default.isPlainObject(header) || header instanceof this.constructor) { setHeaders(header, valueOrRewrite); } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { setHeaders(parseHeaders_default(header), valueOrRewrite); } else if (utils_default.isHeaders(header)) { for (const [key, value] of header.entries()) { setHeader(value, key, rewrite); } } else { header != null && setHeader(valueOrRewrite, header, rewrite); } return this; } get(header, parser) { header = normalizeHeader(header); if (header) { const key = utils_default.findKey(this, header); if (key) { const value = this[key]; if (!parser) { return value; } if (parser === true) { return parseTokens(value); } if (utils_default.isFunction(parser)) { return parser.call(this, value, key); } if (utils_default.isRegExp(parser)) { return parser.exec(value); } throw new TypeError("parser must be boolean|regexp|function"); } } } has(header, matcher) { header = normalizeHeader(header); if (header) { const key = utils_default.findKey(this, header); return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); } return false; } delete(header, matcher) { const self2 = this; let deleted = false; function deleteHeader(_header) { _header = normalizeHeader(_header); if (_header) { const key = utils_default.findKey(self2, _header); if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { delete self2[key]; deleted = true; } } } if (utils_default.isArray(header)) { header.forEach(deleteHeader); } else { deleteHeader(header); } return deleted; } clear(matcher) { const keys = Object.keys(this); let i = keys.length; let deleted = false; while (i--) { const key = keys[i]; if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { delete this[key]; deleted = true; } } return deleted; } normalize(format) { const self2 = this; const headers = {}; utils_default.forEach(this, (value, header) => { const key = utils_default.findKey(headers, header); if (key) { self2[key] = normalizeValue(value); delete self2[header]; return; } const normalized = format ? formatHeader(header) : String(header).trim(); if (normalized !== header) { delete self2[header]; } self2[normalized] = normalizeValue(value); headers[normalized] = true; }); return this; } concat(...targets) { return this.constructor.concat(this, ...targets); } toJSON(asStrings) { const obj = Object.create(null); utils_default.forEach(this, (value, header) => { value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); }); return obj; } [Symbol.iterator]() { return Object.entries(this.toJSON())[Symbol.iterator](); } toString() { return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); } get [Symbol.toStringTag]() { return "AxiosHeaders"; } static from(thing) { return thing instanceof this ? thing : new this(thing); } static concat(first, ...targets) { const computed = new this(first); targets.forEach((target) => computed.set(target)); return computed; } static accessor(header) { const internals = this[$internals] = this[$internals] = { accessors: {} }; const accessors = internals.accessors; const prototype3 = this.prototype; function defineAccessor(_header) { const lHeader = normalizeHeader(_header); if (!accessors[lHeader]) { buildAccessors(prototype3, _header); accessors[lHeader] = true; } } utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); return this; } } AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { let mapped = key[0].toUpperCase() + key.slice(1); return { get: () => value, set(headerValue) { this[mapped] = headerValue; } }; }); utils_default.freezeMethods(AxiosHeaders); var AxiosHeaders_default = AxiosHeaders; // node_modules/axios/lib/core/transformData.js function transformData(fns, response) { const config = this || defaults_default; const context = response || config; const headers = AxiosHeaders_default.from(context.headers); let data = context.data; utils_default.forEach(fns, function transform(fn) { data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); }); headers.normalize(); return data; } // node_modules/axios/lib/cancel/isCancel.js function isCancel(value) { return !!(value && value.__CANCEL__); } // node_modules/axios/lib/cancel/CanceledError.js function CanceledError(message, config, request) { AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config, request); this.name = "CanceledError"; } utils_default.inherits(CanceledError, AxiosError_default, { __CANCEL__: true }); var CanceledError_default = CanceledError; // node_modules/axios/lib/core/settle.js function settle(resolve, reject, response) { const validateStatus2 = response.config.validateStatus; if (!response.status || !validateStatus2 || validateStatus2(response.status)) { resolve(response); } else { reject(new AxiosError_default("Request failed with status code " + response.status, [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response)); } } // node_modules/axios/lib/helpers/parseProtocol.js function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); return match && match[1] || ""; } // node_modules/axios/lib/helpers/speedometer.js function speedometer(samplesCount, min) { samplesCount = samplesCount || 10; const bytes = new Array(samplesCount); const timestamps = new Array(samplesCount); let head = 0; let tail = 0; let firstSampleTS; min = min !== undefined ? min : 1000; return function push(chunkLength) { const now = Date.now(); const startedAt = timestamps[tail]; if (!firstSampleTS) { firstSampleTS = now; } bytes[head] = chunkLength; timestamps[head] = now; let i = tail; let bytesCount = 0; while (i !== head) { bytesCount += bytes[i++]; i = i % samplesCount; } head = (head + 1) % samplesCount; if (head === tail) { tail = (tail + 1) % samplesCount; } if (now - firstSampleTS < min) { return; } const passed = startedAt && now - startedAt; return passed ? Math.round(bytesCount * 1000 / passed) : undefined; }; } var speedometer_default = speedometer; // node_modules/axios/lib/helpers/throttle.js function throttle(fn, freq) { let timestamp = 0; let threshold = 1000 / freq; let lastArgs; let timer; const invoke = (args, now = Date.now()) => { timestamp = now; lastArgs = null; if (timer) { clearTimeout(timer); timer = null; } fn.apply(null, args); }; const throttled = (...args) => { const now = Date.now(); const passed = now - timestamp; if (passed >= threshold) { invoke(args, now); } else { lastArgs = args; if (!timer) { timer = setTimeout(() => { timer = null; invoke(lastArgs); }, threshold - passed); } } }; const flush = () => lastArgs && invoke(lastArgs); return [throttled, flush]; } var throttle_default = throttle; // node_modules/axios/lib/helpers/progressEventReducer.js var progressEventReducer = (listener, isDownloadStream, freq = 3) => { let bytesNotified = 0; const _speedometer = speedometer_default(50, 250); return throttle_default((e) => { const loaded = e.loaded; const total = e.lengthComputable ? e.total : undefined; const progressBytes = loaded - bytesNotified; const rate = _speedometer(progressBytes); const inRange = loaded <= total; bytesNotified = loaded; const data = { loaded, total, progress: total ? loaded / total : undefined, bytes: progressBytes, rate: rate ? rate : undefined, estimated: rate && total && inRange ? (total - loaded) / rate : undefined, event: e, lengthComputable: total != null, [isDownloadStream ? "download" : "upload"]: true }; listener(data); }, freq); }; var progressEventDecorator = (total, throttled) => { const lengthComputable = total != null; return [(loaded) => throttled[0]({ lengthComputable, total, loaded }), throttled[1]]; }; var asyncDecorator = (fn) => (...args) => utils_default.asap(() => fn(...args)); // node_modules/axios/lib/helpers/isURLSameOrigin.js var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? function standardBrowserEnv() { const msie = platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent); const urlParsingNode = document.createElement("a"); let originURL; function resolveURL(url) { let href = url; if (msie) { urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute("href", href); return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); return function isURLSameOrigin(requestURL) { const parsed = utils_default.isString(requestURL) ? resolveURL(requestURL) : requestURL; return parsed.protocol === originURL.protocol && parsed.host === originURL.host; }; }() : function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; }(); // node_modules/axios/lib/helpers/cookies.js var cookies_default = platform_default.hasStandardBrowserEnv ? { write(name, value, expires, path, domain, secure) { const cookie = [name + "=" + encodeURIComponent(value)]; utils_default.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); utils_default.isString(path) && cookie.push("path=" + path); utils_default.isString(domain) && cookie.push("domain=" + domain); secure === true && cookie.push("secure"); document.cookie = cookie.join("; "); }, read(name) { const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); return match ? decodeURIComponent(match[3]) : null; }, remove(name) { this.write(name, "", Date.now() - 86400000); } } : { write() { }, read() { return null; }, remove() { } }; // node_modules/axios/lib/helpers/isAbsoluteURL.js function isAbsoluteURL(url) { return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } // node_modules/axios/lib/helpers/combineURLs.js function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; } // node_modules/axios/lib/core/buildFullPath.js function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; } // node_modules/axios/lib/core/mergeConfig.js var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing; function mergeConfig(config1, config2) { config2 = config2 || {}; const config = {}; function getMergedValue(target, source, caseless) { if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { return utils_default.merge.call({ caseless }, target, source); } else if (utils_default.isPlainObject(source)) { return utils_default.merge({}, source); } else if (utils_default.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(a, b, caseless) { if (!utils_default.isUndefined(b)) { return getMergedValue(a, b, caseless); } else if (!utils_default.isUndefined(a)) { return getMergedValue(undefined, a, caseless); } } function valueFromConfig2(a, b) { if (!utils_default.isUndefined(b)) { return getMergedValue(undefined, b); } } function defaultToConfig2(a, b) { if (!utils_default.isUndefined(b)) { return getMergedValue(undefined, b); } else if (!utils_default.isUndefined(a)) { return getMergedValue(undefined, a); } } function mergeDirectKeys(a, b, prop) { if (prop in config2) { return getMergedValue(a, b); } else if (prop in config1) { return getMergedValue(undefined, a); } } const mergeMap = { url: valueFromConfig2, method: valueFromConfig2, data: valueFromConfig2, baseURL: defaultToConfig2, transformRequest: defaultToConfig2, transformResponse: defaultToConfig2, paramsSerializer: defaultToConfig2, timeout: defaultToConfig2, timeoutMessage: defaultToConfig2, withCredentials: defaultToConfig2, withXSRFToken: defaultToConfig2, adapter: defaultToConfig2, responseType: defaultToConfig2, xsrfCookieName: defaultToConfig2, xsrfHeaderName: defaultToConfig2, onUploadProgress: defaultToConfig2, onDownloadProgress: defaultToConfig2, decompress: defaultToConfig2, maxContentLength: defaultToConfig2, maxBodyLength: defaultToConfig2, beforeRedirect: defaultToConfig2, transport: defaultToConfig2, httpAgent: defaultToConfig2, httpsAgent: defaultToConfig2, cancelToken: defaultToConfig2, socketPath: defaultToConfig2, responseEncoding: defaultToConfig2, validateStatus: mergeDirectKeys, headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) }; utils_default.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { const merge2 = mergeMap[prop] || mergeDeepProperties; const configValue = merge2(config1[prop], config2[prop], prop); utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); }); return config; } // node_modules/axios/lib/helpers/resolveConfig.js var resolveConfig_default = (config) => { const newConfig = mergeConfig({}, config); let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; newConfig.headers = headers = AxiosHeaders_default.from(headers); newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); if (auth) { headers.set("Authorization", "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))); } let contentType; if (utils_default.isFormData(data)) { if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) { headers.setContentType(undefined); } else if ((contentType = headers.getContentType()) !== false) { const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); } } if (platform_default.hasStandardBrowserEnv) { withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) { const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName); if (xsrfValue) { headers.set(xsrfHeaderName, xsrfValue); } } } return newConfig; }; // node_modules/axios/lib/adapters/xhr.js var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; var xhr_default = isXHRAdapterSupported && function(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { const _config = resolveConfig_default(config); let requestData = _config.data; const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize(); let { responseType, onUploadProgress, onDownloadProgress } = _config; let onCanceled; let uploadThrottled, downloadThrottled; let flushUpload, flushDownload; function done() { flushUpload && flushUpload(); flushDownload && flushDownload(); _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); _config.signal && _config.signal.removeEventListener("abort", onCanceled); } let request = new XMLHttpRequest; request.open(_config.method.toUpperCase(), _config.url, true); request.timeout = _config.timeout; function onloadend() { if (!request) { return; } const responseHeaders = AxiosHeaders_default.from("getAllResponseHeaders" in request && request.getAllResponseHeaders()); const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; const response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config, request }; settle(function _resolve(value) { resolve(value); done(); }, function _reject(err) { reject(err); done(); }, response); request = null; } if ("onloadend" in request) { request.onloadend = onloadend; } else { request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { return; } setTimeout(onloadend); }; } request.onabort = function handleAbort() { if (!request) { return; } reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request)); request = null; }; request.onerror = function handleError() { reject(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request)); request = null; }; request.ontimeout = function handleTimeout() { let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; const transitional = _config.transitional || transitional_default; if (_config.timeoutErrorMessage) { timeoutErrorMessage = _config.timeoutErrorMessage; } reject(new AxiosError_default(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, config, request)); request = null; }; requestData === undefined && requestHeaders.setContentType(null); if ("setRequestHeader" in request) { utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { request.setRequestHeader(key, val); }); } if (!utils_default.isUndefined(_config.withCredentials)) { request.withCredentials = !!_config.withCredentials; } if (responseType && responseType !== "json") { request.responseType = _config.responseType; } if (onDownloadProgress) { [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); request.addEventListener("progress", downloadThrottled); } if (onUploadProgress && request.upload) { [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); request.upload.addEventListener("progress", uploadThrottled); request.upload.addEventListener("loadend", flushUpload); } if (_config.cancelToken || _config.signal) { onCanceled = (cancel) => { if (!request) { return; } reject(!cancel || cancel.type ? new CanceledError_default(null, config, request) : cancel); request.abort(); request = null; }; _config.cancelToken && _config.cancelToken.subscribe(onCanceled); if (_config.signal) { _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); } } const protocol = parseProtocol(_config.url); if (protocol && platform_default.protocols.indexOf(protocol) === -1) { reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config)); return; } request.send(requestData || null); }); }; // node_modules/axios/lib/helpers/composeSignals.js var composeSignals = (signals, timeout) => { const { length } = signals = signals ? signals.filter(Boolean) : []; if (timeout || length) { let controller = new AbortController; let aborted; const onabort = function(reason) { if (!aborted) { aborted = true; unsubscribe(); const err = reason instanceof Error ? reason : this.reason; controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err)); } }; let timer = timeout && setTimeout(() => { timer = null; onabort(new AxiosError_default(`timeout ${timeout} of ms exceeded`, AxiosError_default.ETIMEDOUT)); }, timeout); const unsubscribe = () => { if (signals) { timer && clearTimeout(timer); timer = null; signals.forEach((signal2) => { signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); }); signals = null; } }; signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); const { signal } = controller; signal.unsubscribe = () => utils_default.asap(unsubscribe); return signal; } }; var composeSignals_default = composeSignals; // node_modules/axios/lib/helpers/trackStream.js var streamChunk = function* (chunk, chunkSize) { let len = chunk.byteLength; if (!chunkSize || len < chunkSize) { yield chunk; return; } let pos = 0; let end; while (pos < len) { end = pos + chunkSize; yield chunk.slice(pos, end); pos = end; } }; var readBytes = async function* (iterable, chunkSize) { for await (const chunk of readStream(iterable)) { yield* streamChunk(chunk, chunkSize); } }; var readStream = async function* (stream) { if (stream[Symbol.asyncIterator]) { yield* stream; return; } const reader = stream.getReader(); try { for (;; ) { const { done, value } = await reader.read(); if (done) { break; } yield value; } } finally { await reader.cancel(); } }; var trackStream = (stream, chunkSize, onProgress, onFinish) => { const iterator = readBytes(stream, chunkSize); let bytes = 0; let done; let _onFinish = (e) => { if (!done) { done = true; onFinish && onFinish(e); } }; return new ReadableStream({ async pull(controller) { try { const { done: done2, value } = await iterator.next(); if (done2) { _onFinish(); controller.close(); return; } let len = value.byteLength; if (onProgress) { let loadedBytes = bytes += len; onProgress(loadedBytes); } controller.enqueue(new Uint8Array(value)); } catch (err) { _onFinish(err); throw err; } }, cancel(reason) { _onFinish(reason); return iterator.return(); } }, { highWaterMark: 2 }); }; // node_modules/axios/lib/adapters/fetch.js var isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; var isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function"; var encodeText = isFetchSupported && (typeof TextEncoder === "function" ? ((encoder) => (str) => encoder.encode(str))(new TextEncoder) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); var test = (fn, ...args) => { try { return !!fn(...args); } catch (e) { return false; } }; var supportsRequestStream = isReadableStreamSupported && test(() => { let duplexAccessed = false; const hasContentType = new Request(platform_default.origin, { body: new ReadableStream, method: "POST", get duplex() { duplexAccessed = true; return "half"; } }).headers.has("Content-Type"); return duplexAccessed && !hasContentType; }); var DEFAULT_CHUNK_SIZE = 64 * 1024; var supportsResponseStream = isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body)); var resolvers = { stream: supportsResponseStream && ((res) => res.body) }; isFetchSupported && ((res) => { ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { !resolvers[type] && (resolvers[type] = utils_default.isFunction(res[type]) ? (res2) => res2[type]() : (_, config) => { throw new AxiosError_default(`Response type '${type}' is not supported`, AxiosError_default.ERR_NOT_SUPPORT, config); }); }); })(new Response); var getBodyLength = async (body) => { if (body == null) { return 0; } if (utils_default.isBlob(body)) { return body.size; } if (utils_default.isSpecCompliantForm(body)) { const _request = new Request(platform_default.origin, { method: "POST", body }); return (await _request.arrayBuffer()).byteLength; } if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) { return body.byteLength; } if (utils_default.isURLSearchParams(body)) { body = body + ""; } if (utils_default.isString(body)) { return (await encodeText(body)).byteLength; } }; var resolveBodyLength = async (headers, body) => { const length = utils_default.toFiniteNumber(headers.getContentLength()); return length == null ? getBodyLength(body) : length; }; var fetch_default = isFetchSupported && (async (config) => { let { url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, withCredentials = "same-origin", fetchOptions } = resolveConfig_default(config); responseType = responseType ? (responseType + "").toLowerCase() : "text"; let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout); let request; const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { composedSignal.unsubscribe(); }); let requestContentLength; try { if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) { let _request = new Request(url, { method: "POST", body: data, duplex: "half" }); let contentTypeHeader; if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { headers.setContentType(contentTypeHeader); } if (_request.body) { const [onProgress, flush] = progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))); data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); } } if (!utils_default.isString(withCredentials)) { withCredentials = withCredentials ? "include" : "omit"; } const isCredentialsSupported = "credentials" in Request.prototype; request = new Request(url, { ...fetchOptions, signal: composedSignal, method: method.toUpperCase(), headers: headers.normalize().toJSON(), body: data, duplex: "half", credentials: isCredentialsSupported ? withCredentials : undefined }); let response = await fetch(request); const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response"); if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) { const options = {}; ["status", "statusText", "headers"].forEach((prop) => { options[prop] = response[prop]; }); const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length")); const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || []; response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { flush && flush(); unsubscribe && unsubscribe(); }), options); } responseType = responseType || "text"; let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config); !isStreamResponse && unsubscribe && unsubscribe(); return await new Promise((resolve, reject) => { settle(resolve, reject, { data: responseData, headers: AxiosHeaders_default.from(response.headers), status: response.status, statusText: response.statusText, config, request }); }); } catch (err) { unsubscribe && unsubscribe(); if (err && err.name === "TypeError" && /fetch/i.test(err.message)) { throw Object.assign(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request), { cause: err.cause || err }); } throw AxiosError_default.from(err, err && err.code, config, request); } }); // node_modules/axios/lib/adapters/adapters.js var knownAdapters = { http: null_default, xhr: xhr_default, fetch: fetch_default }; utils_default.forEach(knownAdapters, (fn, value) => { if (fn) { try { Object.defineProperty(fn, "name", { value }); } catch (e) { } Object.defineProperty(fn, "adapterName", { value }); } }); var renderReason = (reason) => `- ${reason}`; var isResolvedHandle = (adapter) => utils_default.isFunction(adapter) || adapter === null || adapter === false; var adapters_default = { getAdapter: (adapters) => { adapters = utils_default.isArray(adapters) ? adapters : [adapters]; const { length } = adapters; let nameOrAdapter; let adapter; const rejectedReasons = {}; for (let i = 0;i < length; i++) { nameOrAdapter = adapters[i]; let id; adapter = nameOrAdapter; if (!isResolvedHandle(nameOrAdapter)) { adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; if (adapter === undefined) { throw new AxiosError_default(`Unknown adapter '${id}'`); } } if (adapter) { break; } rejectedReasons[id || "#" + i] = adapter; } if (!adapter) { const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")); let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; throw new AxiosError_default(`There is no suitable adapter to dispatch the request ` + s, "ERR_NOT_SUPPORT"); } return adapter; }, adapters: knownAdapters }; // node_modules/axios/lib/core/dispatchRequest.js function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } if (config.signal && config.signal.aborted) { throw new CanceledError_default(null, config); } } function dispatchRequest(config) { throwIfCancellationRequested(config); config.headers = AxiosHeaders_default.from(config.headers); config.data = transformData.call(config, config.transformRequest); if (["post", "put", "patch"].indexOf(config.method) !== -1) { config.headers.setContentType("application/x-www-form-urlencoded", false); } const adapter = adapters_default.getAdapter(config.adapter || defaults_default.adapter); return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); response.data = transformData.call(config, config.transformResponse, response); response.headers = AxiosHeaders_default.from(response.headers); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); if (reason && reason.response) { reason.response.data = transformData.call(config, config.transformResponse, reason.response); reason.response.headers = AxiosHeaders_default.from(reason.response.headers); } } return Promise.reject(reason); }); } // node_modules/axios/lib/env/data.js var VERSION = "1.7.7"; // node_modules/axios/lib/helpers/validator.js function assertOptions(options, schema, allowUnknown) { if (typeof options !== "object") { throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE); } const keys = Object.keys(options); let i = keys.length; while (i-- > 0) { const opt = keys[i]; const validator = schema[opt]; if (validator) { const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION); } } } var validators = {}; ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { validators[type] = function validator(thing) { return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; }; }); var deprecatedWarnings = {}; validators.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { return "[Axios v" + VERSION + "] Transitional option \'" + opt + "\'" + desc + (message ? ". " + message : ""); } return (value, opt, opts) => { if (validator === false) { throw new AxiosError_default(formatMessage(opt, " has been removed" + (version ? " in " + version : "")), AxiosError_default.ERR_DEPRECATED); } if (version && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; console.warn(formatMessage(opt, " has been deprecated since v" + version + " and will be removed in the near future")); } return validator ? validator(value, opt, opts) : true; }; }; var validator_default = { assertOptions, validators }; // node_modules/axios/lib/core/Axios.js var validators2 = validator_default.validators; class Axios { constructor(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager_default, response: new InterceptorManager_default }; } async request(configOrUrl, config) { try { return await this._request(configOrUrl, config); } catch (err) { if (err instanceof Error) { let dummy; Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : dummy = new Error; const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; try { if (!err.stack) { err.stack = stack; } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { err.stack += "\n" + stack; } } catch (e) { } } throw err; } } _request(configOrUrl, config) { if (typeof configOrUrl === "string") { config = config || {}; config.url = configOrUrl; } else { config = configOrUrl || {}; } config = mergeConfig(this.defaults, config); const { transitional: transitional2, paramsSerializer, headers } = config; if (transitional2 !== undefined) { validator_default.assertOptions(transitional2, { silentJSONParsing: validators2.transitional(validators2.boolean), forcedJSONParsing: validators2.transitional(validators2.boolean), clarifyTimeoutError: validators2.transitional(validators2.boolean) }, false); } if (paramsSerializer != null) { if (utils_default.isFunction(paramsSerializer)) { config.paramsSerializer = { serialize: paramsSerializer }; } else { validator_default.assertOptions(paramsSerializer, { encode: validators2.function, serialize: validators2.function }, true); } } config.method = (config.method || this.defaults.method || "get").toLowerCase(); let contextHeaders = headers && utils_default.merge(headers.common, headers[config.method]); headers && utils_default.forEach(["delete", "get", "head", "post", "put", "patch", "common"], (method) => { delete headers[method]; }); config.headers = AxiosHeaders_default.concat(contextHeaders, headers); const requestInterceptorChain = []; let synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); const responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); let promise; let i = 0; let len; if (!synchronousRequestInterceptors) { const chain = [dispatchRequest.bind(this), undefined]; chain.unshift.apply(chain, requestInterceptorChain); chain.push.apply(chain, responseInterceptorChain); len = chain.length; promise = Promise.resolve(config); while (i < len) { promise = promise.then(chain[i++], chain[i++]); } return promise; } len = requestInterceptorChain.length; let newConfig = config; i = 0; while (i < len) { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected.call(this, error); break; } } try { promise = dispatchRequest.call(this, newConfig); } catch (error) { return Promise.reject(error); } i = 0; len = responseInterceptorChain.length; while (i < len) { promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); } return promise; } getUri(config) { config = mergeConfig(this.defaults, config); const fullPath = buildFullPath(config.baseURL, config.url); return buildURL(fullPath, config.params, config.paramsSerializer); } } utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method, url, data: (config || {}).data })); }; }); utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { return this.request(mergeConfig(config || {}, { method, headers: isForm ? { "Content-Type": "multipart/form-data" } : {}, url, data })); }; } Axios.prototype[method] = generateHTTPMethod(); Axios.prototype[method + "Form"] = generateHTTPMethod(true); }); var Axios_default = Axios; // node_modules/axios/lib/cancel/CancelToken.js class CancelToken { constructor(executor) { if (typeof executor !== "function") { throw new TypeError("executor must be a function."); } let resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); const token = this; this.promise.then((cancel) => { if (!token._listeners) return; let i = token._listeners.length; while (i-- > 0) { token._listeners[i](cancel); } token._listeners = null; }); this.promise.then = (onfulfilled) => { let _resolve; const promise = new Promise((resolve) => { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = function reject() { token.unsubscribe(_resolve); }; return promise; }; executor(function cancel(message, config, request) { if (token.reason) { return; } token.reason = new CanceledError_default(message, config, request); resolvePromise(token.reason); }); } throwIfRequested() { if (this.reason) { throw this.reason; } } subscribe(listener) { if (this.reason) { listener(this.reason); return; } if (this._listeners) { this._listeners.push(listener); } else { this._listeners = [listener]; } } unsubscribe(listener) { if (!this._listeners) { return; } const index = this._listeners.indexOf(listener); if (index !== -1) { this._listeners.splice(index, 1); } } toAbortSignal() { const controller = new AbortController; const abort = (err) => { controller.abort(err); }; this.subscribe(abort); controller.signal.unsubscribe = () => this.unsubscribe(abort); return controller.signal; } static source() { let cancel; const token = new CancelToken(function executor(c) { cancel = c; }); return { token, cancel }; } } var CancelToken_default = CancelToken; // node_modules/axios/lib/helpers/spread.js function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; } // node_modules/axios/lib/helpers/isAxiosError.js function isAxiosError(payload) { return utils_default.isObject(payload) && payload.isAxiosError === true; } // node_modules/axios/lib/helpers/HttpStatusCode.js var HttpStatusCode = { Continue: 100, SwitchingProtocols: 101, Processing: 102, EarlyHints: 103, Ok: 200, Created: 201, Accepted: 202, NonAuthoritativeInformation: 203, NoContent: 204, ResetContent: 205, PartialContent: 206, MultiStatus: 207, AlreadyReported: 208, ImUsed: 226, MultipleChoices: 300, MovedPermanently: 301, Found: 302, SeeOther: 303, NotModified: 304, UseProxy: 305, Unused: 306, TemporaryRedirect: 307, PermanentRedirect: 308, BadRequest: 400, Unauthorized: 401, PaymentRequired: 402, Forbidden: 403, NotFound: 404, MethodNotAllowed: 405, NotAcceptable: 406, ProxyAuthenticationRequired: 407, RequestTimeout: 408, Conflict: 409, Gone: 410, LengthRequired: 411, PreconditionFailed: 412, PayloadTooLarge: 413, UriTooLong: 414, UnsupportedMediaType: 415, RangeNotSatisfiable: 416, ExpectationFailed: 417, ImATeapot: 418, MisdirectedRequest: 421, UnprocessableEntity: 422, Locked: 423, FailedDependency: 424, TooEarly: 425, UpgradeRequired: 426, PreconditionRequired: 428, TooManyRequests: 429, RequestHeaderFieldsTooLarge: 431, UnavailableForLegalReasons: 451, InternalServerError: 500, NotImplemented: 501, BadGateway: 502, ServiceUnavailable: 503, GatewayTimeout: 504, HttpVersionNotSupported: 505, VariantAlsoNegotiates: 506, InsufficientStorage: 507, LoopDetected: 508, NotExtended: 510, NetworkAuthenticationRequired: 511 }; Object.entries(HttpStatusCode).forEach(([key, value]) => { HttpStatusCode[value] = key; }); var HttpStatusCode_default = HttpStatusCode; // node_modules/axios/lib/axios.js function createInstance(defaultConfig) { const context = new Axios_default(defaultConfig); const instance = bind(Axios_default.prototype.request, context); utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true }); utils_default.extend(instance, context, null, { allOwnKeys: true }); instance.create = function create(instanceConfig) { return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; return instance; } var axios = createInstance(defaults_default); axios.Axios = Axios_default; axios.CanceledError = CanceledError_default; axios.CancelToken = CancelToken_default; axios.isCancel = isCancel; axios.VERSION = VERSION; axios.toFormData = toFormData_default; axios.AxiosError = AxiosError_default; axios.Cancel = axios.CanceledError; axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = spread; axios.isAxiosError = isAxiosError; axios.mergeConfig = mergeConfig; axios.AxiosHeaders = AxiosHeaders_default; axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); axios.getAdapter = adapters_default.getAdapter; axios.HttpStatusCode = HttpStatusCode_default; axios.default = axios; var axios_default = axios; // node:url function F(s) { return typeof s == "string"; } function K(s) { return typeof s == "object" && s !== null; } function w(s) { return s === null; } function Y(s) { return s == null; } function m() { this.protocol = null, this.slashes = null, this.auth = null, this.host = null, this.port = null, this.hostname = null, this.hash = null, this.search = null, this.query = null, this.pathname = null, this.path = null, this.href = null; } function I(s, r, t) { if (s && K(s) && s instanceof m) return s; var a = new m; return a.parse(s, r, t), a; } var { URL: J, URLSearchParams: X } = globalThis; var S = /^([a-z0-9.+-]+:)/i; var k = /:[0-9]*$/; var H = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; var Q = ["<", ">", '"', "`", " ", "\r", ` `, " "]; var E = ["{", "}", "|", "\\", "^", "`"].concat(Q); var N = ["'"].concat(E); var M = ["%", "/", "?", ";", "#"].concat(N); var D = ["/", "?", "#"]; var tt = 255; var G = /^[+a-z0-9A-Z_-]{0,63}$/; var st = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; var ht = { javascript: true, "javascript:": true }; var Z = { javascript: true, "javascript:": true }; var j = { http: true, https: true, ftp: true, gopher: true, file: true, "http:": true, "https:": true, "ftp:": true, "gopher:": true, "file:": true }; var B = { parse(s) { var r = decodeURIComponent; return (s + "").replace(/\+/g, " ").split("&").filter(Boolean).reduce(function(t, a, o) { var l = a.split("="), f = r(l[0] || ""), h = r(l[1] || ""), g = t[f]; return t[f] = g === undefined ? h : [].concat(g, h), t; }, {}); }, stringify(s) { var r = encodeURIComponent; return Object.keys(s || {}).reduce(function(t, a) { return [].concat(s[a]).forEach(function(o) { t.push(r(a) + "=" + r(o)); }), t; }, []).join("&").replace(/\s/g, "+"); } }; m.prototype.parse = function(s, r, t) { if (!F(s)) throw new TypeError("Parameter 'url' must be a string, not " + typeof s); var a = s.indexOf("?"), o = a !== -1 && a < s.indexOf("#") ? "?" : "#", l = s.split(o), f = /\\/g; l[0] = l[0].replace(f, "/"), s = l.join(o); var h = s; if (h = h.trim(), !t && s.split("#").length === 1) { var g = H.exec(h); if (g) return this.path = h, this.href = h, this.pathname = g[1], g[2] ? (this.search = g[2], r ? this.query = B.parse(this.search.substr(1)) : this.query = this.search.substr(1)) : r && (this.search = "", this.query = {}), this; } var c = S.exec(h); if (c) { c = c[0]; var v = c.toLowerCase(); this.protocol = v, h = h.substr(c.length); } if (t || c || h.match(/^\/\/[^@\/]+@[^@\/]+/)) { var U = h.substr(0, 2) === "//"; U && !(c && Z[c]) && (h = h.substr(2), this.slashes = true); } if (!Z[c] && (U || c && !j[c])) { for (var u = -1, n = 0;n < D.length; n++) { var b = h.indexOf(D[n]); b !== -1 && (u === -1 || b < u) && (u = b); } var R, p; u === -1 ? p = h.lastIndexOf("@") : p = h.lastIndexOf("@", u), p !== -1 && (R = h.slice(0, p), h = h.slice(p + 1), this.auth = decodeURIComponent(R)), u = -1; for (var n = 0;n < M.length; n++) { var b = h.indexOf(M[n]); b !== -1 && (u === -1 || b < u) && (u = b); } u === -1 && (u = h.length), this.host = h.slice(0, u), h = h.slice(u), this.parseHost(), this.hostname = this.hostname || ""; var C = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]"; if (!C) for (var e = this.hostname.split(/\./), n = 0, i = e.length;n < i; n++) { var O = e[n]; if (!!O && !O.match(G)) { for (var y = "", d = 0, L = O.length;d < L; d++) O.charCodeAt(d) > 127 ? y += "x" : y += O[d]; if (!y.match(G)) { var x = e.slice(0, n), q = e.slice(n + 1), A = O.match(st); A && (x.push(A[1]), q.unshift(A[2])), q.length && (h = "/" + q.join(".") + h), this.hostname = x.join("."); break; } } } this.hostname.length > tt ? this.hostname = "" : this.hostname = this.hostname.toLowerCase(), C || (this.hostname = new J(`https://${this.hostname}`).hostname); var $ = this.port ? ":" + this.port : "", V = this.hostname || ""; this.host = V + $, this.href += this.host, C && (this.hostname = this.hostname.substr(1, this.hostname.length - 2), h[0] !== "/" && (h = "/" + h)); } if (!ht[v]) for (var n = 0, i = N.length;n < i; n++) { var P = N[n]; if (h.indexOf(P) !== -1) { var z = encodeURIComponent(P); z === P && (z = escape(P)), h = h.split(P).join(z); } } var T = h.indexOf("#"); T !== -1 && (this.hash = h.substr(T), h = h.slice(0, T)); var _ = h.indexOf("?"); if (_ !== -1 ? (this.search = h.substr(_), this.query = h.substr(_ + 1), r && (this.query = B.parse(this.query)), h = h.slice(0, _)) : r && (this.search = "", this.query = {}), h && (this.pathname = h), j[v] && this.hostname && !this.pathname && (this.pathname = "/"), this.pathname || this.search) { var $ = this.pathname || "", W = this.search || ""; this.path = $ + W; } return this.href = this.format(), this; }; m.prototype.format = function() { var s = this.auth || ""; s && (s = encodeURIComponent(s), s = s.replace(/%3A/i, ":"), s += "@"); var r = this.protocol || "", t = this.pathname || "", a = this.hash || "", o = false, l = ""; this.host ? o = s + this.host : this.hostname && (o = s + (this.hostname.indexOf(":") === -1 ? this.hostname : "[" + this.hostname + "]"), this.port && (o += ":" + this.port)), this.query && K(this.query) && Object.keys(this.query).length && (l = B.stringify(this.query)); var f = this.search || l && "?" + l || ""; return r && r.substr(-1) !== ":" && (r += ":"), this.slashes || (!r || j[r]) && o !== false ? (o = "//" + (o || ""), t && t.charAt(0) !== "/" && (t = "/" + t)) : o || (o = ""), a && a.charAt(0) !== "#" && (a = "#" + a), f && f.charAt(0) !== "?" && (f = "?" + f), t = t.replace(/[?#]/g, function(h) { return encodeURIComponent(h); }), f = f.replace("#", "%23"), r + o + t + f + a; }; m.prototype.resolve = function(s) { return this.resolveObject(I(s, false, true)).format(); }; m.prototype.resolveObject = function(s) { if (F(s)) { var r = new m; r.parse(s, false, true), s = r; } for (var t = new m, a = Object.keys(this), o = 0;o < a.length; o++) { var l = a[o]; t[l] = this[l]; } if (t.hash = s.hash, s.href === "") return t.href = t.format(), t; if (s.slashes && !s.protocol) { for (var f = Object.keys(s), h = 0;h < f.length; h++) { var g = f[h]; g !== "protocol" && (t[g] = s[g]); } return j[t.protocol] && t.hostname && !t.pathname && (t.path = t.pathname = "/"), t.href = t.format(), t; } if (s.protocol && s.protocol !== t.protocol) { if (!j[s.protocol]) { for (var c = Object.keys(s), v = 0;v < c.length; v++) { var U = c[v]; t[U] = s[U]; } return t.href = t.format(), t; } if (t.protocol = s.protocol, !s.host && !Z[s.protocol]) { for (var i = (s.pathname || "").split("/");i.length && !(s.host = i.shift()); ) ; s.host || (s.host = ""), s.hostname || (s.hostname = ""), i[0] !== "" && i.unshift(""), i.length < 2 && i.unshift(""), t.pathname = i.join("/"); } else t.pathname = s.pathname; if (t.search = s.search, t.query = s.query, t.host = s.host || "", t.auth = s.auth, t.hostname = s.hostname || s.host, t.port = s.port, t.pathname || t.search) { var u = t.pathname || "", n = t.search || ""; t.path = u + n; } return t.slashes = t.slashes || s.slashes, t.href = t.format(), t; } var b = t.pathname && t.pathname.charAt(0) === "/", R = s.host || s.pathname && s.pathname.charAt(0) === "/", p = R || b || t.host && s.pathname, C = p, e = t.pathname && t.pathname.split("/") || [], i = s.pathname && s.pathname.split("/") || [], O = t.protocol && !j[t.protocol]; if (O && (t.hostname = "", t.port = null, t.host && (e[0] === "" ? e[0] = t.host : e.unshift(t.host)), t.host = "", s.protocol && (s.hostname = null, s.port = null, s.host && (i[0] === "" ? i[0] = s.host : i.unshift(s.host)), s.host = null), p = p && (i[0] === "" || e[0] === "")), R) t.host = s.host || s.host === "" ? s.host : t.host, t.hostname = s.hostname || s.hostname === "" ? s.hostname : t.hostname, t.search = s.search, t.query = s.query, e = i; else if (i.length) e || (e = []), e.pop(), e = e.concat(i), t.search = s.search, t.query = s.query; else if (!Y(s.search)) { if (O) { t.hostname = t.host = e.shift(); var y = t.host && t.host.indexOf("@") > 0 ? t.host.split("@") : false; y && (t.auth = y.shift(), t.host = t.hostname = y.shift()); } return t.search = s.search, t.query = s.query, (!w(t.pathname) || !w(t.search)) && (t.path = (t.pathname ? t.pathname : "") + (t.search ? t.search : "")), t.href = t.format(), t; } if (!e.length) return t.pathname = null, t.search ? t.path = "/" + t.search : t.path = null, t.href = t.format(), t; for (var d = e.slice(-1)[0], L = (t.host || s.host || e.length > 1) && (d === "." || d === "..") || d === "", x = 0, q = e.length;q >= 0; q--) d = e[q], d === "." ? e.splice(q, 1) : d === ".." ? (e.splice(q, 1), x++) : x && (e.splice(q, 1), x--); if (!p && !C) for (;x--; x) e.unshift(".."); p && e[0] !== "" && (!e[0] || e[0].charAt(0) !== "/") && e.unshift(""), L && e.join("/").substr(-1) !== "/" && e.push(""); var A = e[0] === "" || e[0] && e[0].charAt(0) === "/"; if (O) { t.hostname = t.host = A ? "" : e.length ? e.shift() : ""; var y = t.host && t.host.indexOf("@") > 0 ? t.host.split("@") : false; y && (t.auth = y.shift(), t.host = t.hostname = y.shift()); } return p = p || t.host && e.length, p && !A && e.unshift(""), e.length ? t.pathname = e.join("/") : (t.pathname = null, t.path = null), (!w(t.pathname) || !w(t.search)) && (t.path = (t.pathname ? t.pathname : "") + (t.search ? t.search : "")), t.auth = s.auth || t.auth, t.slashes = t.slashes || s.slashes, t.href = t.format(), t; }; m.prototype.parseHost = function() { var s = this.host, r = k.exec(s); r && (r = r[0], r !== ":" && (this.port = r.substr(1)), s = s.substr(0, s.length - r.length)), s && (this.hostname = s); }; // node_modules/zod-to-json-schema/dist/esm/Options.js var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); var defaultOptions = { name: undefined, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", definitionPath: "definitions", target: "jsonSchema7", strictUnions: false, definitions: {}, errorMessages: false, markdownDescription: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; // node_modules/zod-to-json-schema/dist/esm/Refs.js var getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name], jsonSchema: undefined } ])) }; }; // node_modules/zod-to-json-schema/dist/esm/errorMessages.js function addErrorMessage(res, key, errorMessage, refs) { if (!refs?.errorMessages) return; if (errorMessage) { res.errorMessage = { ...res.errorMessage, [key]: errorMessage }; } } function setResponseValueAndErrors(res, key, value, errorMessage, refs) { res[key] = value; addErrorMessage(res, key, errorMessage, refs); } // node_modules/zod/lib/index.mjs function getErrorMap() { return overrideErrorMap; } function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, overrideMap, overrideMap === errorMap ? undefined : errorMap ].filter((x) => !!x) }); ctx.common.issues.push(issue); } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } function processCreateParams(params) { if (!params) return {}; const { errorMap, invalid_type_error, required_error, description } = params; if (errorMap && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap) return { errorMap, description }; const customMap = (iss, ctx) => { var _a, _b; const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message !== null && message !== undefined ? message : ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: (_a = message !== null && message !== undefined ? message : required_error) !== null && _a !== undefined ? _a : ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: (_b = message !== null && message !== undefined ? message : invalid_type_error) !== null && _b !== undefined ? _b : ctx.defaultError }; }; return { errorMap: customMap, description }; } function timeRegexSource(args) { let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; if (args.precision) { regex = `${regex}\\.\\d{${args.precision}}`; } else if (args.precision == null) { regex = `${regex}(\\.\\d+)?`; } return regex; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}\$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}\$`); } function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / Math.pow(10, decCount); } function deepPartialify(schema) { if (schema instanceof ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema._def, shape: () => newShape }); } else if (schema instanceof ZodArray) { return new ZodArray({ ...schema._def, type: deepPartialify(schema.element) }); } else if (schema instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple) { return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0;index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var util; (function(util2) { util2.assertEqual = (val) => val; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error; } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); const filtered = {}; for (const k2 of validKeys) { filtered[k2] = obj[k2]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); class ZodError extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; var errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; var overrideErrorMap = errorMap; var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== undefined) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage = ""; const maps = errorMaps.filter((m2) => !!m2).slice().reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; class ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x) => x.status === "aborted"; var isDirty = (x) => x.status === "dirty"; var isValid = (x) => x.status === "valid"; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === undefined ? undefined : message.message; })(errorUtil || (errorUtil = {})); var _ZodEnum_cache; var _ZodNativeEnum_cache; class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } } var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); this._error = error; return this._error; } }; } }; class ZodType { constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus, ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params === null || params === undefined ? undefined : params.async) !== null && _a !== undefined ? _a : false, contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap }, path: (params === null || params === undefined ? undefined : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap, async: true }, path: (params === null || params === undefined ? undefined : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this, this._def); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(undefined).success; } isNullable() { return this.safeParse(null).success; } } var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+\$`; var emojiRegex; var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; var dateRegex = new RegExp(`^${dateRegexSource}\$`); class ZodString extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus; let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check.message }); status.dirty(); } } else if (check.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "date", message: check.message }); status.dirty(); } } else if (check.kind === "time") { const regex = timeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check.message }); status.dirty(); } } else if (check.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message) }); } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } datetime(options) { var _a, _b; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === undefined ? undefined : options.precision) === "undefined" ? null : options === null || options === undefined ? undefined : options.precision, offset: (_a = options === null || options === undefined ? undefined : options.offset) !== null && _a !== undefined ? _a : false, local: (_b = options === null || options === undefined ? undefined : options.local) !== null && _b !== undefined ? _b : false, ...errorUtil.errToObj(options === null || options === undefined ? undefined : options.message) }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options }); } return this._addCheck({ kind: "time", precision: typeof (options === null || options === undefined ? undefined : options.precision) === "undefined" ? null : options === null || options === undefined ? undefined : options.precision, ...errorUtil.errToObj(options === null || options === undefined ? undefined : options.message) }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options === null || options === undefined ? undefined : options.position, ...errorUtil.errToObj(options === null || options === undefined ? undefined : options.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } ZodString.create = (params) => { var _a; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a = params === null || params === undefined ? undefined : params.coerce) !== null && _a !== undefined ? _a : false, ...processCreateParams(params) }); }; class ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = undefined; const status = new ParseStatus; for (const check of this._def.checks) { if (check.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } } ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === undefined ? undefined : params.coerce) || false, ...processCreateParams(params) }); }; class ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { input.data = BigInt(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx2.parsedType }); return INVALID; } let ctx = undefined; const status = new ParseStatus; for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check) { return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } ZodBigInt.create = (params) => { var _a; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a = params === null || params === undefined ? undefined : params.coerce) !== null && _a !== undefined ? _a : false, ...processCreateParams(params) }); }; class ZodBoolean extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } } ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === undefined ? undefined : params.coerce) || false, ...processCreateParams(params) }); }; class ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus; let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date" }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date" }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check) { return new ZodDate({ ...this._def, checks: [...this._def.checks, check] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } } ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === undefined ? undefined : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; class ZodSymbol extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input.data); } } ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; class ZodUndefined extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input.data); } } ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; class ZodNull extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input.data); } } ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; class ZodAny extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } } ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; class ZodUnknown extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } } ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; class ZodNever extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } } ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; class ZodVoid extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input.data); } } ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; class ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: tooSmall ? def.exactLength.value : undefined, maximum: tooBig ? def.exactLength.value : undefined, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } } ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; class ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); return this._cached = { shape, keys }; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") ; else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...message !== undefined ? { errorMap: (issue, ctx) => { var _a, _b, _c, _d; const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === undefined ? undefined : _b.call(_a, issue, ctx).message) !== null && _c !== undefined ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) !== null && _d !== undefined ? _d : defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough" }); } extend(augmentation) { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } merge(merging) { const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } setKey(key, schema) { return this.augment({ [key]: schema }); } catchall(index) { return new ZodObject({ ...this._def, catchall: index }); } pick(mask) { const shape = {}; util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } }); return new ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } } ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; class ZodUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = undefined; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } } ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [undefined]; } else if (type instanceof ZodNull) { return [null]; } else if (type instanceof ZodOptional) { return [undefined, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; class ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } static create(discriminator, options, params) { const optionsMap = new Map; for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } } class ZodIntersection extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } } ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; class ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest }); } } ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; class ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } } class ZodMap extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) }; }); if (ctx.common.async) { const finalMap = new Map; return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = new Map; for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } } ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; class ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = new Set; for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; class ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error } }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { const me = this; return OK(async function(...args) { const error = new ZodError([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } } class ZodLazy extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } } ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; class ZodLiteral extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } } ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; class ZodEnum extends ZodType { constructor() { super(...arguments); _ZodEnum_cache.set(this, undefined); } _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); } if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values, newDef = this._def) { return ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } } _ZodEnum_cache = new WeakMap; ZodEnum.create = createZodEnum; class ZodNativeEnum extends ZodType { constructor() { super(...arguments); _ZodNativeEnum_cache.set(this, undefined); } _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); } if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } } _ZodNativeEnum_cache = new WeakMap; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; class ZodPromise extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } } ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; class ZodEffects extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return base; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return base; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } } ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; class ZodOptional extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(undefined); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; class ZodNullable extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; class ZodDefault extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } } ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; class ZodCatch extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } } ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; class ZodNaN extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } } ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var BRAND = Symbol("zod_brand"); class ZodBranded extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } } class ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a, b) { return new ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } } class ZodReadonly extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } } ZodReadonly.create = (type, params) => { return new ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; var late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var stringType = ZodString.create; var numberType = ZodNumber.create; var nanType = ZodNaN.create; var bigIntType = ZodBigInt.create; var booleanType = ZodBoolean.create; var dateType = ZodDate.create; var symbolType = ZodSymbol.create; var undefinedType = ZodUndefined.create; var nullType = ZodNull.create; var anyType = ZodAny.create; var unknownType = ZodUnknown.create; var neverType = ZodNever.create; var voidType = ZodVoid.create; var arrayType = ZodArray.create; var objectType = ZodObject.create; var strictObjectType = ZodObject.strictCreate; var unionType = ZodUnion.create; var discriminatedUnionType = ZodDiscriminatedUnion.create; var intersectionType = ZodIntersection.create; var tupleType = ZodTuple.create; var recordType = ZodRecord.create; var mapType = ZodMap.create; var setType = ZodSet.create; var functionType = ZodFunction.create; var lazyType = ZodLazy.create; var literalType = ZodLiteral.create; var enumType = ZodEnum.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; // node_modules/zod-to-json-schema/dist/esm/parsers/any.js function parseAnyDef() { return {}; } // node_modules/zod-to-json-schema/dist/esm/parsers/array.js function parseArrayDef(def, refs) { const res = { type: "array" }; if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); } if (def.maxLength) { setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } if (def.exactLength) { setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js function parseBigintDef(def, refs) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); break; } } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js function parseBooleanDef() { return { type: "boolean" }; } // node_modules/zod-to-json-schema/dist/esm/parsers/branded.js function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/catch.js var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; // node_modules/zod-to-json-schema/dist/esm/parsers/date.js function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy ?? refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def, refs); } } var integerDateParser = (def, refs) => { const res = { type: "integer", format: "unix-time" }; if (refs.target === "openApi3") { return res; } for (const check of def.checks) { switch (check.kind) { case "min": setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); break; case "max": setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); break; } } return res; }; // node_modules/zod-to-json-schema/dist/esm/parsers/default.js function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } // node_modules/zod-to-json-schema/dist/esm/parsers/effects.js function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {}; } // node_modules/zod-to-json-schema/dist/esm/parsers/enum.js function parseEnumDef(def) { return { type: "string", enum: def.values }; } // node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined; const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); if (schema.unevaluatedProperties === undefined) { unevaluatedProperties = undefined; } } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } else { unevaluatedProperties = undefined; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf, ...unevaluatedProperties } : undefined; } var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; // node_modules/zod-to-json-schema/dist/esm/parsers/literal.js function parseLiteralDef(def, refs) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } if (refs.target === "openApi3") { return { type: parsedType === "bigint" ? "integer" : parsedType, enum: [def.value] }; } return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value }; } // node_modules/zod-to-json-schema/dist/esm/parsers/string.js function parseStringDef(def, refs) { const res = { type: "string" }; function processPattern(value) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(value) : value; } if (def.checks) { for (const check of def.checks) { switch (check.kind) { case "min": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); break; case "max": setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check.message, refs); break; } break; case "url": addFormat(res, "uri", check.message, refs); break; case "uuid": addFormat(res, "uuid", check.message, refs); break; case "regex": addPattern(res, check.regex, check.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check.message, refs); break; case "startsWith": addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); break; case "endsWith": addPattern(res, RegExp(`${processPattern(check.value)}\$`), check.message, refs); break; case "datetime": addFormat(res, "date-time", check.message, refs); break; case "date": addFormat(res, "date", check.message, refs); break; case "time": addFormat(res, "time", check.message, refs); break; case "duration": addFormat(res, "duration", check.message, refs); break; case "length": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); break; case "includes": { addPattern(res, RegExp(processPattern(check.value)), check.message, refs); break; } case "ip": { if (check.version !== "v6") { addFormat(res, "ipv4", check.message, refs); } if (check.version !== "v4") { addFormat(res, "ipv6", check.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji, check.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check.message, refs); break; } case "contentEncoding:base64": { setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check.message, refs); } case "toLowerCase": case "toUpperCase": case "trim": break; default: ((_) => { })(check); } } } return res; } var emojiRegex2; var zodPatterns = { cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, emoji: () => { if (emojiRegex2 === undefined) { emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } return emojiRegex2; }, uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/ }; var escapeNonAlphaNumeric = (value) => Array.from(value).map((c) => /[a-zA-Z0-9]/.test(c) ? c : `\\${c}`).join(""); var addFormat = (schema, value, message, refs) => { if (schema.format || schema.anyOf?.some((x) => x.format)) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format, ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } }); delete schema.format; if (schema.errorMessage) { delete schema.errorMessage.format; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { setResponseValueAndErrors(schema, "format", value, message, refs); } }; var addPattern = (schema, regex, message, refs) => { if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern, ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } }); delete schema.pattern; if (schema.errorMessage) { delete schema.errorMessage.pattern; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.allOf.push({ pattern: processRegExp(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { setResponseValueAndErrors(schema, "pattern", processRegExp(regex, refs), message, refs); } }; var processRegExp = (regexOrFunction, refs) => { const regex = typeof regexOrFunction === "function" ? regexOrFunction() : regexOrFunction; if (!refs.applyRegexFlags || !regex.flags) return regex.source; const flags = { i: regex.flags.includes("i"), m: regex.flags.includes("m"), s: regex.flags.includes("s") }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0;i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r\n]))`; continue; } else if (source[i] === "$") { pattern += `(\$|(?=[\r\n]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } try { const regexTest = new RegExp(pattern); } catch { console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); return regex.source; } return pattern; }; // node_modules/zod-to-json-schema/dist/esm/parsers/record.js function parseRecordDef(def, refs) { if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { type: "object", required: def.keyType._def.values, properties: def.keyType._def.values.reduce((acc, key) => ({ ...acc, [key]: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "properties", key] }) ?? {} }), {}), additionalProperties: false }; } const schema = { type: "object", additionalProperties: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? {} }; if (refs.target === "openApi3") { return schema; } if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { const { type, ...keyType } = parseStringDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } return schema; } // node_modules/zod-to-json-schema/dist/esm/parsers/map.js function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || {}; const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || {}; return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } // node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js function parseNativeEnumDef(def) { const object = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object[object[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object[key]); const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } // node_modules/zod-to-json-schema/dist/esm/parsers/never.js function parseNeverDef() { return { not: {} }; } // node_modules/zod-to-json-schema/dist/esm/parsers/null.js function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true } : { type: "null" }; } // node_modules/zod-to-json-schema/dist/esm/parsers/union.js function parseUnionDef(def, refs) { if (refs.target === "openApi3") return asAnyOf(def, refs); const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every((x) => (x._def.typeName in primitiveMappings) && (!x._def.checks || !x._def.checks.length))) { const types = options.reduce((types2, x) => { const type = primitiveMappings[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce((acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, []); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce((acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, []) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce((acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], []) }; } return asAnyOf(def, refs); } var primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`] })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); return anyOf.length ? { anyOf } : undefined; }; // node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { if (refs.target === "openApi3") { return { type: primitiveMappings[def.innerType._def.typeName], nullable: true }; } return { type: [ primitiveMappings[def.innerType._def.typeName], "null" ] }; } if (refs.target === "openApi3") { const base2 = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath] }); if (base2 && "$ref" in base2) return { allOf: [base2], nullable: true }; return base2 && { ...base2, nullable: true }; } const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } // node_modules/zod-to-json-schema/dist/esm/parsers/number.js function parseNumberDef(def, refs) { const res = { type: "number" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "int": res.type = "integer"; addErrorMessage(res, "type", check.message, refs); break; case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); break; } } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/object.js function decideAdditionalProperties(def, refs) { if (refs.removeAdditionalStrategy === "strict") { return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? true; } else { return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? true; } } function parseObjectDef(def, refs) { const result = { type: "object", ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { if (propDef === undefined || propDef._def === undefined) return acc; const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === undefined) return acc; return { properties: { ...acc.properties, [propName]: parsedDef }, required: propDef.isOptional() ? acc.required : [...acc.required, propName] }; }, { properties: {}, required: [] }), additionalProperties: decideAdditionalProperties(def, refs) }; if (!result.required.length) delete result.required; return result; } // node_modules/zod-to-json-schema/dist/esm/parsers/optional.js var parseOptionalDef = (def, refs) => { if (refs.currentPath.toString() === refs.propertyPath?.toString()) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [ { not: {} }, innerSchema ] } : {}; }; // node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const a = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== undefined) }; }; // node_modules/zod-to-json-schema/dist/esm/parsers/promise.js function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/set.js function parseSetDef(def, refs) { const items = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); } if (def.maxSize) { setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); } return schema; } // node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js function parseTupleDef(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []), additionalItems: parseDef(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"] }) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []) }; } } // node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js function parseUndefinedDef() { return { not: {} }; } // node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js function parseUnknownDef() { return {}; } // node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js var parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; // node_modules/zod-to-json-schema/dist/esm/parseDef.js function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); if (overrideResult !== ignoreOverride) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== undefined) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; refs.seen.set(def, newItem); const jsonSchema = selectParser(def, def.typeName, refs); if (jsonSchema) { addMeta(def, refs, jsonSchema); } newItem.jsonSchema = jsonSchema; return jsonSchema; } var get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); return {}; } return refs.$refStrategy === "seen" ? {} : undefined; } } }; var getRelativePath = (pathA, pathB) => { let i = 0; for (;i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; var selectParser = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); case ZodFirstPartyTypeKind.ZodUnion: case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); case ZodFirstPartyTypeKind.ZodLazy: return parseDef(def.getter()._def, refs); case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); case ZodFirstPartyTypeKind.ZodNaN: case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(); case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(); case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(); case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); case ZodFirstPartyTypeKind.ZodFunction: case ZodFirstPartyTypeKind.ZodVoid: case ZodFirstPartyTypeKind.ZodSymbol: return; default: return ((_) => { return; })(typeName); } }; var addMeta = (def, refs, jsonSchema) => { if (def.description) { jsonSchema.description = def.description; if (refs.markdownDescription) { jsonSchema.markdownDescription = def.description; } } return jsonSchema; }; // node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js var zodToJsonSchema = (schema, options) => { const refs = getRefs(options); const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ ...acc, [name2]: parseDef(schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name2] }, true) ?? {} }), {}) : undefined; const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name; const main = parseDef(schema._def, name === undefined ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name] }, false) ?? {}; const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined; if (title !== undefined) { main.title = title; } const combined = name === undefined ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name ].join("/"), [refs.definitionPath]: { ...definitions, [name]: main } }; if (refs.target === "jsonSchema7") { combined.$schema = "http://json-schema.org/draft-07/schema#"; } else if (refs.target === "jsonSchema2019-09") { combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } return combined; }; // src/index.ts var BASE_URL = "https://plato.so"; class Plato { apiKey; baseUrl; cookies; constructor({ apiKey, baseUrl = BASE_URL, cookies }) { this.apiKey = apiKey; this.baseUrl = baseUrl; this.cookies = cookies; } async startSession() { const session = new PlatoSession(this); await session.start(); return session; } } class PlatoSession { plato; sessionId = null; constructor(plato) { this.plato = plato; } get apiUrl() { const url = new J(this.plato.baseUrl); const port = url.port ? `:${url.port}` : ""; return `${url.protocol}//api.${url.hostname}${port}`; } get chromeWsUrl() { const url = new J(this.plato.baseUrl); const port = url.port ? `:${url.port}` : ""; return `${url.protocol === "https:" ? "wss" : "ws"}://${url.hostname}${port}/ws?browserSessionId=${this.sessionId}`; } get browserUrl() { const url = new J(this.plato.baseUrl); const port = url.port ? `:${url.port}` : ""; return `${url.protocol}//browser.${url.hostname}${port}/plato?browserSessionId=${this.sessionId}`; } async start() { const response = await axios_default.post(`${this.apiUrl}/start-session`, { cookies: this.plato.cookies }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); this.sessionId = response.data.session_id; console.log("Started Plato browser session", this.browserUrl); } async end() { const response = await axios_default.post(`${this.apiUrl}/end-session`, { session_id: this.sessionId }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); return response.data; } async navigate(url) { const response = await axios_default.post(`${this.apiUrl}/navigate`, { session_id: this.sessionId, url }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); return response.data; } async click(description) { const response = await axios_default.post(`${this.apiUrl}/click`, { session_id: this.sessionId, description }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); return response.data; } async type(text) { const response = await axios_default.post(`${this.apiUrl}/type`, { session_id: this.sessionId, text }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); return response.data; } async extract(description, { responseFormat }) { const jsonSchema = zodToJsonSchema(responseFormat); const response = await axios_default.post(`${this.apiUrl}/extract`, { session_id: this.sessionId, description, response_format: jsonSchema }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); return responseFormat.parse(response.data); } async task(task, { startUrl, responseFormat }) { const jsonSchema = responseFormat ? zodToJsonSchema(responseFormat) : undefined; const response = await axios_default.post(`${this.apiUrl}/task`, { session_id: this.sessionId, task, start_url: startUrl, response_format: jsonSchema }, { headers: { Authorization: `Bearer ${this.plato.apiKey}` } }); return responseFormat ? responseFormat.parse(response.data) : response.data; } monitor(url, ...args) { } job(jobId, ...args) { } async dispose() { await this.end(); } }