/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; // node_modules/reusify/reusify.js var require_reusify = __commonJS({ "node_modules/reusify/reusify.js"(exports, module2) { "use strict"; function reusify(Constructor) { var head = new Constructor(); var tail = head; function get() { var current = head; if (current.next) { head = current.next; } else { head = new Constructor(); tail = head; } current.next = null; return current; } function release(obj) { tail.next = obj; tail = obj; } return { get, release }; } module2.exports = reusify; } }); // node_modules/fastq/queue.js var require_queue = __commonJS({ "node_modules/fastq/queue.js"(exports, module2) { "use strict"; var reusify = require_reusify(); function fastqueue(context, worker, _concurrency) { if (typeof context === "function") { _concurrency = worker; worker = context; context = null; } if (!(_concurrency >= 1)) { throw new Error("fastqueue concurrency must be equal to or greater than 1"); } var cache = reusify(Task); var queueHead = null; var queueTail = null; var _running = 0; var errorHandler = null; var self = { push, drain: noop, saturated: noop, pause, paused: false, get concurrency() { return _concurrency; }, set concurrency(value) { if (!(value >= 1)) { throw new Error("fastqueue concurrency must be equal to or greater than 1"); } _concurrency = value; if (self.paused) return; for (; queueHead && _running < _concurrency; ) { _running++; release(); } }, running, resume, idle, length, getQueue, unshift, empty: noop, kill, killAndDrain, error }; return self; function running() { return _running; } function pause() { self.paused = true; } function length() { var current = queueHead; var counter = 0; while (current) { current = current.next; counter++; } return counter; } function getQueue() { var current = queueHead; var tasks = []; while (current) { tasks.push(current.value); current = current.next; } return tasks; } function resume() { if (!self.paused) return; self.paused = false; if (queueHead === null) { _running++; release(); return; } for (; queueHead && _running < _concurrency; ) { _running++; release(); } } function idle() { return _running === 0 && self.length() === 0; } function push(value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop; current.errorHandler = errorHandler; if (_running >= _concurrency || self.paused) { if (queueTail) { queueTail.next = current; queueTail = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function unshift(value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop; current.errorHandler = errorHandler; if (_running >= _concurrency || self.paused) { if (queueHead) { current.next = queueHead; queueHead = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function release(holder) { if (holder) { cache.release(holder); } var next = queueHead; if (next && _running <= _concurrency) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null; } queueHead = next.next; next.next = null; worker.call(context, next.value, next.worked); if (queueTail === null) { self.empty(); } } else { _running--; } } else if (--_running === 0) { self.drain(); } } function kill() { queueHead = null; queueTail = null; self.drain = noop; } function killAndDrain() { queueHead = null; queueTail = null; self.drain(); self.drain = noop; } function error(handler) { errorHandler = handler; } } function noop() { } function Task() { this.value = null; this.callback = noop; this.next = null; this.release = noop; this.context = null; this.errorHandler = null; var self = this; this.worked = function worked(err, result) { var callback = self.callback; var errorHandler = self.errorHandler; var val = self.value; self.value = null; self.callback = noop; if (self.errorHandler) { errorHandler(err, val); } callback.call(self.context, err, result); self.release(self); }; } function queueAsPromised(context, worker, _concurrency) { if (typeof context === "function") { _concurrency = worker; worker = context; context = null; } function asyncWrapper(arg, cb) { worker.call(this, arg).then(function(res) { cb(null, res); }, cb); } var queue = fastqueue(context, asyncWrapper, _concurrency); var pushCb = queue.push; var unshiftCb = queue.unshift; queue.push = push; queue.unshift = unshift; queue.drained = drained; return queue; function push(value) { var p = new Promise(function(resolve, reject) { pushCb(value, function(err, result) { if (err) { reject(err); return; } resolve(result); }); }); p.catch(noop); return p; } function unshift(value) { var p = new Promise(function(resolve, reject) { unshiftCb(value, function(err, result) { if (err) { reject(err); return; } resolve(result); }); }); p.catch(noop); return p; } function drained() { if (queue.idle()) { return new Promise(function(resolve) { resolve(); }); } var previousDrain = queue.drain; var p = new Promise(function(resolve) { queue.drain = function() { previousDrain(); resolve(); }; }); return p; } } module2.exports = fastqueue; module2.exports.promise = queueAsPromised; } }); // node_modules/@fastify/error/index.js var require_error = __commonJS({ "node_modules/@fastify/error/index.js"(exports, module2) { "use strict"; var { format } = require("util"); function toString() { return `${this.name} [${this.code}]: ${this.message}`; } function createError(code, message, statusCode = 500, Base = Error) { if (!code) throw new Error("Fastify error code must not be empty"); if (!message) throw new Error("Fastify error message must not be empty"); code = code.toUpperCase(); !statusCode && (statusCode = void 0); function FastifyError(...args) { if (!new.target) { return new FastifyError(...args); } this.code = code; this.name = "FastifyError"; this.statusCode = statusCode; const lastElement = args.length - 1; if (lastElement !== -1 && args[lastElement] && typeof args[lastElement] === "object" && "cause" in args[lastElement]) { this.cause = args.pop().cause; } this.message = format(message, ...args); Error.stackTraceLimit !== 0 && Error.captureStackTrace(this, FastifyError); } FastifyError.prototype = Object.create(Base.prototype, { constructor: { value: FastifyError, enumerable: false, writable: true, configurable: true } }); FastifyError.prototype[Symbol.toStringTag] = "Error"; FastifyError.prototype.toString = toString; return FastifyError; } module2.exports = createError; module2.exports.default = createError; module2.exports.createError = createError; } }); // node_modules/avvio/lib/errors.js var require_errors = __commonJS({ "node_modules/avvio/lib/errors.js"(exports, module2) { "use strict"; var { createError } = require_error(); module2.exports = { AVV_ERR_EXPOSE_ALREADY_DEFINED: createError( "AVV_ERR_EXPOSE_ALREADY_DEFINED", "'%s' is already defined, specify an expose option for '%s'" ), AVV_ERR_ATTRIBUTE_ALREADY_DEFINED: createError( "AVV_ERR_ATTRIBUTE_ALREADY_DEFINED", "'%s' is already defined" ), AVV_ERR_CALLBACK_NOT_FN: createError( "AVV_ERR_CALLBACK_NOT_FN", "Callback for '%s' hook is not a function. Received: '%s'" ), AVV_ERR_PLUGIN_NOT_VALID: createError( "AVV_ERR_PLUGIN_NOT_VALID", "Plugin must be a function or a promise. Received: '%s'" ), AVV_ERR_ROOT_PLG_BOOTED: createError( "AVV_ERR_ROOT_PLG_BOOTED", "Root plugin has already booted" ), AVV_ERR_PARENT_PLG_LOADED: createError( "AVV_ERR_PARENT_PLG_LOADED", "Impossible to load '%s' plugin because the parent '%s' was already loaded" ), AVV_ERR_READY_TIMEOUT: createError( "AVV_ERR_READY_TIMEOUT", "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" ), AVV_ERR_PLUGIN_EXEC_TIMEOUT: createError( "AVV_ERR_PLUGIN_EXEC_TIMEOUT", "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" ) }; } }); // node_modules/avvio/lib/symbols.js var require_symbols = __commonJS({ "node_modules/avvio/lib/symbols.js"(exports, module2) { "use strict"; var kAvvio = Symbol("avvio.Boot"); var kIsOnCloseHandler = Symbol("isOnCloseHandler"); var kThenifyDoNotWrap = Symbol("avvio.ThenifyDoNotWrap"); var kUntrackNode = Symbol("avvio.TimeTree.untrackNode"); var kTrackNode = Symbol("avvio.TimeTree.trackNode"); var kGetParent = Symbol("avvio.TimeTree.getParent"); var kGetNode = Symbol("avvio.TimeTree.getNode"); var kAddNode = Symbol("avvio.TimeTree.addNode"); var kPluginMeta = Symbol.for("plugin-meta"); module2.exports = { kAvvio, kIsOnCloseHandler, kThenifyDoNotWrap, kUntrackNode, kTrackNode, kGetParent, kGetNode, kAddNode, kPluginMeta }; } }); // node_modules/avvio/lib/time-tree.js var require_time_tree = __commonJS({ "node_modules/avvio/lib/time-tree.js"(exports, module2) { "use strict"; var { kUntrackNode, kTrackNode, kGetParent, kGetNode, kAddNode } = require_symbols(); var TimeTree = class { constructor() { this.root = null; this.tableId = /* @__PURE__ */ new Map(); this.tableLabel = /* @__PURE__ */ new Map(); } /** * @param {TimeTreeNode} node */ [kTrackNode](node) { this.tableId.set(node.id, node); if (this.tableLabel.has(node.label)) { this.tableLabel.get(node.label).push(node); } else { this.tableLabel.set(node.label, [node]); } } /** * @param {TimeTreeNode} node */ [kUntrackNode](node) { this.tableId.delete(node.id); const labelNode = this.tableLabel.get(node.label); labelNode.pop(); if (labelNode.length === 0) { this.tableLabel.delete(node.label); } } /** * @param {string} parent * @returns {TimeTreeNode} */ [kGetParent](parent) { if (parent === null) { return null; } else if (this.tableLabel.has(parent)) { const parentNode = this.tableLabel.get(parent); return parentNode[parentNode.length - 1]; } else { return null; } } /** * * @param {string} nodeId * @returns {TimeTreeNode} */ [kGetNode](nodeId) { return this.tableId.get(nodeId); } /** * @param {string} parent * @param {string} label * @param {number} start * @returns {TimeTreeNode["id"]} */ [kAddNode](parent, label, start) { const parentNode = this[kGetParent](parent); const isRoot = parentNode === null; if (isRoot) { this.root = { parent: null, id: "root", label, nodes: [], start, stop: null, diff: -1 }; this[kTrackNode](this.root); return this.root.id; } const nodeId = `${label}-${Math.random()}`; const childNode = { parent, id: nodeId, label, nodes: [], start, stop: null, diff: -1 }; parentNode.nodes.push(childNode); this[kTrackNode](childNode); return nodeId; } /** * @param {string} parent * @param {string} label * @param {number|undefined} start * @returns {TimeTreeNode["id"]} */ start(parent, label, start = Date.now()) { return this[kAddNode](parent, label, start); } /** * @param {string} nodeId * @param {number|undefined} stop */ stop(nodeId, stop = Date.now()) { const node = this[kGetNode](nodeId); if (node) { node.stop = stop; node.diff = node.stop - node.start || 0; this[kUntrackNode](node); } } /** * @returns {TimeTreeNode} */ toJSON() { return Object.assign({}, this.root); } /** * @returns {string} */ prettyPrint() { return prettyPrintTimeTree(this.toJSON()); } }; function prettyPrintTimeTree(obj, prefix = "") { let result = prefix; const nodesCount = obj.nodes.length; const lastIndex = nodesCount - 1; result += `${obj.label} ${obj.diff} ms `; for (let i = 0; i < nodesCount; ++i) { const node = obj.nodes[i]; const prefix_ = prefix + (i === lastIndex ? " " : "\u2502 "); result += prefix; result += i === lastIndex ? "\u2514\u2500" : "\u251C\u2500"; result += node.nodes.length === 0 ? "\u2500 " : "\u252C "; result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2); } return result; } module2.exports = { TimeTree }; } }); // node_modules/avvio/lib/debug.js var require_debug = __commonJS({ "node_modules/avvio/lib/debug.js"(exports, module2) { "use strict"; var { debuglog } = require("util"); var debug = debuglog("avvio"); module2.exports = { debug }; } }); // node_modules/avvio/lib/create-promise.js var require_create_promise = __commonJS({ "node_modules/avvio/lib/create-promise.js"(exports, module2) { "use strict"; function createPromise() { const obj = { resolve: null, reject: null, promise: null }; obj.promise = new Promise((resolve, reject) => { obj.resolve = resolve; obj.reject = reject; }); return obj; } module2.exports = { createPromise }; } }); // node_modules/avvio/lib/get-plugin-name.js var require_get_plugin_name = __commonJS({ "node_modules/avvio/lib/get-plugin-name.js"(exports, module2) { "use strict"; var { kPluginMeta } = require_symbols(); function getPluginName(plugin, options) { if (plugin[kPluginMeta] && plugin[kPluginMeta].name) { return plugin[kPluginMeta].name; } if (options && options.name) { return options.name; } if (plugin.name) { return plugin.name; } else { return plugin.toString().split("\n").slice(0, 2).map((s) => s.trim()).join(" -- "); } } module2.exports = { getPluginName }; } }); // node_modules/avvio/lib/is-promise-like.js var require_is_promise_like = __commonJS({ "node_modules/avvio/lib/is-promise-like.js"(exports, module2) { "use strict"; function isPromiseLike(maybePromiseLike) { return maybePromiseLike !== null && typeof maybePromiseLike === "object" && typeof maybePromiseLike.then === "function"; } module2.exports = { isPromiseLike }; } }); // node_modules/avvio/lib/plugin.js var require_plugin = __commonJS({ "node_modules/avvio/lib/plugin.js"(exports, module2) { "use strict"; var { EventEmitter } = require("events"); var { inherits } = require("util"); var { debug } = require_debug(); var { createPromise } = require_create_promise(); var { AVV_ERR_PLUGIN_EXEC_TIMEOUT } = require_errors(); var { getPluginName } = require_get_plugin_name(); var { isPromiseLike } = require_is_promise_like(); function Plugin2(queue, func, options, isAfter, timeout) { this.queue = queue; this.func = func; this.options = options; this.isAfter = isAfter; this.timeout = timeout; this.started = false; this.name = getPluginName(func, options); this.queue.pause(); this._error = null; this.loaded = false; this._promise = null; this.startTime = null; } inherits(Plugin2, EventEmitter); Plugin2.prototype.exec = function(server2, callback) { debug("exec", this.name); this.server = server2; const func = this.func; const name = this.name; let completed = false; this.options = typeof this.options === "function" ? this.options(this.server) : this.options; let timer = null; const done = (execErr) => { if (completed) { debug("loading complete", name); return; } this._error = execErr; if (execErr) { debug("exec errored", name); } else { debug("exec completed", name); } completed = true; if (timer) { clearTimeout(timer); } callback(execErr); }; if (this.timeout > 0) { debug("setting up timeout", name, this.timeout); timer = setTimeout(function() { debug("timed out", name); timer = null; const readyTimeoutErr = new AVV_ERR_PLUGIN_EXEC_TIMEOUT(name); readyTimeoutErr.fn = func; done(readyTimeoutErr); }, this.timeout); } this.started = true; this.startTime = Date.now(); this.emit("start", this.server ? this.server.name : null, this.name, Date.now()); const maybePromiseLike = func(this.server, this.options, done); if (isPromiseLike(maybePromiseLike)) { debug("exec: resolving promise", name); maybePromiseLike.then( () => process.nextTick(done), (e) => process.nextTick(done, e) ); } }; Plugin2.prototype.loadedSoFar = function() { debug("loadedSoFar", this.name); if (this.loaded) { return Promise.resolve(); } const setup = () => { this.server.after((afterErr, callback) => { this._error = afterErr; this.queue.pause(); if (this._promise) { if (afterErr) { debug("rejecting promise", this.name, afterErr); this._promise.reject(afterErr); } else { debug("resolving promise", this.name); this._promise.resolve(); } this._promise = null; } process.nextTick(callback, afterErr); }); this.queue.resume(); }; let res; if (!this._promise) { this._promise = createPromise(); res = this._promise.promise; if (!this.server) { this.on("start", setup); } else { setup(); } } else { res = Promise.resolve(); } return res; }; Plugin2.prototype.enqueue = function(plugin, callback) { debug("enqueue", this.name, plugin.name); this.emit("enqueue", this.server ? this.server.name : null, this.name, Date.now()); this.queue.push(plugin, callback); }; Plugin2.prototype.finish = function(err, callback) { debug("finish", this.name, err); const done = () => { if (this.loaded) { return; } debug("loaded", this.name); this.emit("loaded", this.server ? this.server.name : null, this.name, Date.now()); this.loaded = true; callback(err); }; if (err) { if (this._promise) { this._promise.reject(err); this._promise = null; } done(); return; } const check = () => { debug("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap = () => { debug("wrap"); queueMicrotask(check); }; this._promise.resolve(); this._promise.promise.then(wrap, wrap); this._promise = null; } else { done(); } } else { debug("delayed", this.name); this.queue.drain = () => { debug("drain", this.name); this.queue.drain = noop; queueMicrotask(check); }; } }; queueMicrotask(check); this.queue.resume(); }; function noop() { } module2.exports = { Plugin: Plugin2 }; } }); // node_modules/avvio/lib/validate-plugin.js var require_validate_plugin = __commonJS({ "node_modules/avvio/lib/validate-plugin.js"(exports, module2) { "use strict"; var { AVV_ERR_PLUGIN_NOT_VALID } = require_errors(); function validatePlugin(maybePlugin) { if (!(maybePlugin && (typeof maybePlugin === "function" || typeof maybePlugin.then === "function"))) { if (Array.isArray(maybePlugin)) { throw new AVV_ERR_PLUGIN_NOT_VALID("array"); } else if (maybePlugin === null) { throw new AVV_ERR_PLUGIN_NOT_VALID("null"); } else { throw new AVV_ERR_PLUGIN_NOT_VALID(typeof maybePlugin); } } } module2.exports = { validatePlugin }; } }); // node_modules/avvio/lib/is-bundled-or-typescript-plugin.js var require_is_bundled_or_typescript_plugin = __commonJS({ "node_modules/avvio/lib/is-bundled-or-typescript-plugin.js"(exports, module2) { "use strict"; function isBundledOrTypescriptPlugin(maybeBundledOrTypescriptPlugin) { return maybeBundledOrTypescriptPlugin !== null && typeof maybeBundledOrTypescriptPlugin === "object" && typeof maybeBundledOrTypescriptPlugin.default === "function"; } module2.exports = { isBundledOrTypescriptPlugin }; } }); // node_modules/avvio/lib/thenify.js var require_thenify = __commonJS({ "node_modules/avvio/lib/thenify.js"(exports, module2) { "use strict"; var { debug } = require_debug(); var { kThenifyDoNotWrap } = require_symbols(); function thenify() { if (this.booted) { debug("thenify returning undefined because we are already booted"); return; } if (this[kThenifyDoNotWrap]) { this[kThenifyDoNotWrap] = false; return; } debug("thenify"); return (resolve, reject) => { const p = this._loadRegistered(); return p.then(() => { this[kThenifyDoNotWrap] = true; return resolve(this._server); }, reject); }; } module2.exports = { thenify }; } }); // node_modules/avvio/lib/execute-with-thenable.js var require_execute_with_thenable = __commonJS({ "node_modules/avvio/lib/execute-with-thenable.js"(exports, module2) { "use strict"; var { isPromiseLike } = require_is_promise_like(); var { kAvvio } = require_symbols(); function executeWithThenable(func, args, callback) { const result = func.apply(func, args); if (isPromiseLike(result) && !result[kAvvio]) { result.then(() => process.nextTick(callback), (error) => process.nextTick(callback, error)); } else if (callback) { process.nextTick(callback); } } module2.exports = { executeWithThenable }; } }); // node_modules/avvio/boot.js var require_boot = __commonJS({ "node_modules/avvio/boot.js"(exports, module2) { "use strict"; var fastq = require_queue(); var EE = require("events").EventEmitter; var inherits = require("util").inherits; var { AVV_ERR_EXPOSE_ALREADY_DEFINED, AVV_ERR_CALLBACK_NOT_FN, AVV_ERR_ROOT_PLG_BOOTED, AVV_ERR_READY_TIMEOUT, AVV_ERR_ATTRIBUTE_ALREADY_DEFINED } = require_errors(); var { kAvvio, kIsOnCloseHandler } = require_symbols(); var { TimeTree } = require_time_tree(); var { Plugin: Plugin2 } = require_plugin(); var { debug } = require_debug(); var { validatePlugin } = require_validate_plugin(); var { isBundledOrTypescriptPlugin } = require_is_bundled_or_typescript_plugin(); var { isPromiseLike } = require_is_promise_like(); var { thenify } = require_thenify(); var { executeWithThenable } = require_execute_with_thenable(); function Boot(server2, opts, done) { if (typeof server2 === "function" && arguments.length === 1) { done = server2; opts = {}; server2 = null; } if (typeof opts === "function") { done = opts; opts = {}; } opts = opts || {}; opts.autostart = opts.autostart !== false; opts.timeout = Number(opts.timeout) || 0; opts.expose = opts.expose || {}; if (!new.target) { return new Boot(server2, opts, done); } this._server = server2 || this; this._opts = opts; if (server2) { this._expose(); } this._current = []; this._error = null; this._lastUsed = null; this.setMaxListeners(0); if (done) { this.once("start", done); } this.started = false; this.booted = false; this.pluginTree = new TimeTree(); this._readyQ = fastq(this, callWithCbOrNextTick, 1); this._readyQ.pause(); this._readyQ.drain = () => { this.emit("start"); this._readyQ.drain = noop; }; this._closeQ = fastq(this, closeWithCbOrNextTick, 1); this._closeQ.pause(); this._closeQ.drain = () => { this.emit("close"); this._closeQ.drain = noop; }; this._doStart = null; const instance = this; this._root = new Plugin2(fastq(this, this._loadPluginNextTick, 1), function root(server3, opts2, done2) { instance._doStart = done2; opts2.autostart && instance.start(); }, opts, false, 0); this._trackPluginLoading(this._root); this._loadPlugin(this._root, (err) => { debug("root plugin ready"); try { this.emit("preReady"); this._root = null; } catch (preReadyError) { err = err || this._error || preReadyError; } if (err) { this._error = err; if (this._readyQ.length() === 0) { throw err; } } else { this.booted = true; } this._readyQ.resume(); }); } inherits(Boot, EE); Boot.prototype.start = function() { this.started = true; process.nextTick(this._doStart); return this; }; Boot.prototype.override = function(server2, func, opts) { return server2; }; Boot.prototype[kAvvio] = true; Boot.prototype.use = function(plugin, opts) { this._lastUsed = this._addPlugin(plugin, opts, false); return this; }; Boot.prototype._loadRegistered = function() { const plugin = this._current[0]; const weNeedToStart = !this.started && !this.booted; if (weNeedToStart) { process.nextTick(() => this._root.queue.resume()); } if (!plugin) { return Promise.resolve(); } return plugin.loadedSoFar(); }; Object.defineProperty(Boot.prototype, "then", { get: thenify }); Boot.prototype._addPlugin = function(pluginFn, opts, isAfter) { if (isBundledOrTypescriptPlugin(pluginFn)) { pluginFn = pluginFn.default; } validatePlugin(pluginFn); opts = opts || {}; if (this.booted) { throw new AVV_ERR_ROOT_PLG_BOOTED(); } const current = this._current[0]; let timeout = this._opts.timeout; if (!current.loaded && current.timeout > 0) { const delta = Date.now() - current.startTime; timeout = current.timeout - (delta + 3); } const plugin = new Plugin2(fastq(this, this._loadPluginNextTick, 1), pluginFn, opts, isAfter, timeout); this._trackPluginLoading(plugin); if (current.loaded) { throw new Error(plugin.name, current.name); } current.enqueue(plugin, (err) => { err && (this._error = err); }); return plugin; }; Boot.prototype._expose = function _expose() { const instance = this; const server2 = instance._server; const { use: useKey = "use", after: afterKey = "after", ready: readyKey = "ready", onClose: onCloseKey = "onClose", close: closeKey = "close" } = this._opts.expose; if (server2[useKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(useKey, "use"); } server2[useKey] = function(fn, opts) { instance.use(fn, opts); return this; }; if (server2[afterKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(afterKey, "after"); } server2[afterKey] = function(func) { if (typeof func !== "function") { return instance._loadRegistered(); } instance.after(encapsulateThreeParam(func, this)); return this; }; if (server2[readyKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(readyKey, "ready"); } server2[readyKey] = function(func) { if (func && typeof func !== "function") { throw new AVV_ERR_CALLBACK_NOT_FN(readyKey, typeof func); } return instance.ready(func ? encapsulateThreeParam(func, this) : void 0); }; if (server2[onCloseKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(onCloseKey, "onClose"); } server2[onCloseKey] = function(func) { if (typeof func !== "function") { throw new AVV_ERR_CALLBACK_NOT_FN(onCloseKey, typeof func); } instance.onClose(encapsulateTwoParam(func, this)); return this; }; if (server2[closeKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(closeKey, "close"); } server2[closeKey] = function(func) { if (func && typeof func !== "function") { throw new AVV_ERR_CALLBACK_NOT_FN(closeKey, typeof func); } if (func) { instance.close(encapsulateThreeParam(func, this)); return this; } return instance.close(); }; if (server2.then) { throw new AVV_ERR_ATTRIBUTE_ALREADY_DEFINED("then"); } Object.defineProperty(server2, "then", { get: thenify.bind(instance) }); server2[kAvvio] = true; }; Boot.prototype.after = function(func) { if (!func) { return this._loadRegistered(); } this._addPlugin(_after.bind(this), {}, true); function _after(s, opts, done) { callWithCbOrNextTick.call(this, func, done); } return this; }; Boot.prototype.onClose = function(func) { if (typeof func !== "function") { throw new AVV_ERR_CALLBACK_NOT_FN("onClose", typeof func); } func[kIsOnCloseHandler] = true; this._closeQ.unshift(func, (err) => { err && (this._error = err); }); return this; }; Boot.prototype.close = function(func) { let promise; if (func) { if (typeof func !== "function") { throw new AVV_ERR_CALLBACK_NOT_FN("close", typeof func); } } else { promise = new Promise(function(resolve, reject) { func = function(err) { if (err) { return reject(err); } resolve(); }; }); } this.ready(() => { this._error = null; this._closeQ.push(func); process.nextTick(this._closeQ.resume.bind(this._closeQ)); }); return promise; }; Boot.prototype.ready = function(func) { if (func) { if (typeof func !== "function") { throw new AVV_ERR_CALLBACK_NOT_FN("ready", typeof func); } this._readyQ.push(func); queueMicrotask(this.start.bind(this)); return; } return new Promise((resolve, reject) => { this._readyQ.push(readyPromiseCB); this.start(); const relativeContext = this._current[0].server; function readyPromiseCB(err, context, done) { if (err) { reject(err); } else { resolve(relativeContext); } process.nextTick(done); } }); }; Boot.prototype._trackPluginLoading = function(plugin) { var _a; const parentName = ((_a = this._current[0]) == null ? void 0 : _a.name) || null; plugin.once("start", (serverName, funcName, time) => { const nodeId = this.pluginTree.start(parentName || null, funcName, time); plugin.once("loaded", (serverName2, funcName2, time2) => { this.pluginTree.stop(nodeId, time2); }); }); }; Boot.prototype.prettyPrint = function() { return this.pluginTree.prettyPrint(); }; Boot.prototype.toJSON = function() { return this.pluginTree.toJSON(); }; Boot.prototype._loadPlugin = function(plugin, callback) { const instance = this; if (isPromiseLike(plugin.func)) { plugin.func.then((fn) => { if (typeof fn.default === "function") { fn = fn.default; } plugin.func = fn; this._loadPlugin(plugin, callback); }, callback); return; } const last = instance._current[0]; instance._current.unshift(plugin); if (instance._error && !plugin.isAfter) { debug("skipping loading of plugin as instance errored and it is not an after", plugin.name); process.nextTick(execCallback); return; } let server2 = last && last.server || instance._server; if (!plugin.isAfter) { try { server2 = instance.override(server2, plugin.func, plugin.options); } catch (overrideErr) { debug("override errored", plugin.name); return execCallback(overrideErr); } } plugin.exec(server2, execCallback); function execCallback(err) { plugin.finish(err, (err2) => { instance._current.shift(); callback(err2); }); } }; Boot.prototype._loadPluginNextTick = function(plugin, callback) { process.nextTick(this._loadPlugin.bind(this), plugin, callback); }; function noop() { } function callWithCbOrNextTick(func, cb) { const context = this._server; const err = this._error; this._error = null; if (func.length === 0) { this._error = err; executeWithThenable(func, [], cb); } else if (func.length === 1) { executeWithThenable(func, [err], cb); } else { if (this._opts.timeout === 0) { const wrapCb = (err2) => { this._error = err2; cb(this._error); }; if (func.length === 2) { func(err, wrapCb); } else { func(err, context, wrapCb); } } else { timeoutCall.call(this, func, err, context, cb); } } } function timeoutCall(func, rootErr, context, cb) { const name = func.name; debug("setting up ready timeout", name, this._opts.timeout); let timer = setTimeout(() => { debug("timed out", name); timer = null; const toutErr = new AVV_ERR_READY_TIMEOUT(name); toutErr.fn = func; this._error = toutErr; cb(toutErr); }, this._opts.timeout); if (func.length === 2) { func(rootErr, timeoutCb.bind(this)); } else { func(rootErr, context, timeoutCb.bind(this)); } function timeoutCb(err) { if (timer) { clearTimeout(timer); this._error = err; cb(this._error); } else { } } } function closeWithCbOrNextTick(func, cb) { const context = this._server; const isOnCloseHandler = func[kIsOnCloseHandler]; if (func.length === 0 || func.length === 1) { let promise; if (isOnCloseHandler) { promise = func(context); } else { promise = func(this._error); } if (promise && typeof promise.then === "function") { debug("resolving close/onClose promise"); promise.then( () => process.nextTick(cb), (e) => process.nextTick(cb, e) ); } else { process.nextTick(cb); } } else if (func.length === 2) { if (isOnCloseHandler) { func(context, cb); } else { func(this._error, cb); } } else { if (isOnCloseHandler) { func(context, cb); } else { func(this._error, context, cb); } } } function encapsulateTwoParam(func, that) { return _encapsulateTwoParam.bind(that); function _encapsulateTwoParam(context, cb) { let res; if (func.length === 0) { res = func(); if (res && res.then) { res.then(function() { process.nextTick(cb); }, cb); } else { process.nextTick(cb); } } else if (func.length === 1) { res = func(this); if (res && res.then) { res.then(function() { process.nextTick(cb); }, cb); } else { process.nextTick(cb); } } else { func(this, cb); } } } function encapsulateThreeParam(func, that) { return _encapsulateThreeParam.bind(that); function _encapsulateThreeParam(err, cb) { let res; if (!func) { process.nextTick(cb); } else if (func.length === 0) { res = func(); if (res && res.then) { res.then(function() { process.nextTick(cb, err); }, cb); } else { process.nextTick(cb, err); } } else if (func.length === 1) { res = func(err); if (res && res.then) { res.then(function() { process.nextTick(cb); }, cb); } else { process.nextTick(cb); } } else if (func.length === 2) { func(err, cb); } else { func(err, this, cb); } } } module2.exports = Boot; module2.exports.express = function(app) { return Boot(app, { expose: { use: "load" } }); }; } }); // node_modules/fastify/lib/symbols.js var require_symbols2 = __commonJS({ "node_modules/fastify/lib/symbols.js"(exports, module2) { "use strict"; var keys = { kAvvioBoot: Symbol("fastify.avvioBoot"), kChildren: Symbol("fastify.children"), kServerBindings: Symbol("fastify.serverBindings"), kBodyLimit: Symbol("fastify.bodyLimit"), kRoutePrefix: Symbol("fastify.routePrefix"), kLogLevel: Symbol("fastify.logLevel"), kLogSerializers: Symbol("fastify.logSerializers"), kHooks: Symbol("fastify.hooks"), kContentTypeParser: Symbol("fastify.contentTypeParser"), kState: Symbol("fastify.state"), kOptions: Symbol("fastify.options"), kDisableRequestLogging: Symbol("fastify.disableRequestLogging"), kPluginNameChain: Symbol("fastify.pluginNameChain"), kRouteContext: Symbol("fastify.context"), kPublicRouteContext: Symbol("fastify.routeOptions"), kGenReqId: Symbol("fastify.genReqId"), // Schema kSchemaController: Symbol("fastify.schemaController"), kSchemaHeaders: Symbol("headers-schema"), kSchemaParams: Symbol("params-schema"), kSchemaQuerystring: Symbol("querystring-schema"), kSchemaBody: Symbol("body-schema"), kSchemaResponse: Symbol("response-schema"), kSchemaErrorFormatter: Symbol("fastify.schemaErrorFormatter"), kSchemaVisited: Symbol("fastify.schemas.visited"), // Request kRequest: Symbol("fastify.Request"), kRequestPayloadStream: Symbol("fastify.RequestPayloadStream"), kRequestAcceptVersion: Symbol("fastify.RequestAcceptVersion"), kRequestCacheValidateFns: Symbol("fastify.request.cache.validateFns"), kRequestOriginalUrl: Symbol("fastify.request.originalUrl"), // 404 kFourOhFour: Symbol("fastify.404"), kCanSetNotFoundHandler: Symbol("fastify.canSetNotFoundHandler"), kFourOhFourLevelInstance: Symbol("fastify.404LogLevelInstance"), kFourOhFourContext: Symbol("fastify.404ContextKey"), kDefaultJsonParse: Symbol("fastify.defaultJSONParse"), // Reply kReply: Symbol("fastify.Reply"), kReplySerializer: Symbol("fastify.reply.serializer"), kReplyIsError: Symbol("fastify.reply.isError"), kReplyHeaders: Symbol("fastify.reply.headers"), kReplyTrailers: Symbol("fastify.reply.trailers"), kReplyHasStatusCode: Symbol("fastify.reply.hasStatusCode"), kReplyHijacked: Symbol("fastify.reply.hijacked"), kReplyStartTime: Symbol("fastify.reply.startTime"), kReplyNextErrorHandler: Symbol("fastify.reply.nextErrorHandler"), kReplyEndTime: Symbol("fastify.reply.endTime"), kReplyErrorHandlerCalled: Symbol("fastify.reply.errorHandlerCalled"), kReplyIsRunningOnErrorHook: Symbol("fastify.reply.isRunningOnErrorHook"), kReplySerializerDefault: Symbol("fastify.replySerializerDefault"), kReplyCacheSerializeFns: Symbol("fastify.reply.cache.serializeFns"), // This symbol is only meant to be used for fastify tests and should not be used for any other purpose kTestInternals: Symbol("fastify.testInternals"), kErrorHandler: Symbol("fastify.errorHandler"), kChildLoggerFactory: Symbol("fastify.childLoggerFactory"), kHasBeenDecorated: Symbol("fastify.hasBeenDecorated"), kKeepAliveConnections: Symbol("fastify.keepAliveConnections"), kRouteByFastify: Symbol("fastify.routeByFastify") }; module2.exports = keys; } }); // node_modules/process-warning/index.js var require_process_warning = __commonJS({ "node_modules/process-warning/index.js"(exports, module2) { "use strict"; var { format } = require("util"); function createDeprecation(params) { return createWarning({ ...params, name: "DeprecationWarning" }); } function createWarning({ name, code, message, unlimited = false } = {}) { if (!name) throw new Error("Warning name must not be empty"); if (!code) throw new Error("Warning code must not be empty"); if (!message) throw new Error("Warning message must not be empty"); if (typeof unlimited !== "boolean") throw new Error("Warning opts.unlimited must be a boolean"); code = code.toUpperCase(); let warningContainer = { [name]: function(a, b, c) { if (warning.emitted === true && warning.unlimited !== true) { return; } warning.emitted = true; process.emitWarning(warning.format(a, b, c), warning.name, warning.code); } }; if (unlimited) { warningContainer = { [name]: function(a, b, c) { warning.emitted = true; process.emitWarning(warning.format(a, b, c), warning.name, warning.code); } }; } const warning = warningContainer[name]; warning.emitted = false; warning.message = message; warning.unlimited = unlimited; warning.code = code; warning.format = function(a, b, c) { let formatted; if (a && b && c) { formatted = format(message, a, b, c); } else if (a && b) { formatted = format(message, a, b); } else if (a) { formatted = format(message, a); } else { formatted = message; } return formatted; }; return warning; } var out = { createWarning, createDeprecation }; module2.exports = out; module2.exports.default = out; module2.exports.processWarning = out; } }); // node_modules/fastify/lib/warnings.js var require_warnings = __commonJS({ "node_modules/fastify/lib/warnings.js"(exports, module2) { "use strict"; var { createDeprecation, createWarning } = require_process_warning(); var FSTDEP005 = createDeprecation({ code: "FSTDEP005", message: 'You are accessing the deprecated "request.connection" property. Use "request.socket" instead.' }); var FSTDEP006 = createDeprecation({ code: "FSTDEP006", message: "You are decorating Request/Reply with a reference type. This reference is shared amongst all requests. Use onRequest hook instead. Property: %s" }); var FSTDEP007 = createDeprecation({ code: "FSTDEP007", message: 'You are trying to set a HEAD route using "exposeHeadRoute" route flag when a sibling route is already set. See documentation for more info.' }); var FSTDEP008 = createDeprecation({ code: "FSTDEP008", message: 'You are using route constraints via the route { version: "..." } option, use { constraints: { version: "..." } } option instead.' }); var FSTDEP009 = createDeprecation({ code: "FSTDEP009", message: 'You are using a custom route versioning strategy via the server { versioning: "..." } option, use { constraints: { version: "..." } } option instead.' }); var FSTDEP010 = createDeprecation({ code: "FSTDEP010", message: 'Modifying the "reply.sent" property is deprecated. Use the "reply.hijack()" method instead.' }); var FSTDEP011 = createDeprecation({ code: "FSTDEP011", message: 'Variadic listen method is deprecated. Please use ".listen(optionsObject)" instead. The variadic signature will be removed in `fastify@5`.' }); var FSTDEP012 = createDeprecation({ code: "FSTDEP012", message: 'request.context property access is deprecated. Please use "request.routeOptions.config" or "request.routeOptions.schema" instead for accessing Route settings. The "request.context" will be removed in `fastify@5`.' }); var FSTDEP013 = createDeprecation({ code: "FSTDEP013", message: 'Direct return of "trailers" function is deprecated. Please use "callback" or "async-await" for return value. The support of direct return will removed in `fastify@5`.' }); var FSTDEP014 = createDeprecation({ code: "FSTDEP014", message: "You are trying to set/access the default route. This property is deprecated. Please, use setNotFoundHandler if you want to custom a 404 handler or the wildcard (*) to match all routes." }); var FSTDEP015 = createDeprecation({ code: "FSTDEP015", message: 'You are accessing the deprecated "request.routeSchema" property. Use "request.routeOptions.schema" instead. Property "req.routeSchema" will be removed in `fastify@5`.' }); var FSTDEP016 = createDeprecation({ code: "FSTDEP016", message: 'You are accessing the deprecated "request.routeConfig" property. Use "request.routeOptions.config" instead. Property "req.routeConfig" will be removed in `fastify@5`.' }); var FSTDEP017 = createDeprecation({ code: "FSTDEP017", message: 'You are accessing the deprecated "request.routerPath" property. Use "request.routeOptions.url" instead. Property "req.routerPath" will be removed in `fastify@5`.' }); var FSTDEP018 = createDeprecation({ code: "FSTDEP018", message: 'You are accessing the deprecated "request.routerMethod" property. Use "request.routeOptions.method" instead. Property "req.routerMethod" will be removed in `fastify@5`.' }); var FSTDEP019 = createDeprecation({ code: "FSTDEP019", message: 'reply.context property access is deprecated. Please use "request.routeOptions.config" or "request.routeOptions.schema" instead for accessing Route settings. The "reply.context" will be removed in `fastify@5`.' }); var FSTDEP020 = createDeprecation({ code: "FSTDEP020", message: 'You are using the deprecated "reply.getResponseTime()" method. Use the "reply.elapsedTime" property instead. Method "reply.getResponseTime()" will be removed in `fastify@5`.' }); var FSTDEP021 = createDeprecation({ code: "FSTDEP021", message: "The `reply.redirect()` method has a new signature: `reply.redirect(url: string, code?: number)`. It will be enforced in `fastify@v5`" }); var FSTWRN001 = createWarning({ name: "FastifyWarning", code: "FSTWRN001", message: "The %s schema for %s: %s is missing. This may indicate the schema is not well specified.", unlimited: true }); var FSTWRN002 = createWarning({ name: "FastifyWarning", code: "FSTWRN002", message: "The %s plugin being registered mixes async and callback styles, which will result in an error in `fastify@5`", unlimited: true }); module2.exports = { FSTDEP005, FSTDEP006, FSTDEP007, FSTDEP008, FSTDEP009, FSTDEP010, FSTDEP011, FSTDEP012, FSTDEP013, FSTDEP014, FSTDEP015, FSTDEP016, FSTDEP017, FSTDEP018, FSTDEP019, FSTDEP020, FSTDEP021, FSTWRN001, FSTWRN002 }; } }); // node_modules/fastify/lib/errors.js var require_errors2 = __commonJS({ "node_modules/fastify/lib/errors.js"(exports, module2) { "use strict"; var createError = require_error(); var codes = { /** * Basic */ FST_ERR_NOT_FOUND: createError( "FST_ERR_NOT_FOUND", "Not Found", 404 ), FST_ERR_OPTIONS_NOT_OBJ: createError( "FST_ERR_OPTIONS_NOT_OBJ", "Options must be an object", 500, TypeError ), FST_ERR_QSP_NOT_FN: createError( "FST_ERR_QSP_NOT_FN", "querystringParser option should be a function, instead got '%s'", 500, TypeError ), FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN: createError( "FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN", "schemaController.bucket option should be a function, instead got '%s'", 500, TypeError ), FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN: createError( "FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN", "schemaErrorFormatter option should be a non async function. Instead got '%s'.", 500, TypeError ), FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ: createError( "FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ", "ajv.customOptions option should be an object, instead got '%s'", 500, TypeError ), FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR: createError( "FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR", "ajv.plugins option should be an array, instead got '%s'", 500, TypeError ), FST_ERR_VERSION_CONSTRAINT_NOT_STR: createError( "FST_ERR_VERSION_CONSTRAINT_NOT_STR", "Version constraint should be a string.", 500, TypeError ), FST_ERR_VALIDATION: createError( "FST_ERR_VALIDATION", "%s", 400 ), FST_ERR_LISTEN_OPTIONS_INVALID: createError( "FST_ERR_LISTEN_OPTIONS_INVALID", "Invalid listen options: '%s'", 500, TypeError ), FST_ERR_ERROR_HANDLER_NOT_FN: createError( "FST_ERR_ERROR_HANDLER_NOT_FN", "Error Handler must be a function", 500, TypeError ), /** * ContentTypeParser */ FST_ERR_CTP_ALREADY_PRESENT: createError( "FST_ERR_CTP_ALREADY_PRESENT", "Content type parser '%s' already present." ), FST_ERR_CTP_INVALID_TYPE: createError( "FST_ERR_CTP_INVALID_TYPE", "The content type should be a string or a RegExp", 500, TypeError ), FST_ERR_CTP_EMPTY_TYPE: createError( "FST_ERR_CTP_EMPTY_TYPE", "The content type cannot be an empty string", 500, TypeError ), FST_ERR_CTP_INVALID_HANDLER: createError( "FST_ERR_CTP_INVALID_HANDLER", "The content type handler should be a function", 500, TypeError ), FST_ERR_CTP_INVALID_PARSE_TYPE: createError( "FST_ERR_CTP_INVALID_PARSE_TYPE", "The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.", 500, TypeError ), FST_ERR_CTP_BODY_TOO_LARGE: createError( "FST_ERR_CTP_BODY_TOO_LARGE", "Request body is too large", 413, RangeError ), FST_ERR_CTP_INVALID_MEDIA_TYPE: createError( "FST_ERR_CTP_INVALID_MEDIA_TYPE", "Unsupported Media Type: %s", 415 ), FST_ERR_CTP_INVALID_CONTENT_LENGTH: createError( "FST_ERR_CTP_INVALID_CONTENT_LENGTH", "Request body size did not match Content-Length", 400, RangeError ), FST_ERR_CTP_EMPTY_JSON_BODY: createError( "FST_ERR_CTP_EMPTY_JSON_BODY", "Body cannot be empty when content-type is set to 'application/json'", 400 ), FST_ERR_CTP_INSTANCE_ALREADY_STARTED: createError( "FST_ERR_CTP_INSTANCE_ALREADY_STARTED", 'Cannot call "%s" when fastify instance is already started!', 400 ), /** * decorate */ FST_ERR_DEC_ALREADY_PRESENT: createError( "FST_ERR_DEC_ALREADY_PRESENT", "The decorator '%s' has already been added!" ), FST_ERR_DEC_DEPENDENCY_INVALID_TYPE: createError( "FST_ERR_DEC_DEPENDENCY_INVALID_TYPE", "The dependencies of decorator '%s' must be of type Array.", 500, TypeError ), FST_ERR_DEC_MISSING_DEPENDENCY: createError( "FST_ERR_DEC_MISSING_DEPENDENCY", "The decorator is missing dependency '%s'." ), FST_ERR_DEC_AFTER_START: createError( "FST_ERR_DEC_AFTER_START", "The decorator '%s' has been added after start!" ), /** * hooks */ FST_ERR_HOOK_INVALID_TYPE: createError( "FST_ERR_HOOK_INVALID_TYPE", "The hook name must be a string", 500, TypeError ), FST_ERR_HOOK_INVALID_HANDLER: createError( "FST_ERR_HOOK_INVALID_HANDLER", "%s hook should be a function, instead got %s", 500, TypeError ), FST_ERR_HOOK_INVALID_ASYNC_HANDLER: createError( "FST_ERR_HOOK_INVALID_ASYNC_HANDLER", "Async function has too many arguments. Async hooks should not use the 'done' argument.", 500, TypeError ), FST_ERR_HOOK_NOT_SUPPORTED: createError( "FST_ERR_HOOK_NOT_SUPPORTED", "%s hook not supported!", 500, TypeError ), /** * Middlewares */ FST_ERR_MISSING_MIDDLEWARE: createError( "FST_ERR_MISSING_MIDDLEWARE", "You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.", 500 ), FST_ERR_HOOK_TIMEOUT: createError( "FST_ERR_HOOK_TIMEOUT", "A callback for '%s' hook timed out. You may have forgotten to call 'done' function or to resolve a Promise" ), /** * logger */ FST_ERR_LOG_INVALID_DESTINATION: createError( "FST_ERR_LOG_INVALID_DESTINATION", "Cannot specify both logger.stream and logger.file options" ), FST_ERR_LOG_INVALID_LOGGER: createError( "FST_ERR_LOG_INVALID_LOGGER", "Invalid logger object provided. The logger instance should have these functions(s): '%s'.", 500, TypeError ), /** * reply */ FST_ERR_REP_INVALID_PAYLOAD_TYPE: createError( "FST_ERR_REP_INVALID_PAYLOAD_TYPE", "Attempted to send payload of invalid type '%s'. Expected a string or Buffer.", 500, TypeError ), FST_ERR_REP_RESPONSE_BODY_CONSUMED: createError( "FST_ERR_REP_RESPONSE_BODY_CONSUMED", "Response.body is already consumed." ), FST_ERR_REP_ALREADY_SENT: createError( "FST_ERR_REP_ALREADY_SENT", 'Reply was already sent, did you forget to "return reply" in "%s" (%s)?' ), FST_ERR_REP_SENT_VALUE: createError( "FST_ERR_REP_SENT_VALUE", "The only possible value for reply.sent is true.", 500, TypeError ), FST_ERR_SEND_INSIDE_ONERR: createError( "FST_ERR_SEND_INSIDE_ONERR", "You cannot use `send` inside the `onError` hook" ), FST_ERR_SEND_UNDEFINED_ERR: createError( "FST_ERR_SEND_UNDEFINED_ERR", "Undefined error has occurred" ), FST_ERR_BAD_STATUS_CODE: createError( "FST_ERR_BAD_STATUS_CODE", "Called reply with an invalid status code: %s" ), FST_ERR_BAD_TRAILER_NAME: createError( "FST_ERR_BAD_TRAILER_NAME", "Called reply.trailer with an invalid header name: %s" ), FST_ERR_BAD_TRAILER_VALUE: createError( "FST_ERR_BAD_TRAILER_VALUE", "Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function." ), FST_ERR_FAILED_ERROR_SERIALIZATION: createError( "FST_ERR_FAILED_ERROR_SERIALIZATION", "Failed to serialize an error. Error: %s. Original error: %s" ), FST_ERR_MISSING_SERIALIZATION_FN: createError( "FST_ERR_MISSING_SERIALIZATION_FN", 'Missing serialization function. Key "%s"' ), FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN: createError( "FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN", 'Missing serialization function. Key "%s:%s"' ), FST_ERR_REQ_INVALID_VALIDATION_INVOCATION: createError( "FST_ERR_REQ_INVALID_VALIDATION_INVOCATION", 'Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.' ), /** * schemas */ FST_ERR_SCH_MISSING_ID: createError( "FST_ERR_SCH_MISSING_ID", "Missing schema $id property" ), FST_ERR_SCH_ALREADY_PRESENT: createError( "FST_ERR_SCH_ALREADY_PRESENT", "Schema with id '%s' already declared!" ), FST_ERR_SCH_CONTENT_MISSING_SCHEMA: createError( "FST_ERR_SCH_CONTENT_MISSING_SCHEMA", "Schema is missing for the content type '%s'" ), FST_ERR_SCH_DUPLICATE: createError( "FST_ERR_SCH_DUPLICATE", "Schema with '%s' already present!" ), FST_ERR_SCH_VALIDATION_BUILD: createError( "FST_ERR_SCH_VALIDATION_BUILD", "Failed building the validation schema for %s: %s, due to error %s" ), FST_ERR_SCH_SERIALIZATION_BUILD: createError( "FST_ERR_SCH_SERIALIZATION_BUILD", "Failed building the serialization schema for %s: %s, due to error %s" ), FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX: createError( "FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX", 'response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }' ), /** * http2 */ FST_ERR_HTTP2_INVALID_VERSION: createError( "FST_ERR_HTTP2_INVALID_VERSION", "HTTP2 is available only from node >= 8.8.1" ), /** * initialConfig */ FST_ERR_INIT_OPTS_INVALID: createError( "FST_ERR_INIT_OPTS_INVALID", "Invalid initialization options: '%s'" ), FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE: createError( "FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE", "Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method" ), /** * router */ FST_ERR_DUPLICATED_ROUTE: createError( "FST_ERR_DUPLICATED_ROUTE", "Method '%s' already declared for route '%s'" ), FST_ERR_BAD_URL: createError( "FST_ERR_BAD_URL", "'%s' is not a valid url component", 400, URIError ), FST_ERR_ASYNC_CONSTRAINT: createError( "FST_ERR_ASYNC_CONSTRAINT", "Unexpected error from async constraint", 500 ), FST_ERR_DEFAULT_ROUTE_INVALID_TYPE: createError( "FST_ERR_DEFAULT_ROUTE_INVALID_TYPE", "The defaultRoute type should be a function", 500, TypeError ), FST_ERR_INVALID_URL: createError( "FST_ERR_INVALID_URL", "URL must be a string. Received '%s'", 400, TypeError ), FST_ERR_ROUTE_OPTIONS_NOT_OBJ: createError( "FST_ERR_ROUTE_OPTIONS_NOT_OBJ", 'Options for "%s:%s" route must be an object', 500, TypeError ), FST_ERR_ROUTE_DUPLICATED_HANDLER: createError( "FST_ERR_ROUTE_DUPLICATED_HANDLER", 'Duplicate handler for "%s:%s" route is not allowed!', 500 ), FST_ERR_ROUTE_HANDLER_NOT_FN: createError( "FST_ERR_ROUTE_HANDLER_NOT_FN", "Error Handler for %s:%s route, if defined, must be a function", 500, TypeError ), FST_ERR_ROUTE_MISSING_HANDLER: createError( "FST_ERR_ROUTE_MISSING_HANDLER", 'Missing handler function for "%s:%s" route.', 500 ), FST_ERR_ROUTE_METHOD_INVALID: createError( "FST_ERR_ROUTE_METHOD_INVALID", "Provided method is invalid!", 500, TypeError ), FST_ERR_ROUTE_METHOD_NOT_SUPPORTED: createError( "FST_ERR_ROUTE_METHOD_NOT_SUPPORTED", "%s method is not supported.", 500 ), FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED: createError( "FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED", "Body validation schema for %s:%s route is not supported!", 500 ), FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT: createError( "FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT", "'bodyLimit' option must be an integer > 0. Got '%s'", 500, TypeError ), FST_ERR_ROUTE_REWRITE_NOT_STR: createError( "FST_ERR_ROUTE_REWRITE_NOT_STR", 'Rewrite url for "%s" needs to be of type "string" but received "%s"', 500, TypeError ), /** * again listen when close server */ FST_ERR_REOPENED_CLOSE_SERVER: createError( "FST_ERR_REOPENED_CLOSE_SERVER", "Fastify has already been closed and cannot be reopened" ), FST_ERR_REOPENED_SERVER: createError( "FST_ERR_REOPENED_SERVER", "Fastify is already listening" ), FST_ERR_INSTANCE_ALREADY_LISTENING: createError( "FST_ERR_INSTANCE_ALREADY_LISTENING", "Fastify instance is already listening. %s" ), /** * plugin */ FST_ERR_PLUGIN_VERSION_MISMATCH: createError( "FST_ERR_PLUGIN_VERSION_MISMATCH", "fastify-plugin: %s - expected '%s' fastify version, '%s' is installed" ), FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE: createError( "FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE", "The decorator '%s'%s is not present in %s" ), /** * Avvio Errors */ FST_ERR_PLUGIN_CALLBACK_NOT_FN: createError( "FST_ERR_PLUGIN_CALLBACK_NOT_FN", "fastify-plugin: %s", 500, TypeError ), FST_ERR_PLUGIN_NOT_VALID: createError( "FST_ERR_PLUGIN_NOT_VALID", "fastify-plugin: %s" ), FST_ERR_ROOT_PLG_BOOTED: createError( "FST_ERR_ROOT_PLG_BOOTED", "fastify-plugin: %s" ), FST_ERR_PARENT_PLUGIN_BOOTED: createError( "FST_ERR_PARENT_PLUGIN_BOOTED", "fastify-plugin: %s" ), FST_ERR_PLUGIN_TIMEOUT: createError( "FST_ERR_PLUGIN_TIMEOUT", "fastify-plugin: %s" ) }; function appendStackTrace(oldErr, newErr) { newErr.cause = oldErr; return newErr; } module2.exports = codes; module2.exports.appendStackTrace = appendStackTrace; module2.exports.AVVIO_ERRORS_MAP = { AVV_ERR_CALLBACK_NOT_FN: codes.FST_ERR_PLUGIN_CALLBACK_NOT_FN, AVV_ERR_PLUGIN_NOT_VALID: codes.FST_ERR_PLUGIN_NOT_VALID, AVV_ERR_ROOT_PLG_BOOTED: codes.FST_ERR_ROOT_PLG_BOOTED, AVV_ERR_PARENT_PLG_LOADED: codes.FST_ERR_PARENT_PLUGIN_BOOTED, AVV_ERR_READY_TIMEOUT: codes.FST_ERR_PLUGIN_TIMEOUT, AVV_ERR_PLUGIN_EXEC_TIMEOUT: codes.FST_ERR_PLUGIN_TIMEOUT }; } }); // node_modules/fastify/lib/hooks.js var require_hooks = __commonJS({ "node_modules/fastify/lib/hooks.js"(exports, module2) { "use strict"; var applicationHooks = [ "onRoute", "onRegister", "onReady", "onListen", "preClose", "onClose" ]; var lifecycleHooks = [ "onTimeout", "onRequest", "preParsing", "preValidation", "preSerialization", "preHandler", "onSend", "onResponse", "onError", "onRequestAbort" ]; var supportedHooks = lifecycleHooks.concat(applicationHooks); var { FST_ERR_HOOK_INVALID_TYPE, FST_ERR_HOOK_INVALID_HANDLER, FST_ERR_SEND_UNDEFINED_ERR, FST_ERR_HOOK_TIMEOUT, FST_ERR_HOOK_NOT_SUPPORTED, AVVIO_ERRORS_MAP, appendStackTrace } = require_errors2(); var { kChildren, kHooks, kRequestPayloadStream } = require_symbols2(); function Hooks() { this.onRequest = []; this.preParsing = []; this.preValidation = []; this.preSerialization = []; this.preHandler = []; this.onResponse = []; this.onSend = []; this.onError = []; this.onRoute = []; this.onRegister = []; this.onReady = []; this.onListen = []; this.onTimeout = []; this.onRequestAbort = []; this.preClose = []; } Hooks.prototype = /* @__PURE__ */ Object.create(null); Hooks.prototype.validate = function(hook, fn) { if (typeof hook !== "string") throw new FST_ERR_HOOK_INVALID_TYPE(); if (Array.isArray(this[hook]) === false) { throw new FST_ERR_HOOK_NOT_SUPPORTED(hook); } if (typeof fn !== "function") throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(fn)); }; Hooks.prototype.add = function(hook, fn) { this.validate(hook, fn); this[hook].push(fn); }; function buildHooks(h) { const hooks = new Hooks(); hooks.onRequest = h.onRequest.slice(); hooks.preParsing = h.preParsing.slice(); hooks.preValidation = h.preValidation.slice(); hooks.preSerialization = h.preSerialization.slice(); hooks.preHandler = h.preHandler.slice(); hooks.onSend = h.onSend.slice(); hooks.onResponse = h.onResponse.slice(); hooks.onError = h.onError.slice(); hooks.onRoute = h.onRoute.slice(); hooks.onRegister = h.onRegister.slice(); hooks.onTimeout = h.onTimeout.slice(); hooks.onRequestAbort = h.onRequestAbort.slice(); hooks.onReady = []; hooks.onListen = []; hooks.preClose = []; return hooks; } function hookRunnerApplication(hookName, boot, server2, cb) { const hooks = server2[kHooks][hookName]; let i = 0; let c = 0; next(); function exit(err) { if (err) { if (err.code === "AVV_ERR_READY_TIMEOUT") { err = appendStackTrace(err, new FST_ERR_HOOK_TIMEOUT(hookName)); } else { err = AVVIO_ERRORS_MAP[err.code] != null ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message)) : err; } cb(err); return; } cb(); } function next(err) { if (err) { exit(err); return; } if (i === hooks.length && c === server2[kChildren].length) { if (i === 0 && c === 0) { exit(); } else { boot(function manageTimeout(err2, done) { exit(err2); done(err2); }); } return; } if (i === hooks.length && c < server2[kChildren].length) { const child = server2[kChildren][c++]; hookRunnerApplication(hookName, boot, child, next); return; } boot(wrap(hooks[i++], server2)); next(); } function wrap(fn, server3) { return function(err, done) { if (err) { done(err); return; } if (fn.length === 1) { try { fn.call(server3, done); } catch (error) { done(error); } return; } try { const ret = fn.call(server3); if (ret && typeof ret.then === "function") { ret.then(done, done); return; } } catch (error) { err = error; } done(err); }; } } function onListenHookRunner(server2) { const hooks = server2[kHooks].onListen; const hooksLen = hooks.length; let i = 0; let c = 0; next(); function next(err) { err && server2.log.error(err); if (i === hooksLen) { while (c < server2[kChildren].length) { const child = server2[kChildren][c++]; onListenHookRunner(child); } return; } wrap(hooks[i++], server2, next); } async function wrap(fn, server3, done) { if (fn.length === 1) { try { fn.call(server3, done); } catch (e) { done(e); } return; } try { const ret = fn.call(server3); if (ret && typeof ret.then === "function") { ret.then(done, done); return; } done(); } catch (error) { done(error); } } } function hookRunnerGenerator(iterator) { return function hookRunner(functions, request, reply, cb) { let i = 0; function next(err) { if (err || i === functions.length) { cb(err, request, reply); return; } let result; try { result = iterator(functions[i++], request, reply, next); } catch (error) { cb(error, request, reply); return; } if (result && typeof result.then === "function") { result.then(handleResolve, handleReject); } } function handleResolve() { next(); } function handleReject(err) { if (!err) { err = new FST_ERR_SEND_UNDEFINED_ERR(); } cb(err, request, reply); } next(); }; } function onResponseHookIterator(fn, request, reply, next) { return fn(request, reply, next); } var onResponseHookRunner = hookRunnerGenerator(onResponseHookIterator); var preValidationHookRunner = hookRunnerGenerator(hookIterator); var preHandlerHookRunner = hookRunnerGenerator(hookIterator); var onTimeoutHookRunner = hookRunnerGenerator(hookIterator); var onRequestHookRunner = hookRunnerGenerator(hookIterator); function onSendHookRunner(functions, request, reply, payload, cb) { let i = 0; function next(err, newPayload) { if (err) { cb(err, request, reply, payload); return; } if (newPayload !== void 0) { payload = newPayload; } if (i === functions.length) { cb(null, request, reply, payload); return; } let result; try { result = functions[i++](request, reply, payload, next); } catch (error) { cb(error, request, reply); return; } if (result && typeof result.then === "function") { result.then(handleResolve, handleReject); } } function handleResolve(newPayload) { next(null, newPayload); } function handleReject(err) { if (!err) { err = new FST_ERR_SEND_UNDEFINED_ERR(); } cb(err, request, reply, payload); } next(); } var preSerializationHookRunner = onSendHookRunner; function preParsingHookRunner(functions, request, reply, cb) { let i = 0; function next(err, newPayload) { if (reply.sent) { return; } if (newPayload !== void 0) { request[kRequestPayloadStream] = newPayload; } if (err || i === functions.length) { cb(err, request, reply); return; } let result; try { result = functions[i++](request, reply, request[kRequestPayloadStream], next); } catch (error) { cb(error, request, reply); return; } if (result && typeof result.then === "function") { result.then(handleResolve, handleReject); } } function handleResolve(newPayload) { next(null, newPayload); } function handleReject(err) { if (!err) { err = new FST_ERR_SEND_UNDEFINED_ERR(); } cb(err, request, reply); } next(); } function onRequestAbortHookRunner(functions, request, cb) { let i = 0; function next(err) { if (err || i === functions.length) { cb(err, request); return; } let result; try { result = functions[i++](request, next); } catch (error) { cb(error, request); return; } if (result && typeof result.then === "function") { result.then(handleResolve, handleReject); } } function handleResolve() { next(); } function handleReject(err) { if (!err) { err = new FST_ERR_SEND_UNDEFINED_ERR(); } cb(err, request); } next(); } function hookIterator(fn, request, reply, next) { if (reply.sent === true) return void 0; return fn(request, reply, next); } module2.exports = { Hooks, buildHooks, hookRunnerGenerator, preParsingHookRunner, onResponseHookRunner, onSendHookRunner, preSerializationHookRunner, onRequestAbortHookRunner, hookIterator, hookRunnerApplication, onListenHookRunner, preHandlerHookRunner, preValidationHookRunner, onRequestHookRunner, onTimeoutHookRunner, lifecycleHooks, supportedHooks }; } }); // node_modules/fastify/lib/server.js var require_server = __commonJS({ "node_modules/fastify/lib/server.js"(exports, module2) { "use strict"; var http = require("http"); var https = require("https"); var dns = require("dns"); var { FSTDEP011 } = require_warnings(); var { kState, kOptions, kServerBindings } = require_symbols2(); var { onListenHookRunner } = require_hooks(); var { FST_ERR_HTTP2_INVALID_VERSION, FST_ERR_REOPENED_CLOSE_SERVER, FST_ERR_REOPENED_SERVER, FST_ERR_LISTEN_OPTIONS_INVALID } = require_errors2(); module2.exports.createServer = createServer; module2.exports.compileValidateHTTPVersion = compileValidateHTTPVersion; function defaultResolveServerListeningText(address) { return `Server listening at ${address}`; } function createServer(options, httpHandler) { const server2 = getServerInstance(options, httpHandler); function listen(listenOptions, ...args) { var _a, _b, _c; let cb = args.slice(-1).pop(); const firstArgType = Object.prototype.toString.call(arguments[0]); if (arguments.length === 0) { listenOptions = normalizeListenArgs([]); } else if (arguments.length > 0 && (firstArgType !== "[object Object]" && firstArgType !== "[object Function]")) { FSTDEP011(); listenOptions = normalizeListenArgs(Array.from(arguments)); cb = listenOptions.cb; } else if (args.length > 1) { FSTDEP011(); const hostPath = listenOptions.path ? [listenOptions.path] : [(_a = listenOptions.port) != null ? _a : 0, (_b = listenOptions.host) != null ? _b : "localhost"]; Object.assign(listenOptions, normalizeListenArgs([...hostPath, ...args])); } else { listenOptions.cb = cb; } if (listenOptions.signal) { if (typeof listenOptions.signal.on !== "function" && typeof listenOptions.signal.addEventListener !== "function") { throw new FST_ERR_LISTEN_OPTIONS_INVALID("Invalid options.signal"); } if (listenOptions.signal.aborted) { this.close(); } else { const onAborted = () => { this.close(); }; listenOptions.signal.addEventListener("abort", onAborted, { once: true }); } } let host; if (listenOptions.path == null) { host = (_c = listenOptions.host) != null ? _c : "localhost"; } else { host = listenOptions.host; } if (Object.prototype.hasOwnProperty.call(listenOptions, "host") === false) { listenOptions.host = host; } if (host === "localhost") { listenOptions.cb = (err, address) => { if (err) { cb(err, address); return; } multipleBindings.call(this, server2, httpHandler, options, listenOptions, () => { this[kState].listening = true; cb(null, address); onListenHookRunner(this); }); }; } else { listenOptions.cb = (err, address) => { if (err) { cb(err, address); return; } this[kState].listening = true; cb(null, address); onListenHookRunner(this); }; } if (cb === void 0) { const listening = listenPromise.call(this, server2, listenOptions); return listening.then((address) => { return new Promise((resolve, reject) => { if (host === "localhost") { multipleBindings.call(this, server2, httpHandler, options, listenOptions, () => { this[kState].listening = true; resolve(address); onListenHookRunner(this); }); } else { resolve(address); onListenHookRunner(this); } }); }); } this.ready(listenCallback.call(this, server2, listenOptions)); } return { server: server2, listen }; } function multipleBindings(mainServer, httpHandler, serverOpts, listenOptions, onListen) { this[kState].listening = false; dns.lookup(listenOptions.host, { all: true }, (dnsErr, addresses) => { if (dnsErr) { onListen(); return; } const isMainServerListening = mainServer.listening && serverOpts.serverFactory; let binding = 0; let bound = 0; if (!isMainServerListening) { const primaryAddress = mainServer.address(); for (const adr of addresses) { if (adr.address !== primaryAddress.address) { binding++; const secondaryOpts = Object.assign({}, listenOptions, { host: adr.address, port: primaryAddress.port, cb: (_ignoreErr) => { bound++; if (!_ignoreErr) { this[kServerBindings].push(secondaryServer); } if (bound === binding) { onListen(); } } }); const secondaryServer = getServerInstance(serverOpts, httpHandler); const closeSecondary = () => { secondaryServer.close(() => { }); if (serverOpts.forceCloseConnections === "idle") { secondaryServer.closeIdleConnections(); } else if (typeof secondaryServer.closeAllConnections === "function" && serverOpts.forceCloseConnections) { secondaryServer.closeAllConnections(); } }; secondaryServer.on("upgrade", mainServer.emit.bind(mainServer, "upgrade")); mainServer.on("unref", closeSecondary); mainServer.on("close", closeSecondary); mainServer.on("error", closeSecondary); this[kState].listening = false; listenCallback.call(this, secondaryServer, secondaryOpts)(); } } } if (binding === 0) { onListen(); return; } const originUnref = mainServer.unref; mainServer.unref = function() { originUnref.call(mainServer); mainServer.emit("unref"); }; }); } function listenCallback(server2, listenOptions) { const wrap = (err) => { server2.removeListener("error", wrap); if (!err) { const address = logServerAddress.call(this, server2, listenOptions.listenTextResolver || defaultResolveServerListeningText); listenOptions.cb(null, address); } else { this[kState].listening = false; listenOptions.cb(err, null); } }; return (err) => { if (err != null) return listenOptions.cb(err); if (this[kState].listening && this[kState].closing) { return listenOptions.cb(new FST_ERR_REOPENED_CLOSE_SERVER(), null); } else if (this[kState].listening) { return listenOptions.cb(new FST_ERR_REOPENED_SERVER(), null); } server2.once("error", wrap); if (!this[kState].closing) { server2.listen(listenOptions, wrap); this[kState].listening = true; } }; } function listenPromise(server2, listenOptions) { if (this[kState].listening && this[kState].closing) { return Promise.reject(new FST_ERR_REOPENED_CLOSE_SERVER()); } else if (this[kState].listening) { return Promise.reject(new FST_ERR_REOPENED_SERVER()); } return this.ready().then(() => { let errEventHandler; const errEvent = new Promise((resolve, reject) => { errEventHandler = (err) => { this[kState].listening = false; reject(err); }; server2.once("error", errEventHandler); }); const listen = new Promise((resolve, reject) => { server2.listen(listenOptions, () => { server2.removeListener("error", errEventHandler); resolve(logServerAddress.call(this, server2, listenOptions.listenTextResolver || defaultResolveServerListeningText)); }); this[kState].listening = true; }); return Promise.race([ errEvent, // e.g invalid port range error is always emitted before the server listening listen ]); }); } function compileValidateHTTPVersion(options) { let bypass = false; const map = /* @__PURE__ */ new Map(); if (options.serverFactory) { bypass = true; } if (options.http2) { map.set("2.0", true); if (options.https && options.https.allowHTTP1 === true) { map.set("1.1", true); map.set("1.0", true); } } else { map.set("1.1", true); map.set("1.0", true); } return function validateHTTPVersion(httpVersion) { return bypass || map.has(httpVersion); }; } function getServerInstance(options, httpHandler) { let server2 = null; const httpsOptions = options.https === true ? {} : options.https; if (options.serverFactory) { server2 = options.serverFactory(httpHandler, options); } else if (options.http2) { if (typeof httpsOptions === "object") { server2 = http2().createSecureServer(httpsOptions, httpHandler); } else { server2 = http2().createServer(httpHandler); } server2.on("session", sessionTimeout(options.http2SessionTimeout)); } else { if (httpsOptions) { server2 = https.createServer(httpsOptions, httpHandler); } else { server2 = http.createServer(options.http, httpHandler); } server2.keepAliveTimeout = options.keepAliveTimeout; server2.requestTimeout = options.requestTimeout; if (options.maxRequestsPerSocket > 0) { server2.maxRequestsPerSocket = options.maxRequestsPerSocket; } } if (!options.serverFactory) { server2.setTimeout(options.connectionTimeout); } return server2; } function normalizeListenArgs(args) { if (args.length === 0) { return { port: 0, host: "localhost" }; } const cb = typeof args[args.length - 1] === "function" ? args.pop() : void 0; const options = { cb }; const firstArg = args[0]; const argsLength = args.length; const lastArg = args[argsLength - 1]; if (typeof firstArg === "string" && isNaN(firstArg)) { options.path = firstArg; options.backlog = argsLength > 1 ? lastArg : void 0; } else { options.port = argsLength >= 1 && Number.isInteger(firstArg) ? firstArg : normalizePort(firstArg); options.host = argsLength >= 2 && args[1] ? args[1] : "localhost"; options.backlog = argsLength >= 3 ? args[2] : void 0; } return options; } function normalizePort(firstArg) { const port = Number(firstArg); return port >= 0 && !Number.isNaN(port) && Number.isInteger(port) ? port : 0; } function logServerAddress(server2, listenTextResolver) { let address = server2.address(); const isUnixSocket = typeof address === "string"; if (!isUnixSocket) { if (address.address.indexOf(":") === -1) { address = address.address + ":" + address.port; } else { address = "[" + address.address + "]:" + address.port; } } address = (isUnixSocket ? "" : "http" + (this[kOptions].https ? "s" : "") + "://") + address; const serverListeningText = listenTextResolver(address); this.log.info(serverListeningText); return address; } function http2() { try { return require("http2"); } catch (err) { throw new FST_ERR_HTTP2_INVALID_VERSION(); } } function sessionTimeout(timeout) { return function(session) { session.setTimeout(timeout, close); }; } function close() { this.close(); } } }); // node_modules/fastify/lib/validation.js var require_validation = __commonJS({ "node_modules/fastify/lib/validation.js"(exports, module2) { "use strict"; var { kSchemaHeaders: headersSchema, kSchemaParams: paramsSchema, kSchemaQuerystring: querystringSchema, kSchemaBody: bodySchema, kSchemaResponse: responseSchema } = require_symbols2(); var scChecker = /^[1-5]{1}[0-9]{2}$|^[1-5]xx$|^default$/; var { FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX } = require_errors2(); var { FSTWRN001 } = require_warnings(); function compileSchemasForSerialization(context, compile) { if (!context.schema || !context.schema.response) { return; } const { method, url } = context.config || {}; context[responseSchema] = Object.keys(context.schema.response).reduce(function(acc, statusCode) { const schema = context.schema.response[statusCode]; statusCode = statusCode.toLowerCase(); if (!scChecker.exec(statusCode)) { throw new FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX(); } if (schema.content) { const contentTypesSchemas = {}; for (const mediaName of Object.keys(schema.content)) { const contentSchema = schema.content[mediaName].schema; contentTypesSchemas[mediaName] = compile({ schema: contentSchema, url, method, httpStatus: statusCode, contentType: mediaName }); } acc[statusCode] = contentTypesSchemas; } else { acc[statusCode] = compile({ schema, url, method, httpStatus: statusCode }); } return acc; }, {}); } function compileSchemasForValidation(context, compile, isCustom) { const { schema } = context; if (!schema) { return; } const { method, url } = context.config || {}; const headers = schema.headers; if (headers && (isCustom || Object.getPrototypeOf(headers) !== Object.prototype)) { context[headersSchema] = compile({ schema: headers, method, url, httpPart: "headers" }); } else if (headers) { const headersSchemaLowerCase = {}; Object.keys(headers).forEach((k) => { headersSchemaLowerCase[k] = headers[k]; }); if (headersSchemaLowerCase.required instanceof Array) { headersSchemaLowerCase.required = headersSchemaLowerCase.required.map((h) => h.toLowerCase()); } if (headers.properties) { headersSchemaLowerCase.properties = {}; Object.keys(headers.properties).forEach((k) => { headersSchemaLowerCase.properties[k.toLowerCase()] = headers.properties[k]; }); } context[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url, httpPart: "headers" }); } else if (Object.prototype.hasOwnProperty.call(schema, "headers")) { FSTWRN001("headers", method, url); } if (schema.body) { context[bodySchema] = compile({ schema: schema.body, method, url, httpPart: "body" }); } else if (Object.prototype.hasOwnProperty.call(schema, "body")) { FSTWRN001("body", method, url); } if (schema.querystring) { context[querystringSchema] = compile({ schema: schema.querystring, method, url, httpPart: "querystring" }); } else if (Object.prototype.hasOwnProperty.call(schema, "querystring")) { FSTWRN001("querystring", method, url); } if (schema.params) { context[paramsSchema] = compile({ schema: schema.params, method, url, httpPart: "params" }); } else if (Object.prototype.hasOwnProperty.call(schema, "params")) { FSTWRN001("params", method, url); } } function validateParam(validatorFunction, request, paramName) { const isUndefined = request[paramName] === void 0; const ret = validatorFunction && validatorFunction(isUndefined ? null : request[paramName]); if (ret == null ? void 0 : ret.then) { return ret.then((res) => { return answer(res); }).catch((err) => { return err; }); } return answer(ret); function answer(ret2) { if (ret2 === false) return validatorFunction.errors; if (ret2 && ret2.error) return ret2.error; if (ret2 && ret2.value) request[paramName] = ret2.value; return false; } } function validate(context, request, execution) { const runExecution = execution === void 0; if (runExecution || !execution.skipParams) { const params = validateParam(context[paramsSchema], request, "params"); if (params) { if (typeof params.then !== "function") { return wrapValidationError(params, "params", context.schemaErrorFormatter); } else { return validateAsyncParams(params, context, request); } } } if (runExecution || !execution.skipBody) { const body = validateParam(context[bodySchema], request, "body"); if (body) { if (typeof body.then !== "function") { return wrapValidationError(body, "body", context.schemaErrorFormatter); } else { return validateAsyncBody(body, context, request); } } } if (runExecution || !execution.skipQuery) { const query = validateParam(context[querystringSchema], request, "query"); if (query) { if (typeof query.then !== "function") { return wrapValidationError(query, "querystring", context.schemaErrorFormatter); } else { return validateAsyncQuery(query, context, request); } } } const headers = validateParam(context[headersSchema], request, "headers"); if (headers) { if (typeof headers.then !== "function") { return wrapValidationError(headers, "headers", context.schemaErrorFormatter); } else { return validateAsyncHeaders(headers, context, request); } } return false; } function validateAsyncParams(validatePromise, context, request) { return validatePromise.then((paramsResult) => { if (paramsResult) { return wrapValidationError(paramsResult, "params", context.schemaErrorFormatter); } return validate(context, request, { skipParams: true }); }); } function validateAsyncBody(validatePromise, context, request) { return validatePromise.then((bodyResult) => { if (bodyResult) { return wrapValidationError(bodyResult, "body", context.schemaErrorFormatter); } return validate(context, request, { skipParams: true, skipBody: true }); }); } function validateAsyncQuery(validatePromise, context, request) { return validatePromise.then((queryResult) => { if (queryResult) { return wrapValidationError(queryResult, "querystring", context.schemaErrorFormatter); } return validate(context, request, { skipParams: true, skipBody: true, skipQuery: true }); }); } function validateAsyncHeaders(validatePromise, context, request) { return validatePromise.then((headersResult) => { if (headersResult) { return wrapValidationError(headersResult, "headers", context.schemaErrorFormatter); } return false; }); } function wrapValidationError(result, dataVar, schemaErrorFormatter) { if (result instanceof Error) { result.statusCode = result.statusCode || 400; result.code = result.code || "FST_ERR_VALIDATION"; result.validationContext = result.validationContext || dataVar; return result; } const error = schemaErrorFormatter(result, dataVar); error.statusCode = error.statusCode || 400; error.code = error.code || "FST_ERR_VALIDATION"; error.validation = result; error.validationContext = dataVar; return error; } module2.exports = { symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema }, compileSchemasForValidation, compileSchemasForSerialization, validate }; } }); // node_modules/fastify/lib/wrapThenable.js var require_wrapThenable = __commonJS({ "node_modules/fastify/lib/wrapThenable.js"(exports, module2) { "use strict"; var { kReplyIsError, kReplyHijacked } = require_symbols2(); function wrapThenable(thenable, reply) { thenable.then(function(payload) { if (reply[kReplyHijacked] === true) { return; } if (payload !== void 0 || reply.sent === false && reply.raw.headersSent === false && reply.request.raw.aborted === false) { try { reply.send(payload); } catch (err) { reply[kReplyIsError] = true; reply.send(err); } } }, function(err) { if (reply.sent === true) { reply.log.error({ err }, "Promise errored, but reply.sent = true was set"); return; } reply[kReplyIsError] = true; try { reply.send(err); } catch (err2) { reply.send(err2); } }); } module2.exports = wrapThenable; } }); // node_modules/fastify/lib/handleRequest.js var require_handleRequest = __commonJS({ "node_modules/fastify/lib/handleRequest.js"(exports, module2) { "use strict"; var { validate: validateSchema } = require_validation(); var { preValidationHookRunner, preHandlerHookRunner } = require_hooks(); var wrapThenable = require_wrapThenable(); var { kReplyIsError, kRouteContext } = require_symbols2(); function handleRequest(err, request, reply) { if (reply.sent === true) return; if (err != null) { reply[kReplyIsError] = true; reply.send(err); return; } const method = request.raw.method; const headers = request.headers; const context = request[kRouteContext]; if (method === "GET" || method === "HEAD") { handler(request, reply); return; } const contentType = headers["content-type"]; if (method === "POST" || method === "PUT" || method === "PATCH" || method === "TRACE" || method === "SEARCH" || method === "PROPFIND" || method === "PROPPATCH" || method === "LOCK" || method === "REPORT" || method === "MKCALENDAR") { if (contentType === void 0) { if (headers["transfer-encoding"] === void 0 && (headers["content-length"] === "0" || headers["content-length"] === void 0)) { handler(request, reply); } else { context.contentTypeParser.run("", handler, request, reply); } } else { context.contentTypeParser.run(contentType, handler, request, reply); } return; } if (method === "OPTIONS" || method === "DELETE") { if (contentType !== void 0 && (headers["transfer-encoding"] !== void 0 || headers["content-length"] !== void 0)) { context.contentTypeParser.run(contentType, handler, request, reply); } else { handler(request, reply); } return; } handler(request, reply); } function handler(request, reply) { try { if (request[kRouteContext].preValidation !== null) { preValidationHookRunner( request[kRouteContext].preValidation, request, reply, preValidationCallback ); } else { preValidationCallback(null, request, reply); } } catch (err) { preValidationCallback(err, request, reply); } } function preValidationCallback(err, request, reply) { if (reply.sent === true) return; if (err != null) { reply[kReplyIsError] = true; reply.send(err); return; } const validationErr = validateSchema(reply[kRouteContext], request); const isAsync = validationErr && typeof validationErr.then === "function" || false; if (isAsync) { const cb = validationCompleted.bind(null, request, reply); validationErr.then(cb, cb); } else { validationCompleted(request, reply, validationErr); } } function validationCompleted(request, reply, validationErr) { if (validationErr) { if (reply[kRouteContext].attachValidation === false) { reply.send(validationErr); return; } reply.request.validationError = validationErr; } if (request[kRouteContext].preHandler !== null) { preHandlerHookRunner( request[kRouteContext].preHandler, request, reply, preHandlerCallback ); } else { preHandlerCallback(null, request, reply); } } function preHandlerCallback(err, request, reply) { if (reply.sent) return; if (err != null) { reply[kReplyIsError] = true; reply.send(err); return; } let result; try { result = request[kRouteContext].handler(request, reply); } catch (err2) { reply[kReplyIsError] = true; reply.send(err2); return; } if (result !== void 0) { if (result !== null && typeof result.then === "function") { wrapThenable(result, reply); } else { reply.send(result); } } } module2.exports = handleRequest; module2.exports[Symbol.for("internals")] = { handler, preHandlerCallback }; } }); // node_modules/abstract-logging/index.js var require_abstract_logging = __commonJS({ "node_modules/abstract-logging/index.js"(exports, module2) { "use strict"; function noop() { } var proto = { fatal: noop, error: noop, warn: noop, info: noop, debug: noop, trace: noop }; Object.defineProperty(module2, "exports", { get() { return Object.create(proto); } }); } }); // node_modules/pino-std-serializers/lib/err-helpers.js var require_err_helpers = __commonJS({ "node_modules/pino-std-serializers/lib/err-helpers.js"(exports, module2) { "use strict"; var isErrorLike = (err) => { return err && typeof err.message === "string"; }; var getErrorCause = (err) => { if (!err) return; const cause = err.cause; if (typeof cause === "function") { const causeResult = err.cause(); return isErrorLike(causeResult) ? causeResult : void 0; } else { return isErrorLike(cause) ? cause : void 0; } }; var _stackWithCauses = (err, seen) => { if (!isErrorLike(err)) return ""; const stack = err.stack || ""; if (seen.has(err)) { return stack + "\ncauses have become circular..."; } const cause = getErrorCause(err); if (cause) { seen.add(err); return stack + "\ncaused by: " + _stackWithCauses(cause, seen); } else { return stack; } }; var stackWithCauses = (err) => _stackWithCauses(err, /* @__PURE__ */ new Set()); var _messageWithCauses = (err, seen, skip) => { if (!isErrorLike(err)) return ""; const message = skip ? "" : err.message || ""; if (seen.has(err)) { return message + ": ..."; } const cause = getErrorCause(err); if (cause) { seen.add(err); const skipIfVErrorStyleCause = typeof err.cause === "function"; return message + (skipIfVErrorStyleCause ? "" : ": ") + _messageWithCauses(cause, seen, skipIfVErrorStyleCause); } else { return message; } }; var messageWithCauses = (err) => _messageWithCauses(err, /* @__PURE__ */ new Set()); module2.exports = { isErrorLike, getErrorCause, stackWithCauses, messageWithCauses }; } }); // node_modules/pino-std-serializers/lib/err-proto.js var require_err_proto = __commonJS({ "node_modules/pino-std-serializers/lib/err-proto.js"(exports, module2) { "use strict"; var seen = Symbol("circular-ref-tag"); var rawSymbol = Symbol("pino-raw-err-ref"); var pinoErrProto = Object.create({}, { type: { enumerable: true, writable: true, value: void 0 }, message: { enumerable: true, writable: true, value: void 0 }, stack: { enumerable: true, writable: true, value: void 0 }, aggregateErrors: { enumerable: true, writable: true, value: void 0 }, raw: { enumerable: false, get: function() { return this[rawSymbol]; }, set: function(val) { this[rawSymbol] = val; } } }); Object.defineProperty(pinoErrProto, rawSymbol, { writable: true, value: {} }); module2.exports = { pinoErrProto, pinoErrorSymbols: { seen, rawSymbol } }; } }); // node_modules/pino-std-serializers/lib/err.js var require_err = __commonJS({ "node_modules/pino-std-serializers/lib/err.js"(exports, module2) { "use strict"; module2.exports = errSerializer; var { messageWithCauses, stackWithCauses, isErrorLike } = require_err_helpers(); var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); var { seen } = pinoErrorSymbols; var { toString } = Object.prototype; function errSerializer(err) { if (!isErrorLike(err)) { return err; } err[seen] = void 0; const _err = Object.create(pinoErrProto); _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; _err.message = messageWithCauses(err); _err.stack = stackWithCauses(err); if (Array.isArray(err.errors)) { _err.aggregateErrors = err.errors.map((err2) => errSerializer(err2)); } for (const key in err) { if (_err[key] === void 0) { const val = err[key]; if (isErrorLike(val)) { if (key !== "cause" && !Object.prototype.hasOwnProperty.call(val, seen)) { _err[key] = errSerializer(val); } } else { _err[key] = val; } } } delete err[seen]; _err.raw = err; return _err; } } }); // node_modules/pino-std-serializers/lib/err-with-cause.js var require_err_with_cause = __commonJS({ "node_modules/pino-std-serializers/lib/err-with-cause.js"(exports, module2) { "use strict"; module2.exports = errWithCauseSerializer; var { isErrorLike } = require_err_helpers(); var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); var { seen } = pinoErrorSymbols; var { toString } = Object.prototype; function errWithCauseSerializer(err) { if (!isErrorLike(err)) { return err; } err[seen] = void 0; const _err = Object.create(pinoErrProto); _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; _err.message = err.message; _err.stack = err.stack; if (Array.isArray(err.errors)) { _err.aggregateErrors = err.errors.map((err2) => errWithCauseSerializer(err2)); } if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) { _err.cause = errWithCauseSerializer(err.cause); } for (const key in err) { if (_err[key] === void 0) { const val = err[key]; if (isErrorLike(val)) { if (!Object.prototype.hasOwnProperty.call(val, seen)) { _err[key] = errWithCauseSerializer(val); } } else { _err[key] = val; } } } delete err[seen]; _err.raw = err; return _err; } } }); // node_modules/pino-std-serializers/lib/req.js var require_req = __commonJS({ "node_modules/pino-std-serializers/lib/req.js"(exports, module2) { "use strict"; module2.exports = { mapHttpRequest, reqSerializer }; var rawSymbol = Symbol("pino-raw-req-ref"); var pinoReqProto = Object.create({}, { id: { enumerable: true, writable: true, value: "" }, method: { enumerable: true, writable: true, value: "" }, url: { enumerable: true, writable: true, value: "" }, query: { enumerable: true, writable: true, value: "" }, params: { enumerable: true, writable: true, value: "" }, headers: { enumerable: true, writable: true, value: {} }, remoteAddress: { enumerable: true, writable: true, value: "" }, remotePort: { enumerable: true, writable: true, value: "" }, raw: { enumerable: false, get: function() { return this[rawSymbol]; }, set: function(val) { this[rawSymbol] = val; } } }); Object.defineProperty(pinoReqProto, rawSymbol, { writable: true, value: {} }); function reqSerializer(req) { const connection = req.info || req.socket; const _req = Object.create(pinoReqProto); _req.id = typeof req.id === "function" ? req.id() : req.id || (req.info ? req.info.id : void 0); _req.method = req.method; if (req.originalUrl) { _req.url = req.originalUrl; } else { const path = req.path; _req.url = typeof path === "string" ? path : req.url ? req.url.path || req.url : void 0; } if (req.query) { _req.query = req.query; } if (req.params) { _req.params = req.params; } _req.headers = req.headers; _req.remoteAddress = connection && connection.remoteAddress; _req.remotePort = connection && connection.remotePort; _req.raw = req.raw || req; return _req; } function mapHttpRequest(req) { return { req: reqSerializer(req) }; } } }); // node_modules/pino-std-serializers/lib/res.js var require_res = __commonJS({ "node_modules/pino-std-serializers/lib/res.js"(exports, module2) { "use strict"; module2.exports = { mapHttpResponse, resSerializer }; var rawSymbol = Symbol("pino-raw-res-ref"); var pinoResProto = Object.create({}, { statusCode: { enumerable: true, writable: true, value: 0 }, headers: { enumerable: true, writable: true, value: "" }, raw: { enumerable: false, get: function() { return this[rawSymbol]; }, set: function(val) { this[rawSymbol] = val; } } }); Object.defineProperty(pinoResProto, rawSymbol, { writable: true, value: {} }); function resSerializer(res) { const _res = Object.create(pinoResProto); _res.statusCode = res.headersSent ? res.statusCode : null; _res.headers = res.getHeaders ? res.getHeaders() : res._headers; _res.raw = res; return _res; } function mapHttpResponse(res) { return { res: resSerializer(res) }; } } }); // node_modules/pino-std-serializers/index.js var require_pino_std_serializers = __commonJS({ "node_modules/pino-std-serializers/index.js"(exports, module2) { "use strict"; var errSerializer = require_err(); var errWithCauseSerializer = require_err_with_cause(); var reqSerializers = require_req(); var resSerializers = require_res(); module2.exports = { err: errSerializer, errWithCause: errWithCauseSerializer, mapHttpRequest: reqSerializers.mapHttpRequest, mapHttpResponse: resSerializers.mapHttpResponse, req: reqSerializers.reqSerializer, res: resSerializers.resSerializer, wrapErrorSerializer: function wrapErrorSerializer(customSerializer) { if (customSerializer === errSerializer) return customSerializer; return function wrapErrSerializer(err) { return customSerializer(errSerializer(err)); }; }, wrapRequestSerializer: function wrapRequestSerializer(customSerializer) { if (customSerializer === reqSerializers.reqSerializer) return customSerializer; return function wrappedReqSerializer(req) { return customSerializer(reqSerializers.reqSerializer(req)); }; }, wrapResponseSerializer: function wrapResponseSerializer(customSerializer) { if (customSerializer === resSerializers.resSerializer) return customSerializer; return function wrappedResSerializer(res) { return customSerializer(resSerializers.resSerializer(res)); }; } }; } }); // node_modules/pino/lib/caller.js var require_caller = __commonJS({ "node_modules/pino/lib/caller.js"(exports, module2) { "use strict"; function noOpPrepareStackTrace(_, stack) { return stack; } module2.exports = function getCallers() { const originalPrepare = Error.prepareStackTrace; Error.prepareStackTrace = noOpPrepareStackTrace; const stack = new Error().stack; Error.prepareStackTrace = originalPrepare; if (!Array.isArray(stack)) { return void 0; } const entries = stack.slice(2); const fileNames = []; for (const entry of entries) { if (!entry) { continue; } fileNames.push(entry.getFileName()); } return fileNames; }; } }); // node_modules/fast-redact/lib/validator.js var require_validator = __commonJS({ "node_modules/fast-redact/lib/validator.js"(exports, module2) { "use strict"; module2.exports = validator; function validator(opts = {}) { const { ERR_PATHS_MUST_BE_STRINGS = () => "fast-redact - Paths must be (non-empty) strings", ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})` } = opts; return function validate({ paths }) { paths.forEach((s) => { if (typeof s !== "string") { throw Error(ERR_PATHS_MUST_BE_STRINGS()); } try { if (/〇/.test(s)) throw Error(); const expr = (s[0] === "[" ? "" : ".") + s.replace(/^\*/, "\u3007").replace(/\.\*/g, ".\u3007").replace(/\[\*\]/g, "[\u3007]"); if (/\n|\r|;/.test(expr)) throw Error(); if (/\/\*/.test(expr)) throw Error(); Function(` 'use strict' const o = new Proxy({}, { get: () => o, set: () => { throw Error() } }); const \u3007 = null; o${expr} if ([o${expr}].length !== 1) throw Error()`)(); } catch (e) { throw Error(ERR_INVALID_PATH(s)); } }); }; } } }); // node_modules/fast-redact/lib/rx.js var require_rx = __commonJS({ "node_modules/fast-redact/lib/rx.js"(exports, module2) { "use strict"; module2.exports = /[^.[\]]+|\[((?:.)*?)\]/g; } }); // node_modules/fast-redact/lib/parse.js var require_parse = __commonJS({ "node_modules/fast-redact/lib/parse.js"(exports, module2) { "use strict"; var rx = require_rx(); module2.exports = parse; function parse({ paths }) { const wildcards = []; var wcLen = 0; const secret = paths.reduce(function(o, strPath, ix) { var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, "")); const leadingBracket = strPath[0] === "["; path = path.map((p) => { if (p[0] === "[") return p.substr(1, p.length - 2); else return p; }); const star = path.indexOf("*"); if (star > -1) { const before = path.slice(0, star); const beforeStr = before.join("."); const after = path.slice(star + 1, path.length); const nested = after.length > 0; wcLen++; wildcards.push({ before, beforeStr, after, nested }); } else { o[strPath] = { path, val: void 0, precensored: false, circle: "", escPath: JSON.stringify(strPath), leadingBracket }; } return o; }, {}); return { wildcards, wcLen, secret }; } } }); // node_modules/fast-redact/lib/redactor.js var require_redactor = __commonJS({ "node_modules/fast-redact/lib/redactor.js"(exports, module2) { "use strict"; var rx = require_rx(); module2.exports = redactor; function redactor({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { const redact = Function("o", ` if (typeof o !== 'object' || o == null) { ${strictImpl(strict, serialize)} } const { censor, secret } = this const originalSecret = {} const secretKeys = Object.keys(secret) for (var i = 0; i < secretKeys.length; i++) { originalSecret[secretKeys[i]] = secret[secretKeys[i]] } ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} this.compileRestore() ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} this.secret = originalSecret ${resultTmpl(serialize)} `).bind(state); redact.state = state; if (serialize === false) { redact.restore = (o) => state.restore(o); } return redact; } function redactTmpl(secret, isCensorFct, censorFctTakesPath) { return Object.keys(secret).map((path) => { const { escPath, leadingBracket, path: arrPath } = secret[path]; const skip = leadingBracket ? 1 : 0; const delim = leadingBracket ? "" : "."; const hops = []; var match; while ((match = rx.exec(path)) !== null) { const [, ix] = match; const { index, input } = match; if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))); } var existence = hops.map((p) => `o${delim}${p}`).join(" && "); if (existence.length === 0) existence += `o${delim}${path} != null`; else existence += ` && o${delim}${path} != null`; const circularDetection = ` switch (true) { ${hops.reverse().map((p) => ` case o${delim}${p} === censor: secret[${escPath}].circle = ${JSON.stringify(p)} break `).join("\n")} } `; const censorArgs = censorFctTakesPath ? `val, ${JSON.stringify(arrPath)}` : `val`; return ` if (${existence}) { const val = o${delim}${path} if (val === censor) { secret[${escPath}].precensored = true } else { secret[${escPath}].val = val o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : "censor"} ${circularDetection} } } `; }).join("\n"); } function dynamicRedactTmpl(hasWildcards, isCensorFct, censorFctTakesPath) { return hasWildcards === true ? ` { const { wildcards, wcLen, groupRedact, nestedRedact } = this for (var i = 0; i < wcLen; i++) { const { before, beforeStr, after, nested } = wildcards[i] if (nested === true) { secret[beforeStr] = secret[beforeStr] || [] nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) } } ` : ""; } function resultTmpl(serialize) { return serialize === false ? `return o` : ` var s = this.serialize(o) this.restore(o) return s `; } function strictImpl(strict, serialize) { return strict === true ? `throw Error('fast-redact: primitives cannot be redacted')` : serialize === false ? `return o` : `return this.serialize(o)`; } } }); // node_modules/fast-redact/lib/modifiers.js var require_modifiers = __commonJS({ "node_modules/fast-redact/lib/modifiers.js"(exports, module2) { "use strict"; module2.exports = { groupRedact, groupRestore, nestedRedact, nestedRestore }; function groupRestore({ keys, values, target }) { if (target == null || typeof target === "string") return; const length = keys.length; for (var i = 0; i < length; i++) { const k = keys[i]; target[k] = values[i]; } } function groupRedact(o, path, censor, isCensorFct, censorFctTakesPath) { const target = get(o, path); if (target == null || typeof target === "string") return { keys: null, values: null, target, flat: true }; const keys = Object.keys(target); const keysLength = keys.length; const pathLength = path.length; const pathWithKey = censorFctTakesPath ? [...path] : void 0; const values = new Array(keysLength); for (var i = 0; i < keysLength; i++) { const key = keys[i]; values[i] = target[key]; if (censorFctTakesPath) { pathWithKey[pathLength] = key; target[key] = censor(target[key], pathWithKey); } else if (isCensorFct) { target[key] = censor(target[key]); } else { target[key] = censor; } } return { keys, values, target, flat: true }; } function nestedRestore(instructions) { for (let i = 0; i < instructions.length; i++) { const { target, path, value } = instructions[i]; let current = target; for (let i2 = path.length - 1; i2 > 0; i2--) { current = current[path[i2]]; } current[path[0]] = value; } } function nestedRedact(store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { const target = get(o, path); if (target == null) return; const keys = Object.keys(target); const keysLength = keys.length; for (var i = 0; i < keysLength; i++) { const key = keys[i]; specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath); } return store; } function has(obj, prop) { return obj !== void 0 && obj !== null ? "hasOwn" in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop) : false; } function specialSet(store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { const afterPathLen = afterPath.length; const lastPathIndex = afterPathLen - 1; const originalKey = k; var i = -1; var n; var nv; var ov; var oov = null; var wc = null; var kIsWc; var wcov; var consecutive = false; var level = 0; var depth = 0; var redactPathCurrent = tree(); ov = n = o[k]; if (typeof n !== "object") return; while (n != null && ++i < afterPathLen) { depth += 1; k = afterPath[i]; oov = ov; if (k !== "*" && !wc && !(typeof n === "object" && k in n)) { break; } if (k === "*") { if (wc === "*") { consecutive = true; } wc = k; if (i !== lastPathIndex) { continue; } } if (wc) { const wcKeys = Object.keys(n); for (var j = 0; j < wcKeys.length; j++) { const wck = wcKeys[j]; wcov = n[wck]; kIsWc = k === "*"; if (consecutive) { redactPathCurrent = node(redactPathCurrent, wck, depth); level = i; ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1); } else { if (kIsWc || typeof wcov === "object" && wcov !== null && k in wcov) { if (kIsWc) { ov = wcov; } else { ov = wcov[k]; } nv = i !== lastPathIndex ? ov : isCensorFct ? censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov) : censor; if (kIsWc) { const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey]); store.push(rv); n[wck] = nv; } else { if (wcov[k] === nv) { } else if (nv === void 0 && censor !== void 0 || has(wcov, k) && nv === ov) { redactPathCurrent = node(redactPathCurrent, wck, depth); } else { redactPathCurrent = node(redactPathCurrent, wck, depth); const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey]); store.push(rv); wcov[k] = nv; } } } } } wc = null; } else { ov = n[k]; redactPathCurrent = node(redactPathCurrent, k, depth); nv = i !== lastPathIndex ? ov : isCensorFct ? censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov) : censor; if (has(n, k) && nv === ov || nv === void 0 && censor !== void 0) { } else { const rv = restoreInstr(redactPathCurrent, ov, o[originalKey]); store.push(rv); n[k] = nv; } n = n[k]; } if (typeof n !== "object") break; if (ov === oov || typeof ov === "undefined") { } } } function get(o, p) { var i = -1; var l = p.length; var n = o; while (n != null && ++i < l) { n = n[p[i]]; } return n; } function iterateNthLevel(wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) { if (level === 0) { if (kIsWc || typeof wcov === "object" && wcov !== null && k in wcov) { if (kIsWc) { ov = wcov; } else { ov = wcov[k]; } nv = i !== lastPathIndex ? ov : isCensorFct ? censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov) : censor; if (kIsWc) { const rv = restoreInstr(redactPathCurrent, ov, parent); store.push(rv); n[wck] = nv; } else { if (wcov[k] === nv) { } else if (nv === void 0 && censor !== void 0 || has(wcov, k) && nv === ov) { } else { const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent); store.push(rv); wcov[k] = nv; } } } } for (const key in wcov) { if (typeof wcov[key] === "object") { redactPathCurrent = node(redactPathCurrent, key, depth); iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1); } } } function tree() { return { parent: null, key: null, children: [], depth: 0 }; } function node(parent, key, depth) { if (parent.depth === depth) { return node(parent.parent, key, depth); } var child = { parent, key, depth, children: [] }; parent.children.push(child); return child; } function restoreInstr(node2, value, target) { let current = node2; const path = []; do { path.push(current.key); current = current.parent; } while (current.parent != null); return { path, value, target }; } } }); // node_modules/fast-redact/lib/restorer.js var require_restorer = __commonJS({ "node_modules/fast-redact/lib/restorer.js"(exports, module2) { "use strict"; var { groupRestore, nestedRestore } = require_modifiers(); module2.exports = restorer; function restorer() { return function compileRestore() { if (this.restore) { this.restore.state.secret = this.secret; return; } const { secret, wcLen } = this; const paths = Object.keys(secret); const resetters = resetTmpl(secret, paths); const hasWildcards = wcLen > 0; const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }; this.restore = Function( "o", restoreTmpl(resetters, paths, hasWildcards) ).bind(state); this.restore.state = state; }; } function resetTmpl(secret, paths) { return paths.map((path) => { const { circle, escPath, leadingBracket } = secret[path]; const delim = leadingBracket ? "" : "."; const reset = circle ? `o.${circle} = secret[${escPath}].val` : `o${delim}${path} = secret[${escPath}].val`; const clear = `secret[${escPath}].val = undefined`; return ` if (secret[${escPath}].val !== undefined) { try { ${reset} } catch (e) {} ${clear} } `; }).join(""); } function restoreTmpl(resetters, paths, hasWildcards) { const dynamicReset = hasWildcards === true ? ` const keys = Object.keys(secret) const len = keys.length for (var i = len - 1; i >= ${paths.length}; i--) { const k = keys[i] const o = secret[k] if (o) { if (o.flat === true) this.groupRestore(o) else this.nestedRestore(o) secret[k] = null } } ` : ""; return ` const secret = this.secret ${dynamicReset} ${resetters} return o `; } } }); // node_modules/fast-redact/lib/state.js var require_state = __commonJS({ "node_modules/fast-redact/lib/state.js"(exports, module2) { "use strict"; module2.exports = state; function state(o) { const { secret, censor, compileRestore, serialize, groupRedact, nestedRedact, wildcards, wcLen } = o; const builder = [{ secret, censor, compileRestore }]; if (serialize !== false) builder.push({ serialize }); if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }); return Object.assign(...builder); } } }); // node_modules/fast-redact/index.js var require_fast_redact = __commonJS({ "node_modules/fast-redact/index.js"(exports, module2) { "use strict"; var validator = require_validator(); var parse = require_parse(); var redactor = require_redactor(); var restorer = require_restorer(); var { groupRedact, nestedRedact } = require_modifiers(); var state = require_state(); var rx = require_rx(); var validate = validator(); var noop = (o) => o; noop.restore = noop; var DEFAULT_CENSOR = "[REDACTED]"; fastRedact.rx = rx; fastRedact.validator = validator; module2.exports = fastRedact; function fastRedact(opts = {}) { const paths = Array.from(new Set(opts.paths || [])); const serialize = "serialize" in opts ? opts.serialize === false ? opts.serialize : typeof opts.serialize === "function" ? opts.serialize : JSON.stringify : JSON.stringify; const remove = opts.remove; if (remove === true && serialize !== JSON.stringify) { throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify"); } const censor = remove === true ? void 0 : "censor" in opts ? opts.censor : DEFAULT_CENSOR; const isCensorFct = typeof censor === "function"; const censorFctTakesPath = isCensorFct && censor.length > 1; if (paths.length === 0) return serialize || noop; validate({ paths, serialize, censor }); const { wildcards, wcLen, secret } = parse({ paths, censor }); const compileRestore = restorer(); const strict = "strict" in opts ? opts.strict : true; return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ secret, censor, compileRestore, serialize, groupRedact, nestedRedact, wildcards, wcLen })); } } }); // node_modules/pino/lib/symbols.js var require_symbols3 = __commonJS({ "node_modules/pino/lib/symbols.js"(exports, module2) { "use strict"; var setLevelSym = Symbol("pino.setLevel"); var getLevelSym = Symbol("pino.getLevel"); var levelValSym = Symbol("pino.levelVal"); var levelCompSym = Symbol("pino.levelComp"); var useLevelLabelsSym = Symbol("pino.useLevelLabels"); var useOnlyCustomLevelsSym = Symbol("pino.useOnlyCustomLevels"); var mixinSym = Symbol("pino.mixin"); var lsCacheSym = Symbol("pino.lsCache"); var chindingsSym = Symbol("pino.chindings"); var asJsonSym = Symbol("pino.asJson"); var writeSym = Symbol("pino.write"); var redactFmtSym = Symbol("pino.redactFmt"); var timeSym = Symbol("pino.time"); var timeSliceIndexSym = Symbol("pino.timeSliceIndex"); var streamSym = Symbol("pino.stream"); var stringifySym = Symbol("pino.stringify"); var stringifySafeSym = Symbol("pino.stringifySafe"); var stringifiersSym = Symbol("pino.stringifiers"); var endSym = Symbol("pino.end"); var formatOptsSym = Symbol("pino.formatOpts"); var messageKeySym = Symbol("pino.messageKey"); var errorKeySym = Symbol("pino.errorKey"); var nestedKeySym = Symbol("pino.nestedKey"); var nestedKeyStrSym = Symbol("pino.nestedKeyStr"); var mixinMergeStrategySym = Symbol("pino.mixinMergeStrategy"); var msgPrefixSym = Symbol("pino.msgPrefix"); var wildcardFirstSym = Symbol("pino.wildcardFirst"); var serializersSym = Symbol.for("pino.serializers"); var formattersSym = Symbol.for("pino.formatters"); var hooksSym = Symbol.for("pino.hooks"); var needsMetadataGsym = Symbol.for("pino.metadata"); module2.exports = { setLevelSym, getLevelSym, levelValSym, levelCompSym, useLevelLabelsSym, mixinSym, lsCacheSym, chindingsSym, asJsonSym, writeSym, serializersSym, redactFmtSym, timeSym, timeSliceIndexSym, streamSym, stringifySym, stringifySafeSym, stringifiersSym, endSym, formatOptsSym, messageKeySym, errorKeySym, nestedKeySym, wildcardFirstSym, needsMetadataGsym, useOnlyCustomLevelsSym, formattersSym, hooksSym, nestedKeyStrSym, mixinMergeStrategySym, msgPrefixSym }; } }); // node_modules/pino/lib/redaction.js var require_redaction = __commonJS({ "node_modules/pino/lib/redaction.js"(exports, module2) { "use strict"; var fastRedact = require_fast_redact(); var { redactFmtSym, wildcardFirstSym } = require_symbols3(); var { rx, validator } = fastRedact; var validate = validator({ ERR_PATHS_MUST_BE_STRINGS: () => "pino \u2013 redacted paths must be strings", ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})` }); var CENSOR = "[Redacted]"; var strict = false; function redaction(opts, serialize) { const { paths, censor } = handle(opts); const shape = paths.reduce((o, str) => { rx.lastIndex = 0; const first = rx.exec(str); const next = rx.exec(str); let ns = first[1] !== void 0 ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, "$1") : first[0]; if (ns === "*") { ns = wildcardFirstSym; } if (next === null) { o[ns] = null; return o; } if (o[ns] === null) { return o; } const { index } = next; const nextPath = `${str.substr(index, str.length - 1)}`; o[ns] = o[ns] || []; if (ns !== wildcardFirstSym && o[ns].length === 0) { o[ns].push(...o[wildcardFirstSym] || []); } if (ns === wildcardFirstSym) { Object.keys(o).forEach(function(k) { if (o[k]) { o[k].push(nextPath); } }); } o[ns].push(nextPath); return o; }, {}); const result = { [redactFmtSym]: fastRedact({ paths, censor, serialize, strict }) }; const topCensor = (...args) => { return typeof censor === "function" ? serialize(censor(...args)) : serialize(censor); }; return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => { if (shape[k] === null) { o[k] = (value) => topCensor(value, [k]); } else { const wrappedCensor = typeof censor === "function" ? (value, path) => { return censor(value, [k, ...path]); } : censor; o[k] = fastRedact({ paths: shape[k], censor: wrappedCensor, serialize, strict }); } return o; }, result); } function handle(opts) { if (Array.isArray(opts)) { opts = { paths: opts, censor: CENSOR }; validate(opts); return opts; } let { paths, censor = CENSOR, remove } = opts; if (Array.isArray(paths) === false) { throw Error("pino \u2013 redact must contain an array of strings"); } if (remove === true) censor = void 0; validate({ paths, censor }); return { paths, censor }; } module2.exports = redaction; } }); // node_modules/pino/lib/time.js var require_time = __commonJS({ "node_modules/pino/lib/time.js"(exports, module2) { "use strict"; var nullTime = () => ""; var epochTime = () => `,"time":${Date.now()}`; var unixTime = () => `,"time":${Math.round(Date.now() / 1e3)}`; var isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"`; module2.exports = { nullTime, epochTime, unixTime, isoTime }; } }); // node_modules/quick-format-unescaped/index.js var require_quick_format_unescaped = __commonJS({ "node_modules/quick-format-unescaped/index.js"(exports, module2) { "use strict"; function tryStringify(o) { try { return JSON.stringify(o); } catch (e) { return '"[Circular]"'; } } module2.exports = format; function format(f, args, opts) { var ss = opts && opts.stringify || tryStringify; var offset = 1; if (typeof f === "object" && f !== null) { var len = args.length + offset; if (len === 1) return f; var objects = new Array(len); objects[0] = ss(f); for (var index = 1; index < len; index++) { objects[index] = ss(args[index]); } return objects.join(" "); } if (typeof f !== "string") { return f; } var argLen = args.length; if (argLen === 0) return f; var str = ""; var a = 1 - offset; var lastPos = -1; var flen = f && f.length || 0; for (var i = 0; i < flen; ) { if (f.charCodeAt(i) === 37 && i + 1 < flen) { lastPos = lastPos > -1 ? lastPos : 0; switch (f.charCodeAt(i + 1)) { case 100: case 102: if (a >= argLen) break; if (args[a] == null) break; if (lastPos < i) str += f.slice(lastPos, i); str += Number(args[a]); lastPos = i + 2; i++; break; case 105: if (a >= argLen) break; if (args[a] == null) break; if (lastPos < i) str += f.slice(lastPos, i); str += Math.floor(Number(args[a])); lastPos = i + 2; i++; break; case 79: case 111: case 106: if (a >= argLen) break; if (args[a] === void 0) break; if (lastPos < i) str += f.slice(lastPos, i); var type = typeof args[a]; if (type === "string") { str += "'" + args[a] + "'"; lastPos = i + 2; i++; break; } if (type === "function") { str += args[a].name || ""; lastPos = i + 2; i++; break; } str += ss(args[a]); lastPos = i + 2; i++; break; case 115: if (a >= argLen) break; if (lastPos < i) str += f.slice(lastPos, i); str += String(args[a]); lastPos = i + 2; i++; break; case 37: if (lastPos < i) str += f.slice(lastPos, i); str += "%"; lastPos = i + 2; i++; a--; break; } ++a; } ++i; } if (lastPos === -1) return f; else if (lastPos < flen) { str += f.slice(lastPos); } return str; } } }); // node_modules/atomic-sleep/index.js var require_atomic_sleep = __commonJS({ "node_modules/atomic-sleep/index.js"(exports, module2) { "use strict"; if (typeof SharedArrayBuffer !== "undefined" && typeof Atomics !== "undefined") { let sleep = function(ms) { const valid = ms > 0 && ms < Infinity; if (valid === false) { if (typeof ms !== "number" && typeof ms !== "bigint") { throw TypeError("sleep: ms must be a number"); } throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); } Atomics.wait(nil, 0, 0, Number(ms)); }; const nil = new Int32Array(new SharedArrayBuffer(4)); module2.exports = sleep; } else { let sleep = function(ms) { const valid = ms > 0 && ms < Infinity; if (valid === false) { if (typeof ms !== "number" && typeof ms !== "bigint") { throw TypeError("sleep: ms must be a number"); } throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); } const target = Date.now() + Number(ms); while (target > Date.now()) { } }; module2.exports = sleep; } } }); // node_modules/sonic-boom/index.js var require_sonic_boom = __commonJS({ "node_modules/sonic-boom/index.js"(exports, module2) { "use strict"; var fs = require("fs"); var EventEmitter = require("events"); var inherits = require("util").inherits; var path = require("path"); var sleep = require_atomic_sleep(); var BUSY_WRITE_TIMEOUT = 100; var kEmptyBuffer = Buffer.allocUnsafe(0); var MAX_WRITE = 16 * 1024; var kContentModeBuffer = "buffer"; var kContentModeUtf8 = "utf8"; function openFile(file, sonic) { sonic._opening = true; sonic._writing = true; sonic._asyncDrainScheduled = false; function fileOpened(err, fd) { if (err) { sonic._reopening = false; sonic._writing = false; sonic._opening = false; if (sonic.sync) { process.nextTick(() => { if (sonic.listenerCount("error") > 0) { sonic.emit("error", err); } }); } else { sonic.emit("error", err); } return; } const reopening = sonic._reopening; sonic.fd = fd; sonic.file = file; sonic._reopening = false; sonic._opening = false; sonic._writing = false; if (sonic.sync) { process.nextTick(() => sonic.emit("ready")); } else { sonic.emit("ready"); } if (sonic.destroyed) { return; } if (!sonic._writing && sonic._len > sonic.minLength || sonic._flushPending) { sonic._actualWrite(); } else if (reopening) { process.nextTick(() => sonic.emit("drain")); } } const flags = sonic.append ? "a" : "w"; const mode = sonic.mode; if (sonic.sync) { try { if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true }); const fd = fs.openSync(file, flags, mode); fileOpened(null, fd); } catch (err) { fileOpened(err); throw err; } } else if (sonic.mkdir) { fs.mkdir(path.dirname(file), { recursive: true }, (err) => { if (err) return fileOpened(err); fs.open(file, flags, mode, fileOpened); }); } else { fs.open(file, flags, mode, fileOpened); } } function SonicBoom(opts) { if (!(this instanceof SonicBoom)) { return new SonicBoom(opts); } let { fd, dest, minLength, maxLength, maxWrite, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}; fd = fd || dest; this._len = 0; this.fd = -1; this._bufs = []; this._lens = []; this._writing = false; this._ending = false; this._reopening = false; this._asyncDrainScheduled = false; this._flushPending = false; this._hwm = Math.max(minLength || 0, 16387); this.file = null; this.destroyed = false; this.minLength = minLength || 0; this.maxLength = maxLength || 0; this.maxWrite = maxWrite || MAX_WRITE; this.sync = sync || false; this.writable = true; this._fsync = fsync || false; this.append = append || false; this.mode = mode; this.retryEAGAIN = retryEAGAIN || (() => true); this.mkdir = mkdir || false; let fsWriteSync; let fsWrite; if (contentMode === kContentModeBuffer) { this._writingBuf = kEmptyBuffer; this.write = writeBuffer; this.flush = flushBuffer; this.flushSync = flushBufferSync; this._actualWrite = actualWriteBuffer; fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf); fsWrite = () => fs.write(this.fd, this._writingBuf, this.release); } else if (contentMode === void 0 || contentMode === kContentModeUtf8) { this._writingBuf = ""; this.write = write; this.flush = flush; this.flushSync = flushSync; this._actualWrite = actualWrite; fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, "utf8"); fsWrite = () => fs.write(this.fd, this._writingBuf, "utf8", this.release); } else { throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`); } if (typeof fd === "number") { this.fd = fd; process.nextTick(() => this.emit("ready")); } else if (typeof fd === "string") { openFile(fd, this); } else { throw new Error("SonicBoom supports only file descriptors and files"); } if (this.minLength >= this.maxWrite) { throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`); } this.release = (err, n) => { if (err) { if ((err.code === "EAGAIN" || err.code === "EBUSY") && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) { if (this.sync) { try { sleep(BUSY_WRITE_TIMEOUT); this.release(void 0, 0); } catch (err2) { this.release(err2); } } else { setTimeout(fsWrite, BUSY_WRITE_TIMEOUT); } } else { this._writing = false; this.emit("error", err); } return; } this.emit("write", n); const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n); this._len = releasedBufObj.len; this._writingBuf = releasedBufObj.writingBuf; if (this._writingBuf.length) { if (!this.sync) { fsWrite(); return; } try { do { const n2 = fsWriteSync(); const releasedBufObj2 = releaseWritingBuf(this._writingBuf, this._len, n2); this._len = releasedBufObj2.len; this._writingBuf = releasedBufObj2.writingBuf; } while (this._writingBuf.length); } catch (err2) { this.release(err2); return; } } if (this._fsync) { fs.fsyncSync(this.fd); } const len = this._len; if (this._reopening) { this._writing = false; this._reopening = false; this.reopen(); } else if (len > this.minLength) { this._actualWrite(); } else if (this._ending) { if (len > 0) { this._actualWrite(); } else { this._writing = false; actualClose(this); } } else { this._writing = false; if (this.sync) { if (!this._asyncDrainScheduled) { this._asyncDrainScheduled = true; process.nextTick(emitDrain, this); } } else { this.emit("drain"); } } }; this.on("newListener", function(name) { if (name === "drain") { this._asyncDrainScheduled = false; } }); } function releaseWritingBuf(writingBuf, len, n) { if (typeof writingBuf === "string" && Buffer.byteLength(writingBuf) !== n) { n = Buffer.from(writingBuf).subarray(0, n).toString().length; } len = Math.max(len - n, 0); writingBuf = writingBuf.slice(n); return { writingBuf, len }; } function emitDrain(sonic) { const hasListeners = sonic.listenerCount("drain") > 0; if (!hasListeners) return; sonic._asyncDrainScheduled = false; sonic.emit("drain"); } inherits(SonicBoom, EventEmitter); function mergeBuf(bufs, len) { if (bufs.length === 0) { return kEmptyBuffer; } if (bufs.length === 1) { return bufs[0]; } return Buffer.concat(bufs, len); } function write(data) { if (this.destroyed) { throw new Error("SonicBoom destroyed"); } const len = this._len + data.length; const bufs = this._bufs; if (this.maxLength && len > this.maxLength) { this.emit("drop", data); return this._len < this._hwm; } if (bufs.length === 0 || bufs[bufs.length - 1].length + data.length > this.maxWrite) { bufs.push("" + data); } else { bufs[bufs.length - 1] += data; } this._len = len; if (!this._writing && this._len >= this.minLength) { this._actualWrite(); } return this._len < this._hwm; } function writeBuffer(data) { if (this.destroyed) { throw new Error("SonicBoom destroyed"); } const len = this._len + data.length; const bufs = this._bufs; const lens = this._lens; if (this.maxLength && len > this.maxLength) { this.emit("drop", data); return this._len < this._hwm; } if (bufs.length === 0 || lens[lens.length - 1] + data.length > this.maxWrite) { bufs.push([data]); lens.push(data.length); } else { bufs[bufs.length - 1].push(data); lens[lens.length - 1] += data.length; } this._len = len; if (!this._writing && this._len >= this.minLength) { this._actualWrite(); } return this._len < this._hwm; } function callFlushCallbackOnDrain(cb) { this._flushPending = true; const onDrain = () => { if (!this._fsync) { fs.fsync(this.fd, (err) => { this._flushPending = false; cb(err); }); } else { this._flushPending = false; cb(); } this.off("error", onError); }; const onError = (err) => { this._flushPending = false; cb(err); this.off("drain", onDrain); }; this.once("drain", onDrain); this.once("error", onError); } function flush(cb) { if (cb != null && typeof cb !== "function") { throw new Error("flush cb must be a function"); } if (this.destroyed) { const error = new Error("SonicBoom destroyed"); if (cb) { cb(error); return; } throw error; } if (this.minLength <= 0) { cb == null ? void 0 : cb(); return; } if (cb) { callFlushCallbackOnDrain.call(this, cb); } if (this._writing) { return; } if (this._bufs.length === 0) { this._bufs.push(""); } this._actualWrite(); } function flushBuffer(cb) { if (cb != null && typeof cb !== "function") { throw new Error("flush cb must be a function"); } if (this.destroyed) { const error = new Error("SonicBoom destroyed"); if (cb) { cb(error); return; } throw error; } if (this.minLength <= 0) { cb == null ? void 0 : cb(); return; } if (cb) { callFlushCallbackOnDrain.call(this, cb); } if (this._writing) { return; } if (this._bufs.length === 0) { this._bufs.push([]); this._lens.push(0); } this._actualWrite(); } SonicBoom.prototype.reopen = function(file) { if (this.destroyed) { throw new Error("SonicBoom destroyed"); } if (this._opening) { this.once("ready", () => { this.reopen(file); }); return; } if (this._ending) { return; } if (!this.file) { throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom"); } if (file) { this.file = file; } this._reopening = true; if (this._writing) { return; } const fd = this.fd; this.once("ready", () => { if (fd !== this.fd) { fs.close(fd, (err) => { if (err) { return this.emit("error", err); } }); } }); openFile(this.file, this); }; SonicBoom.prototype.end = function() { if (this.destroyed) { throw new Error("SonicBoom destroyed"); } if (this._opening) { this.once("ready", () => { this.end(); }); return; } if (this._ending) { return; } this._ending = true; if (this._writing) { return; } if (this._len > 0 && this.fd >= 0) { this._actualWrite(); } else { actualClose(this); } }; function flushSync() { if (this.destroyed) { throw new Error("SonicBoom destroyed"); } if (this.fd < 0) { throw new Error("sonic boom is not ready yet"); } if (!this._writing && this._writingBuf.length > 0) { this._bufs.unshift(this._writingBuf); this._writingBuf = ""; } let buf = ""; while (this._bufs.length || buf) { if (buf.length <= 0) { buf = this._bufs[0]; } try { const n = fs.writeSync(this.fd, buf, "utf8"); const releasedBufObj = releaseWritingBuf(buf, this._len, n); buf = releasedBufObj.writingBuf; this._len = releasedBufObj.len; if (buf.length <= 0) { this._bufs.shift(); } } catch (err) { const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { throw err; } sleep(BUSY_WRITE_TIMEOUT); } } try { fs.fsyncSync(this.fd); } catch (e) { } } function flushBufferSync() { if (this.destroyed) { throw new Error("SonicBoom destroyed"); } if (this.fd < 0) { throw new Error("sonic boom is not ready yet"); } if (!this._writing && this._writingBuf.length > 0) { this._bufs.unshift([this._writingBuf]); this._writingBuf = kEmptyBuffer; } let buf = kEmptyBuffer; while (this._bufs.length || buf.length) { if (buf.length <= 0) { buf = mergeBuf(this._bufs[0], this._lens[0]); } try { const n = fs.writeSync(this.fd, buf); buf = buf.subarray(n); this._len = Math.max(this._len - n, 0); if (buf.length <= 0) { this._bufs.shift(); this._lens.shift(); } } catch (err) { const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { throw err; } sleep(BUSY_WRITE_TIMEOUT); } } } SonicBoom.prototype.destroy = function() { if (this.destroyed) { return; } actualClose(this); }; function actualWrite() { const release = this.release; this._writing = true; this._writingBuf = this._writingBuf || this._bufs.shift() || ""; if (this.sync) { try { const written = fs.writeSync(this.fd, this._writingBuf, "utf8"); release(null, written); } catch (err) { release(err); } } else { fs.write(this.fd, this._writingBuf, "utf8", release); } } function actualWriteBuffer() { const release = this.release; this._writing = true; this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift()); if (this.sync) { try { const written = fs.writeSync(this.fd, this._writingBuf); release(null, written); } catch (err) { release(err); } } else { fs.write(this.fd, this._writingBuf, release); } } function actualClose(sonic) { if (sonic.fd === -1) { sonic.once("ready", actualClose.bind(null, sonic)); return; } sonic.destroyed = true; sonic._bufs = []; sonic._lens = []; fs.fsync(sonic.fd, closeWrapped); function closeWrapped() { if (sonic.fd !== 1 && sonic.fd !== 2) { fs.close(sonic.fd, done); } else { done(); } } function done(err) { if (err) { sonic.emit("error", err); return; } if (sonic._ending && !sonic._writing) { sonic.emit("finish"); } sonic.emit("close"); } } SonicBoom.SonicBoom = SonicBoom; SonicBoom.default = SonicBoom; module2.exports = SonicBoom; } }); // node_modules/on-exit-leak-free/index.js var require_on_exit_leak_free = __commonJS({ "node_modules/on-exit-leak-free/index.js"(exports, module2) { "use strict"; var refs = { exit: [], beforeExit: [] }; var functions = { exit: onExit, beforeExit: onBeforeExit }; var registry; function ensureRegistry() { if (registry === void 0) { registry = new FinalizationRegistry(clear); } } function install(event) { if (refs[event].length > 0) { return; } process.on(event, functions[event]); } function uninstall(event) { if (refs[event].length > 0) { return; } process.removeListener(event, functions[event]); if (refs.exit.length === 0 && refs.beforeExit.length === 0) { registry = void 0; } } function onExit() { callRefs("exit"); } function onBeforeExit() { callRefs("beforeExit"); } function callRefs(event) { for (const ref of refs[event]) { const obj = ref.deref(); const fn = ref.fn; if (obj !== void 0) { fn(obj, event); } } refs[event] = []; } function clear(ref) { for (const event of ["exit", "beforeExit"]) { const index = refs[event].indexOf(ref); refs[event].splice(index, index + 1); uninstall(event); } } function _register(event, obj, fn) { if (obj === void 0) { throw new Error("the object can't be undefined"); } install(event); const ref = new WeakRef(obj); ref.fn = fn; ensureRegistry(); registry.register(obj, ref); refs[event].push(ref); } function register(obj, fn) { _register("exit", obj, fn); } function registerBeforeExit(obj, fn) { _register("beforeExit", obj, fn); } function unregister(obj) { if (registry === void 0) { return; } registry.unregister(obj); for (const event of ["exit", "beforeExit"]) { refs[event] = refs[event].filter((ref) => { const _obj = ref.deref(); return _obj && _obj !== obj; }); uninstall(event); } } module2.exports = { register, registerBeforeExit, unregister }; } }); // node_modules/thread-stream/package.json var require_package = __commonJS({ "node_modules/thread-stream/package.json"(exports, module2) { module2.exports = { name: "thread-stream", version: "3.1.0", description: "A streaming way to send data to a Node.js Worker Thread", main: "index.js", types: "index.d.ts", dependencies: { "real-require": "^0.2.0" }, devDependencies: { "@types/node": "^20.1.0", "@types/tap": "^15.0.0", "@yao-pkg/pkg": "^5.11.5", desm: "^1.3.0", fastbench: "^1.0.1", husky: "^9.0.6", "pino-elasticsearch": "^8.0.0", "sonic-boom": "^4.0.1", standard: "^17.0.0", tap: "^16.2.0", "ts-node": "^10.8.0", typescript: "^5.3.2", "why-is-node-running": "^2.2.2" }, scripts: { build: "tsc --noEmit", test: 'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts', "test:ci": "standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts", "test:ci:js": 'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"', "test:ci:ts": 'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"', "test:yarn": 'npm run transpile && tap "test/**/*.test.js" --no-check-coverage', transpile: "sh ./test/ts/transpile.sh", prepare: "husky install" }, standard: { ignore: [ "test/ts/**/*", "test/syntax-error.mjs" ] }, repository: { type: "git", url: "git+https://github.com/mcollina/thread-stream.git" }, keywords: [ "worker", "thread", "threads", "stream" ], author: "Matteo Collina ", license: "MIT", bugs: { url: "https://github.com/mcollina/thread-stream/issues" }, homepage: "https://github.com/mcollina/thread-stream#readme" }; } }); // node_modules/thread-stream/lib/wait.js var require_wait = __commonJS({ "node_modules/thread-stream/lib/wait.js"(exports, module2) { "use strict"; var MAX_TIMEOUT = 1e3; function wait(state, index, expected, timeout, done) { const max = Date.now() + timeout; let current = Atomics.load(state, index); if (current === expected) { done(null, "ok"); return; } let prior = current; const check = (backoff) => { if (Date.now() > max) { done(null, "timed-out"); } else { setTimeout(() => { prior = current; current = Atomics.load(state, index); if (current === prior) { check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2); } else { if (current === expected) done(null, "ok"); else done(null, "not-equal"); } }, backoff); } }; check(1); } function waitDiff(state, index, expected, timeout, done) { const max = Date.now() + timeout; let current = Atomics.load(state, index); if (current !== expected) { done(null, "ok"); return; } const check = (backoff) => { if (Date.now() > max) { done(null, "timed-out"); } else { setTimeout(() => { current = Atomics.load(state, index); if (current !== expected) { done(null, "ok"); } else { check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2); } }, backoff); } }; check(1); } module2.exports = { wait, waitDiff }; } }); // node_modules/thread-stream/lib/indexes.js var require_indexes = __commonJS({ "node_modules/thread-stream/lib/indexes.js"(exports, module2) { "use strict"; var WRITE_INDEX = 4; var READ_INDEX = 8; module2.exports = { WRITE_INDEX, READ_INDEX }; } }); // node_modules/thread-stream/index.js var require_thread_stream = __commonJS({ "node_modules/thread-stream/index.js"(exports, module2) { "use strict"; var { version } = require_package(); var { EventEmitter } = require("events"); var { Worker } = require("worker_threads"); var { join } = require("path"); var { pathToFileURL } = require("url"); var { wait } = require_wait(); var { WRITE_INDEX, READ_INDEX } = require_indexes(); var buffer = require("buffer"); var assert = require("assert"); var kImpl = Symbol("kImpl"); var MAX_STRING = buffer.constants.MAX_STRING_LENGTH; var FakeWeakRef = class { constructor(value) { this._value = value; } deref() { return this._value; } }; var FakeFinalizationRegistry = class { register() { } unregister() { } }; var FinalizationRegistry2 = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry; var WeakRef2 = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef; var registry = new FinalizationRegistry2((worker) => { if (worker.exited) { return; } worker.terminate(); }); function createWorker(stream, opts) { const { filename, workerData } = opts; const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; const toExecute = bundlerOverrides["thread-stream-worker"] || join(__dirname, "lib", "worker.js"); const worker = new Worker(toExecute, { ...opts.workerOpts, trackUnmanagedFds: false, workerData: { filename: filename.indexOf("file://") === 0 ? filename : pathToFileURL(filename).href, dataBuf: stream[kImpl].dataBuf, stateBuf: stream[kImpl].stateBuf, workerData: { $context: { threadStreamVersion: version }, ...workerData } } }); worker.stream = new FakeWeakRef(stream); worker.on("message", onWorkerMessage); worker.on("exit", onWorkerExit); registry.register(stream, worker); return worker; } function drain(stream) { assert(!stream[kImpl].sync); if (stream[kImpl].needDrain) { stream[kImpl].needDrain = false; stream.emit("drain"); } } function nextFlush(stream) { const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); let leftover = stream[kImpl].data.length - writeIndex; if (leftover > 0) { if (stream[kImpl].buf.length === 0) { stream[kImpl].flushing = false; if (stream[kImpl].ending) { end(stream); } else if (stream[kImpl].needDrain) { process.nextTick(drain, stream); } return; } let toWrite = stream[kImpl].buf.slice(0, leftover); let toWriteBytes = Buffer.byteLength(toWrite); if (toWriteBytes <= leftover) { stream[kImpl].buf = stream[kImpl].buf.slice(leftover); write(stream, toWrite, nextFlush.bind(null, stream)); } else { stream.flush(() => { if (stream.destroyed) { return; } Atomics.store(stream[kImpl].state, READ_INDEX, 0); Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); while (toWriteBytes > stream[kImpl].data.length) { leftover = leftover / 2; toWrite = stream[kImpl].buf.slice(0, leftover); toWriteBytes = Buffer.byteLength(toWrite); } stream[kImpl].buf = stream[kImpl].buf.slice(leftover); write(stream, toWrite, nextFlush.bind(null, stream)); }); } } else if (leftover === 0) { if (writeIndex === 0 && stream[kImpl].buf.length === 0) { return; } stream.flush(() => { Atomics.store(stream[kImpl].state, READ_INDEX, 0); Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); nextFlush(stream); }); } else { destroy(stream, new Error("overwritten")); } } function onWorkerMessage(msg) { const stream = this.stream.deref(); if (stream === void 0) { this.exited = true; this.terminate(); return; } switch (msg.code) { case "READY": this.stream = new WeakRef2(stream); stream.flush(() => { stream[kImpl].ready = true; stream.emit("ready"); }); break; case "ERROR": destroy(stream, msg.err); break; case "EVENT": if (Array.isArray(msg.args)) { stream.emit(msg.name, ...msg.args); } else { stream.emit(msg.name, msg.args); } break; case "WARNING": process.emitWarning(msg.err); break; default: destroy(stream, new Error("this should not happen: " + msg.code)); } } function onWorkerExit(code) { const stream = this.stream.deref(); if (stream === void 0) { return; } registry.unregister(stream); stream.worker.exited = true; stream.worker.off("exit", onWorkerExit); destroy(stream, code !== 0 ? new Error("the worker thread exited") : null); } var ThreadStream = class extends EventEmitter { constructor(opts = {}) { super(); if (opts.bufferSize < 4) { throw new Error("bufferSize must at least fit a 4-byte utf-8 char"); } this[kImpl] = {}; this[kImpl].stateBuf = new SharedArrayBuffer(128); this[kImpl].state = new Int32Array(this[kImpl].stateBuf); this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024); this[kImpl].data = Buffer.from(this[kImpl].dataBuf); this[kImpl].sync = opts.sync || false; this[kImpl].ending = false; this[kImpl].ended = false; this[kImpl].needDrain = false; this[kImpl].destroyed = false; this[kImpl].flushing = false; this[kImpl].ready = false; this[kImpl].finished = false; this[kImpl].errored = null; this[kImpl].closed = false; this[kImpl].buf = ""; this.worker = createWorker(this, opts); this.on("message", (message, transferList) => { this.worker.postMessage(message, transferList); }); } write(data) { if (this[kImpl].destroyed) { error(this, new Error("the worker has exited")); return false; } if (this[kImpl].ending) { error(this, new Error("the worker is ending")); return false; } if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) { try { writeSync(this); this[kImpl].flushing = true; } catch (err) { destroy(this, err); return false; } } this[kImpl].buf += data; if (this[kImpl].sync) { try { writeSync(this); return true; } catch (err) { destroy(this, err); return false; } } if (!this[kImpl].flushing) { this[kImpl].flushing = true; setImmediate(nextFlush, this); } this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0; return !this[kImpl].needDrain; } end() { if (this[kImpl].destroyed) { return; } this[kImpl].ending = true; end(this); } flush(cb) { if (this[kImpl].destroyed) { if (typeof cb === "function") { process.nextTick(cb, new Error("the worker has exited")); } return; } const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX); wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => { if (err) { destroy(this, err); process.nextTick(cb, err); return; } if (res === "not-equal") { this.flush(cb); return; } process.nextTick(cb); }); } flushSync() { if (this[kImpl].destroyed) { return; } writeSync(this); flushSync(this); } unref() { this.worker.unref(); } ref() { this.worker.ref(); } get ready() { return this[kImpl].ready; } get destroyed() { return this[kImpl].destroyed; } get closed() { return this[kImpl].closed; } get writable() { return !this[kImpl].destroyed && !this[kImpl].ending; } get writableEnded() { return this[kImpl].ending; } get writableFinished() { return this[kImpl].finished; } get writableNeedDrain() { return this[kImpl].needDrain; } get writableObjectMode() { return false; } get writableErrored() { return this[kImpl].errored; } }; function error(stream, err) { setImmediate(() => { stream.emit("error", err); }); } function destroy(stream, err) { if (stream[kImpl].destroyed) { return; } stream[kImpl].destroyed = true; if (err) { stream[kImpl].errored = err; error(stream, err); } if (!stream.worker.exited) { stream.worker.terminate().catch(() => { }).then(() => { stream[kImpl].closed = true; stream.emit("close"); }); } else { setImmediate(() => { stream[kImpl].closed = true; stream.emit("close"); }); } } function write(stream, data, cb) { const current = Atomics.load(stream[kImpl].state, WRITE_INDEX); const length = Buffer.byteLength(data); stream[kImpl].data.write(data, current); Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length); Atomics.notify(stream[kImpl].state, WRITE_INDEX); cb(); return true; } function end(stream) { if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) { return; } stream[kImpl].ended = true; try { stream.flushSync(); let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); Atomics.store(stream[kImpl].state, WRITE_INDEX, -1); Atomics.notify(stream[kImpl].state, WRITE_INDEX); let spins = 0; while (readIndex !== -1) { Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); if (readIndex === -2) { destroy(stream, new Error("end() failed")); return; } if (++spins === 10) { destroy(stream, new Error("end() took too long (10s)")); return; } } process.nextTick(() => { stream[kImpl].finished = true; stream.emit("finish"); }); } catch (err) { destroy(stream, err); } } function writeSync(stream) { const cb = () => { if (stream[kImpl].ending) { end(stream); } else if (stream[kImpl].needDrain) { process.nextTick(drain, stream); } }; stream[kImpl].flushing = false; while (stream[kImpl].buf.length !== 0) { const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); let leftover = stream[kImpl].data.length - writeIndex; if (leftover === 0) { flushSync(stream); Atomics.store(stream[kImpl].state, READ_INDEX, 0); Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); continue; } else if (leftover < 0) { throw new Error("overwritten"); } let toWrite = stream[kImpl].buf.slice(0, leftover); let toWriteBytes = Buffer.byteLength(toWrite); if (toWriteBytes <= leftover) { stream[kImpl].buf = stream[kImpl].buf.slice(leftover); write(stream, toWrite, cb); } else { flushSync(stream); Atomics.store(stream[kImpl].state, READ_INDEX, 0); Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); while (toWriteBytes > stream[kImpl].buf.length) { leftover = leftover / 2; toWrite = stream[kImpl].buf.slice(0, leftover); toWriteBytes = Buffer.byteLength(toWrite); } stream[kImpl].buf = stream[kImpl].buf.slice(leftover); write(stream, toWrite, cb); } } } function flushSync(stream) { if (stream[kImpl].flushing) { throw new Error("unable to flush while flushing"); } const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); let spins = 0; while (true) { const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); if (readIndex === -2) { throw Error("_flushSync failed"); } if (readIndex !== writeIndex) { Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); } else { break; } if (++spins === 10) { throw new Error("_flushSync took too long (10s)"); } } } module2.exports = ThreadStream; } }); // node_modules/pino/lib/transport.js var require_transport = __commonJS({ "node_modules/pino/lib/transport.js"(exports, module2) { "use strict"; var { createRequire } = require("module"); var getCallers = require_caller(); var { join, isAbsolute, sep } = require("path"); var sleep = require_atomic_sleep(); var onExit = require_on_exit_leak_free(); var ThreadStream = require_thread_stream(); function setupOnExit(stream) { onExit.register(stream, autoEnd); onExit.registerBeforeExit(stream, flush); stream.on("close", function() { onExit.unregister(stream); }); } function buildStream(filename, workerData, workerOpts) { const stream = new ThreadStream({ filename, workerData, workerOpts }); stream.on("ready", onReady); stream.on("close", function() { process.removeListener("exit", onExit2); }); process.on("exit", onExit2); function onReady() { process.removeListener("exit", onExit2); stream.unref(); if (workerOpts.autoEnd !== false) { setupOnExit(stream); } } function onExit2() { if (stream.closed) { return; } stream.flushSync(); sleep(100); stream.end(); } return stream; } function autoEnd(stream) { stream.ref(); stream.flushSync(); stream.end(); stream.once("close", function() { stream.unref(); }); } function flush(stream) { stream.flushSync(); } function transport(fullOptions) { const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers() } = fullOptions; const options = { ...fullOptions.options }; const callers = typeof caller === "string" ? [caller] : caller; const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; let target = fullOptions.target; if (target && targets) { throw new Error("only one of target or targets can be specified"); } if (targets) { target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js"); options.targets = targets.filter((dest) => dest.target).map((dest) => { return { ...dest, target: fixTarget(dest.target) }; }); options.pipelines = targets.filter((dest) => dest.pipeline).map((dest) => { return dest.pipeline.map((t) => { return { ...t, level: dest.level, // duplicate the pipeline `level` property defined in the upper level target: fixTarget(t.target) }; }); }); } else if (pipeline) { target = bundlerOverrides["pino-worker"] || join(__dirname, "worker.js"); options.pipelines = [pipeline.map((dest) => { return { ...dest, target: fixTarget(dest.target) }; })]; } if (levels) { options.levels = levels; } if (dedupe) { options.dedupe = dedupe; } options.pinoWillSendConfig = true; return buildStream(fixTarget(target), options, worker); function fixTarget(origin) { origin = bundlerOverrides[origin] || origin; if (isAbsolute(origin) || origin.indexOf("file://") === 0) { return origin; } if (origin === "pino/file") { return join(__dirname, "..", "file.js"); } let fixTarget2; for (const filePath of callers) { try { const context = filePath === "node:repl" ? process.cwd() + sep : filePath; fixTarget2 = createRequire(context).resolve(origin); break; } catch (err) { continue; } } if (!fixTarget2) { throw new Error(`unable to determine transport target for "${origin}"`); } return fixTarget2; } } module2.exports = transport; } }); // node_modules/pino/lib/tools.js var require_tools = __commonJS({ "node_modules/pino/lib/tools.js"(exports, module2) { "use strict"; var format = require_quick_format_unescaped(); var { mapHttpRequest, mapHttpResponse } = require_pino_std_serializers(); var SonicBoom = require_sonic_boom(); var onExit = require_on_exit_leak_free(); var { lsCacheSym, chindingsSym, writeSym, serializersSym, formatOptsSym, endSym, stringifiersSym, stringifySym, stringifySafeSym, wildcardFirstSym, nestedKeySym, formattersSym, messageKeySym, errorKeySym, nestedKeyStrSym, msgPrefixSym } = require_symbols3(); var { isMainThread } = require("worker_threads"); var transport = require_transport(); function noop() { } function genLog(level, hook) { if (!hook) return LOG; return function hookWrappedLog(...args) { hook.call(this, args, LOG, level); }; function LOG(o, ...n) { if (typeof o === "object") { let msg = o; if (o !== null) { if (o.method && o.headers && o.socket) { o = mapHttpRequest(o); } else if (typeof o.setHeader === "function") { o = mapHttpResponse(o); } } let formatParams; if (msg === null && n.length === 0) { formatParams = [null]; } else { msg = n.shift(); formatParams = n; } if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { msg = this[msgPrefixSym] + msg; } this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level); } else { let msg = o === void 0 ? n.shift() : o; if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { msg = this[msgPrefixSym] + msg; } this[writeSym](null, format(msg, n, this[formatOptsSym]), level); } } } function asString(str) { let result = ""; let last = 0; let found = false; let point = 255; const l = str.length; if (l > 100) { return JSON.stringify(str); } for (var i = 0; i < l && point >= 32; i++) { point = str.charCodeAt(i); if (point === 34 || point === 92) { result += str.slice(last, i) + "\\"; last = i; found = true; } } if (!found) { result = str; } else { result += str.slice(last); } return point < 32 ? JSON.stringify(str) : '"' + result + '"'; } function asJson(obj, msg, num, time) { const stringify2 = this[stringifySym]; const stringifySafe = this[stringifySafeSym]; const stringifiers = this[stringifiersSym]; const end = this[endSym]; const chindings = this[chindingsSym]; const serializers = this[serializersSym]; const formatters = this[formattersSym]; const messageKey = this[messageKeySym]; const errorKey = this[errorKeySym]; let data = this[lsCacheSym][num] + time; data = data + chindings; let value; if (formatters.log) { obj = formatters.log(obj); } const wildcardStringifier = stringifiers[wildcardFirstSym]; let propStr = ""; for (const key in obj) { value = obj[key]; if (Object.prototype.hasOwnProperty.call(obj, key) && value !== void 0) { if (serializers[key]) { value = serializers[key](value); } else if (key === errorKey && serializers.err) { value = serializers.err(value); } const stringifier = stringifiers[key] || wildcardStringifier; switch (typeof value) { case "undefined": case "function": continue; case "number": if (Number.isFinite(value) === false) { value = null; } case "boolean": if (stringifier) value = stringifier(value); break; case "string": value = (stringifier || asString)(value); break; default: value = (stringifier || stringify2)(value, stringifySafe); } if (value === void 0) continue; const strKey = asString(key); propStr += "," + strKey + ":" + value; } } let msgStr = ""; if (msg !== void 0) { value = serializers[messageKey] ? serializers[messageKey](msg) : msg; const stringifier = stringifiers[messageKey] || wildcardStringifier; switch (typeof value) { case "function": break; case "number": if (Number.isFinite(value) === false) { value = null; } case "boolean": if (stringifier) value = stringifier(value); msgStr = ',"' + messageKey + '":' + value; break; case "string": value = (stringifier || asString)(value); msgStr = ',"' + messageKey + '":' + value; break; default: value = (stringifier || stringify2)(value, stringifySafe); msgStr = ',"' + messageKey + '":' + value; } } if (this[nestedKeySym] && propStr) { return data + this[nestedKeyStrSym] + propStr.slice(1) + "}" + msgStr + end; } else { return data + propStr + msgStr + end; } } function asChindings(instance, bindings) { let value; let data = instance[chindingsSym]; const stringify2 = instance[stringifySym]; const stringifySafe = instance[stringifySafeSym]; const stringifiers = instance[stringifiersSym]; const wildcardStringifier = stringifiers[wildcardFirstSym]; const serializers = instance[serializersSym]; const formatter = instance[formattersSym].bindings; bindings = formatter(bindings); for (const key in bindings) { value = bindings[key]; const valid = key !== "level" && key !== "serializers" && key !== "formatters" && key !== "customLevels" && bindings.hasOwnProperty(key) && value !== void 0; if (valid === true) { value = serializers[key] ? serializers[key](value) : value; value = (stringifiers[key] || wildcardStringifier || stringify2)(value, stringifySafe); if (value === void 0) continue; data += ',"' + key + '":' + value; } } return data; } function hasBeenTampered(stream) { return stream.write !== stream.constructor.prototype.write; } var hasNodeCodeCoverage = process.env.NODE_V8_COVERAGE || process.env.V8_COVERAGE; function buildSafeSonicBoom(opts) { const stream = new SonicBoom(opts); stream.on("error", filterBrokenPipe); if (!hasNodeCodeCoverage && !opts.sync && isMainThread) { onExit.register(stream, autoEnd); stream.on("close", function() { onExit.unregister(stream); }); } return stream; function filterBrokenPipe(err) { if (err.code === "EPIPE") { stream.write = noop; stream.end = noop; stream.flushSync = noop; stream.destroy = noop; return; } stream.removeListener("error", filterBrokenPipe); stream.emit("error", err); } } function autoEnd(stream, eventName) { if (stream.destroyed) { return; } if (eventName === "beforeExit") { stream.flush(); stream.on("drain", function() { stream.end(); }); } else { stream.flushSync(); } } function createArgsNormalizer(defaultOptions) { return function normalizeArgs(instance, caller, opts = {}, stream) { if (typeof opts === "string") { stream = buildSafeSonicBoom({ dest: opts }); opts = {}; } else if (typeof stream === "string") { if (opts && opts.transport) { throw Error("only one of option.transport or stream can be specified"); } stream = buildSafeSonicBoom({ dest: stream }); } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { stream = opts; opts = {}; } else if (opts.transport) { if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) { throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)"); } if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === "function") { throw Error("option.transport.targets do not allow custom level formatters"); } let customLevels; if (opts.customLevels) { customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels); } stream = transport({ caller, ...opts.transport, levels: customLevels }); } opts = Object.assign({}, defaultOptions, opts); opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers); opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters); if (opts.prettyPrint) { throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)"); } const { enabled, onChild } = opts; if (enabled === false) opts.level = "silent"; if (!onChild) opts.onChild = noop; if (!stream) { if (!hasBeenTampered(process.stdout)) { stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 }); } else { stream = process.stdout; } } return { opts, stream }; }; } function stringify(obj, stringifySafeFn) { try { return JSON.stringify(obj); } catch (_) { try { const stringify2 = stringifySafeFn || this[stringifySafeSym]; return stringify2(obj); } catch (_2) { return '"[unable to serialize, circular reference is too complex to analyze]"'; } } } function buildFormatters(level, bindings, log) { return { level, bindings, log }; } function normalizeDestFileDescriptor(destination) { const fd = Number(destination); if (typeof destination === "string" && Number.isFinite(fd)) { return fd; } if (destination === void 0) { return 1; } return destination; } module2.exports = { noop, buildSafeSonicBoom, asChindings, asJson, genLog, createArgsNormalizer, stringify, buildFormatters, normalizeDestFileDescriptor }; } }); // node_modules/pino/lib/constants.js var require_constants = __commonJS({ "node_modules/pino/lib/constants.js"(exports, module2) { var DEFAULT_LEVELS = { trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60 }; var SORTING_ORDER = { ASC: "ASC", DESC: "DESC" }; module2.exports = { DEFAULT_LEVELS, SORTING_ORDER }; } }); // node_modules/pino/lib/levels.js var require_levels = __commonJS({ "node_modules/pino/lib/levels.js"(exports, module2) { "use strict"; var { lsCacheSym, levelValSym, useOnlyCustomLevelsSym, streamSym, formattersSym, hooksSym, levelCompSym } = require_symbols3(); var { noop, genLog } = require_tools(); var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); var levelMethods = { fatal: (hook) => { const logFatal = genLog(DEFAULT_LEVELS.fatal, hook); return function(...args) { const stream = this[streamSym]; logFatal.call(this, ...args); if (typeof stream.flushSync === "function") { try { stream.flushSync(); } catch (e) { } } }; }, error: (hook) => genLog(DEFAULT_LEVELS.error, hook), warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook), info: (hook) => genLog(DEFAULT_LEVELS.info, hook), debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook), trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook) }; var nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => { o[DEFAULT_LEVELS[k]] = k; return o; }, {}); var initialLsCache = Object.keys(nums).reduce((o, k) => { o[k] = '{"level":' + Number(k); return o; }, {}); function genLsCache(instance) { const formatter = instance[formattersSym].level; const { labels } = instance.levels; const cache = {}; for (const label in labels) { const level = formatter(labels[label], Number(label)); cache[label] = JSON.stringify(level).slice(0, -1); } instance[lsCacheSym] = cache; return instance; } function isStandardLevel(level, useOnlyCustomLevels) { if (useOnlyCustomLevels) { return false; } switch (level) { case "fatal": case "error": case "warn": case "info": case "debug": case "trace": return true; default: return false; } } function setLevel(level) { const { labels, values } = this.levels; if (typeof level === "number") { if (labels[level] === void 0) throw Error("unknown level value" + level); level = labels[level]; } if (values[level] === void 0) throw Error("unknown level " + level); const preLevelVal = this[levelValSym]; const levelVal = this[levelValSym] = values[level]; const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]; const levelComparison = this[levelCompSym]; const hook = this[hooksSym].logMethod; for (const key in values) { if (levelComparison(values[key], levelVal) === false) { this[key] = noop; continue; } this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook); } this.emit( "level-change", level, levelVal, labels[preLevelVal], preLevelVal, this ); } function getLevel(level) { const { levels, levelVal } = this; return levels && levels.labels ? levels.labels[levelVal] : ""; } function isLevelEnabled(logLevel) { const { values } = this.levels; const logLevelVal = values[logLevel]; return logLevelVal !== void 0 && this[levelCompSym](logLevelVal, this[levelValSym]); } function compareLevel(direction, current, expected) { if (direction === SORTING_ORDER.DESC) { return current <= expected; } return current >= expected; } function genLevelComparison(levelComparison) { if (typeof levelComparison === "string") { return compareLevel.bind(null, levelComparison); } return levelComparison; } function mappings(customLevels = null, useOnlyCustomLevels = false) { const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => { o[customLevels[k]] = k; return o; }, {}) : null; const labels = Object.assign( Object.create(Object.prototype, { Infinity: { value: "silent" } }), useOnlyCustomLevels ? null : nums, customNums ); const values = Object.assign( Object.create(Object.prototype, { silent: { value: Infinity } }), useOnlyCustomLevels ? null : DEFAULT_LEVELS, customLevels ); return { labels, values }; } function assertDefaultLevelFound(defaultLevel, customLevels, useOnlyCustomLevels) { if (typeof defaultLevel === "number") { const values = [].concat( Object.keys(customLevels || {}).map((key) => customLevels[key]), useOnlyCustomLevels ? [] : Object.keys(nums).map((level) => +level), Infinity ); if (!values.includes(defaultLevel)) { throw Error(`default level:${defaultLevel} must be included in custom levels`); } return; } const labels = Object.assign( Object.create(Object.prototype, { silent: { value: Infinity } }), useOnlyCustomLevels ? null : DEFAULT_LEVELS, customLevels ); if (!(defaultLevel in labels)) { throw Error(`default level:${defaultLevel} must be included in custom levels`); } } function assertNoLevelCollisions(levels, customLevels) { const { labels, values } = levels; for (const k in customLevels) { if (k in values) { throw Error("levels cannot be overridden"); } if (customLevels[k] in labels) { throw Error("pre-existing level values cannot be used for new levels"); } } } function assertLevelComparison(levelComparison) { if (typeof levelComparison === "function") { return; } if (typeof levelComparison === "string" && Object.values(SORTING_ORDER).includes(levelComparison)) { return; } throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type'); } module2.exports = { initialLsCache, genLsCache, levelMethods, getLevel, setLevel, isLevelEnabled, mappings, assertNoLevelCollisions, assertDefaultLevelFound, genLevelComparison, assertLevelComparison }; } }); // node_modules/pino/lib/meta.js var require_meta = __commonJS({ "node_modules/pino/lib/meta.js"(exports, module2) { "use strict"; module2.exports = { version: "9.2.0" }; } }); // node_modules/pino/lib/proto.js var require_proto = __commonJS({ "node_modules/pino/lib/proto.js"(exports, module2) { "use strict"; var { EventEmitter } = require("events"); var { lsCacheSym, levelValSym, setLevelSym, getLevelSym, chindingsSym, parsedChindingsSym, mixinSym, asJsonSym, writeSym, mixinMergeStrategySym, timeSym, timeSliceIndexSym, streamSym, serializersSym, formattersSym, errorKeySym, messageKeySym, useOnlyCustomLevelsSym, needsMetadataGsym, redactFmtSym, stringifySym, formatOptsSym, stringifiersSym, msgPrefixSym } = require_symbols3(); var { getLevel, setLevel, isLevelEnabled, mappings, initialLsCache, genLsCache, assertNoLevelCollisions } = require_levels(); var { asChindings, asJson, buildFormatters, stringify } = require_tools(); var { version } = require_meta(); var redaction = require_redaction(); var constructor = class Pino { }; var prototype = { constructor, child, bindings, setBindings, flush, isLevelEnabled, version, get level() { return this[getLevelSym](); }, set level(lvl) { this[setLevelSym](lvl); }, get levelVal() { return this[levelValSym]; }, set levelVal(n) { throw Error("levelVal is read-only"); }, [lsCacheSym]: initialLsCache, [writeSym]: write, [asJsonSym]: asJson, [getLevelSym]: getLevel, [setLevelSym]: setLevel }; Object.setPrototypeOf(prototype, EventEmitter.prototype); module2.exports = function() { return Object.create(prototype); }; var resetChildingsFormatter = (bindings2) => bindings2; function child(bindings2, options) { if (!bindings2) { throw Error("missing bindings for child Pino"); } options = options || {}; const serializers = this[serializersSym]; const formatters = this[formattersSym]; const instance = Object.create(this); if (options.hasOwnProperty("serializers") === true) { instance[serializersSym] = /* @__PURE__ */ Object.create(null); for (const k in serializers) { instance[serializersSym][k] = serializers[k]; } const parentSymbols = Object.getOwnPropertySymbols(serializers); for (var i = 0; i < parentSymbols.length; i++) { const ks = parentSymbols[i]; instance[serializersSym][ks] = serializers[ks]; } for (const bk in options.serializers) { instance[serializersSym][bk] = options.serializers[bk]; } const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers); for (var bi = 0; bi < bindingsSymbols.length; bi++) { const bks = bindingsSymbols[bi]; instance[serializersSym][bks] = options.serializers[bks]; } } else instance[serializersSym] = serializers; if (options.hasOwnProperty("formatters")) { const { level, bindings: chindings, log } = options.formatters; instance[formattersSym] = buildFormatters( level || formatters.level, chindings || resetChildingsFormatter, log || formatters.log ); } else { instance[formattersSym] = buildFormatters( formatters.level, resetChildingsFormatter, formatters.log ); } if (options.hasOwnProperty("customLevels") === true) { assertNoLevelCollisions(this.levels, options.customLevels); instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym]); genLsCache(instance); } if (typeof options.redact === "object" && options.redact !== null || Array.isArray(options.redact)) { instance.redact = options.redact; const stringifiers = redaction(instance.redact, stringify); const formatOpts = { stringify: stringifiers[redactFmtSym] }; instance[stringifySym] = stringify; instance[stringifiersSym] = stringifiers; instance[formatOptsSym] = formatOpts; } if (typeof options.msgPrefix === "string") { instance[msgPrefixSym] = (this[msgPrefixSym] || "") + options.msgPrefix; } instance[chindingsSym] = asChindings(instance, bindings2); const childLevel = options.level || this.level; instance[setLevelSym](childLevel); this.onChild(instance); return instance; } function bindings() { const chindings = this[chindingsSym]; const chindingsJson = `{${chindings.substr(1)}}`; const bindingsFromJson = JSON.parse(chindingsJson); delete bindingsFromJson.pid; delete bindingsFromJson.hostname; return bindingsFromJson; } function setBindings(newBindings) { const chindings = asChindings(this, newBindings); this[chindingsSym] = chindings; delete this[parsedChindingsSym]; } function defaultMixinMergeStrategy(mergeObject, mixinObject) { return Object.assign(mixinObject, mergeObject); } function write(_obj, msg, num) { const t = this[timeSym](); const mixin = this[mixinSym]; const errorKey = this[errorKeySym]; const messageKey = this[messageKeySym]; const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy; let obj; if (_obj === void 0 || _obj === null) { obj = {}; } else if (_obj instanceof Error) { obj = { [errorKey]: _obj }; if (msg === void 0) { msg = _obj.message; } } else { obj = _obj; if (msg === void 0 && _obj[messageKey] === void 0 && _obj[errorKey]) { msg = _obj[errorKey].message; } } if (mixin) { obj = mixinMergeStrategy(obj, mixin(obj, num, this)); } const s = this[asJsonSym](obj, msg, num, t); const stream = this[streamSym]; if (stream[needsMetadataGsym] === true) { stream.lastLevel = num; stream.lastObj = obj; stream.lastMsg = msg; stream.lastTime = t.slice(this[timeSliceIndexSym]); stream.lastLogger = this; } stream.write(s); } function noop() { } function flush(cb) { if (cb != null && typeof cb !== "function") { throw Error("callback must be a function"); } const stream = this[streamSym]; if (typeof stream.flush === "function") { stream.flush(cb || noop); } else if (cb) cb(); } } }); // node_modules/safe-stable-stringify/index.js var require_safe_stable_stringify = __commonJS({ "node_modules/safe-stable-stringify/index.js"(exports, module2) { "use strict"; var { hasOwnProperty } = Object.prototype; var stringify = configure(); stringify.configure = configure; stringify.stringify = stringify; stringify.default = stringify; exports.stringify = stringify; exports.configure = configure; module2.exports = stringify; var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/; function strEscape(str) { if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { return `"${str}"`; } return JSON.stringify(str); } function insertSort(array) { if (array.length > 200) { return array.sort(); } for (let i = 1; i < array.length; i++) { const currentValue = array[i]; let position = i; while (position !== 0 && array[position - 1] > currentValue) { array[position] = array[position - 1]; position--; } array[position] = currentValue; } return array; } var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( Object.getPrototypeOf( Object.getPrototypeOf( new Int8Array() ) ), Symbol.toStringTag ).get; function isTypedArrayWithEntries(value) { return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; } function stringifyTypedArray(array, separator, maximumBreadth) { if (array.length < maximumBreadth) { maximumBreadth = array.length; } const whitespace = separator === "," ? "" : " "; let res = `"0":${whitespace}${array[0]}`; for (let i = 1; i < maximumBreadth; i++) { res += `${separator}"${i}":${whitespace}${array[i]}`; } return res; } function getCircularValueOption(options) { if (hasOwnProperty.call(options, "circularValue")) { const circularValue = options.circularValue; if (typeof circularValue === "string") { return `"${circularValue}"`; } if (circularValue == null) { return circularValue; } if (circularValue === Error || circularValue === TypeError) { return { toString() { throw new TypeError("Converting circular structure to JSON"); } }; } throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); } return '"[Circular]"'; } function getBooleanOption(options, key) { let value; if (hasOwnProperty.call(options, key)) { value = options[key]; if (typeof value !== "boolean") { throw new TypeError(`The "${key}" argument must be of type boolean`); } } return value === void 0 ? true : value; } function getPositiveIntegerOption(options, key) { let value; if (hasOwnProperty.call(options, key)) { value = options[key]; if (typeof value !== "number") { throw new TypeError(`The "${key}" argument must be of type number`); } if (!Number.isInteger(value)) { throw new TypeError(`The "${key}" argument must be an integer`); } if (value < 1) { throw new RangeError(`The "${key}" argument must be >= 1`); } } return value === void 0 ? Infinity : value; } function getItemCount(number) { if (number === 1) { return "1 item"; } return `${number} items`; } function getUniqueReplacerSet(replacerArray) { const replacerSet = /* @__PURE__ */ new Set(); for (const value of replacerArray) { if (typeof value === "string" || typeof value === "number") { replacerSet.add(String(value)); } } return replacerSet; } function getStrictOption(options) { if (hasOwnProperty.call(options, "strict")) { const value = options.strict; if (typeof value !== "boolean") { throw new TypeError('The "strict" argument must be of type boolean'); } if (value) { return (value2) => { let message = `Object can not safely be stringified. Received type ${typeof value2}`; if (typeof value2 !== "function") message += ` (${value2.toString()})`; throw new Error(message); }; } } } function configure(options) { options = { ...options }; const fail = getStrictOption(options); if (fail) { if (options.bigint === void 0) { options.bigint = false; } if (!("circularValue" in options)) { options.circularValue = Error; } } const circularValue = getCircularValueOption(options); const bigint = getBooleanOption(options, "bigint"); const deterministic = getBooleanOption(options, "deterministic"); const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { let value = parent[key]; if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { value = value.toJSON(key); } value = replacer.call(parent, key, value); switch (typeof value) { case "string": return strEscape(value); case "object": { if (value === null) { return "null"; } if (stack.indexOf(value) !== -1) { return circularValue; } let res = ""; let join = ","; const originalIndentation = indentation; if (Array.isArray(value)) { if (value.length === 0) { return "[]"; } if (maximumDepth < stack.length + 1) { return '"[Array]"'; } stack.push(value); if (spacer !== "") { indentation += spacer; res += ` ${indentation}`; join = `, ${indentation}`; } const maximumValuesToStringify = Math.min(value.length, maximumBreadth); let i = 0; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); res += tmp2 !== void 0 ? tmp2 : "null"; res += join; } const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); res += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; res += `${join}"... ${getItemCount(removedKeys)} not stringified"`; } if (spacer !== "") { res += ` ${originalIndentation}`; } stack.pop(); return `[${res}]`; } let keys = Object.keys(value); const keyLength = keys.length; if (keyLength === 0) { return "{}"; } if (maximumDepth < stack.length + 1) { return '"[Object]"'; } let whitespace = ""; let separator = ""; if (spacer !== "") { indentation += spacer; join = `, ${indentation}`; whitespace = " "; } const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); if (deterministic && !isTypedArrayWithEntries(value)) { keys = insertSort(keys); } stack.push(value); for (let i = 0; i < maximumPropertiesToStringify; i++) { const key2 = keys[i]; const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; separator = join; } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth; res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; separator = join; } if (spacer !== "" && separator.length > 1) { res = ` ${indentation}${res} ${originalIndentation}`; } stack.pop(); return `{${res}}`; } case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null"; case "boolean": return value === true ? "true" : "false"; case "undefined": return void 0; case "bigint": if (bigint) { return String(value); } default: return fail ? fail(value) : void 0; } } function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return strEscape(value); case "object": { if (value === null) { return "null"; } if (stack.indexOf(value) !== -1) { return circularValue; } const originalIndentation = indentation; let res = ""; let join = ","; if (Array.isArray(value)) { if (value.length === 0) { return "[]"; } if (maximumDepth < stack.length + 1) { return '"[Array]"'; } stack.push(value); if (spacer !== "") { indentation += spacer; res += ` ${indentation}`; join = `, ${indentation}`; } const maximumValuesToStringify = Math.min(value.length, maximumBreadth); let i = 0; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); res += tmp2 !== void 0 ? tmp2 : "null"; res += join; } const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); res += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; res += `${join}"... ${getItemCount(removedKeys)} not stringified"`; } if (spacer !== "") { res += ` ${originalIndentation}`; } stack.pop(); return `[${res}]`; } stack.push(value); let whitespace = ""; if (spacer !== "") { indentation += spacer; join = `, ${indentation}`; whitespace = " "; } let separator = ""; for (const key2 of replacer) { const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; separator = join; } } if (spacer !== "" && separator.length > 1) { res = ` ${indentation}${res} ${originalIndentation}`; } stack.pop(); return `{${res}}`; } case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null"; case "boolean": return value === true ? "true" : "false"; case "undefined": return void 0; case "bigint": if (bigint) { return String(value); } default: return fail ? fail(value) : void 0; } } function stringifyIndent(key, value, stack, spacer, indentation) { switch (typeof value) { case "string": return strEscape(value); case "object": { if (value === null) { return "null"; } if (typeof value.toJSON === "function") { value = value.toJSON(key); if (typeof value !== "object") { return stringifyIndent(key, value, stack, spacer, indentation); } if (value === null) { return "null"; } } if (stack.indexOf(value) !== -1) { return circularValue; } const originalIndentation = indentation; if (Array.isArray(value)) { if (value.length === 0) { return "[]"; } if (maximumDepth < stack.length + 1) { return '"[Array]"'; } stack.push(value); indentation += spacer; let res2 = ` ${indentation}`; const join2 = `, ${indentation}`; const maximumValuesToStringify = Math.min(value.length, maximumBreadth); let i = 0; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation); res2 += tmp2 !== void 0 ? tmp2 : "null"; res2 += join2; } const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation); res2 += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; res2 += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; } res2 += ` ${originalIndentation}`; stack.pop(); return `[${res2}]`; } let keys = Object.keys(value); const keyLength = keys.length; if (keyLength === 0) { return "{}"; } if (maximumDepth < stack.length + 1) { return '"[Object]"'; } indentation += spacer; const join = `, ${indentation}`; let res = ""; let separator = ""; let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); if (isTypedArrayWithEntries(value)) { res += stringifyTypedArray(value, join, maximumBreadth); keys = keys.slice(value.length); maximumPropertiesToStringify -= value.length; separator = join; } if (deterministic) { keys = insertSort(keys); } stack.push(value); for (let i = 0; i < maximumPropertiesToStringify; i++) { const key2 = keys[i]; const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}: ${tmp}`; separator = join; } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth; res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; separator = join; } if (separator !== "") { res = ` ${indentation}${res} ${originalIndentation}`; } stack.pop(); return `{${res}}`; } case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null"; case "boolean": return value === true ? "true" : "false"; case "undefined": return void 0; case "bigint": if (bigint) { return String(value); } default: return fail ? fail(value) : void 0; } } function stringifySimple(key, value, stack) { switch (typeof value) { case "string": return strEscape(value); case "object": { if (value === null) { return "null"; } if (typeof value.toJSON === "function") { value = value.toJSON(key); if (typeof value !== "object") { return stringifySimple(key, value, stack); } if (value === null) { return "null"; } } if (stack.indexOf(value) !== -1) { return circularValue; } let res = ""; if (Array.isArray(value)) { if (value.length === 0) { return "[]"; } if (maximumDepth < stack.length + 1) { return '"[Array]"'; } stack.push(value); const maximumValuesToStringify = Math.min(value.length, maximumBreadth); let i = 0; for (; i < maximumValuesToStringify - 1; i++) { const tmp2 = stringifySimple(String(i), value[i], stack); res += tmp2 !== void 0 ? tmp2 : "null"; res += ","; } const tmp = stringifySimple(String(i), value[i], stack); res += tmp !== void 0 ? tmp : "null"; if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1; res += `,"... ${getItemCount(removedKeys)} not stringified"`; } stack.pop(); return `[${res}]`; } let keys = Object.keys(value); const keyLength = keys.length; if (keyLength === 0) { return "{}"; } if (maximumDepth < stack.length + 1) { return '"[Object]"'; } let separator = ""; let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); if (isTypedArrayWithEntries(value)) { res += stringifyTypedArray(value, ",", maximumBreadth); keys = keys.slice(value.length); maximumPropertiesToStringify -= value.length; separator = ","; } if (deterministic) { keys = insertSort(keys); } stack.push(value); for (let i = 0; i < maximumPropertiesToStringify; i++) { const key2 = keys[i]; const tmp = stringifySimple(key2, value[key2], stack); if (tmp !== void 0) { res += `${separator}${strEscape(key2)}:${tmp}`; separator = ","; } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth; res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; } stack.pop(); return `{${res}}`; } case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null"; case "boolean": return value === true ? "true" : "false"; case "undefined": return void 0; case "bigint": if (bigint) { return String(value); } default: return fail ? fail(value) : void 0; } } function stringify2(value, replacer, space) { if (arguments.length > 1) { let spacer = ""; if (typeof space === "number") { spacer = " ".repeat(Math.min(space, 10)); } else if (typeof space === "string") { spacer = space.slice(0, 10); } if (replacer != null) { if (typeof replacer === "function") { return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); } if (Array.isArray(replacer)) { return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); } } if (spacer.length !== 0) { return stringifyIndent("", value, [], spacer, ""); } } return stringifySimple("", value, []); } return stringify2; } } }); // node_modules/pino/lib/multistream.js var require_multistream = __commonJS({ "node_modules/pino/lib/multistream.js"(exports, module2) { "use strict"; var metadata = Symbol.for("pino.metadata"); var { DEFAULT_LEVELS } = require_constants(); var DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info; function multistream(streamsArray, opts) { let counter = 0; streamsArray = streamsArray || []; opts = opts || { dedupe: false }; const streamLevels = Object.create(DEFAULT_LEVELS); streamLevels.silent = Infinity; if (opts.levels && typeof opts.levels === "object") { Object.keys(opts.levels).forEach((i) => { streamLevels[i] = opts.levels[i]; }); } const res = { write, add, emit, flushSync, end, minLevel: 0, streams: [], clone, [metadata]: true, streamLevels }; if (Array.isArray(streamsArray)) { streamsArray.forEach(add, res); } else { add.call(res, streamsArray); } streamsArray = null; return res; function write(data) { let dest; const level = this.lastLevel; const { streams } = this; let recordedLevel = 0; let stream; for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) { dest = streams[i]; if (dest.level <= level) { if (recordedLevel !== 0 && recordedLevel !== dest.level) { break; } stream = dest.stream; if (stream[metadata]) { const { lastTime, lastMsg, lastObj, lastLogger } = this; stream.lastLevel = level; stream.lastTime = lastTime; stream.lastMsg = lastMsg; stream.lastObj = lastObj; stream.lastLogger = lastLogger; } stream.write(data); if (opts.dedupe) { recordedLevel = dest.level; } } else if (!opts.dedupe) { break; } } } function emit(...args) { for (const { stream } of this.streams) { if (typeof stream.emit === "function") { stream.emit(...args); } } } function flushSync() { for (const { stream } of this.streams) { if (typeof stream.flushSync === "function") { stream.flushSync(); } } } function add(dest) { if (!dest) { return res; } const isStream = typeof dest.write === "function" || dest.stream; const stream_ = dest.write ? dest : dest.stream; if (!isStream) { throw Error("stream object needs to implement either StreamEntry or DestinationStream interface"); } const { streams, streamLevels: streamLevels2 } = this; let level; if (typeof dest.levelVal === "number") { level = dest.levelVal; } else if (typeof dest.level === "string") { level = streamLevels2[dest.level]; } else if (typeof dest.level === "number") { level = dest.level; } else { level = DEFAULT_INFO_LEVEL; } const dest_ = { stream: stream_, level, levelVal: void 0, id: counter++ }; streams.unshift(dest_); streams.sort(compareByLevel); this.minLevel = streams[0].level; return res; } function end() { for (const { stream } of this.streams) { if (typeof stream.flushSync === "function") { stream.flushSync(); } stream.end(); } } function clone(level) { const streams = new Array(this.streams.length); for (let i = 0; i < streams.length; i++) { streams[i] = { level, stream: this.streams[i].stream }; } return { write, add, minLevel: level, streams, clone, emit, flushSync, [metadata]: true }; } } function compareByLevel(a, b) { return a.level - b.level; } function initLoopVar(length, dedupe) { return dedupe ? length - 1 : 0; } function adjustLoopVar(i, dedupe) { return dedupe ? i - 1 : i + 1; } function checkLoopVar(i, length, dedupe) { return dedupe ? i >= 0 : i < length; } module2.exports = multistream; } }); // node_modules/pino/pino.js var require_pino = __commonJS({ "node_modules/pino/pino.js"(exports, module2) { "use strict"; var os = require("os"); var stdSerializers = require_pino_std_serializers(); var caller = require_caller(); var redaction = require_redaction(); var time = require_time(); var proto = require_proto(); var symbols = require_symbols3(); var { configure } = require_safe_stable_stringify(); var { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require_levels(); var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); var { createArgsNormalizer, asChindings, buildSafeSonicBoom, buildFormatters, stringify, normalizeDestFileDescriptor, noop } = require_tools(); var { version } = require_meta(); var { chindingsSym, redactFmtSym, serializersSym, timeSym, timeSliceIndexSym, streamSym, stringifySym, stringifySafeSym, stringifiersSym, setLevelSym, endSym, formatOptsSym, messageKeySym, errorKeySym, nestedKeySym, mixinSym, levelCompSym, useOnlyCustomLevelsSym, formattersSym, hooksSym, nestedKeyStrSym, mixinMergeStrategySym, msgPrefixSym } = symbols; var { epochTime, nullTime } = time; var { pid } = process; var hostname = os.hostname(); var defaultErrorSerializer = stdSerializers.err; var defaultOptions = { level: "info", levelComparison: SORTING_ORDER.ASC, levels: DEFAULT_LEVELS, messageKey: "msg", errorKey: "err", nestedKey: null, enabled: true, base: { pid, hostname }, serializers: Object.assign(/* @__PURE__ */ Object.create(null), { err: defaultErrorSerializer }), formatters: Object.assign(/* @__PURE__ */ Object.create(null), { bindings(bindings) { return bindings; }, level(label, number) { return { level: number }; } }), hooks: { logMethod: void 0 }, timestamp: epochTime, name: void 0, redact: null, customLevels: null, useOnlyCustomLevels: false, depthLimit: 5, edgeLimit: 100 }; var normalize = createArgsNormalizer(defaultOptions); var serializers = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers); function pino(...args) { const instance = {}; const { opts, stream } = normalize(instance, caller(), ...args); const { redact, crlf, serializers: serializers2, timestamp, messageKey, errorKey, nestedKey, base, name, level, customLevels, levelComparison, mixin, mixinMergeStrategy, useOnlyCustomLevels, formatters, hooks, depthLimit, edgeLimit, onChild, msgPrefix } = opts; const stringifySafe = configure({ maximumDepth: depthLimit, maximumBreadth: edgeLimit }); const allFormatters = buildFormatters( formatters.level, formatters.bindings, formatters.log ); const stringifyFn = stringify.bind({ [stringifySafeSym]: stringifySafe }); const stringifiers = redact ? redaction(redact, stringifyFn) : {}; const formatOpts = redact ? { stringify: stringifiers[redactFmtSym] } : { stringify: stringifyFn }; const end = "}" + (crlf ? "\r\n" : "\n"); const coreChindings = asChindings.bind(null, { [chindingsSym]: "", [serializersSym]: serializers2, [stringifiersSym]: stringifiers, [stringifySym]: stringify, [stringifySafeSym]: stringifySafe, [formattersSym]: allFormatters }); let chindings = ""; if (base !== null) { if (name === void 0) { chindings = coreChindings(base); } else { chindings = coreChindings(Object.assign({}, base, { name })); } } const time2 = timestamp instanceof Function ? timestamp : timestamp ? epochTime : nullTime; const timeSliceIndex = time2().indexOf(":") + 1; if (useOnlyCustomLevels && !customLevels) throw Error("customLevels is required if useOnlyCustomLevels is set true"); if (mixin && typeof mixin !== "function") throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`); if (msgPrefix && typeof msgPrefix !== "string") throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`); assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels); const levels = mappings(customLevels, useOnlyCustomLevels); if (typeof stream.emit === "function") { stream.emit("message", { code: "PINO_CONFIG", config: { levels, messageKey, errorKey } }); } assertLevelComparison(levelComparison); const levelCompFunc = genLevelComparison(levelComparison); Object.assign(instance, { levels, [levelCompSym]: levelCompFunc, [useOnlyCustomLevelsSym]: useOnlyCustomLevels, [streamSym]: stream, [timeSym]: time2, [timeSliceIndexSym]: timeSliceIndex, [stringifySym]: stringify, [stringifySafeSym]: stringifySafe, [stringifiersSym]: stringifiers, [endSym]: end, [formatOptsSym]: formatOpts, [messageKeySym]: messageKey, [errorKeySym]: errorKey, [nestedKeySym]: nestedKey, // protect against injection [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : "", [serializersSym]: serializers2, [mixinSym]: mixin, [mixinMergeStrategySym]: mixinMergeStrategy, [chindingsSym]: chindings, [formattersSym]: allFormatters, [hooksSym]: hooks, silent: noop, onChild, [msgPrefixSym]: msgPrefix }); Object.setPrototypeOf(instance, proto()); genLsCache(instance); instance[setLevelSym](level); return instance; } module2.exports = pino; module2.exports.destination = (dest = process.stdout.fd) => { if (typeof dest === "object") { dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd); return buildSafeSonicBoom(dest); } else { return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 }); } }; module2.exports.transport = require_transport(); module2.exports.multistream = require_multistream(); module2.exports.levels = mappings(); module2.exports.stdSerializers = serializers; module2.exports.stdTimeFunctions = Object.assign({}, time); module2.exports.symbols = symbols; module2.exports.version = version; module2.exports.default = pino; module2.exports.pino = pino; } }); // node_modules/fastify/lib/logger.js var require_logger = __commonJS({ "node_modules/fastify/lib/logger.js"(exports, module2) { "use strict"; var nullLogger = require_abstract_logging(); var pino = require_pino(); var { serializersSym } = pino.symbols; var { FST_ERR_LOG_INVALID_DESTINATION, FST_ERR_LOG_INVALID_LOGGER } = require_errors2(); function createPinoLogger(opts) { if (opts.stream && opts.file) { throw new FST_ERR_LOG_INVALID_DESTINATION(); } else if (opts.file) { opts.stream = pino.destination(opts.file); delete opts.file; } const prevLogger = opts.logger; const prevGenReqId = opts.genReqId; let logger = null; if (prevLogger) { opts.logger = void 0; opts.genReqId = void 0; if (prevLogger[serializersSym]) { opts.serializers = Object.assign({}, opts.serializers, prevLogger[serializersSym]); } logger = prevLogger.child({}, opts); opts.logger = prevLogger; opts.genReqId = prevGenReqId; } else { logger = pino(opts, opts.stream); } return logger; } var serializers = { req: function asReqValue(req) { return { method: req.method, url: req.url, version: req.headers && req.headers["accept-version"], hostname: req.hostname, remoteAddress: req.ip, remotePort: req.socket ? req.socket.remotePort : void 0 }; }, err: pino.stdSerializers.err, res: function asResValue(reply) { return { statusCode: reply.statusCode }; } }; function now() { const ts = process.hrtime(); return ts[0] * 1e3 + ts[1] / 1e6; } function createLogger(options) { if (!options.logger) { const logger2 = nullLogger; logger2.child = () => logger2; return { logger: logger2, hasLogger: false }; } if (validateLogger(options.logger)) { const logger2 = createPinoLogger({ logger: options.logger, serializers: Object.assign({}, serializers, options.logger.serializers) }); return { logger: logger2, hasLogger: true }; } const localLoggerOptions = {}; if (Object.prototype.toString.call(options.logger) === "[object Object]") { Reflect.ownKeys(options.logger).forEach((prop) => { Object.defineProperty(localLoggerOptions, prop, { value: options.logger[prop], writable: true, enumerable: true, configurable: true }); }); } localLoggerOptions.level = localLoggerOptions.level || "info"; localLoggerOptions.serializers = Object.assign({}, serializers, localLoggerOptions.serializers); options.logger = localLoggerOptions; const logger = createPinoLogger(options.logger); return { logger, hasLogger: true }; } function validateLogger(logger, strict) { const methods = ["info", "error", "debug", "fatal", "warn", "trace", "child"]; const missingMethods = logger ? methods.filter((method) => !logger[method] || typeof logger[method] !== "function") : methods; if (!missingMethods.length) { return true; } else if (missingMethods.length === methods.length && !strict) { return false; } else { throw FST_ERR_LOG_INVALID_LOGGER(missingMethods.join(",")); } } function createChildLogger(context, logger, req, reqId, loggerOpts) { const loggerBindings = { [context.requestIdLogLabel]: reqId }; const child = context.childLoggerFactory.call(context.server, logger, loggerBindings, loggerOpts || {}, req); if (context.childLoggerFactory !== defaultChildLoggerFactory) { validateLogger(child, true); } return child; } function defaultChildLoggerFactory(logger, bindings, opts) { return logger.child(bindings, opts); } module2.exports = { createLogger, createChildLogger, defaultChildLoggerFactory, serializers, now }; } }); // node_modules/rfdc/index.js var require_rfdc = __commonJS({ "node_modules/rfdc/index.js"(exports, module2) { "use strict"; module2.exports = rfdc; function copyBuffer(cur) { if (cur instanceof Buffer) { return Buffer.from(cur); } return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length); } function rfdc(opts) { opts = opts || {}; if (opts.circles) return rfdcCircles(opts); const constructorHandlers = /* @__PURE__ */ new Map(); constructorHandlers.set(Date, (o) => new Date(o)); constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))); constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))); if (opts.constructorHandlers) { for (const handler2 of opts.constructorHandlers) { constructorHandlers.set(handler2[0], handler2[1]); } } let handler = null; return opts.proto ? cloneProto : clone; function cloneArray(a, fn) { const keys = Object.keys(a); const a2 = new Array(keys.length); for (let i = 0; i < keys.length; i++) { const k = keys[i]; const cur = a[k]; if (typeof cur !== "object" || cur === null) { a2[k] = cur; } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { a2[k] = handler(cur, fn); } else if (ArrayBuffer.isView(cur)) { a2[k] = copyBuffer(cur); } else { a2[k] = fn(cur); } } return a2; } function clone(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, clone); if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, clone); } const o2 = {}; for (const k in o) { if (Object.hasOwnProperty.call(o, k) === false) continue; const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, clone); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { o2[k] = clone(cur); } } return o2; } function cloneProto(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, cloneProto); if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, cloneProto); } const o2 = {}; for (const k in o) { const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, cloneProto); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { o2[k] = cloneProto(cur); } } return o2; } } function rfdcCircles(opts) { const refs = []; const refsNew = []; const constructorHandlers = /* @__PURE__ */ new Map(); constructorHandlers.set(Date, (o) => new Date(o)); constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))); constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))); if (opts.constructorHandlers) { for (const handler2 of opts.constructorHandlers) { constructorHandlers.set(handler2[0], handler2[1]); } } let handler = null; return opts.proto ? cloneProto : clone; function cloneArray(a, fn) { const keys = Object.keys(a); const a2 = new Array(keys.length); for (let i = 0; i < keys.length; i++) { const k = keys[i]; const cur = a[k]; if (typeof cur !== "object" || cur === null) { a2[k] = cur; } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { a2[k] = handler(cur, fn); } else if (ArrayBuffer.isView(cur)) { a2[k] = copyBuffer(cur); } else { const index = refs.indexOf(cur); if (index !== -1) { a2[k] = refsNew[index]; } else { a2[k] = fn(cur); } } } return a2; } function clone(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, clone); if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, clone); } const o2 = {}; refs.push(o); refsNew.push(o2); for (const k in o) { if (Object.hasOwnProperty.call(o, k) === false) continue; const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, clone); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { const i = refs.indexOf(cur); if (i !== -1) { o2[k] = refsNew[i]; } else { o2[k] = clone(cur); } } } refs.pop(); refsNew.pop(); return o2; } function cloneProto(o) { if (typeof o !== "object" || o === null) return o; if (Array.isArray(o)) return cloneArray(o, cloneProto); if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, cloneProto); } const o2 = {}; refs.push(o); refsNew.push(o2); for (const k in o) { const cur = o[k]; if (typeof cur !== "object" || cur === null) { o2[k] = cur; } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, cloneProto); } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur); } else { const i = refs.indexOf(cur); if (i !== -1) { o2[k] = refsNew[i]; } else { o2[k] = cloneProto(cur); } } } refs.pop(); refsNew.pop(); return o2; } } } }); // node_modules/fastify/lib/schemas.js var require_schemas = __commonJS({ "node_modules/fastify/lib/schemas.js"(exports, module2) { "use strict"; var fastClone = require_rfdc()({ circles: false, proto: true }); var { kSchemaVisited, kSchemaResponse } = require_symbols2(); var kFluentSchema = Symbol.for("fluent-schema-object"); var { FST_ERR_SCH_MISSING_ID, FST_ERR_SCH_ALREADY_PRESENT, FST_ERR_SCH_DUPLICATE, FST_ERR_SCH_CONTENT_MISSING_SCHEMA } = require_errors2(); var SCHEMAS_SOURCE = ["params", "body", "querystring", "query", "headers"]; function Schemas(initStore) { this.store = initStore || {}; } Schemas.prototype.add = function(inputSchema) { const schema = fastClone( inputSchema.isFluentSchema || inputSchema.isFluentJSONSchema || inputSchema[kFluentSchema] ? inputSchema.valueOf() : inputSchema ); const id = schema.$id; if (!id) { throw new FST_ERR_SCH_MISSING_ID(); } if (this.store[id]) { throw new FST_ERR_SCH_ALREADY_PRESENT(id); } this.store[id] = schema; }; Schemas.prototype.getSchemas = function() { return Object.assign({}, this.store); }; Schemas.prototype.getSchema = function(schemaId) { return this.store[schemaId]; }; function isCustomSchemaPrototype(schema) { return typeof schema === "object" && Object.getPrototypeOf(schema) !== Object.prototype; } function normalizeSchema(routeSchemas, serverOptions) { if (routeSchemas[kSchemaVisited]) { return routeSchemas; } if (routeSchemas.query) { if (routeSchemas.querystring) { throw new FST_ERR_SCH_DUPLICATE("querystring"); } routeSchemas.querystring = routeSchemas.query; } generateFluentSchema(routeSchemas); for (const key of SCHEMAS_SOURCE) { const schema = routeSchemas[key]; if (schema && !isCustomSchemaPrototype(schema)) { routeSchemas[key] = getSchemaAnyway(schema, serverOptions.jsonShorthand); } } if (routeSchemas.response) { const httpCodes = Object.keys(routeSchemas.response); for (const code of httpCodes) { if (isCustomSchemaPrototype(routeSchemas.response[code])) { continue; } const contentProperty = routeSchemas.response[code].content; let hasContentMultipleContentTypes = false; if (contentProperty) { const keys = Object.keys(contentProperty); for (let i = 0; i < keys.length; i++) { const mediaName = keys[i]; if (!contentProperty[mediaName].schema) { if (keys.length === 1) { break; } throw new FST_ERR_SCH_CONTENT_MISSING_SCHEMA(mediaName); } routeSchemas.response[code].content[mediaName].schema = getSchemaAnyway(contentProperty[mediaName].schema, serverOptions.jsonShorthand); if (i === keys.length - 1) { hasContentMultipleContentTypes = true; } } } if (!hasContentMultipleContentTypes) { routeSchemas.response[code] = getSchemaAnyway(routeSchemas.response[code], serverOptions.jsonShorthand); } } } routeSchemas[kSchemaVisited] = true; return routeSchemas; } function generateFluentSchema(schema) { for (const key of SCHEMAS_SOURCE) { if (schema[key] && (schema[key].isFluentSchema || schema[key][kFluentSchema])) { schema[key] = schema[key].valueOf(); } } if (schema.response) { const httpCodes = Object.keys(schema.response); for (const code of httpCodes) { if (schema.response[code].isFluentSchema || schema.response[code][kFluentSchema]) { schema.response[code] = schema.response[code].valueOf(); } } } } function getSchemaAnyway(schema, jsonShorthand) { if (!jsonShorthand || schema.$ref || schema.oneOf || schema.allOf || schema.anyOf || schema.$merge || schema.$patch) return schema; if (!schema.type && !schema.properties) { return { type: "object", properties: schema }; } return schema; } function getSchemaSerializer(context, statusCode, contentType) { const responseSchemaDef = context[kSchemaResponse]; if (!responseSchemaDef) { return false; } if (responseSchemaDef[statusCode]) { if (responseSchemaDef[statusCode].constructor === Object && contentType) { const mediaName = contentType.split(";", 1)[0]; if (responseSchemaDef[statusCode][mediaName]) { return responseSchemaDef[statusCode][mediaName]; } return false; } return responseSchemaDef[statusCode]; } const fallbackStatusCode = (statusCode + "")[0] + "xx"; if (responseSchemaDef[fallbackStatusCode]) { if (responseSchemaDef[fallbackStatusCode].constructor === Object && contentType) { const mediaName = contentType.split(";", 1)[0]; if (responseSchemaDef[fallbackStatusCode][mediaName]) { return responseSchemaDef[fallbackStatusCode][mediaName]; } return false; } return responseSchemaDef[fallbackStatusCode]; } if (responseSchemaDef.default) { if (responseSchemaDef.default.constructor === Object && contentType) { const mediaName = contentType.split(";", 1)[0]; if (responseSchemaDef.default[mediaName]) { return responseSchemaDef.default[mediaName]; } return false; } return responseSchemaDef.default; } return false; } module2.exports = { buildSchemas(initStore) { return new Schemas(initStore); }, getSchemaSerializer, normalizeSchema }; } }); // node_modules/fast-json-stringify/lib/serializer.js var require_serializer = __commonJS({ "node_modules/fast-json-stringify/lib/serializer.js"(exports, module2) { "use strict"; var STR_ESCAPE = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; module2.exports = class Serializer { constructor(options) { switch (options && options.rounding) { case "floor": this.parseInteger = Math.floor; break; case "ceil": this.parseInteger = Math.ceil; break; case "round": this.parseInteger = Math.round; break; case "trunc": default: this.parseInteger = Math.trunc; break; } this._options = options; } asInteger(i) { if (Number.isInteger(i)) { return "" + i; } else if (typeof i === "bigint") { return i.toString(); } const integer = this.parseInteger(i); if (integer === Infinity || integer === -Infinity || integer !== integer) { throw new Error(`The value "${i}" cannot be converted to an integer.`); } return "" + integer; } asNumber(i) { const num = Number(i); if (num !== num) { throw new Error(`The value "${i}" cannot be converted to a number.`); } else if (num === Infinity || num === -Infinity) { return "null"; } else { return "" + num; } } asBoolean(bool) { return bool && "true" || "false"; } asDateTime(date) { if (date === null) return '""'; if (date instanceof Date) { return '"' + date.toISOString() + '"'; } if (typeof date === "string") { return '"' + date + '"'; } throw new Error(`The value "${date}" cannot be converted to a date-time.`); } asDate(date) { if (date === null) return '""'; if (date instanceof Date) { return '"' + new Date(date.getTime() - date.getTimezoneOffset() * 6e4).toISOString().slice(0, 10) + '"'; } if (typeof date === "string") { return '"' + date + '"'; } throw new Error(`The value "${date}" cannot be converted to a date.`); } asTime(date) { if (date === null) return '""'; if (date instanceof Date) { return '"' + new Date(date.getTime() - date.getTimezoneOffset() * 6e4).toISOString().slice(11, 19) + '"'; } if (typeof date === "string") { return '"' + date + '"'; } throw new Error(`The value "${date}" cannot be converted to a time.`); } asString(str) { const len = str.length; if (len < 42) { let result = ""; let last = -1; let point = 255; for (var i = 0; i < len; i++) { point = str.charCodeAt(i); if (point === 34 || // '"' point === 92) { last === -1 && (last = 0); result += str.slice(last, i) + "\\"; last = i; } else if (point < 32 || point >= 55296 && point <= 57343) { return JSON.stringify(str); } } return last === -1 && '"' + str + '"' || '"' + result + str.slice(last) + '"'; } else if (len < 5e3 && STR_ESCAPE.test(str) === false) { return '"' + str + '"'; } else { return JSON.stringify(str); } } asUnsafeString(str) { return '"' + str + '"'; } getState() { return this._options; } static restoreFromState(state) { return new Serializer(state); } }; } }); // node_modules/fastify/lib/error-serializer.js var require_error_serializer = __commonJS({ "node_modules/fastify/lib/error-serializer.js"(exports, module2) { "use strict"; var Serializer = require_serializer(); var serializerState = { "mode": "standalone" }; var serializer = Serializer.restoreFromState(serializerState); var validator = null; module2.exports = function anonymous(validator2, serializer2) { const JSON_STR_BEGIN_OBJECT = "{"; const JSON_STR_END_OBJECT = "}"; const JSON_STR_BEGIN_ARRAY = "["; const JSON_STR_END_ARRAY = "]"; const JSON_STR_COMMA = ","; const JSON_STR_COLONS = ":"; const JSON_STR_QUOTE = '"'; const JSON_STR_EMPTY_OBJECT = JSON_STR_BEGIN_OBJECT + JSON_STR_END_OBJECT; const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY; const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE; const JSON_STR_NULL = "null"; function anonymous0(input) { const obj = input && typeof input.toJSON === "function" ? input.toJSON() : input; if (obj === null) return JSON_STR_EMPTY_OBJECT; let value; let json = JSON_STR_BEGIN_OBJECT; let addComma = false; value = obj["statusCode"]; if (value !== void 0) { !addComma && (addComma = true) || (json += JSON_STR_COMMA); json += '"statusCode":'; json += serializer2.asNumber(value); } value = obj["code"]; if (value !== void 0) { !addComma && (addComma = true) || (json += JSON_STR_COMMA); json += '"code":'; if (typeof value !== "string") { if (value === null) { json += JSON_STR_EMPTY_STRING; } else if (value instanceof Date) { json += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE; } else if (value instanceof RegExp) { json += serializer2.asString(value.source); } else { json += serializer2.asString(value.toString()); } } else { json += serializer2.asString(value); } } value = obj["error"]; if (value !== void 0) { !addComma && (addComma = true) || (json += JSON_STR_COMMA); json += '"error":'; if (typeof value !== "string") { if (value === null) { json += JSON_STR_EMPTY_STRING; } else if (value instanceof Date) { json += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE; } else if (value instanceof RegExp) { json += serializer2.asString(value.source); } else { json += serializer2.asString(value.toString()); } } else { json += serializer2.asString(value); } } value = obj["message"]; if (value !== void 0) { !addComma && (addComma = true) || (json += JSON_STR_COMMA); json += '"message":'; if (typeof value !== "string") { if (value === null) { json += JSON_STR_EMPTY_STRING; } else if (value instanceof Date) { json += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE; } else if (value instanceof RegExp) { json += serializer2.asString(value.source); } else { json += serializer2.asString(value.toString()); } } else { json += serializer2.asString(value); } } return json + JSON_STR_END_OBJECT; } const main = anonymous0; return main; }(validator, serializer); } }); // node_modules/fastify/lib/error-handler.js var require_error_handler = __commonJS({ "node_modules/fastify/lib/error-handler.js"(exports, module2) { "use strict"; var statusCodes = require("http").STATUS_CODES; var wrapThenable = require_wrapThenable(); var { kReplyHeaders, kReplyNextErrorHandler, kReplyIsRunningOnErrorHook, kReplyHasStatusCode, kRouteContext, kDisableRequestLogging } = require_symbols2(); var { FST_ERR_REP_INVALID_PAYLOAD_TYPE, FST_ERR_FAILED_ERROR_SERIALIZATION } = require_errors2(); var { getSchemaSerializer } = require_schemas(); var serializeError = require_error_serializer(); var rootErrorHandler = { func: defaultErrorHandler, toJSON() { return this.func.name.toString() + "()"; } }; function handleError(reply, error, cb) { reply[kReplyIsRunningOnErrorHook] = false; const context = reply[kRouteContext]; if (reply[kReplyNextErrorHandler] === false) { fallbackErrorHandler(error, reply, function(reply2, payload) { try { reply2.raw.writeHead(reply2.raw.statusCode, reply2[kReplyHeaders]); } catch (error2) { if (!reply2.log[kDisableRequestLogging]) { reply2.log.warn( { req: reply2.request, res: reply2, err: error2 }, error2 && error2.message ); } reply2.raw.writeHead(reply2.raw.statusCode); } reply2.raw.end(payload); }); return; } const errorHandler = reply[kReplyNextErrorHandler] || context.errorHandler; reply[kReplyNextErrorHandler] = Object.getPrototypeOf(errorHandler); delete reply[kReplyHeaders]["content-type"]; delete reply[kReplyHeaders]["content-length"]; const func = errorHandler.func; if (!func) { reply[kReplyNextErrorHandler] = false; fallbackErrorHandler(error, reply, cb); return; } try { const result = func(error, reply.request, reply); if (result !== void 0) { if (result !== null && typeof result.then === "function") { wrapThenable(result, reply); } else { reply.send(result); } } } catch (err) { reply.send(err); } } function defaultErrorHandler(error, request, reply) { setErrorHeaders(error, reply); if (!reply[kReplyHasStatusCode] || reply.statusCode === 200) { const statusCode = error.statusCode || error.status; reply.code(statusCode >= 400 ? statusCode : 500); } if (reply.statusCode < 500) { if (!reply.log[kDisableRequestLogging]) { reply.log.info( { res: reply, err: error }, error && error.message ); } } else { if (!reply.log[kDisableRequestLogging]) { reply.log.error( { req: request, res: reply, err: error }, error && error.message ); } } reply.send(error); } function fallbackErrorHandler(error, reply, cb) { var _a; const res = reply.raw; const statusCode = reply.statusCode; reply[kReplyHeaders]["content-type"] = (_a = reply[kReplyHeaders]["content-type"]) != null ? _a : "application/json; charset=utf-8"; let payload; try { const serializerFn = getSchemaSerializer(reply[kRouteContext], statusCode, reply[kReplyHeaders]["content-type"]); payload = serializerFn === false ? serializeError({ error: statusCodes[statusCode + ""], code: error.code, message: error.message, statusCode }) : serializerFn(Object.create(error, { error: { value: statusCodes[statusCode + ""] }, message: { value: error.message }, statusCode: { value: statusCode } })); } catch (err) { if (!reply.log[kDisableRequestLogging]) { reply.log.error({ err, statusCode: res.statusCode }, "The serializer for the given status code failed"); } reply.code(500); payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error.message)); } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)); } reply[kReplyHeaders]["content-length"] = "" + Buffer.byteLength(payload); cb(reply, payload); } function buildErrorHandler(parent = rootErrorHandler, func) { if (!func) { return parent; } const errorHandler = Object.create(parent); errorHandler.func = func; return errorHandler; } function setErrorHeaders(error, reply) { const res = reply.raw; let statusCode = res.statusCode; statusCode = statusCode >= 400 ? statusCode : 500; if (error != null) { if (error.headers !== void 0) { reply.headers(error.headers); } if (error.status >= 400) { statusCode = error.status; } else if (error.statusCode >= 400) { statusCode = error.statusCode; } } res.statusCode = statusCode; } module2.exports = { buildErrorHandler, handleError }; } }); // node_modules/fastify/lib/reply.js var require_reply = __commonJS({ "node_modules/fastify/lib/reply.js"(exports, module2) { "use strict"; var eos = require("stream").finished; var Readable = require("stream").Readable; var { kFourOhFourContext, kPublicRouteContext, kReplyErrorHandlerCalled, kReplyHijacked, kReplyStartTime, kReplyEndTime, kReplySerializer, kReplySerializerDefault, kReplyIsError, kReplyHeaders, kReplyTrailers, kReplyHasStatusCode, kReplyIsRunningOnErrorHook, kReplyNextErrorHandler, kDisableRequestLogging, kSchemaResponse, kReplyCacheSerializeFns, kSchemaController, kOptions, kRouteContext } = require_symbols2(); var { onSendHookRunner, onResponseHookRunner, preHandlerHookRunner, preSerializationHookRunner } = require_hooks(); var internals = require_handleRequest()[Symbol.for("internals")]; var loggerUtils = require_logger(); var now = loggerUtils.now; var { handleError } = require_error_handler(); var { getSchemaSerializer } = require_schemas(); var CONTENT_TYPE = { JSON: "application/json; charset=utf-8", PLAIN: "text/plain; charset=utf-8", OCTET: "application/octet-stream" }; var { FST_ERR_REP_INVALID_PAYLOAD_TYPE, FST_ERR_REP_RESPONSE_BODY_CONSUMED, FST_ERR_REP_ALREADY_SENT, FST_ERR_REP_SENT_VALUE, FST_ERR_SEND_INSIDE_ONERR, FST_ERR_BAD_STATUS_CODE, FST_ERR_BAD_TRAILER_NAME, FST_ERR_BAD_TRAILER_VALUE, FST_ERR_MISSING_SERIALIZATION_FN, FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN } = require_errors2(); var { FSTDEP010, FSTDEP013, FSTDEP019, FSTDEP020, FSTDEP021 } = require_warnings(); var toString = Object.prototype.toString; function Reply(res, request, log) { this.raw = res; this[kReplySerializer] = null; this[kReplyErrorHandlerCalled] = false; this[kReplyIsError] = false; this[kReplyIsRunningOnErrorHook] = false; this.request = request; this[kReplyHeaders] = {}; this[kReplyTrailers] = null; this[kReplyHasStatusCode] = false; this[kReplyStartTime] = void 0; this.log = log; } Reply.props = []; Object.defineProperties(Reply.prototype, { [kRouteContext]: { get() { return this.request[kRouteContext]; } }, // TODO: remove once v5 is done // Is temporary to avoid constant conflicts between `next` and `main` context: { get() { FSTDEP019(); return this.request[kRouteContext]; } }, elapsedTime: { get() { if (this[kReplyStartTime] === void 0) { return 0; } return (this[kReplyEndTime] || now()) - this[kReplyStartTime]; } }, server: { get() { return this.request[kRouteContext].server; } }, sent: { enumerable: true, get() { return (this[kReplyHijacked] || this.raw.writableEnded) === true; }, set(value) { FSTDEP010(); if (value !== true) { throw new FST_ERR_REP_SENT_VALUE(); } if (this.sent && this[kReplyHijacked]) { throw new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method); } this[kReplyHijacked] = true; } }, statusCode: { get() { return this.raw.statusCode; }, set(value) { this.code(value); } }, [kPublicRouteContext]: { get() { return this.request[kPublicRouteContext]; } } }); Reply.prototype.hijack = function() { this[kReplyHijacked] = true; return this; }; Reply.prototype.send = function(payload) { if (this[kReplyIsRunningOnErrorHook] === true) { throw new FST_ERR_SEND_INSIDE_ONERR(); } if (this.sent) { this.log.warn({ err: new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method) }); return this; } if (payload instanceof Error || this[kReplyIsError] === true) { this[kReplyIsError] = false; onErrorHook(this, payload, onSendHook); return this; } if (payload === void 0) { onSendHook(this, payload); return this; } const contentType = this.getHeader("content-type"); const hasContentType = contentType !== void 0; if (payload !== null) { if ( // node:stream typeof payload.pipe === "function" || // node:stream/web typeof payload.getReader === "function" || // Response toString.call(payload) === "[object Response]" ) { onSendHook(this, payload); return this; } if ((payload == null ? void 0 : payload.buffer) instanceof ArrayBuffer) { if (hasContentType === false) { this[kReplyHeaders]["content-type"] = CONTENT_TYPE.OCTET; } const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength); onSendHook(this, payloadToSend); return this; } if (hasContentType === false && typeof payload === "string") { this[kReplyHeaders]["content-type"] = CONTENT_TYPE.PLAIN; onSendHook(this, payload); return this; } } if (this[kReplySerializer] !== null) { if (typeof payload !== "string") { preSerializationHook(this, payload); return this; } else { payload = this[kReplySerializer](payload); } } else if (hasContentType === false || contentType.indexOf("json") > -1) { if (hasContentType === false) { this[kReplyHeaders]["content-type"] = CONTENT_TYPE.JSON; } else { if (contentType.indexOf("charset") === -1) { const customContentType = contentType.trim(); if (customContentType.endsWith(";")) { this[kReplyHeaders]["content-type"] = `${customContentType} charset=utf-8`; } else { this[kReplyHeaders]["content-type"] = `${customContentType}; charset=utf-8`; } } } if (typeof payload !== "string") { preSerializationHook(this, payload); return this; } } onSendHook(this, payload); return this; }; Reply.prototype.getHeader = function(key) { key = key.toLowerCase(); const res = this.raw; let value = this[kReplyHeaders][key]; if (value === void 0 && res.hasHeader(key)) { value = res.getHeader(key); } return value; }; Reply.prototype.getHeaders = function() { return { ...this.raw.getHeaders(), ...this[kReplyHeaders] }; }; Reply.prototype.hasHeader = function(key) { key = key.toLowerCase(); return this[kReplyHeaders][key] !== void 0 || this.raw.hasHeader(key); }; Reply.prototype.removeHeader = function(key) { delete this[kReplyHeaders][key.toLowerCase()]; return this; }; Reply.prototype.header = function(key, value = "") { key = key.toLowerCase(); if (this[kReplyHeaders][key] && key === "set-cookie") { if (typeof this[kReplyHeaders][key] === "string") { this[kReplyHeaders][key] = [this[kReplyHeaders][key]]; } if (Array.isArray(value)) { Array.prototype.push.apply(this[kReplyHeaders][key], value); } else { this[kReplyHeaders][key].push(value); } } else { this[kReplyHeaders][key] = value; } return this; }; Reply.prototype.headers = function(headers) { const keys = Object.keys(headers); for (var i = 0; i !== keys.length; ++i) { const key = keys[i]; this.header(key, headers[key]); } return this; }; var INVALID_TRAILERS = /* @__PURE__ */ new Set([ "transfer-encoding", "content-length", "host", "cache-control", "max-forwards", "te", "authorization", "set-cookie", "content-encoding", "content-type", "content-range", "trailer" ]); Reply.prototype.trailer = function(key, fn) { key = key.toLowerCase(); if (INVALID_TRAILERS.has(key)) { throw new FST_ERR_BAD_TRAILER_NAME(key); } if (typeof fn !== "function") { throw new FST_ERR_BAD_TRAILER_VALUE(key, typeof fn); } if (this[kReplyTrailers] === null) this[kReplyTrailers] = {}; this[kReplyTrailers][key] = fn; return this; }; Reply.prototype.hasTrailer = function(key) { var _a; return ((_a = this[kReplyTrailers]) == null ? void 0 : _a[key.toLowerCase()]) !== void 0; }; Reply.prototype.removeTrailer = function(key) { if (this[kReplyTrailers] === null) return this; this[kReplyTrailers][key.toLowerCase()] = void 0; return this; }; Reply.prototype.code = function(code) { const intValue = Number(code); if (isNaN(intValue) || intValue < 100 || intValue > 599) { throw new FST_ERR_BAD_STATUS_CODE(code || String(code)); } this.raw.statusCode = intValue; this[kReplyHasStatusCode] = true; return this; }; Reply.prototype.status = Reply.prototype.code; Reply.prototype.getSerializationFunction = function(schemaOrStatus, contentType) { var _a, _b, _c, _d; let serialize2; if (typeof schemaOrStatus === "string" || typeof schemaOrStatus === "number") { if (typeof contentType === "string") { serialize2 = (_b = (_a = this[kRouteContext][kSchemaResponse]) == null ? void 0 : _a[schemaOrStatus]) == null ? void 0 : _b[contentType]; } else { serialize2 = (_c = this[kRouteContext][kSchemaResponse]) == null ? void 0 : _c[schemaOrStatus]; } } else if (typeof schemaOrStatus === "object") { serialize2 = (_d = this[kRouteContext][kReplyCacheSerializeFns]) == null ? void 0 : _d.get(schemaOrStatus); } return serialize2; }; Reply.prototype.compileSerializationSchema = function(schema, httpStatus = null, contentType = null) { var _a; const { request } = this; const { method, url } = request; if ((_a = this[kRouteContext][kReplyCacheSerializeFns]) == null ? void 0 : _a.has(schema)) { return this[kRouteContext][kReplyCacheSerializeFns].get(schema); } const serializerCompiler = this[kRouteContext].serializerCompiler || this.server[kSchemaController].serializerCompiler || // We compile the schemas if no custom serializerCompiler is provided // nor set (this.server[kSchemaController].setupSerializer(this.server[kOptions]) || this.server[kSchemaController].serializerCompiler); const serializeFn = serializerCompiler({ schema, method, url, httpStatus, contentType }); if (this[kRouteContext][kReplyCacheSerializeFns] == null) { this[kRouteContext][kReplyCacheSerializeFns] = /* @__PURE__ */ new WeakMap(); } this[kRouteContext][kReplyCacheSerializeFns].set(schema, serializeFn); return serializeFn; }; Reply.prototype.serializeInput = function(input, schema, httpStatus, contentType) { var _a, _b, _c, _d; const possibleContentType = httpStatus; let serialize2; httpStatus = typeof schema === "string" || typeof schema === "number" ? schema : httpStatus; contentType = httpStatus && possibleContentType !== httpStatus ? possibleContentType : contentType; if (httpStatus != null) { if (contentType != null) { serialize2 = (_b = (_a = this[kRouteContext][kSchemaResponse]) == null ? void 0 : _a[httpStatus]) == null ? void 0 : _b[contentType]; } else { serialize2 = (_c = this[kRouteContext][kSchemaResponse]) == null ? void 0 : _c[httpStatus]; } if (serialize2 == null) { if (contentType) throw new FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN(httpStatus, contentType); throw new FST_ERR_MISSING_SERIALIZATION_FN(httpStatus); } } else { if ((_d = this[kRouteContext][kReplyCacheSerializeFns]) == null ? void 0 : _d.has(schema)) { serialize2 = this[kRouteContext][kReplyCacheSerializeFns].get(schema); } else { serialize2 = this.compileSerializationSchema(schema, httpStatus, contentType); } } return serialize2(input); }; Reply.prototype.serialize = function(payload) { if (this[kReplySerializer] !== null) { return this[kReplySerializer](payload); } else { if (this[kRouteContext] && this[kRouteContext][kReplySerializerDefault]) { return this[kRouteContext][kReplySerializerDefault](payload, this.raw.statusCode); } else { return serialize(this[kRouteContext], payload, this.raw.statusCode); } } }; Reply.prototype.serializer = function(fn) { this[kReplySerializer] = fn; return this; }; Reply.prototype.type = function(type) { this[kReplyHeaders]["content-type"] = type; return this; }; Reply.prototype.redirect = function(url, code) { if (typeof url === "number") { FSTDEP021(); const temp = code; code = url; url = temp; } if (!code) { code = this[kReplyHasStatusCode] ? this.raw.statusCode : 302; } return this.header("location", url).code(code).send(); }; Reply.prototype.callNotFound = function() { notFound(this); return this; }; Reply.prototype.getResponseTime = function() { FSTDEP020(); return this.elapsedTime; }; Reply.prototype.then = function(fulfilled, rejected) { if (this.sent) { fulfilled(); return; } eos(this.raw, (err) => { if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { if (rejected) { rejected(err); } else { this.log && this.log.warn("unhandled rejection on reply.then"); } } else { fulfilled(); } }); }; function preSerializationHook(reply, payload) { if (reply[kRouteContext].preSerialization !== null) { preSerializationHookRunner( reply[kRouteContext].preSerialization, reply.request, reply, payload, preSerializationHookEnd ); } else { preSerializationHookEnd(null, reply.request, reply, payload); } } function preSerializationHookEnd(err, request, reply, payload) { if (err != null) { onErrorHook(reply, err); return; } try { if (reply[kReplySerializer] !== null) { payload = reply[kReplySerializer](payload); } else if (reply[kRouteContext] && reply[kRouteContext][kReplySerializerDefault]) { payload = reply[kRouteContext][kReplySerializerDefault](payload, reply.raw.statusCode); } else { payload = serialize(reply[kRouteContext], payload, reply.raw.statusCode, reply[kReplyHeaders]["content-type"]); } } catch (e) { wrapSerializationError(e, reply); onErrorHook(reply, e); return; } onSendHook(reply, payload); } function wrapSerializationError(error, reply) { error.serialization = reply[kRouteContext].config; } function onSendHook(reply, payload) { if (reply[kRouteContext].onSend !== null) { onSendHookRunner( reply[kRouteContext].onSend, reply.request, reply, payload, wrapOnSendEnd ); } else { onSendEnd(reply, payload); } } function wrapOnSendEnd(err, request, reply, payload) { if (err != null) { onErrorHook(reply, err); } else { onSendEnd(reply, payload); } } function safeWriteHead(reply, statusCode) { const res = reply.raw; try { res.writeHead(statusCode, reply[kReplyHeaders]); } catch (err) { if (err.code === "ERR_HTTP_HEADERS_SENT") { reply.log.warn(`Reply was already sent, did you forget to "return reply" in the "${reply.request.raw.url}" (${reply.request.raw.method}) route?`); } throw err; } } function onSendEnd(reply, payload) { const res = reply.raw; const req = reply.request; if (reply[kReplyTrailers] !== null) { const trailerHeaders = Object.keys(reply[kReplyTrailers]); let header = ""; for (const trailerName of trailerHeaders) { if (typeof reply[kReplyTrailers][trailerName] !== "function") continue; header += " "; header += trailerName; } reply.header("Transfer-Encoding", "chunked"); reply.header("Trailer", header.trim()); } const isResponse = toString.call(payload) === "[object Response]"; if (isResponse) { if (typeof payload.status === "number") { reply.code(payload.status); } } const statusCode = res.statusCode; if (payload === void 0 || payload === null) { if (statusCode >= 200 && statusCode !== 204 && statusCode !== 304 && req.method !== "HEAD" && reply[kReplyTrailers] === null) { reply[kReplyHeaders]["content-length"] = "0"; } safeWriteHead(reply, statusCode); sendTrailer(payload, res, reply); return; } if (statusCode >= 100 && statusCode < 200 || statusCode === 204) { reply.removeHeader("content-type"); reply.removeHeader("content-length"); safeWriteHead(reply, statusCode); sendTrailer(void 0, res, reply); if (typeof payload.resume === "function") { payload.on("error", noop); payload.resume(); } return; } if (typeof payload.pipe === "function") { sendStream(payload, res, reply); return; } if (typeof payload.getReader === "function") { sendWebStream(payload, res, reply); return; } if (isResponse) { if (typeof payload.headers === "object" && typeof payload.headers.forEach === "function") { for (const [headerName, headerValue] of payload.headers) { reply.header(headerName, headerValue); } } if (payload.body != null) { if (payload.bodyUsed) { throw new FST_ERR_REP_RESPONSE_BODY_CONSUMED(); } sendWebStream(payload.body, res, reply); } return; } if (typeof payload !== "string" && !Buffer.isBuffer(payload)) { throw new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload); } if (reply[kReplyTrailers] === null) { const contentLength = reply[kReplyHeaders]["content-length"]; if (!contentLength || req.raw.method !== "HEAD" && Number(contentLength) !== Buffer.byteLength(payload)) { reply[kReplyHeaders]["content-length"] = "" + Buffer.byteLength(payload); } } safeWriteHead(reply, statusCode); res.write(payload); sendTrailer(payload, res, reply); } function logStreamError(logger, err, res) { if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { if (!logger[kDisableRequestLogging]) { logger.info({ res }, "stream closed prematurely"); } } else { logger.warn({ err }, "response terminated with an error with headers already sent"); } } function sendWebStream(payload, res, reply) { const nodeStream = Readable.fromWeb(payload); sendStream(nodeStream, res, reply); } function sendStream(payload, res, reply) { let sourceOpen = true; let errorLogged = false; sendStreamTrailer(payload, res, reply); eos(payload, { readable: true, writable: false }, function(err) { sourceOpen = false; if (err != null) { if (res.headersSent || reply.request.raw.aborted === true) { if (!errorLogged) { errorLogged = true; logStreamError(reply.log, err, res); } res.destroy(); } else { onErrorHook(reply, err); } } }); eos(res, function(err) { if (sourceOpen) { if (err != null && res.headersSent && !errorLogged) { errorLogged = true; logStreamError(reply.log, err, res); } if (typeof payload.destroy === "function") { payload.destroy(); } else if (typeof payload.close === "function") { payload.close(noop); } else if (typeof payload.abort === "function") { payload.abort(); } else { reply.log.warn("stream payload does not end properly"); } } }); if (!res.headersSent) { for (const key in reply[kReplyHeaders]) { res.setHeader(key, reply[kReplyHeaders][key]); } } else { reply.log.warn("response will send, but you shouldn't use res.writeHead in stream mode"); } payload.pipe(res); } function sendTrailer(payload, res, reply) { if (reply[kReplyTrailers] === null) { res.end(null, null, null); return; } const trailerHeaders = Object.keys(reply[kReplyTrailers]); const trailers = {}; let handled = 0; let skipped = true; function send() { if (handled === 0) { res.addTrailers(trailers); res.end(null, null, null); } } for (const trailerName of trailerHeaders) { let cb = function(err, value) { handled++; if (err) reply.log.debug(err); else trailers[trailerName] = value; process.nextTick(send); }; if (typeof reply[kReplyTrailers][trailerName] !== "function") continue; skipped = false; handled--; const result = reply[kReplyTrailers][trailerName](reply, payload, cb); if (typeof result === "object" && typeof result.then === "function") { result.then((v) => cb(null, v), cb); } else if (result !== null && result !== void 0) { FSTDEP013(); cb(null, result); } } if (skipped) res.end(null, null, null); } function sendStreamTrailer(payload, res, reply) { if (reply[kReplyTrailers] === null) return; payload.on("end", () => sendTrailer(null, res, reply)); } function onErrorHook(reply, error, cb) { if (reply[kRouteContext].onError !== null && !reply[kReplyNextErrorHandler]) { reply[kReplyIsRunningOnErrorHook] = true; onSendHookRunner( reply[kRouteContext].onError, reply.request, reply, error, () => handleError(reply, error, cb) ); } else { handleError(reply, error, cb); } } function setupResponseListeners(reply) { reply[kReplyStartTime] = now(); const onResFinished = (err) => { reply[kReplyEndTime] = now(); reply.raw.removeListener("finish", onResFinished); reply.raw.removeListener("error", onResFinished); const ctx = reply[kRouteContext]; if (ctx && ctx.onResponse !== null) { onResponseHookRunner( ctx.onResponse, reply.request, reply, onResponseCallback ); } else { onResponseCallback(err, reply.request, reply); } }; reply.raw.on("finish", onResFinished); reply.raw.on("error", onResFinished); } function onResponseCallback(err, request, reply) { if (reply.log[kDisableRequestLogging]) { return; } const responseTime = reply.elapsedTime; if (err != null) { reply.log.error({ res: reply, err, responseTime }, "request errored"); return; } reply.log.info({ res: reply, responseTime }, "request completed"); } function buildReply(R) { const props = R.props.slice(); function _Reply(res, request, log) { this.raw = res; this[kReplyIsError] = false; this[kReplyErrorHandlerCalled] = false; this[kReplyHijacked] = false; this[kReplySerializer] = null; this.request = request; this[kReplyHeaders] = {}; this[kReplyTrailers] = null; this[kReplyStartTime] = void 0; this[kReplyEndTime] = void 0; this.log = log; var prop; for (var i = 0; i < props.length; i++) { prop = props[i]; this[prop.key] = prop.value; } } Object.setPrototypeOf(_Reply.prototype, R.prototype); Object.setPrototypeOf(_Reply, R); _Reply.parent = R; _Reply.props = props; return _Reply; } function notFound(reply) { if (reply[kRouteContext][kFourOhFourContext] === null) { reply.log.warn("Trying to send a NotFound error inside a 404 handler. Sending basic 404 response."); reply.code(404).send("404 Not Found"); return; } reply.request[kRouteContext] = reply[kRouteContext][kFourOhFourContext]; if (reply[kRouteContext].preHandler !== null) { preHandlerHookRunner( reply[kRouteContext].preHandler, reply.request, reply, internals.preHandlerCallback ); } else { internals.preHandlerCallback(null, reply.request, reply); } } function serialize(context, data, statusCode, contentType) { const fnSerialize = getSchemaSerializer(context, statusCode, contentType); if (fnSerialize) { return fnSerialize(data); } return JSON.stringify(data); } function noop() { } module2.exports = Reply; module2.exports.buildReply = buildReply; module2.exports.setupResponseListeners = setupResponseListeners; } }); // node_modules/forwarded/index.js var require_forwarded = __commonJS({ "node_modules/forwarded/index.js"(exports, module2) { "use strict"; module2.exports = forwarded; function forwarded(req) { if (!req) { throw new TypeError("argument req is required"); } var proxyAddrs = parse(req.headers["x-forwarded-for"] || ""); var socketAddr = getSocketAddr(req); var addrs = [socketAddr].concat(proxyAddrs); return addrs; } function getSocketAddr(req) { return req.socket ? req.socket.remoteAddress : req.connection.remoteAddress; } function parse(header) { var end = header.length; var list = []; var start = header.length; for (var i = header.length - 1; i >= 0; i--) { switch (header.charCodeAt(i)) { case 32: if (start === end) { start = end = i; } break; case 44: if (start !== end) { list.push(header.substring(start, end)); } start = end = i; break; default: start = i; break; } } if (start !== end) { list.push(header.substring(start, end)); } return list; } } }); // node_modules/ipaddr.js/lib/ipaddr.js var require_ipaddr = __commonJS({ "node_modules/ipaddr.js/lib/ipaddr.js"(exports, module2) { (function() { var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; ipaddr = {}; root = this; if (typeof module2 !== "undefined" && module2 !== null && module2.exports) { module2.exports = ipaddr; } else { root["ipaddr"] = ipaddr; } matchCIDR = function(first, second, partSize, cidrBits) { var part, shift; if (first.length !== second.length) { throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); } part = 0; while (cidrBits > 0) { shift = partSize - cidrBits; if (shift < 0) { shift = 0; } if (first[part] >> shift !== second[part] >> shift) { return false; } cidrBits -= partSize; part += 1; } return true; }; ipaddr.subnetMatch = function(address, rangeList, defaultName) { var k, len, rangeName, rangeSubnets, subnet; if (defaultName == null) { defaultName = "unicast"; } for (rangeName in rangeList) { rangeSubnets = rangeList[rangeName]; if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { rangeSubnets = [rangeSubnets]; } for (k = 0, len = rangeSubnets.length; k < len; k++) { subnet = rangeSubnets[k]; if (address.kind() === subnet[0].kind()) { if (address.match.apply(address, subnet)) { return rangeName; } } } } return defaultName; }; ipaddr.IPv4 = function() { function IPv4(octets) { var k, len, octet; if (octets.length !== 4) { throw new Error("ipaddr: ipv4 octet count should be 4"); } for (k = 0, len = octets.length; k < len; k++) { octet = octets[k]; if (!(0 <= octet && octet <= 255)) { throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); } } this.octets = octets; } IPv4.prototype.kind = function() { return "ipv4"; }; IPv4.prototype.toString = function() { return this.octets.join("."); }; IPv4.prototype.toNormalizedString = function() { return this.toString(); }; IPv4.prototype.toByteArray = function() { return this.octets.slice(0); }; IPv4.prototype.match = function(other, cidrRange) { var ref; if (cidrRange === void 0) { ref = other, other = ref[0], cidrRange = ref[1]; } if (other.kind() !== "ipv4") { throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); } return matchCIDR(this.octets, other.octets, 8, cidrRange); }; IPv4.prototype.SpecialRanges = { unspecified: [[new IPv4([0, 0, 0, 0]), 8]], broadcast: [[new IPv4([255, 255, 255, 255]), 32]], multicast: [[new IPv4([224, 0, 0, 0]), 4]], linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], loopback: [[new IPv4([127, 0, 0, 0]), 8]], carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] }; IPv4.prototype.range = function() { return ipaddr.subnetMatch(this, this.SpecialRanges); }; IPv4.prototype.toIPv4MappedAddress = function() { return ipaddr.IPv6.parse("::ffff:" + this.toString()); }; IPv4.prototype.prefixLengthFromSubnetMask = function() { var cidr, i, k, octet, stop, zeros, zerotable; zerotable = { 0: 8, 128: 7, 192: 6, 224: 5, 240: 4, 248: 3, 252: 2, 254: 1, 255: 0 }; cidr = 0; stop = false; for (i = k = 3; k >= 0; i = k += -1) { octet = this.octets[i]; if (octet in zerotable) { zeros = zerotable[octet]; if (stop && zeros !== 0) { return null; } if (zeros !== 8) { stop = true; } cidr += zeros; } else { return null; } } return 32 - cidr; }; return IPv4; }(); ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; ipv4Regexes = { fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", "i"), longValue: new RegExp("^" + ipv4Part + "$", "i") }; ipaddr.IPv4.parser = function(string) { var match, parseIntAuto, part, shift, value; parseIntAuto = function(string2) { if (string2[0] === "0" && string2[1] !== "x") { return parseInt(string2, 8); } else { return parseInt(string2); } }; if (match = string.match(ipv4Regexes.fourOctet)) { return function() { var k, len, ref, results; ref = match.slice(1, 6); results = []; for (k = 0, len = ref.length; k < len; k++) { part = ref[k]; results.push(parseIntAuto(part)); } return results; }(); } else if (match = string.match(ipv4Regexes.longValue)) { value = parseIntAuto(match[1]); if (value > 4294967295 || value < 0) { throw new Error("ipaddr: address outside defined range"); } return function() { var k, results; results = []; for (shift = k = 0; k <= 24; shift = k += 8) { results.push(value >> shift & 255); } return results; }().reverse(); } else { return null; } }; ipaddr.IPv6 = function() { function IPv6(parts, zoneId) { var i, k, l, len, part, ref; if (parts.length === 16) { this.parts = []; for (i = k = 0; k <= 14; i = k += 2) { this.parts.push(parts[i] << 8 | parts[i + 1]); } } else if (parts.length === 8) { this.parts = parts; } else { throw new Error("ipaddr: ipv6 part count should be 8 or 16"); } ref = this.parts; for (l = 0, len = ref.length; l < len; l++) { part = ref[l]; if (!(0 <= part && part <= 65535)) { throw new Error("ipaddr: ipv6 part should fit in 16 bits"); } } if (zoneId) { this.zoneId = zoneId; } } IPv6.prototype.kind = function() { return "ipv6"; }; IPv6.prototype.toString = function() { return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, "::"); }; IPv6.prototype.toRFC5952String = function() { var bestMatchIndex, bestMatchLength, match, regex, string; regex = /((^|:)(0(:|$)){2,})/g; string = this.toNormalizedString(); bestMatchIndex = 0; bestMatchLength = -1; while (match = regex.exec(string)) { if (match[0].length > bestMatchLength) { bestMatchIndex = match.index; bestMatchLength = match[0].length; } } if (bestMatchLength < 0) { return string; } return string.substring(0, bestMatchIndex) + "::" + string.substring(bestMatchIndex + bestMatchLength); }; IPv6.prototype.toByteArray = function() { var bytes, k, len, part, ref; bytes = []; ref = this.parts; for (k = 0, len = ref.length; k < len; k++) { part = ref[k]; bytes.push(part >> 8); bytes.push(part & 255); } return bytes; }; IPv6.prototype.toNormalizedString = function() { var addr, part, suffix; addr = function() { var k, len, ref, results; ref = this.parts; results = []; for (k = 0, len = ref.length; k < len; k++) { part = ref[k]; results.push(part.toString(16)); } return results; }.call(this).join(":"); suffix = ""; if (this.zoneId) { suffix = "%" + this.zoneId; } return addr + suffix; }; IPv6.prototype.toFixedLengthString = function() { var addr, part, suffix; addr = function() { var k, len, ref, results; ref = this.parts; results = []; for (k = 0, len = ref.length; k < len; k++) { part = ref[k]; results.push(part.toString(16).padStart(4, "0")); } return results; }.call(this).join(":"); suffix = ""; if (this.zoneId) { suffix = "%" + this.zoneId; } return addr + suffix; }; IPv6.prototype.match = function(other, cidrRange) { var ref; if (cidrRange === void 0) { ref = other, other = ref[0], cidrRange = ref[1]; } if (other.kind() !== "ipv6") { throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); } return matchCIDR(this.parts, other.parts, 16, cidrRange); }; IPv6.prototype.SpecialRanges = { unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], linkLocal: [new IPv6([65152, 0, 0, 0, 0, 0, 0, 0]), 10], multicast: [new IPv6([65280, 0, 0, 0, 0, 0, 0, 0]), 8], loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], uniqueLocal: [new IPv6([64512, 0, 0, 0, 0, 0, 0, 0]), 7], ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 65535, 0, 0]), 96], rfc6145: [new IPv6([0, 0, 0, 0, 65535, 0, 0, 0]), 96], rfc6052: [new IPv6([100, 65435, 0, 0, 0, 0, 0, 0]), 96], "6to4": [new IPv6([8194, 0, 0, 0, 0, 0, 0, 0]), 16], teredo: [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 32], reserved: [[new IPv6([8193, 3512, 0, 0, 0, 0, 0, 0]), 32]] }; IPv6.prototype.range = function() { return ipaddr.subnetMatch(this, this.SpecialRanges); }; IPv6.prototype.isIPv4MappedAddress = function() { return this.range() === "ipv4Mapped"; }; IPv6.prototype.toIPv4Address = function() { var high, low, ref; if (!this.isIPv4MappedAddress()) { throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); } ref = this.parts.slice(-2), high = ref[0], low = ref[1]; return new ipaddr.IPv4([high >> 8, high & 255, low >> 8, low & 255]); }; IPv6.prototype.prefixLengthFromSubnetMask = function() { var cidr, i, k, part, stop, zeros, zerotable; zerotable = { 0: 16, 32768: 15, 49152: 14, 57344: 13, 61440: 12, 63488: 11, 64512: 10, 65024: 9, 65280: 8, 65408: 7, 65472: 6, 65504: 5, 65520: 4, 65528: 3, 65532: 2, 65534: 1, 65535: 0 }; cidr = 0; stop = false; for (i = k = 7; k >= 0; i = k += -1) { part = this.parts[i]; if (part in zerotable) { zeros = zerotable[part]; if (stop && zeros !== 0) { return null; } if (zeros !== 16) { stop = true; } cidr += zeros; } else { return null; } } return 128 - cidr; }; return IPv6; }(); ipv6Part = "(?:[0-9a-f]+::?)+"; zoneIndex = "%[0-9a-z]{1,}"; ipv6Regexes = { zoneIndex: new RegExp(zoneIndex, "i"), "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", "i"), transitional: new RegExp("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)" + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), "i") }; expandIPv6 = function(string, parts) { var colonCount, lastColon, part, replacement, replacementCount, zoneId; if (string.indexOf("::") !== string.lastIndexOf("::")) { return null; } zoneId = (string.match(ipv6Regexes["zoneIndex"]) || [])[0]; if (zoneId) { zoneId = zoneId.substring(1); string = string.replace(/%.+$/, ""); } colonCount = 0; lastColon = -1; while ((lastColon = string.indexOf(":", lastColon + 1)) >= 0) { colonCount++; } if (string.substr(0, 2) === "::") { colonCount--; } if (string.substr(-2, 2) === "::") { colonCount--; } if (colonCount > parts) { return null; } replacementCount = parts - colonCount; replacement = ":"; while (replacementCount--) { replacement += "0:"; } string = string.replace("::", replacement); if (string[0] === ":") { string = string.slice(1); } if (string[string.length - 1] === ":") { string = string.slice(0, -1); } parts = function() { var k, len, ref, results; ref = string.split(":"); results = []; for (k = 0, len = ref.length; k < len; k++) { part = ref[k]; results.push(parseInt(part, 16)); } return results; }(); return { parts, zoneId }; }; ipaddr.IPv6.parser = function(string) { var addr, k, len, match, octet, octets, zoneId; if (ipv6Regexes["native"].test(string)) { return expandIPv6(string, 8); } else if (match = string.match(ipv6Regexes["transitional"])) { zoneId = match[6] || ""; addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); if (addr.parts) { octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; for (k = 0, len = octets.length; k < len; k++) { octet = octets[k]; if (!(0 <= octet && octet <= 255)) { return null; } } addr.parts.push(octets[0] << 8 | octets[1]); addr.parts.push(octets[2] << 8 | octets[3]); return { parts: addr.parts, zoneId: addr.zoneId }; } } return null; }; ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { return this.parser(string) !== null; }; ipaddr.IPv4.isValid = function(string) { var e; try { new this(this.parser(string)); return true; } catch (error1) { e = error1; return false; } }; ipaddr.IPv4.isValidFourPartDecimal = function(string) { if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { return true; } else { return false; } }; ipaddr.IPv6.isValid = function(string) { var addr, e; if (typeof string === "string" && string.indexOf(":") === -1) { return false; } try { addr = this.parser(string); new this(addr.parts, addr.zoneId); return true; } catch (error1) { e = error1; return false; } }; ipaddr.IPv4.parse = function(string) { var parts; parts = this.parser(string); if (parts === null) { throw new Error("ipaddr: string is not formatted like ip address"); } return new this(parts); }; ipaddr.IPv6.parse = function(string) { var addr; addr = this.parser(string); if (addr.parts === null) { throw new Error("ipaddr: string is not formatted like ip address"); } return new this(addr.parts, addr.zoneId); }; ipaddr.IPv4.parseCIDR = function(string) { var maskLength, match, parsed; if (match = string.match(/^(.+)\/(\d+)$/)) { maskLength = parseInt(match[2]); if (maskLength >= 0 && maskLength <= 32) { parsed = [this.parse(match[1]), maskLength]; Object.defineProperty(parsed, "toString", { value: function() { return this.join("/"); } }); return parsed; } } throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); }; ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { var filledOctetCount, j, octets; prefix = parseInt(prefix); if (prefix < 0 || prefix > 32) { throw new Error("ipaddr: invalid IPv4 prefix length"); } octets = [0, 0, 0, 0]; j = 0; filledOctetCount = Math.floor(prefix / 8); while (j < filledOctetCount) { octets[j] = 255; j++; } if (filledOctetCount < 4) { octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8; } return new this(octets); }; ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; try { cidr = this.parseCIDR(string); ipInterfaceOctets = cidr[0].toByteArray(); subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); octets = []; i = 0; while (i < 4) { octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); i++; } return new this(octets); } catch (error1) { error = error1; throw new Error("ipaddr: the address does not have IPv4 CIDR format"); } }; ipaddr.IPv4.networkAddressFromCIDR = function(string) { var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; try { cidr = this.parseCIDR(string); ipInterfaceOctets = cidr[0].toByteArray(); subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); octets = []; i = 0; while (i < 4) { octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); i++; } return new this(octets); } catch (error1) { error = error1; throw new Error("ipaddr: the address does not have IPv4 CIDR format"); } }; ipaddr.IPv6.parseCIDR = function(string) { var maskLength, match, parsed; if (match = string.match(/^(.+)\/(\d+)$/)) { maskLength = parseInt(match[2]); if (maskLength >= 0 && maskLength <= 128) { parsed = [this.parse(match[1]), maskLength]; Object.defineProperty(parsed, "toString", { value: function() { return this.join("/"); } }); return parsed; } } throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); }; ipaddr.isValid = function(string) { return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); }; ipaddr.parse = function(string) { if (ipaddr.IPv6.isValid(string)) { return ipaddr.IPv6.parse(string); } else if (ipaddr.IPv4.isValid(string)) { return ipaddr.IPv4.parse(string); } else { throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); } }; ipaddr.parseCIDR = function(string) { var e; try { return ipaddr.IPv6.parseCIDR(string); } catch (error1) { e = error1; try { return ipaddr.IPv4.parseCIDR(string); } catch (error12) { e = error12; throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); } } }; ipaddr.fromByteArray = function(bytes) { var length; length = bytes.length; if (length === 4) { return new ipaddr.IPv4(bytes); } else if (length === 16) { return new ipaddr.IPv6(bytes); } else { throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); } }; ipaddr.process = function(string) { var addr; addr = this.parse(string); if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) { return addr.toIPv4Address(); } else { return addr; } }; }).call(exports); } }); // node_modules/proxy-addr/index.js var require_proxy_addr = __commonJS({ "node_modules/proxy-addr/index.js"(exports, module2) { "use strict"; module2.exports = proxyaddr; module2.exports.all = alladdrs; module2.exports.compile = compile; var forwarded = require_forwarded(); var ipaddr = require_ipaddr(); var DIGIT_REGEXP = /^[0-9]+$/; var isip = ipaddr.isValid; var parseip = ipaddr.parse; var IP_RANGES = { linklocal: ["169.254.0.0/16", "fe80::/10"], loopback: ["127.0.0.1/8", "::1/128"], uniquelocal: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"] }; function alladdrs(req, trust) { var addrs = forwarded(req); if (!trust) { return addrs; } if (typeof trust !== "function") { trust = compile(trust); } for (var i = 0; i < addrs.length - 1; i++) { if (trust(addrs[i], i)) continue; addrs.length = i + 1; } return addrs; } function compile(val) { if (!val) { throw new TypeError("argument is required"); } var trust; if (typeof val === "string") { trust = [val]; } else if (Array.isArray(val)) { trust = val.slice(); } else { throw new TypeError("unsupported trust argument"); } for (var i = 0; i < trust.length; i++) { val = trust[i]; if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { continue; } val = IP_RANGES[val]; trust.splice.apply(trust, [i, 1].concat(val)); i += val.length - 1; } return compileTrust(compileRangeSubnets(trust)); } function compileRangeSubnets(arr) { var rangeSubnets = new Array(arr.length); for (var i = 0; i < arr.length; i++) { rangeSubnets[i] = parseipNotation(arr[i]); } return rangeSubnets; } function compileTrust(rangeSubnets) { var len = rangeSubnets.length; return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets); } function parseipNotation(note) { var pos = note.lastIndexOf("/"); var str = pos !== -1 ? note.substring(0, pos) : note; if (!isip(str)) { throw new TypeError("invalid IP address: " + str); } var ip = parseip(str); if (pos === -1 && ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) { ip = ip.toIPv4Address(); } var max = ip.kind() === "ipv6" ? 128 : 32; var range = pos !== -1 ? note.substring(pos + 1, note.length) : null; if (range === null) { range = max; } else if (DIGIT_REGEXP.test(range)) { range = parseInt(range, 10); } else if (ip.kind() === "ipv4" && isip(range)) { range = parseNetmask(range); } else { range = null; } if (range <= 0 || range > max) { throw new TypeError("invalid range on address: " + note); } return [ip, range]; } function parseNetmask(netmask) { var ip = parseip(netmask); var kind = ip.kind(); return kind === "ipv4" ? ip.prefixLengthFromSubnetMask() : null; } function proxyaddr(req, trust) { if (!req) { throw new TypeError("req argument is required"); } if (!trust) { throw new TypeError("trust argument is required"); } var addrs = alladdrs(req, trust); var addr = addrs[addrs.length - 1]; return addr; } function trustNone() { return false; } function trustMulti(subnets) { return function trust(addr) { if (!isip(addr)) return false; var ip = parseip(addr); var ipconv; var kind = ip.kind(); for (var i = 0; i < subnets.length; i++) { var subnet = subnets[i]; var subnetip = subnet[0]; var subnetkind = subnetip.kind(); var subnetrange = subnet[1]; var trusted = ip; if (kind !== subnetkind) { if (subnetkind === "ipv4" && !ip.isIPv4MappedAddress()) { continue; } if (!ipconv) { ipconv = subnetkind === "ipv4" ? ip.toIPv4Address() : ip.toIPv4MappedAddress(); } trusted = ipconv; } if (trusted.match(subnetip, subnetrange)) { return true; } } return false; }; } function trustSingle(subnet) { var subnetip = subnet[0]; var subnetkind = subnetip.kind(); var subnetisipv4 = subnetkind === "ipv4"; var subnetrange = subnet[1]; return function trust(addr) { if (!isip(addr)) return false; var ip = parseip(addr); var kind = ip.kind(); if (kind !== subnetkind) { if (subnetisipv4 && !ip.isIPv4MappedAddress()) { return false; } ip = subnetisipv4 ? ip.toIPv4Address() : ip.toIPv4MappedAddress(); } return ip.match(subnetip, subnetrange); }; } } }); // node_modules/semver/internal/constants.js var require_constants2 = __commonJS({ "node_modules/semver/internal/constants.js"(exports, module2) { var SEMVER_SPEC_VERSION = "2.0.0"; var MAX_LENGTH = 256; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; var MAX_SAFE_COMPONENT_LENGTH = 16; var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; var RELEASE_TYPES = [ "major", "premajor", "minor", "preminor", "patch", "prepatch", "prerelease" ]; module2.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 1, FLAG_LOOSE: 2 }; } }); // node_modules/semver/internal/debug.js var require_debug2 = __commonJS({ "node_modules/semver/internal/debug.js"(exports, module2) { var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { }; module2.exports = debug; } }); // node_modules/semver/internal/re.js var require_re = __commonJS({ "node_modules/semver/internal/re.js"(exports, module2) { var { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH } = require_constants2(); var debug = require_debug2(); exports = module2.exports = {}; var re = exports.re = []; var safeRe = exports.safeRe = []; var src = exports.src = []; var t = exports.t = {}; var R = 0; var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; var safeRegexReplacements = [ ["\\s", 1], ["\\d", MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] ]; var makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); } return value; }; var createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value); const index = R++; debug(name, index, value); t[name] = index; src[index] = value; re[index] = new RegExp(value, isGlobal ? "g" : void 0); safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0); }; createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`); createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); createToken("FULL", `^${src[t.FULLPLAIN]}$`); createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); createToken("GTLT", "((?:<|>)?=?)"); createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); createToken("COERCERTL", src[t.COERCE], true); createToken("COERCERTLFULL", src[t.COERCEFULL], true); createToken("LONETILDE", "(?:~>?)"); createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); exports.tildeTrimReplace = "$1~"; createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); createToken("LONECARET", "(?:\\^)"); createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); exports.caretTrimReplace = "$1^"; createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); exports.comparatorTrimReplace = "$1$2$3"; createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); createToken("STAR", "(<|>)?=?\\s*\\*"); createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); } }); // node_modules/semver/internal/parse-options.js var require_parse_options = __commonJS({ "node_modules/semver/internal/parse-options.js"(exports, module2) { var looseOption = Object.freeze({ loose: true }); var emptyOpts = Object.freeze({}); var parseOptions = (options) => { if (!options) { return emptyOpts; } if (typeof options !== "object") { return looseOption; } return options; }; module2.exports = parseOptions; } }); // node_modules/semver/internal/identifiers.js var require_identifiers = __commonJS({ "node_modules/semver/internal/identifiers.js"(exports, module2) { var numeric = /^[0-9]+$/; var compareIdentifiers = (a, b) => { const anum = numeric.test(a); const bnum = numeric.test(b); if (anum && bnum) { a = +a; b = +b; } return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; }; var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); module2.exports = { compareIdentifiers, rcompareIdentifiers }; } }); // node_modules/semver/classes/semver.js var require_semver = __commonJS({ "node_modules/semver/classes/semver.js"(exports, module2) { var debug = require_debug2(); var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants2(); var { safeRe: re, t } = require_re(); var parseOptions = require_parse_options(); var { compareIdentifiers } = require_identifiers(); var SemVer = class { constructor(version, options) { options = parseOptions(options); if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version; } else { version = version.version; } } else if (typeof version !== "string") { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ); } debug("SemVer", version, options); this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); if (!m) { throw new TypeError(`Invalid Version: ${version}`); } this.raw = version; this.major = +m[1]; this.minor = +m[2]; this.patch = +m[3]; if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError("Invalid major version"); } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError("Invalid minor version"); } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError("Invalid patch version"); } if (!m[4]) { this.prerelease = []; } else { this.prerelease = m[4].split(".").map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER) { return num; } } return id; }); } this.build = m[5] ? m[5].split(".") : []; this.format(); } format() { this.version = `${this.major}.${this.minor}.${this.patch}`; if (this.prerelease.length) { this.version += `-${this.prerelease.join(".")}`; } return this.version; } toString() { return this.version; } compare(other) { debug("SemVer.compare", this.version, this.options, other); if (!(other instanceof SemVer)) { if (typeof other === "string" && other === this.version) { return 0; } other = new SemVer(other, this.options); } if (other.version === this.version) { return 0; } return this.compareMain(other) || this.comparePre(other); } compareMain(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); } comparePre(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } if (this.prerelease.length && !other.prerelease.length) { return -1; } else if (!this.prerelease.length && other.prerelease.length) { return 1; } else if (!this.prerelease.length && !other.prerelease.length) { return 0; } let i = 0; do { const a = this.prerelease[i]; const b = other.prerelease[i]; debug("prerelease compare", i, a, b); if (a === void 0 && b === void 0) { return 0; } else if (b === void 0) { return 1; } else if (a === void 0) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers(a, b); } } while (++i); } compareBuild(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; debug("build compare", i, a, b); if (a === void 0 && b === void 0) { return 0; } else if (b === void 0) { return 1; } else if (a === void 0) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers(a, b); } } while (++i); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release, identifier, identifierBase) { switch (release) { case "premajor": this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc("pre", identifier, identifierBase); break; case "preminor": this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc("pre", identifier, identifierBase); break; case "prepatch": this.prerelease.length = 0; this.inc("patch", identifier, identifierBase); this.inc("pre", identifier, identifierBase); break; case "prerelease": if (this.prerelease.length === 0) { this.inc("patch", identifier, identifierBase); } this.inc("pre", identifier, identifierBase); break; case "major": if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case "minor": if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case "patch": if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; case "pre": { const base = Number(identifierBase) ? 1 : 0; if (!identifier && identifierBase === false) { throw new Error("invalid increment argument: identifier is empty"); } if (this.prerelease.length === 0) { this.prerelease = [base]; } else { let i = this.prerelease.length; while (--i >= 0) { if (typeof this.prerelease[i] === "number") { this.prerelease[i]++; i = -2; } } if (i === -1) { if (identifier === this.prerelease.join(".") && identifierBase === false) { throw new Error("invalid increment argument: identifier already exists"); } this.prerelease.push(base); } } if (identifier) { let prerelease = [identifier, base]; if (identifierBase === false) { prerelease = [identifier]; } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease; } } else { this.prerelease = prerelease; } } break; } default: throw new Error(`invalid increment argument: ${release}`); } this.raw = this.format(); if (this.build.length) { this.raw += `+${this.build.join(".")}`; } return this; } }; module2.exports = SemVer; } }); // node_modules/semver/functions/parse.js var require_parse2 = __commonJS({ "node_modules/semver/functions/parse.js"(exports, module2) { var SemVer = require_semver(); var parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version; } try { return new SemVer(version, options); } catch (er) { if (!throwErrors) { return null; } throw er; } }; module2.exports = parse; } }); // node_modules/semver/functions/valid.js var require_valid = __commonJS({ "node_modules/semver/functions/valid.js"(exports, module2) { var parse = require_parse2(); var valid = (version, options) => { const v = parse(version, options); return v ? v.version : null; }; module2.exports = valid; } }); // node_modules/semver/functions/clean.js var require_clean = __commonJS({ "node_modules/semver/functions/clean.js"(exports, module2) { var parse = require_parse2(); var clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ""), options); return s ? s.version : null; }; module2.exports = clean; } }); // node_modules/semver/functions/inc.js var require_inc = __commonJS({ "node_modules/semver/functions/inc.js"(exports, module2) { var SemVer = require_semver(); var inc = (version, release, options, identifier, identifierBase) => { if (typeof options === "string") { identifierBase = identifier; identifier = options; options = void 0; } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version; } catch (er) { return null; } }; module2.exports = inc; } }); // node_modules/semver/functions/diff.js var require_diff = __commonJS({ "node_modules/semver/functions/diff.js"(exports, module2) { var parse = require_parse2(); var diff = (version1, version2) => { const v1 = parse(version1, null, true); const v2 = parse(version2, null, true); const comparison = v1.compare(v2); if (comparison === 0) { return null; } const v1Higher = comparison > 0; const highVersion = v1Higher ? v1 : v2; const lowVersion = v1Higher ? v2 : v1; const highHasPre = !!highVersion.prerelease.length; const lowHasPre = !!lowVersion.prerelease.length; if (lowHasPre && !highHasPre) { if (!lowVersion.patch && !lowVersion.minor) { return "major"; } if (highVersion.patch) { return "patch"; } if (highVersion.minor) { return "minor"; } return "major"; } const prefix = highHasPre ? "pre" : ""; if (v1.major !== v2.major) { return prefix + "major"; } if (v1.minor !== v2.minor) { return prefix + "minor"; } if (v1.patch !== v2.patch) { return prefix + "patch"; } return "prerelease"; }; module2.exports = diff; } }); // node_modules/semver/functions/major.js var require_major = __commonJS({ "node_modules/semver/functions/major.js"(exports, module2) { var SemVer = require_semver(); var major = (a, loose) => new SemVer(a, loose).major; module2.exports = major; } }); // node_modules/semver/functions/minor.js var require_minor = __commonJS({ "node_modules/semver/functions/minor.js"(exports, module2) { var SemVer = require_semver(); var minor = (a, loose) => new SemVer(a, loose).minor; module2.exports = minor; } }); // node_modules/semver/functions/patch.js var require_patch = __commonJS({ "node_modules/semver/functions/patch.js"(exports, module2) { var SemVer = require_semver(); var patch = (a, loose) => new SemVer(a, loose).patch; module2.exports = patch; } }); // node_modules/semver/functions/prerelease.js var require_prerelease = __commonJS({ "node_modules/semver/functions/prerelease.js"(exports, module2) { var parse = require_parse2(); var prerelease = (version, options) => { const parsed = parse(version, options); return parsed && parsed.prerelease.length ? parsed.prerelease : null; }; module2.exports = prerelease; } }); // node_modules/semver/functions/compare.js var require_compare = __commonJS({ "node_modules/semver/functions/compare.js"(exports, module2) { var SemVer = require_semver(); var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)); module2.exports = compare; } }); // node_modules/semver/functions/rcompare.js var require_rcompare = __commonJS({ "node_modules/semver/functions/rcompare.js"(exports, module2) { var compare = require_compare(); var rcompare = (a, b, loose) => compare(b, a, loose); module2.exports = rcompare; } }); // node_modules/semver/functions/compare-loose.js var require_compare_loose = __commonJS({ "node_modules/semver/functions/compare-loose.js"(exports, module2) { var compare = require_compare(); var compareLoose = (a, b) => compare(a, b, true); module2.exports = compareLoose; } }); // node_modules/semver/functions/compare-build.js var require_compare_build = __commonJS({ "node_modules/semver/functions/compare-build.js"(exports, module2) { var SemVer = require_semver(); var compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose); const versionB = new SemVer(b, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB); }; module2.exports = compareBuild; } }); // node_modules/semver/functions/sort.js var require_sort = __commonJS({ "node_modules/semver/functions/sort.js"(exports, module2) { var compareBuild = require_compare_build(); var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)); module2.exports = sort; } }); // node_modules/semver/functions/rsort.js var require_rsort = __commonJS({ "node_modules/semver/functions/rsort.js"(exports, module2) { var compareBuild = require_compare_build(); var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); module2.exports = rsort; } }); // node_modules/semver/functions/gt.js var require_gt = __commonJS({ "node_modules/semver/functions/gt.js"(exports, module2) { var compare = require_compare(); var gt = (a, b, loose) => compare(a, b, loose) > 0; module2.exports = gt; } }); // node_modules/semver/functions/lt.js var require_lt = __commonJS({ "node_modules/semver/functions/lt.js"(exports, module2) { var compare = require_compare(); var lt = (a, b, loose) => compare(a, b, loose) < 0; module2.exports = lt; } }); // node_modules/semver/functions/eq.js var require_eq = __commonJS({ "node_modules/semver/functions/eq.js"(exports, module2) { var compare = require_compare(); var eq = (a, b, loose) => compare(a, b, loose) === 0; module2.exports = eq; } }); // node_modules/semver/functions/neq.js var require_neq = __commonJS({ "node_modules/semver/functions/neq.js"(exports, module2) { var compare = require_compare(); var neq = (a, b, loose) => compare(a, b, loose) !== 0; module2.exports = neq; } }); // node_modules/semver/functions/gte.js var require_gte = __commonJS({ "node_modules/semver/functions/gte.js"(exports, module2) { var compare = require_compare(); var gte = (a, b, loose) => compare(a, b, loose) >= 0; module2.exports = gte; } }); // node_modules/semver/functions/lte.js var require_lte = __commonJS({ "node_modules/semver/functions/lte.js"(exports, module2) { var compare = require_compare(); var lte = (a, b, loose) => compare(a, b, loose) <= 0; module2.exports = lte; } }); // node_modules/semver/functions/cmp.js var require_cmp = __commonJS({ "node_modules/semver/functions/cmp.js"(exports, module2) { var eq = require_eq(); var neq = require_neq(); var gt = require_gt(); var gte = require_gte(); var lt = require_lt(); var lte = require_lte(); var cmp = (a, op, b, loose) => { switch (op) { case "===": if (typeof a === "object") { a = a.version; } if (typeof b === "object") { b = b.version; } return a === b; case "!==": if (typeof a === "object") { a = a.version; } if (typeof b === "object") { b = b.version; } return a !== b; case "": case "=": case "==": return eq(a, b, loose); case "!=": return neq(a, b, loose); case ">": return gt(a, b, loose); case ">=": return gte(a, b, loose); case "<": return lt(a, b, loose); case "<=": return lte(a, b, loose); default: throw new TypeError(`Invalid operator: ${op}`); } }; module2.exports = cmp; } }); // node_modules/semver/functions/coerce.js var require_coerce = __commonJS({ "node_modules/semver/functions/coerce.js"(exports, module2) { var SemVer = require_semver(); var parse = require_parse2(); var { safeRe: re, t } = require_re(); var coerce = (version, options) => { if (version instanceof SemVer) { return version; } if (typeof version === "number") { version = String(version); } if (typeof version !== "string") { return null; } options = options || {}; let match = null; if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]); } else { const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]; let next; while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next; } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; } coerceRtlRegex.lastIndex = -1; } if (match === null) { return null; } const major = match[2]; const minor = match[3] || "0"; const patch = match[4] || "0"; const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ""; const build = options.includePrerelease && match[6] ? `+${match[6]}` : ""; return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options); }; module2.exports = coerce; } }); // node_modules/semver/internal/lrucache.js var require_lrucache = __commonJS({ "node_modules/semver/internal/lrucache.js"(exports, module2) { var LRUCache = class { constructor() { this.max = 1e3; this.map = /* @__PURE__ */ new Map(); } get(key) { const value = this.map.get(key); if (value === void 0) { return void 0; } else { this.map.delete(key); this.map.set(key, value); return value; } } delete(key) { return this.map.delete(key); } set(key, value) { const deleted = this.delete(key); if (!deleted && value !== void 0) { if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value; this.delete(firstKey); } this.map.set(key, value); } return this; } }; module2.exports = LRUCache; } }); // node_modules/semver/classes/range.js var require_range = __commonJS({ "node_modules/semver/classes/range.js"(exports, module2) { var Range = class { constructor(range, options) { options = parseOptions(options); if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range; } else { return new Range(range.raw, options); } } if (range instanceof Comparator) { this.raw = range.value; this.set = [[range]]; this.format(); return this; } this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; this.raw = range.trim().split(/\s+/).join(" "); this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length); if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`); } if (this.set.length > 1) { const first = this.set[0]; this.set = this.set.filter((c) => !isNullSet(c[0])); if (this.set.length === 0) { this.set = [first]; } else if (this.set.length > 1) { for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c]; break; } } } } this.format(); } format() { this.range = this.set.map((comps) => comps.join(" ").trim()).join("||").trim(); return this.range; } toString() { return this.range; } parseRange(range) { const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); const memoKey = memoOpts + ":" + range; const cached = cache.get(memoKey); if (cached) { return cached; } const loose = this.options.loose; const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); debug("hyphen replace", range); range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); debug("comparator trim", range); range = range.replace(re[t.TILDETRIM], tildeTrimReplace); debug("tilde trim", range); range = range.replace(re[t.CARETTRIM], caretTrimReplace); debug("caret trim", range); let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); if (loose) { rangeList = rangeList.filter((comp) => { debug("loose invalid filter", comp, this.options); return !!comp.match(re[t.COMPARATORLOOSE]); }); } debug("range list", rangeList); const rangeMap = /* @__PURE__ */ new Map(); const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); for (const comp of comparators) { if (isNullSet(comp)) { return [comp]; } rangeMap.set(comp.value, comp); } if (rangeMap.size > 1 && rangeMap.has("")) { rangeMap.delete(""); } const result = [...rangeMap.values()]; cache.set(memoKey, result); return result; } intersects(range, options) { if (!(range instanceof Range)) { throw new TypeError("a Range is required"); } return this.set.some((thisComparators) => { return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options); }); }); }); }); } // if ANY of the sets match ALL of its comparators, then pass test(version) { if (!version) { return false; } if (typeof version === "string") { try { version = new SemVer(version, this.options); } catch (er) { return false; } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true; } } return false; } }; module2.exports = Range; var LRU = require_lrucache(); var cache = new LRU(); var parseOptions = require_parse_options(); var Comparator = require_comparator(); var debug = require_debug2(); var SemVer = require_semver(); var { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace } = require_re(); var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants2(); var isNullSet = (c) => c.value === "<0.0.0-0"; var isAny = (c) => c.value === ""; var isSatisfiable = (comparators, options) => { let result = true; const remainingComparators = comparators.slice(); let testComparator = remainingComparators.pop(); while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options); }); testComparator = remainingComparators.pop(); } return result; }; var parseComparator = (comp, options) => { debug("comp", comp, options); comp = replaceCarets(comp, options); debug("caret", comp); comp = replaceTildes(comp, options); debug("tildes", comp); comp = replaceXRanges(comp, options); debug("xrange", comp); comp = replaceStars(comp, options); debug("stars", comp); return comp; }; var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; var replaceTildes = (comp, options) => { return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" "); }; var replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { debug("tilde", comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ""; } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; } else if (isX(p)) { ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { debug("replaceTilde pr", pr); ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; } debug("tilde return", ret); return ret; }); }; var replaceCarets = (comp, options) => { return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); }; var replaceCaret = (comp, options) => { debug("caret", comp, options); const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; const z = options.includePrerelease ? "-0" : ""; return comp.replace(r, (_, M, m, p, pr) => { debug("caret", comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ""; } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; } else if (isX(p)) { if (M === "0") { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } } else if (pr) { debug("replaceCaret pr", pr); if (M === "0") { if (m === "0") { ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; } else { ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; } } else { ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; } } else { debug("no pr"); if (M === "0") { if (m === "0") { ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; } else { ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; } } else { ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; } } debug("caret return", ret); return ret; }); }; var replaceXRanges = (comp, options) => { debug("replaceXRanges", comp, options); return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); }; var replaceXRange = (comp, options) => { comp = comp.trim(); const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug("xRange", comp, ret, gtlt, M, m, p, pr); const xM = isX(M); const xm = xM || isX(m); const xp = xm || isX(p); const anyX = xp; if (gtlt === "=" && anyX) { gtlt = ""; } pr = options.includePrerelease ? "-0" : ""; if (xM) { if (gtlt === ">" || gtlt === "<") { ret = "<0.0.0-0"; } else { ret = "*"; } } else if (gtlt && anyX) { if (xm) { m = 0; } p = 0; if (gtlt === ">") { gtlt = ">="; if (xm) { M = +M + 1; m = 0; p = 0; } else { m = +m + 1; p = 0; } } else if (gtlt === "<=") { gtlt = "<"; if (xm) { M = +M + 1; } else { m = +m + 1; } } if (gtlt === "<") { pr = "-0"; } ret = `${gtlt + M}.${m}.${p}${pr}`; } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; } else if (xp) { ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; } debug("xRange return", ret); return ret; }); }; var replaceStars = (comp, options) => { debug("replaceStars", comp, options); return comp.trim().replace(re[t.STAR], ""); }; var replaceGTE0 = (comp, options) => { debug("replaceGTE0", comp, options); return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); }; var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = ""; } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? "-0" : ""}`; } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; } else if (fpr) { from = `>=${from}`; } else { from = `>=${from}${incPr ? "-0" : ""}`; } if (isX(tM)) { to = ""; } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0`; } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0`; } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}`; } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0`; } else { to = `<=${to}`; } return `${from} ${to}`.trim(); }; var testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false; } } if (version.prerelease.length && !options.includePrerelease) { for (let i = 0; i < set.length; i++) { debug(set[i].semver); if (set[i].semver === Comparator.ANY) { continue; } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver; if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true; } } } return false; } return true; }; } }); // node_modules/semver/classes/comparator.js var require_comparator = __commonJS({ "node_modules/semver/classes/comparator.js"(exports, module2) { var ANY = Symbol("SemVer ANY"); var Comparator = class { static get ANY() { return ANY; } constructor(comp, options) { options = parseOptions(options); if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp; } else { comp = comp.value; } } comp = comp.trim().split(/\s+/).join(" "); debug("comparator", comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); if (this.semver === ANY) { this.value = ""; } else { this.value = this.operator + this.semver.version; } debug("comp", this); } parse(comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; const m = comp.match(r); if (!m) { throw new TypeError(`Invalid comparator: ${comp}`); } this.operator = m[1] !== void 0 ? m[1] : ""; if (this.operator === "=") { this.operator = ""; } if (!m[2]) { this.semver = ANY; } else { this.semver = new SemVer(m[2], this.options.loose); } } toString() { return this.value; } test(version) { debug("Comparator.test", version, this.options.loose); if (this.semver === ANY || version === ANY) { return true; } if (typeof version === "string") { try { version = new SemVer(version, this.options); } catch (er) { return false; } } return cmp(version, this.operator, this.semver, this.options); } intersects(comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError("a Comparator is required"); } if (this.operator === "") { if (this.value === "") { return true; } return new Range(comp.value, options).test(this.value); } else if (comp.operator === "") { if (comp.value === "") { return true; } return new Range(this.value, options).test(comp.semver); } options = parseOptions(options); if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { return false; } if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { return false; } if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { return true; } if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { return true; } if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { return true; } if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { return true; } if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { return true; } return false; } }; module2.exports = Comparator; var parseOptions = require_parse_options(); var { safeRe: re, t } = require_re(); var cmp = require_cmp(); var debug = require_debug2(); var SemVer = require_semver(); var Range = require_range(); } }); // node_modules/semver/functions/satisfies.js var require_satisfies = __commonJS({ "node_modules/semver/functions/satisfies.js"(exports, module2) { var Range = require_range(); var satisfies = (version, range, options) => { try { range = new Range(range, options); } catch (er) { return false; } return range.test(version); }; module2.exports = satisfies; } }); // node_modules/semver/ranges/to-comparators.js var require_to_comparators = __commonJS({ "node_modules/semver/ranges/to-comparators.js"(exports, module2) { var Range = require_range(); var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); module2.exports = toComparators; } }); // node_modules/semver/ranges/max-satisfying.js var require_max_satisfying = __commonJS({ "node_modules/semver/ranges/max-satisfying.js"(exports, module2) { var SemVer = require_semver(); var Range = require_range(); var maxSatisfying = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { rangeObj = new Range(range, options); } catch (er) { return null; } versions.forEach((v) => { if (rangeObj.test(v)) { if (!max || maxSV.compare(v) === -1) { max = v; maxSV = new SemVer(max, options); } } }); return max; }; module2.exports = maxSatisfying; } }); // node_modules/semver/ranges/min-satisfying.js var require_min_satisfying = __commonJS({ "node_modules/semver/ranges/min-satisfying.js"(exports, module2) { var SemVer = require_semver(); var Range = require_range(); var minSatisfying = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { rangeObj = new Range(range, options); } catch (er) { return null; } versions.forEach((v) => { if (rangeObj.test(v)) { if (!min || minSV.compare(v) === 1) { min = v; minSV = new SemVer(min, options); } } }); return min; }; module2.exports = minSatisfying; } }); // node_modules/semver/ranges/min-version.js var require_min_version = __commonJS({ "node_modules/semver/ranges/min-version.js"(exports, module2) { var SemVer = require_semver(); var Range = require_range(); var gt = require_gt(); var minVersion = (range, loose) => { range = new Range(range, loose); let minver = new SemVer("0.0.0"); if (range.test(minver)) { return minver; } minver = new SemVer("0.0.0-0"); if (range.test(minver)) { return minver; } minver = null; for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i]; let setMin = null; comparators.forEach((comparator) => { const compver = new SemVer(comparator.semver.version); switch (comparator.operator) { case ">": if (compver.prerelease.length === 0) { compver.patch++; } else { compver.prerelease.push(0); } compver.raw = compver.format(); case "": case ">=": if (!setMin || gt(compver, setMin)) { setMin = compver; } break; case "<": case "<=": break; default: throw new Error(`Unexpected operation: ${comparator.operator}`); } }); if (setMin && (!minver || gt(minver, setMin))) { minver = setMin; } } if (minver && range.test(minver)) { return minver; } return null; }; module2.exports = minVersion; } }); // node_modules/semver/ranges/valid.js var require_valid2 = __commonJS({ "node_modules/semver/ranges/valid.js"(exports, module2) { var Range = require_range(); var validRange = (range, options) => { try { return new Range(range, options).range || "*"; } catch (er) { return null; } }; module2.exports = validRange; } }); // node_modules/semver/ranges/outside.js var require_outside = __commonJS({ "node_modules/semver/ranges/outside.js"(exports, module2) { var SemVer = require_semver(); var Comparator = require_comparator(); var { ANY } = Comparator; var Range = require_range(); var satisfies = require_satisfies(); var gt = require_gt(); var lt = require_lt(); var lte = require_lte(); var gte = require_gte(); var outside = (version, range, hilo, options) => { version = new SemVer(version, options); range = new Range(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case ">": gtfn = gt; ltefn = lte; ltfn = lt; comp = ">"; ecomp = ">="; break; case "<": gtfn = lt; ltefn = gte; ltfn = gt; comp = "<"; ecomp = "<="; break; default: throw new TypeError('Must provide a hilo val of "<" or ">"'); } if (satisfies(version, range, options)) { return false; } for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i]; let high = null; let low = null; comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator(">=0.0.0"); } high = high || comparator; low = low || comparator; if (gtfn(comparator.semver, high.semver, options)) { high = comparator; } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator; } }); if (high.operator === comp || high.operator === ecomp) { return false; } if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false; } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false; } } return true; }; module2.exports = outside; } }); // node_modules/semver/ranges/gtr.js var require_gtr = __commonJS({ "node_modules/semver/ranges/gtr.js"(exports, module2) { var outside = require_outside(); var gtr = (version, range, options) => outside(version, range, ">", options); module2.exports = gtr; } }); // node_modules/semver/ranges/ltr.js var require_ltr = __commonJS({ "node_modules/semver/ranges/ltr.js"(exports, module2) { var outside = require_outside(); var ltr = (version, range, options) => outside(version, range, "<", options); module2.exports = ltr; } }); // node_modules/semver/ranges/intersects.js var require_intersects = __commonJS({ "node_modules/semver/ranges/intersects.js"(exports, module2) { var Range = require_range(); var intersects = (r1, r2, options) => { r1 = new Range(r1, options); r2 = new Range(r2, options); return r1.intersects(r2, options); }; module2.exports = intersects; } }); // node_modules/semver/ranges/simplify.js var require_simplify = __commonJS({ "node_modules/semver/ranges/simplify.js"(exports, module2) { var satisfies = require_satisfies(); var compare = require_compare(); module2.exports = (versions, range, options) => { const set = []; let first = null; let prev = null; const v = versions.sort((a, b) => compare(a, b, options)); for (const version of v) { const included = satisfies(version, range, options); if (included) { prev = version; if (!first) { first = version; } } else { if (prev) { set.push([first, prev]); } prev = null; first = null; } } if (first) { set.push([first, null]); } const ranges = []; for (const [min, max] of set) { if (min === max) { ranges.push(min); } else if (!max && min === v[0]) { ranges.push("*"); } else if (!max) { ranges.push(`>=${min}`); } else if (min === v[0]) { ranges.push(`<=${max}`); } else { ranges.push(`${min} - ${max}`); } } const simplified = ranges.join(" || "); const original = typeof range.raw === "string" ? range.raw : String(range); return simplified.length < original.length ? simplified : range; }; } }); // node_modules/semver/ranges/subset.js var require_subset = __commonJS({ "node_modules/semver/ranges/subset.js"(exports, module2) { var Range = require_range(); var Comparator = require_comparator(); var { ANY } = Comparator; var satisfies = require_satisfies(); var compare = require_compare(); var subset = (sub, dom, options = {}) => { if (sub === dom) { return true; } sub = new Range(sub, options); dom = new Range(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) { continue OUTER; } } if (sawNonNull) { return false; } } return true; }; var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; var minimumVersion = [new Comparator(">=0.0.0")]; var simpleSubset = (sub, dom, options) => { if (sub === dom) { return true; } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true; } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease; } else { sub = minimumVersion; } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true; } else { dom = minimumVersion; } } const eqSet = /* @__PURE__ */ new Set(); let gt, lt; for (const c of sub) { if (c.operator === ">" || c.operator === ">=") { gt = higherGT(gt, c, options); } else if (c.operator === "<" || c.operator === "<=") { lt = lowerLT(lt, c, options); } else { eqSet.add(c.semver); } } if (eqSet.size > 1) { return null; } let gtltComp; if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options); if (gtltComp > 0) { return null; } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { return null; } } for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null; } if (lt && !satisfies(eq, String(lt), options)) { return null; } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false; } } return true; } let higher, lower; let hasDomLT, hasDomGT; let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false; } for (const c of dom) { hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">="; hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<="; if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false; } } if (c.operator === ">" || c.operator === ">=") { higher = higherGT(gt, c, options); if (higher === c && higher !== gt) { return false; } } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) { return false; } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false; } } if (c.operator === "<" || c.operator === "<=") { lower = lowerLT(lt, c, options); if (lower === c && lower !== lt) { return false; } } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) { return false; } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false; } } if (gt && hasDomLT && !lt && gtltComp !== 0) { return false; } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false; } if (needDomGTPre || needDomLTPre) { return false; } return true; }; var higherGT = (a, b, options) => { if (!a) { return b; } const comp = compare(a.semver, b.semver, options); return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a; }; var lowerLT = (a, b, options) => { if (!a) { return b; } const comp = compare(a.semver, b.semver, options); return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a; }; module2.exports = subset; } }); // node_modules/semver/index.js var require_semver2 = __commonJS({ "node_modules/semver/index.js"(exports, module2) { var internalRe = require_re(); var constants = require_constants2(); var SemVer = require_semver(); var identifiers = require_identifiers(); var parse = require_parse2(); var valid = require_valid(); var clean = require_clean(); var inc = require_inc(); var diff = require_diff(); var major = require_major(); var minor = require_minor(); var patch = require_patch(); var prerelease = require_prerelease(); var compare = require_compare(); var rcompare = require_rcompare(); var compareLoose = require_compare_loose(); var compareBuild = require_compare_build(); var sort = require_sort(); var rsort = require_rsort(); var gt = require_gt(); var lt = require_lt(); var eq = require_eq(); var neq = require_neq(); var gte = require_gte(); var lte = require_lte(); var cmp = require_cmp(); var coerce = require_coerce(); var Comparator = require_comparator(); var Range = require_range(); var satisfies = require_satisfies(); var toComparators = require_to_comparators(); var maxSatisfying = require_max_satisfying(); var minSatisfying = require_min_satisfying(); var minVersion = require_min_version(); var validRange = require_valid2(); var outside = require_outside(); var gtr = require_gtr(); var ltr = require_ltr(); var intersects = require_intersects(); var simplifyRange = require_simplify(); var subset = require_subset(); module2.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers }; } }); // node_modules/fastify/lib/request.js var require_request = __commonJS({ "node_modules/fastify/lib/request.js"(exports, module2) { "use strict"; var proxyAddr = require_proxy_addr(); var semver = require_semver2(); var { FSTDEP005, FSTDEP012, FSTDEP015, FSTDEP016, FSTDEP017, FSTDEP018 } = require_warnings(); var { kHasBeenDecorated, kSchemaBody, kSchemaHeaders, kSchemaParams, kSchemaQuerystring, kSchemaController, kOptions, kRequestCacheValidateFns, kRouteContext, kPublicRouteContext, kRequestOriginalUrl } = require_symbols2(); var { FST_ERR_REQ_INVALID_VALIDATION_INVOCATION } = require_errors2(); var HTTP_PART_SYMBOL_MAP = { body: kSchemaBody, headers: kSchemaHeaders, params: kSchemaParams, querystring: kSchemaQuerystring, query: kSchemaQuerystring }; function Request(id, params, req, query, log, context) { this.id = id; this[kRouteContext] = context; this.params = params; this.raw = req; this.query = query; this.log = log; this.body = void 0; } Request.props = []; function getTrustProxyFn(tp) { if (typeof tp === "function") { return tp; } if (tp === true) { return function() { return true; }; } if (typeof tp === "number") { return function(a, i) { return i < tp; }; } if (typeof tp === "string") { const values = tp.split(",").map((it) => it.trim()); return proxyAddr.compile(values); } return proxyAddr.compile(tp); } function buildRequest(R, trustProxy) { if (trustProxy) { return buildRequestWithTrustProxy(R, trustProxy); } return buildRegularRequest(R); } function buildRegularRequest(R) { const props = R.props.slice(); function _Request(id, params, req, query, log, context) { this.id = id; this[kRouteContext] = context; this.params = params; this.raw = req; this.query = query; this.log = log; this.body = void 0; var prop; for (var i = 0; i < props.length; i++) { prop = props[i]; this[prop.key] = prop.value; } } Object.setPrototypeOf(_Request.prototype, R.prototype); Object.setPrototypeOf(_Request, R); _Request.props = props; _Request.parent = R; return _Request; } function getLastEntryInMultiHeaderValue(headerValue) { const lastIndex = headerValue.lastIndexOf(","); return lastIndex === -1 ? headerValue.trim() : headerValue.slice(lastIndex + 1).trim(); } function buildRequestWithTrustProxy(R, trustProxy) { const _Request = buildRegularRequest(R); const proxyFn = getTrustProxyFn(trustProxy); _Request[kHasBeenDecorated] = true; Object.defineProperties(_Request.prototype, { ip: { get() { return proxyAddr(this.raw, proxyFn); } }, ips: { get() { return proxyAddr.all(this.raw, proxyFn); } }, hostname: { get() { if (this.ip !== void 0 && this.headers["x-forwarded-host"]) { return getLastEntryInMultiHeaderValue(this.headers["x-forwarded-host"]); } return this.headers.host || this.headers[":authority"]; } }, protocol: { get() { if (this.headers["x-forwarded-proto"]) { return getLastEntryInMultiHeaderValue(this.headers["x-forwarded-proto"]); } if (this.socket) { return this.socket.encrypted ? "https" : "http"; } } } }); return _Request; } Object.defineProperties(Request.prototype, { server: { get() { return this[kRouteContext].server; } }, url: { get() { return this.raw.url; } }, originalUrl: { get() { if (!this[kRequestOriginalUrl]) { this[kRequestOriginalUrl] = this.raw.originalUrl || this.raw.url; } return this[kRequestOriginalUrl]; } }, method: { get() { return this.raw.method; } }, context: { get() { FSTDEP012(); return this[kRouteContext]; } }, routerPath: { get() { var _a; FSTDEP017(); return (_a = this[kRouteContext].config) == null ? void 0 : _a.url; } }, routeOptions: { get() { var _a, _b; const context = this[kRouteContext]; const routeLimit = context._parserOptions.limit; const serverLimit = context.server.initialConfig.bodyLimit; const version = context.server.hasConstraintStrategy("version") ? this.raw.headers["accept-version"] : void 0; const options = { method: (_a = context.config) == null ? void 0 : _a.method, url: (_b = context.config) == null ? void 0 : _b.url, bodyLimit: routeLimit || serverLimit, attachValidation: context.attachValidation, logLevel: context.logLevel, exposeHeadRoute: context.exposeHeadRoute, prefixTrailingSlash: context.prefixTrailingSlash, handler: context.handler, version }; Object.defineProperties(options, { config: { get: () => context.config }, schema: { get: () => context.schema } }); return Object.freeze(options); } }, routerMethod: { get() { var _a; FSTDEP018(); return (_a = this[kRouteContext].config) == null ? void 0 : _a.method; } }, routeConfig: { get() { var _a; FSTDEP016(); return (_a = this[kRouteContext][kPublicRouteContext]) == null ? void 0 : _a.config; } }, routeSchema: { get() { FSTDEP015(); return this[kRouteContext][kPublicRouteContext].schema; } }, is404: { get() { var _a; return ((_a = this[kRouteContext].config) == null ? void 0 : _a.url) === void 0; } }, connection: { get() { if (semver.gte(process.versions.node, "13.0.0")) { FSTDEP005(); } return this.raw.connection; } }, socket: { get() { return this.raw.socket; } }, ip: { get() { if (this.socket) { return this.socket.remoteAddress; } } }, hostname: { get() { return this.raw.headers.host || this.raw.headers[":authority"]; } }, protocol: { get() { if (this.socket) { return this.socket.encrypted ? "https" : "http"; } } }, headers: { get() { if (this.additionalHeaders) { return Object.assign({}, this.raw.headers, this.additionalHeaders); } return this.raw.headers; }, set(headers) { this.additionalHeaders = headers; } }, getValidationFunction: { value: function(httpPartOrSchema) { var _a; if (typeof httpPartOrSchema === "string") { const symbol = HTTP_PART_SYMBOL_MAP[httpPartOrSchema]; return this[kRouteContext][symbol]; } else if (typeof httpPartOrSchema === "object") { return (_a = this[kRouteContext][kRequestCacheValidateFns]) == null ? void 0 : _a.get(httpPartOrSchema); } } }, compileValidationSchema: { value: function(schema, httpPart = null) { var _a; const { method, url } = this; if ((_a = this[kRouteContext][kRequestCacheValidateFns]) == null ? void 0 : _a.has(schema)) { return this[kRouteContext][kRequestCacheValidateFns].get(schema); } const validatorCompiler = this[kRouteContext].validatorCompiler || this.server[kSchemaController].validatorCompiler || // We compile the schemas if no custom validatorCompiler is provided // nor set (this.server[kSchemaController].setupValidator(this.server[kOptions]) || this.server[kSchemaController].validatorCompiler); const validateFn = validatorCompiler({ schema, method, url, httpPart }); if (this[kRouteContext][kRequestCacheValidateFns] == null) { this[kRouteContext][kRequestCacheValidateFns] = /* @__PURE__ */ new WeakMap(); } this[kRouteContext][kRequestCacheValidateFns].set(schema, validateFn); return validateFn; } }, validateInput: { value: function(input, schema, httpPart) { var _a; httpPart = typeof schema === "string" ? schema : httpPart; const symbol = httpPart != null && typeof httpPart === "string" && HTTP_PART_SYMBOL_MAP[httpPart]; let validate; if (symbol) { validate = this[kRouteContext][symbol]; } if (validate == null && (schema == null || typeof schema !== "object" || Array.isArray(schema))) { throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart); } if (validate == null) { if ((_a = this[kRouteContext][kRequestCacheValidateFns]) == null ? void 0 : _a.has(schema)) { validate = this[kRouteContext][kRequestCacheValidateFns].get(schema); } else { validate = this.compileValidationSchema(schema, httpPart); } } return validate(input); } } }); module2.exports = Request; module2.exports.buildRequest = buildRequest; } }); // node_modules/fastify/lib/context.js var require_context = __commonJS({ "node_modules/fastify/lib/context.js"(exports, module2) { "use strict"; var { kFourOhFourContext, kReplySerializerDefault, kSchemaErrorFormatter, kErrorHandler, kChildLoggerFactory, kOptions, kReply, kRequest, kBodyLimit, kLogLevel, kContentTypeParser, kRouteByFastify, kRequestCacheValidateFns, kReplyCacheSerializeFns, kPublicRouteContext } = require_symbols2(); function Context({ schema, handler, config, requestIdLogLabel, childLoggerFactory, errorHandler, bodyLimit, logLevel, logSerializers, attachValidation, validatorCompiler, serializerCompiler, replySerializer, schemaErrorFormatter, exposeHeadRoute, prefixTrailingSlash, server: server2, isFastify }) { this.schema = schema; this.handler = handler; this.Reply = server2[kReply]; this.Request = server2[kRequest]; this.contentTypeParser = server2[kContentTypeParser]; this.onRequest = null; this.onSend = null; this.onError = null; this.onTimeout = null; this.preHandler = null; this.onResponse = null; this.preSerialization = null; this.onRequestAbort = null; this.config = config; this.errorHandler = errorHandler || server2[kErrorHandler]; this.requestIdLogLabel = requestIdLogLabel || server2[kOptions].requestIdLogLabel; this.childLoggerFactory = childLoggerFactory || server2[kChildLoggerFactory]; this._middie = null; this._parserOptions = { limit: bodyLimit || server2[kBodyLimit] }; this.exposeHeadRoute = exposeHeadRoute; this.prefixTrailingSlash = prefixTrailingSlash; this.logLevel = logLevel || server2[kLogLevel]; this.logSerializers = logSerializers; this[kFourOhFourContext] = null; this.attachValidation = attachValidation; this[kReplySerializerDefault] = replySerializer; this.schemaErrorFormatter = schemaErrorFormatter || server2[kSchemaErrorFormatter] || defaultSchemaErrorFormatter; this[kRouteByFastify] = isFastify; this[kRequestCacheValidateFns] = null; this[kReplyCacheSerializeFns] = null; this.validatorCompiler = validatorCompiler || null; this.serializerCompiler = serializerCompiler || null; this[kPublicRouteContext] = getPublicRouteContext(this); this.server = server2; } function getPublicRouteContext(context) { return Object.create(null, { schema: { enumerable: true, get() { return context.schema; } }, config: { enumerable: true, get() { return context.config; } } }); } function defaultSchemaErrorFormatter(errors, dataVar) { let text = ""; const separator = ", "; for (var i = 0; i !== errors.length; ++i) { const e = errors[i]; text += dataVar + (e.instancePath || "") + " " + e.message + separator; } return new Error(text.slice(0, -separator.length)); } module2.exports = Context; } }); // node_modules/fastify/lib/httpMethods.js var require_httpMethods = __commonJS({ "node_modules/fastify/lib/httpMethods.js"(exports, module2) { "use strict"; module2.exports = { supportedMethods: [ "DELETE", "GET", "HEAD", "PATCH", "POST", "PUT", "OPTIONS", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", "TRACE", "SEARCH", "REPORT", "MKCALENDAR" ] }; } }); // node_modules/fastify/lib/decorate.js var require_decorate = __commonJS({ "node_modules/fastify/lib/decorate.js"(exports, module2) { "use strict"; var { kReply, kRequest, kState, kHasBeenDecorated } = require_symbols2(); var { FST_ERR_DEC_ALREADY_PRESENT, FST_ERR_DEC_MISSING_DEPENDENCY, FST_ERR_DEC_AFTER_START, FST_ERR_DEC_DEPENDENCY_INVALID_TYPE } = require_errors2(); var { FSTDEP006 } = require_warnings(); function decorate(instance, name, fn, dependencies) { if (Object.prototype.hasOwnProperty.call(instance, name)) { throw new FST_ERR_DEC_ALREADY_PRESENT(name); } checkDependencies(instance, name, dependencies); if (fn && (typeof fn.getter === "function" || typeof fn.setter === "function")) { Object.defineProperty(instance, name, { get: fn.getter, set: fn.setter }); } else { instance[name] = fn; } } function decorateConstructor(konstructor, name, fn, dependencies) { const instance = konstructor.prototype; if (Object.prototype.hasOwnProperty.call(instance, name) || hasKey(konstructor, name)) { throw new FST_ERR_DEC_ALREADY_PRESENT(name); } konstructor[kHasBeenDecorated] = true; checkDependencies(konstructor, name, dependencies); if (fn && (typeof fn.getter === "function" || typeof fn.setter === "function")) { Object.defineProperty(instance, name, { get: fn.getter, set: fn.setter }); } else if (typeof fn === "function") { instance[name] = fn; } else { konstructor.props.push({ key: name, value: fn }); } } function checkReferenceType(name, fn) { if (typeof fn === "object" && fn && !(typeof fn.getter === "function" || typeof fn.setter === "function")) { FSTDEP006(name); } } function decorateFastify(name, fn, dependencies) { assertNotStarted(this, name); decorate(this, name, fn, dependencies); return this; } function checkExistence(instance, name) { if (name) { return name in instance || instance.prototype && name in instance.prototype || hasKey(instance, name); } return instance in this; } function hasKey(fn, name) { if (fn.props) { return fn.props.find(({ key }) => key === name); } return false; } function checkRequestExistence(name) { if (name && hasKey(this[kRequest], name)) return true; return checkExistence(this[kRequest].prototype, name); } function checkReplyExistence(name) { if (name && hasKey(this[kReply], name)) return true; return checkExistence(this[kReply].prototype, name); } function checkDependencies(instance, name, deps) { if (deps === void 0 || deps === null) { return; } if (!Array.isArray(deps)) { throw new FST_ERR_DEC_DEPENDENCY_INVALID_TYPE(name); } for (var i = 0; i !== deps.length; ++i) { if (!checkExistence(instance, deps[i])) { throw new FST_ERR_DEC_MISSING_DEPENDENCY(deps[i]); } } } function decorateReply(name, fn, dependencies) { assertNotStarted(this, name); checkReferenceType(name, fn); decorateConstructor(this[kReply], name, fn, dependencies); return this; } function decorateRequest(name, fn, dependencies) { assertNotStarted(this, name); checkReferenceType(name, fn); decorateConstructor(this[kRequest], name, fn, dependencies); return this; } function assertNotStarted(instance, name) { if (instance[kState].started) { throw new FST_ERR_DEC_AFTER_START(name); } } module2.exports = { add: decorateFastify, exist: checkExistence, existRequest: checkRequestExistence, existReply: checkReplyExistence, dependencies: checkDependencies, decorateReply, decorateRequest }; } }); // node_modules/toad-cache/dist/toad-cache.cjs var require_toad_cache = __commonJS({ "node_modules/toad-cache/dist/toad-cache.cjs"(exports) { "use strict"; var FifoMap = class { constructor(max = 1e3, ttlInMsecs = 0) { if (isNaN(max) || max < 0) { throw new Error("Invalid max value"); } if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { throw new Error("Invalid ttl value"); } this.first = null; this.items = /* @__PURE__ */ new Map(); this.last = null; this.max = max; this.ttl = ttlInMsecs; } get size() { return this.items.size; } clear() { this.items = /* @__PURE__ */ new Map(); this.first = null; this.last = null; } delete(key) { if (this.items.has(key)) { const deletedItem = this.items.get(key); this.items.delete(key); if (deletedItem.prev !== null) { deletedItem.prev.next = deletedItem.next; } if (deletedItem.next !== null) { deletedItem.next.prev = deletedItem.prev; } if (this.first === deletedItem) { this.first = deletedItem.next; } if (this.last === deletedItem) { this.last = deletedItem.prev; } } } deleteMany(keys) { for (var i = 0; i < keys.length; i++) { this.delete(keys[i]); } } evict() { if (this.size > 0) { const item = this.first; this.items.delete(item.key); if (this.size === 0) { this.first = null; this.last = null; } else { this.first = item.next; this.first.prev = null; } } } expiresAt(key) { if (this.items.has(key)) { return this.items.get(key).expiry; } } get(key) { if (this.items.has(key)) { const item = this.items.get(key); if (this.ttl > 0 && item.expiry <= Date.now()) { this.delete(key); return; } return item.value; } } getMany(keys) { const result = []; for (var i = 0; i < keys.length; i++) { result.push(this.get(keys[i])); } return result; } keys() { return this.items.keys(); } set(key, value) { if (this.items.has(key)) { const item2 = this.items.get(key); item2.value = value; item2.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; return; } if (this.max > 0 && this.size === this.max) { this.evict(); } const item = { expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, key, prev: this.last, next: null, value }; this.items.set(key, item); if (this.size === 1) { this.first = item; } else { this.last.next = item; } this.last = item; } }; var LruMap = class { constructor(max = 1e3, ttlInMsecs = 0) { if (isNaN(max) || max < 0) { throw new Error("Invalid max value"); } if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { throw new Error("Invalid ttl value"); } this.first = null; this.items = /* @__PURE__ */ new Map(); this.last = null; this.max = max; this.ttl = ttlInMsecs; } get size() { return this.items.size; } bumpLru(item) { if (this.last === item) { return; } const last = this.last; const next = item.next; const prev = item.prev; if (this.first === item) { this.first = next; } item.next = null; item.prev = last; last.next = item; if (prev !== null) { prev.next = next; } if (next !== null) { next.prev = prev; } this.last = item; } clear() { this.items = /* @__PURE__ */ new Map(); this.first = null; this.last = null; } delete(key) { if (this.items.has(key)) { const item = this.items.get(key); this.items.delete(key); if (item.prev !== null) { item.prev.next = item.next; } if (item.next !== null) { item.next.prev = item.prev; } if (this.first === item) { this.first = item.next; } if (this.last === item) { this.last = item.prev; } } } deleteMany(keys) { for (var i = 0; i < keys.length; i++) { this.delete(keys[i]); } } evict() { if (this.size > 0) { const item = this.first; this.items.delete(item.key); if (this.size === 0) { this.first = null; this.last = null; } else { this.first = item.next; this.first.prev = null; } } } expiresAt(key) { if (this.items.has(key)) { return this.items.get(key).expiry; } } get(key) { if (this.items.has(key)) { const item = this.items.get(key); if (this.ttl > 0 && item.expiry <= Date.now()) { this.delete(key); return; } this.bumpLru(item); return item.value; } } getMany(keys) { const result = []; for (var i = 0; i < keys.length; i++) { result.push(this.get(keys[i])); } return result; } keys() { return this.items.keys(); } set(key, value) { if (this.items.has(key)) { const item2 = this.items.get(key); item2.value = value; item2.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; if (this.last !== item2) { this.bumpLru(item2); } return; } if (this.max > 0 && this.size === this.max) { this.evict(); } const item = { expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, key, prev: this.last, next: null, value }; this.items.set(key, item); if (this.size === 1) { this.first = item; } else { this.last.next = item; } this.last = item; } }; var LruObject = class { constructor(max = 1e3, ttlInMsecs = 0) { if (isNaN(max) || max < 0) { throw new Error("Invalid max value"); } if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { throw new Error("Invalid ttl value"); } this.first = null; this.items = /* @__PURE__ */ Object.create(null); this.last = null; this.size = 0; this.max = max; this.ttl = ttlInMsecs; } bumpLru(item) { if (this.last === item) { return; } const last = this.last; const next = item.next; const prev = item.prev; if (this.first === item) { this.first = next; } item.next = null; item.prev = last; last.next = item; if (prev !== null) { prev.next = next; } if (next !== null) { next.prev = prev; } this.last = item; } clear() { this.items = /* @__PURE__ */ Object.create(null); this.first = null; this.last = null; this.size = 0; } delete(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const item = this.items[key]; delete this.items[key]; this.size--; if (item.prev !== null) { item.prev.next = item.next; } if (item.next !== null) { item.next.prev = item.prev; } if (this.first === item) { this.first = item.next; } if (this.last === item) { this.last = item.prev; } } } deleteMany(keys) { for (var i = 0; i < keys.length; i++) { this.delete(keys[i]); } } evict() { if (this.size > 0) { const item = this.first; delete this.items[item.key]; if (--this.size === 0) { this.first = null; this.last = null; } else { this.first = item.next; this.first.prev = null; } } } expiresAt(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { return this.items[key].expiry; } } get(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const item = this.items[key]; if (this.ttl > 0 && item.expiry <= Date.now()) { this.delete(key); return; } this.bumpLru(item); return item.value; } } getMany(keys) { const result = []; for (var i = 0; i < keys.length; i++) { result.push(this.get(keys[i])); } return result; } keys() { return Object.keys(this.items); } set(key, value) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const item2 = this.items[key]; item2.value = value; item2.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; if (this.last !== item2) { this.bumpLru(item2); } return; } if (this.max > 0 && this.size === this.max) { this.evict(); } const item = { expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, key, prev: this.last, next: null, value }; this.items[key] = item; if (++this.size === 1) { this.first = item; } else { this.last.next = item; } this.last = item; } }; var HitStatisticsRecord = class { constructor() { this.records = {}; } initForCache(cacheId, currentTimeStamp) { this.records[cacheId] = { [currentTimeStamp]: { cacheSize: 0, hits: 0, falsyHits: 0, emptyHits: 0, misses: 0, expirations: 0, evictions: 0, invalidateOne: 0, invalidateAll: 0, sets: 0 } }; } resetForCache(cacheId) { for (let key of Object.keys(this.records[cacheId])) { this.records[cacheId][key] = { cacheSize: 0, hits: 0, falsyHits: 0, emptyHits: 0, misses: 0, expirations: 0, evictions: 0, invalidateOne: 0, invalidateAll: 0, sets: 0 }; } } getStatistics() { return this.records; } }; function getTimestamp(date) { return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`; } var HitStatistics = class { constructor(cacheId, statisticTtlInHours, globalStatisticsRecord) { this.cacheId = cacheId; this.statisticTtlInHours = statisticTtlInHours; this.collectionStart = new Date(); this.currentTimeStamp = getTimestamp(this.collectionStart); this.records = globalStatisticsRecord || new HitStatisticsRecord(); this.records.initForCache(this.cacheId, this.currentTimeStamp); } get currentRecord() { if (!this.records.records[this.cacheId][this.currentTimeStamp]) { this.records.records[this.cacheId][this.currentTimeStamp] = { cacheSize: 0, hits: 0, falsyHits: 0, emptyHits: 0, misses: 0, expirations: 0, evictions: 0, sets: 0, invalidateOne: 0, invalidateAll: 0 }; } return this.records.records[this.cacheId][this.currentTimeStamp]; } hoursPassed() { return (Date.now() - this.collectionStart) / 1e3 / 60 / 60; } addHit() { this.archiveIfNeeded(); this.currentRecord.hits++; } addFalsyHit() { this.archiveIfNeeded(); this.currentRecord.falsyHits++; } addEmptyHit() { this.archiveIfNeeded(); this.currentRecord.emptyHits++; } addMiss() { this.archiveIfNeeded(); this.currentRecord.misses++; } addEviction() { this.archiveIfNeeded(); this.currentRecord.evictions++; } setCacheSize(currentSize) { this.archiveIfNeeded(); this.currentRecord.cacheSize = currentSize; } addExpiration() { this.archiveIfNeeded(); this.currentRecord.expirations++; } addSet() { this.archiveIfNeeded(); this.currentRecord.sets++; } addInvalidateOne() { this.archiveIfNeeded(); this.currentRecord.invalidateOne++; } addInvalidateAll() { this.archiveIfNeeded(); this.currentRecord.invalidateAll++; } getStatistics() { return this.records.getStatistics(); } archiveIfNeeded() { if (this.hoursPassed() >= this.statisticTtlInHours) { this.collectionStart = new Date(); this.currentTimeStamp = getTimestamp(this.collectionStart); this.records.initForCache(this.cacheId, this.currentTimeStamp); } } }; var LruObjectHitStatistics = class extends LruObject { constructor(max, ttlInMsecs, cacheId, globalStatisticsRecord, statisticTtlInHours) { super(max || 1e3, ttlInMsecs || 0); if (!cacheId) { throw new Error("Cache id is mandatory"); } this.hitStatistics = new HitStatistics( cacheId, statisticTtlInHours !== void 0 ? statisticTtlInHours : 24, globalStatisticsRecord ); } getStatistics() { return this.hitStatistics.getStatistics(); } set(key, value) { super.set(key, value); this.hitStatistics.addSet(); this.hitStatistics.setCacheSize(this.size); } evict() { super.evict(); this.hitStatistics.addEviction(); this.hitStatistics.setCacheSize(this.size); } delete(key, isExpiration = false) { super.delete(key); if (!isExpiration) { this.hitStatistics.addInvalidateOne(); } this.hitStatistics.setCacheSize(this.size); } clear() { super.clear(); this.hitStatistics.addInvalidateAll(); this.hitStatistics.setCacheSize(this.size); } get(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const item = this.items[key]; if (this.ttl > 0 && item.expiry <= Date.now()) { this.delete(key, true); this.hitStatistics.addExpiration(); return; } this.bumpLru(item); if (!item.value) { this.hitStatistics.addFalsyHit(); } if (item.value === void 0 || item.value === null || item.value === "") { this.hitStatistics.addEmptyHit(); } this.hitStatistics.addHit(); return item.value; } this.hitStatistics.addMiss(); } }; var FifoObject = class { constructor(max = 1e3, ttlInMsecs = 0) { if (isNaN(max) || max < 0) { throw new Error("Invalid max value"); } if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { throw new Error("Invalid ttl value"); } this.first = null; this.items = /* @__PURE__ */ Object.create(null); this.last = null; this.size = 0; this.max = max; this.ttl = ttlInMsecs; } clear() { this.items = /* @__PURE__ */ Object.create(null); this.first = null; this.last = null; this.size = 0; } delete(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const deletedItem = this.items[key]; delete this.items[key]; this.size--; if (deletedItem.prev !== null) { deletedItem.prev.next = deletedItem.next; } if (deletedItem.next !== null) { deletedItem.next.prev = deletedItem.prev; } if (this.first === deletedItem) { this.first = deletedItem.next; } if (this.last === deletedItem) { this.last = deletedItem.prev; } } } deleteMany(keys) { for (var i = 0; i < keys.length; i++) { this.delete(keys[i]); } } evict() { if (this.size > 0) { const item = this.first; delete this.items[item.key]; if (--this.size === 0) { this.first = null; this.last = null; } else { this.first = item.next; this.first.prev = null; } } } expiresAt(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { return this.items[key].expiry; } } get(key) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const item = this.items[key]; if (this.ttl > 0 && item.expiry <= Date.now()) { this.delete(key); return; } return item.value; } } getMany(keys) { const result = []; for (var i = 0; i < keys.length; i++) { result.push(this.get(keys[i])); } return result; } keys() { return Object.keys(this.items); } set(key, value) { if (Object.prototype.hasOwnProperty.call(this.items, key)) { const item2 = this.items[key]; item2.value = value; item2.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; return; } if (this.max > 0 && this.size === this.max) { this.evict(); } const item = { expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, key, prev: this.last, next: null, value }; this.items[key] = item; if (++this.size === 1) { this.first = item; } else { this.last.next = item; } this.last = item; } }; exports.Fifo = FifoObject; exports.FifoMap = FifoMap; exports.FifoObject = FifoObject; exports.HitStatisticsRecord = HitStatisticsRecord; exports.Lru = LruObject; exports.LruHitStatistics = LruObjectHitStatistics; exports.LruMap = LruMap; exports.LruObject = LruObject; exports.LruObjectHitStatistics = LruObjectHitStatistics; } }); // node_modules/fast-content-type-parse/index.js var require_fast_content_type_parse = __commonJS({ "node_modules/fast-content-type-parse/index.js"(exports, module2) { "use strict"; var NullObject = function NullObject2() { }; NullObject.prototype = /* @__PURE__ */ Object.create(null); var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu; var quotedPairRE = /\\([\v\u0020-\u00ff])/gu; var mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u; var defaultContentType = { type: "", parameters: new NullObject() }; Object.freeze(defaultContentType.parameters); Object.freeze(defaultContentType); function parse(header) { if (typeof header !== "string") { throw new TypeError("argument header is required and must be a string"); } let index = header.indexOf(";"); const type = index !== -1 ? header.slice(0, index).trim() : header.trim(); if (mediaTypeRE.test(type) === false) { throw new TypeError("invalid media type"); } const result = { type: type.toLowerCase(), parameters: new NullObject() }; if (index === -1) { return result; } let key; let match; let value; paramRE.lastIndex = index; while (match = paramRE.exec(header)) { if (match.index !== index) { throw new TypeError("invalid parameter format"); } index += match[0].length; key = match[1].toLowerCase(); value = match[2]; if (value[0] === '"') { value = value.slice(1, value.length - 1); quotedPairRE.test(value) && (value = value.replace(quotedPairRE, "$1")); } result.parameters[key] = value; } if (index !== header.length) { throw new TypeError("invalid parameter format"); } return result; } function safeParse(header) { if (typeof header !== "string") { return defaultContentType; } let index = header.indexOf(";"); const type = index !== -1 ? header.slice(0, index).trim() : header.trim(); if (mediaTypeRE.test(type) === false) { return defaultContentType; } const result = { type: type.toLowerCase(), parameters: new NullObject() }; if (index === -1) { return result; } let key; let match; let value; paramRE.lastIndex = index; while (match = paramRE.exec(header)) { if (match.index !== index) { return defaultContentType; } index += match[0].length; key = match[1].toLowerCase(); value = match[2]; if (value[0] === '"') { value = value.slice(1, value.length - 1); quotedPairRE.test(value) && (value = value.replace(quotedPairRE, "$1")); } result.parameters[key] = value; } if (index !== header.length) { return defaultContentType; } return result; } module2.exports.default = { parse, safeParse }; module2.exports.parse = parse; module2.exports.safeParse = safeParse; module2.exports.defaultContentType = defaultContentType; } }); // node_modules/secure-json-parse/index.js var require_secure_json_parse = __commonJS({ "node_modules/secure-json-parse/index.js"(exports, module2) { "use strict"; var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse(text, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; reviver = void 0; } } if (hasBuffer && Buffer.isBuffer(text)) { text = text.toString(); } if (text && text.charCodeAt(0) === 65279) { text = text.slice(1); } const obj = JSON.parse(text, reviver); if (obj === null || typeof obj !== "object") { return obj; } const protoAction = options && options.protoAction || "error"; const constructorAction = options && options.constructorAction || "error"; if (protoAction === "ignore" && constructorAction === "ignore") { return obj; } if (protoAction !== "ignore" && constructorAction !== "ignore") { if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) { return obj; } } else if (protoAction !== "ignore" && constructorAction === "ignore") { if (suspectProtoRx.test(text) === false) { return obj; } } else { if (suspectConstructorRx.test(text) === false) { return obj; } } return filter(obj, { protoAction, constructorAction, safe: options && options.safe }); } function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } delete node.__proto__; } if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } delete node.constructor; } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function parse(text, reviver, options) { const stackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; try { return _parse(text, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } } function safeParse(text, reviver) { const stackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; try { return _parse(text, reviver, { safe: true }); } catch (_e) { return null; } finally { Error.stackTraceLimit = stackTraceLimit; } } module2.exports = parse; module2.exports.default = parse; module2.exports.parse = parse; module2.exports.safeParse = safeParse; module2.exports.scan = filter; } }); // node_modules/fastify/lib/contentTypeParser.js var require_contentTypeParser = __commonJS({ "node_modules/fastify/lib/contentTypeParser.js"(exports, module2) { "use strict"; var { AsyncResource } = require("async_hooks"); var { FifoMap: Fifo } = require_toad_cache(); var { safeParse: safeParseContentType, defaultContentType } = require_fast_content_type_parse(); var secureJson = require_secure_json_parse(); var { kDefaultJsonParse, kContentTypeParser, kBodyLimit, kRequestPayloadStream, kState, kTestInternals, kReplyIsError, kRouteContext } = require_symbols2(); var { FST_ERR_CTP_INVALID_TYPE, FST_ERR_CTP_EMPTY_TYPE, FST_ERR_CTP_ALREADY_PRESENT, FST_ERR_CTP_INVALID_HANDLER, FST_ERR_CTP_INVALID_PARSE_TYPE, FST_ERR_CTP_BODY_TOO_LARGE, FST_ERR_CTP_INVALID_MEDIA_TYPE, FST_ERR_CTP_INVALID_CONTENT_LENGTH, FST_ERR_CTP_EMPTY_JSON_BODY, FST_ERR_CTP_INSTANCE_ALREADY_STARTED } = require_errors2(); function ContentTypeParser(bodyLimit, onProtoPoisoning, onConstructorPoisoning) { this[kDefaultJsonParse] = getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning); this.customParsers = /* @__PURE__ */ new Map(); this.customParsers.set("application/json", new Parser(true, false, bodyLimit, this[kDefaultJsonParse])); this.customParsers.set("text/plain", new Parser(true, false, bodyLimit, defaultPlainTextParser)); this.parserList = [new ParserListItem("application/json"), new ParserListItem("text/plain")]; this.parserRegExpList = []; this.cache = new Fifo(100); } ContentTypeParser.prototype.add = function(contentType, opts, parserFn) { const contentTypeIsString = typeof contentType === "string"; if (!contentTypeIsString && !(contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE(); if (contentTypeIsString && contentType.length === 0) throw new FST_ERR_CTP_EMPTY_TYPE(); if (typeof parserFn !== "function") throw new FST_ERR_CTP_INVALID_HANDLER(); if (this.existingParser(contentType)) { throw new FST_ERR_CTP_ALREADY_PRESENT(contentType); } if (opts.parseAs !== void 0) { if (opts.parseAs !== "string" && opts.parseAs !== "buffer") { throw new FST_ERR_CTP_INVALID_PARSE_TYPE(opts.parseAs); } } const parser = new Parser( opts.parseAs === "string", opts.parseAs === "buffer", opts.bodyLimit, parserFn ); if (contentTypeIsString && contentType === "*") { this.customParsers.set("", parser); } else { if (contentTypeIsString) { this.parserList.unshift(new ParserListItem(contentType)); } else { contentType.isEssence = contentType.source.indexOf(";") === -1; this.parserRegExpList.unshift(contentType); } this.customParsers.set(contentType.toString(), parser); } }; ContentTypeParser.prototype.hasParser = function(contentType) { return this.customParsers.has(typeof contentType === "string" ? contentType : contentType.toString()); }; ContentTypeParser.prototype.existingParser = function(contentType) { if (contentType === "application/json" && this.customParsers.has(contentType)) { return this.customParsers.get(contentType).fn !== this[kDefaultJsonParse]; } if (contentType === "text/plain" && this.customParsers.has(contentType)) { return this.customParsers.get(contentType).fn !== defaultPlainTextParser; } return this.hasParser(contentType); }; ContentTypeParser.prototype.getParser = function(contentType) { if (this.hasParser(contentType)) { return this.customParsers.get(contentType); } const parser = this.cache.get(contentType); if (parser !== void 0) return parser; const parsed = safeParseContentType(contentType); if (parsed === defaultContentType) { return this.customParsers.get(""); } for (var i = 0; i !== this.parserList.length; ++i) { const parserListItem = this.parserList[i]; if (compareContentType(parsed, parserListItem)) { const parser2 = this.customParsers.get(parserListItem.name); this.cache.set(contentType, parser2); return parser2; } } for (var j = 0; j !== this.parserRegExpList.length; ++j) { const parserRegExp = this.parserRegExpList[j]; if (compareRegExpContentType(contentType, parsed.type, parserRegExp)) { const parser2 = this.customParsers.get(parserRegExp.toString()); this.cache.set(contentType, parser2); return parser2; } } return this.customParsers.get(""); }; ContentTypeParser.prototype.removeAll = function() { this.customParsers = /* @__PURE__ */ new Map(); this.parserRegExpList = []; this.parserList = []; this.cache = new Fifo(100); }; ContentTypeParser.prototype.remove = function(contentType) { if (!(typeof contentType === "string" || contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE(); const removed = this.customParsers.delete(contentType.toString()); const parsers = typeof contentType === "string" ? this.parserList : this.parserRegExpList; const idx = parsers.findIndex((ct) => ct.toString() === contentType.toString()); if (idx > -1) { parsers.splice(idx, 1); } return removed || idx > -1; }; ContentTypeParser.prototype.run = function(contentType, handler, request, reply) { const parser = this.getParser(contentType); if (parser === void 0) { if (request.is404) { handler(request, reply); } else { reply.send(new FST_ERR_CTP_INVALID_MEDIA_TYPE(contentType || void 0)); } return; } const resource = new AsyncResource("content-type-parser:run", request); if (parser.asString === true || parser.asBuffer === true) { rawBody( request, reply, reply[kRouteContext]._parserOptions, parser, done ); } else { const result = parser.fn(request, request[kRequestPayloadStream], done); if (result && typeof result.then === "function") { result.then((body) => done(null, body), done); } } function done(error, body) { resource.runInAsyncScope(() => { resource.emitDestroy(); if (error) { reply[kReplyIsError] = true; reply.send(error); } else { request.body = body; handler(request, reply); } }); } }; function rawBody(request, reply, options, parser, done) { const asString = parser.asString; const limit = options.limit === null ? parser.bodyLimit : options.limit; const contentLength = request.headers["content-length"] === void 0 ? NaN : Number(request.headers["content-length"]); if (contentLength > limit) { reply.header("connection", "close"); reply.send(new FST_ERR_CTP_BODY_TOO_LARGE()); return; } let receivedLength = 0; let body = asString === true ? "" : []; const payload = request[kRequestPayloadStream] || request.raw; if (asString === true) { payload.setEncoding("utf8"); } payload.on("data", onData); payload.on("end", onEnd); payload.on("error", onEnd); payload.resume(); function onData(chunk) { receivedLength += chunk.length; const { receivedEncodedLength = 0 } = payload; if (receivedLength > limit || receivedEncodedLength > limit) { payload.removeListener("data", onData); payload.removeListener("end", onEnd); payload.removeListener("error", onEnd); reply.send(new FST_ERR_CTP_BODY_TOO_LARGE()); return; } if (asString === true) { body += chunk; } else { body.push(chunk); } } function onEnd(err) { payload.removeListener("data", onData); payload.removeListener("end", onEnd); payload.removeListener("error", onEnd); if (err !== void 0) { if (!(typeof err.statusCode === "number" && err.statusCode >= 400)) { err.statusCode = 400; } reply[kReplyIsError] = true; reply.code(err.statusCode).send(err); return; } if (asString === true) { receivedLength = Buffer.byteLength(body); } if (!Number.isNaN(contentLength) && (payload.receivedEncodedLength || receivedLength) !== contentLength) { reply.header("connection", "close"); reply.send(new FST_ERR_CTP_INVALID_CONTENT_LENGTH()); return; } if (asString === false) { body = Buffer.concat(body); } const result = parser.fn(request, body, done); if (result && typeof result.then === "function") { result.then((body2) => done(null, body2), done); } } } function getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning) { return defaultJsonParser; function defaultJsonParser(req, body, done) { if (body === "" || body == null || Buffer.isBuffer(body) && body.length === 0) { return done(new FST_ERR_CTP_EMPTY_JSON_BODY(), void 0); } let json; try { json = secureJson.parse(body, { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning }); } catch (err) { err.statusCode = 400; return done(err, void 0); } done(null, json); } } function defaultPlainTextParser(req, body, done) { done(null, body); } function Parser(asString, asBuffer, bodyLimit, fn) { this.asString = asString; this.asBuffer = asBuffer; this.bodyLimit = bodyLimit; this.fn = fn; } function buildContentTypeParser(c) { const contentTypeParser = new ContentTypeParser(); contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]; contentTypeParser.customParsers = new Map(c.customParsers.entries()); contentTypeParser.parserList = c.parserList.slice(); contentTypeParser.parserRegExpList = c.parserRegExpList.slice(); return contentTypeParser; } function addContentTypeParser(contentType, opts, parser) { if (this[kState].started) { throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED("addContentTypeParser"); } if (typeof opts === "function") { parser = opts; opts = {}; } if (!opts) opts = {}; if (!opts.bodyLimit) opts.bodyLimit = this[kBodyLimit]; if (Array.isArray(contentType)) { contentType.forEach((type) => this[kContentTypeParser].add(type, opts, parser)); } else { this[kContentTypeParser].add(contentType, opts, parser); } return this; } function hasContentTypeParser(contentType) { return this[kContentTypeParser].hasParser(contentType); } function removeContentTypeParser(contentType) { if (this[kState].started) { throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED("removeContentTypeParser"); } if (Array.isArray(contentType)) { for (const type of contentType) { this[kContentTypeParser].remove(type); } } else { this[kContentTypeParser].remove(contentType); } } function removeAllContentTypeParsers() { if (this[kState].started) { throw new FST_ERR_CTP_INSTANCE_ALREADY_STARTED("removeAllContentTypeParsers"); } this[kContentTypeParser].removeAll(); } function compareContentType(contentType, parserListItem) { if (parserListItem.isEssence) { return contentType.type.indexOf(parserListItem) !== -1; } else { if (contentType.type.indexOf(parserListItem.type) === -1) return false; for (const key of parserListItem.parameterKeys) { if (!(key in contentType.parameters)) return false; if (contentType.parameters[key] !== parserListItem.parameters[key]) return false; } return true; } } function compareRegExpContentType(contentType, essenceMIMEType, regexp) { if (regexp.isEssence) { return regexp.test(essenceMIMEType); } else { return regexp.test(contentType); } } function ParserListItem(contentType) { this.name = contentType; const parsed = safeParseContentType(contentType); this.isEssence = contentType.indexOf(";") === -1; if (this.isEssence === false && parsed.type === "") { const tmp = contentType.split(";", 1)[0]; this.type = tmp === "" ? contentType : tmp; } else { this.type = parsed.type; } this.parameters = parsed.parameters; this.parameterKeys = Object.keys(parsed.parameters); } ParserListItem.prototype.toString = function() { return this.name; }; module2.exports = ContentTypeParser; module2.exports.helpers = { buildContentTypeParser, addContentTypeParser, hasContentTypeParser, removeContentTypeParser, removeAllContentTypeParsers }; module2.exports.defaultParsers = { getDefaultJsonParser, defaultTextParser: defaultPlainTextParser }; module2.exports[kTestInternals] = { rawBody }; } }); // node_modules/fast-deep-equal/index.js var require_fast_deep_equal = __commonJS({ "node_modules/fast-deep-equal/index.js"(exports, module2) { "use strict"; module2.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == "object" && typeof b == "object") { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0; ) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0; ) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } return a !== a && b !== b; }; } }); // node_modules/json-schema-ref-resolver/index.js var require_json_schema_ref_resolver = __commonJS({ "node_modules/json-schema-ref-resolver/index.js"(exports, module2) { "use strict"; var deepEqual = require_fast_deep_equal(); var jsonSchemaRefSymbol = Symbol.for("json-schema-ref"); var _schemas, _derefSchemas, _insertRefSymbol, _allowEqualDuplicates, _cloneSchemaWithoutRefs, _parseSchemaRef, parseSchemaRef_fn, _addSchema, addSchema_fn, _addDerefSchema, addDerefSchema_fn, _resolveRef, resolveRef_fn, _insertSchemaBySchemaId, insertSchemaBySchemaId_fn, _insertSchemaByAnchor, insertSchemaByAnchor_fn, _insertDerefSchemaBySchemaId, insertDerefSchemaBySchemaId_fn, _insertDerefSchemaByAnchor, insertDerefSchemaByAnchor_fn; var RefResolver = class { constructor(opts = {}) { __privateAdd(this, _parseSchemaRef); __privateAdd(this, _addSchema); __privateAdd(this, _addDerefSchema); __privateAdd(this, _resolveRef); __privateAdd(this, _insertSchemaBySchemaId); __privateAdd(this, _insertSchemaByAnchor); __privateAdd(this, _insertDerefSchemaBySchemaId); __privateAdd(this, _insertDerefSchemaByAnchor); __privateAdd(this, _schemas, void 0); __privateAdd(this, _derefSchemas, void 0); __privateAdd(this, _insertRefSymbol, void 0); __privateAdd(this, _allowEqualDuplicates, void 0); __privateAdd(this, _cloneSchemaWithoutRefs, void 0); var _a, _b, _c; __privateSet(this, _schemas, {}); __privateSet(this, _derefSchemas, {}); __privateSet(this, _insertRefSymbol, (_a = opts.insertRefSymbol) != null ? _a : false); __privateSet(this, _allowEqualDuplicates, (_b = opts.allowEqualDuplicates) != null ? _b : true); __privateSet(this, _cloneSchemaWithoutRefs, (_c = opts.cloneSchemaWithoutRefs) != null ? _c : false); } addSchema(schema, schemaId) { if (schema.$id !== void 0 && schema.$id.charAt(0) !== "#") { schemaId = schema.$id; } else { __privateMethod(this, _insertSchemaBySchemaId, insertSchemaBySchemaId_fn).call(this, schema, schemaId); } __privateMethod(this, _addSchema, addSchema_fn).call(this, schema, schemaId); } getSchema(schemaId, jsonPointer = "#") { const schema = __privateGet(this, _schemas)[schemaId]; if (schema === void 0) { throw new Error( `Cannot resolve ref "${schemaId}${jsonPointer}". Schema with id "${schemaId}" is not found.` ); } if (schema.anchors[jsonPointer] !== void 0) { return schema.anchors[jsonPointer]; } return getDataByJSONPointer(schema.schema, jsonPointer); } hasSchema(schemaId) { return __privateGet(this, _schemas)[schemaId] !== void 0; } getSchemaRefs(schemaId) { const schema = __privateGet(this, _schemas)[schemaId]; if (schema === void 0) { throw new Error(`Schema with id "${schemaId}" is not found.`); } return schema.refs; } getSchemaDependencies(schemaId, dependencies = {}) { const schema = __privateGet(this, _schemas)[schemaId]; for (const ref of schema.refs) { const dependencySchemaId = ref.schemaId; if (dependencies[dependencySchemaId] !== void 0) continue; dependencies[dependencySchemaId] = this.getSchema(dependencySchemaId); this.getSchemaDependencies(dependencySchemaId, dependencies); } return dependencies; } derefSchema(schemaId) { if (__privateGet(this, _derefSchemas)[schemaId] !== void 0) return; const schema = __privateGet(this, _schemas)[schemaId]; if (schema === void 0) { throw new Error(`Schema with id "${schemaId}" is not found.`); } if (!__privateGet(this, _cloneSchemaWithoutRefs) && schema.refs.length === 0) { __privateGet(this, _derefSchemas)[schemaId] = { schema: schema.schema, anchors: schema.anchors }; } const refs = []; __privateMethod(this, _addDerefSchema, addDerefSchema_fn).call(this, schema.schema, schemaId, refs); const dependencies = this.getSchemaDependencies(schemaId); for (const schemaId2 in dependencies) { const schema2 = dependencies[schemaId2]; __privateMethod(this, _addDerefSchema, addDerefSchema_fn).call(this, schema2, schemaId2, refs); } for (const ref of refs) { const { refSchemaId, refJsonPointer } = __privateMethod(this, _parseSchemaRef, parseSchemaRef_fn).call(this, ref.ref, ref.sourceSchemaId); const targetSchema = this.getDerefSchema(refSchemaId, refJsonPointer); if (targetSchema === null) { throw new Error( `Cannot resolve ref "${ref.ref}". Ref "${refJsonPointer}" is not found in schema "${refSchemaId}".` ); } ref.targetSchema = targetSchema; ref.targetSchemaId = refSchemaId; } for (const ref of refs) { __privateMethod(this, _resolveRef, resolveRef_fn).call(this, ref, refs); } } getDerefSchema(schemaId, jsonPointer = "#") { let derefSchema = __privateGet(this, _derefSchemas)[schemaId]; if (derefSchema === void 0) { this.derefSchema(schemaId); derefSchema = __privateGet(this, _derefSchemas)[schemaId]; } if (derefSchema.anchors[jsonPointer] !== void 0) { return derefSchema.anchors[jsonPointer]; } return getDataByJSONPointer(derefSchema.schema, jsonPointer); } }; _schemas = new WeakMap(); _derefSchemas = new WeakMap(); _insertRefSymbol = new WeakMap(); _allowEqualDuplicates = new WeakMap(); _cloneSchemaWithoutRefs = new WeakMap(); _parseSchemaRef = new WeakSet(); parseSchemaRef_fn = function(ref, schemaId) { const sharpIndex = ref.indexOf("#"); if (sharpIndex === -1) { return { refSchemaId: ref, refJsonPointer: "#" }; } if (sharpIndex === 0) { return { refSchemaId: schemaId, refJsonPointer: ref }; } return { refSchemaId: ref.slice(0, sharpIndex), refJsonPointer: ref.slice(sharpIndex) }; }; _addSchema = new WeakSet(); addSchema_fn = function(schema, rootSchemaId) { const schemaId = schema.$id; if (schemaId !== void 0 && typeof schemaId === "string") { if (schemaId.charAt(0) === "#") { __privateMethod(this, _insertSchemaByAnchor, insertSchemaByAnchor_fn).call(this, schema, rootSchemaId, schemaId); } else { __privateMethod(this, _insertSchemaBySchemaId, insertSchemaBySchemaId_fn).call(this, schema, schemaId); rootSchemaId = schemaId; } } const ref = schema.$ref; if (ref !== void 0 && typeof ref === "string") { const { refSchemaId, refJsonPointer } = __privateMethod(this, _parseSchemaRef, parseSchemaRef_fn).call(this, ref, rootSchemaId); __privateGet(this, _schemas)[rootSchemaId].refs.push({ schemaId: refSchemaId, jsonPointer: refJsonPointer }); } for (const key in schema) { if (typeof schema[key] === "object" && schema[key] !== null) { __privateMethod(this, _addSchema, addSchema_fn).call(this, schema[key], rootSchemaId); } } }; _addDerefSchema = new WeakSet(); addDerefSchema_fn = function(schema, rootSchemaId, refs = []) { const derefSchema = Array.isArray(schema) ? [...schema] : { ...schema }; const schemaId = derefSchema.$id; if (schemaId !== void 0 && typeof schemaId === "string") { if (schemaId.charAt(0) === "#") { __privateMethod(this, _insertDerefSchemaByAnchor, insertDerefSchemaByAnchor_fn).call(this, derefSchema, rootSchemaId, schemaId); } else { __privateMethod(this, _insertDerefSchemaBySchemaId, insertDerefSchemaBySchemaId_fn).call(this, derefSchema, schemaId); rootSchemaId = schemaId; } } if (derefSchema.$ref !== void 0) { refs.push({ ref: derefSchema.$ref, sourceSchemaId: rootSchemaId, sourceSchema: derefSchema }); } for (const key in derefSchema) { const value = derefSchema[key]; if (typeof value === "object" && value !== null) { derefSchema[key] = __privateMethod(this, _addDerefSchema, addDerefSchema_fn).call(this, value, rootSchemaId, refs); } } return derefSchema; }; _resolveRef = new WeakSet(); resolveRef_fn = function(ref, refs) { const { sourceSchema, targetSchema } = ref; if (!sourceSchema.$ref) return; if (__privateGet(this, _insertRefSymbol)) { sourceSchema[jsonSchemaRefSymbol] = sourceSchema.$ref; } delete sourceSchema.$ref; if (targetSchema.$ref) { const targetSchemaRef = refs.find((ref2) => ref2.sourceSchema === targetSchema); __privateMethod(this, _resolveRef, resolveRef_fn).call(this, targetSchemaRef, refs); } for (const key in targetSchema) { if (key === "$id") continue; if (sourceSchema[key] !== void 0) { if (deepEqual(sourceSchema[key], targetSchema[key])) continue; throw new Error( `Cannot resolve ref "${ref.ref}". Property "${key}" is already exist in schema "${ref.sourceSchemaId}".` ); } sourceSchema[key] = targetSchema[key]; } ref.isResolved = true; }; _insertSchemaBySchemaId = new WeakSet(); insertSchemaBySchemaId_fn = function(schema, schemaId) { const foundSchema = __privateGet(this, _schemas)[schemaId]; if (foundSchema !== void 0) { if (__privateGet(this, _allowEqualDuplicates) && deepEqual(schema, foundSchema.schema)) return; throw new Error(`There is already another schema with id "${schemaId}".`); } __privateGet(this, _schemas)[schemaId] = { schema, anchors: {}, refs: [] }; }; _insertSchemaByAnchor = new WeakSet(); insertSchemaByAnchor_fn = function(schema, schemaId, anchor) { const { anchors } = __privateGet(this, _schemas)[schemaId]; if (anchors[anchor] !== void 0) { throw new Error(`There is already another anchor "${anchor}" in a schema "${schemaId}".`); } anchors[anchor] = schema; }; _insertDerefSchemaBySchemaId = new WeakSet(); insertDerefSchemaBySchemaId_fn = function(schema, schemaId) { const foundSchema = __privateGet(this, _derefSchemas)[schemaId]; if (foundSchema !== void 0) return; __privateGet(this, _derefSchemas)[schemaId] = { schema, anchors: {} }; }; _insertDerefSchemaByAnchor = new WeakSet(); insertDerefSchemaByAnchor_fn = function(schema, schemaId, anchor) { const { anchors } = __privateGet(this, _derefSchemas)[schemaId]; anchors[anchor] = schema; }; function getDataByJSONPointer(data, jsonPointer) { const parts = jsonPointer.split("/"); let current = data; for (const part of parts) { if (part === "" || part === "#") continue; if (typeof current !== "object" || current === null) { return null; } current = current[part]; } return current != null ? current : null; } module2.exports = { RefResolver }; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/codegen/code.js var require_code = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/codegen/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; var _CodeOrName = class { }; exports._CodeOrName = _CodeOrName; exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s) { super(); if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a; return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); } get names() { var _a; return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}); } }; exports._Code = _Code; exports.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports._ = _; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== void 0) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports.strConcat = strConcat; function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports.stringify = stringify; function safeStringify(x) { return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; } exports.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports.regexpCode = regexpCode; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/codegen/scope.js var require_scope = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; var code_1 = require_code(); var ValueError = class extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a, _b; if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports.ValueScopeName = ValueScopeName; var line = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = /* @__PURE__ */ new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._)`${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } }; exports.ValueScope = ValueScope; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/codegen/index.js var require_codegen = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/codegen/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; var code_1 = require_code(); var scope_1 = require_scope(); var code_2 = require_code(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope(); Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } }; var Label = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } }; var Break = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } }; var Throw = class extends Node { constructor(error) { super(); this.error = error; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } }; var AnyCode = class extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof If ? e : e.nodes; if (this.nodes.length) return this; return new If(not(cond), e instanceof If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a; this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a, _b; super.optimizeNodes(); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a, _b; super.optimizeNames(names, constants); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error) { super(); this.error = error; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { this.var(name, (0, code_1._)`${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error = this.name("e"); this._currNode = node.catch = new Catch(error); catchCode(error); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error) { return this._leafNode(new Throw(error)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || N2 && n instanceof N2) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } }; exports.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === void 0 || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; } exports.not = not; var andCode = mappend(exports.operators.AND); function and(...args) { return args.reduce(andCode); } exports.and = and; var orCode = mappend(exports.operators.OR); function or(...args) { return args.reduce(orCode); } exports.or = or; function mappend(op) { return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/util.js var require_util = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/util.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; var codegen_1 = require_codegen(); var code_1 = require_code(); function toHash(arr) { const hash = {}; for (const item of arr) hash[item] = true; return hash; } exports.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps !== void 0) setEvaluated(gen, props, ps); return props; } exports.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); } exports.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports.checkStrictMode = checkStrictMode; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/names.js var require_names = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/names.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports.default = names; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/errors.js var require_errors3 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/errors.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var names_1 = require_names(); exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._)`[${errObj}]`); } } exports.reportError = reportError; function reportExtraError(cxt, error = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err}.data`, data); } }); } exports.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error, errorPaths); } function errorObject(cxt, error, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; var errors_1 = require_errors3(); var codegen_1 = require_codegen(); var names_1 = require_names(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); falseSchemaError(it); } else { gen.var(valid, true); } } exports.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/rules.js var require_rules = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/rules.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRules = exports.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports.getRules = getRules; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/applicability.js var require_applicability = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a; return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); } exports.shouldUseRule = shouldUseRule; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/dataType.js var require_dataType = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; var rules_1 = require_rules(); var applicability_1 = require_applicability(); var errors_1 = require_errors3(); var codegen_1 = require_codegen(); var util_1 = require_util(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it }; } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/defaults.js var require_defaults = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assignDefaults = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/code.js var require_code2 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var names_1 = require_names(); var util_2 = require_util(); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); } exports.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports.validateUnion = validateUnion; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/keyword.js var require_keyword = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; var codegen_1 = require_codegen(); var names_1 = require_names(); var code_1 = require_code2(); var errors_1 = require_errors3(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a2; gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors); } } exports.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); } exports.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/subschema.js var require_subschema = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/fast-json-stringify/node_modules/json-schema-traverse/index.js var require_json_schema_traverse = __commonJS({ "node_modules/fast-json-stringify/node_modules/json-schema-traverse/index.js"(exports, module2) { "use strict"; var traverse = module2.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/resolve.js var require_resolve = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/resolve.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; var util_1 = require_util(); var equal = require_fast_deep_equal(); var traverse = require_json_schema_traverse(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports.getSchemaRefs = getSchemaRefs; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/index.js var require_validate = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/validate/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema(); var dataType_1 = require_dataType(); var applicability_1 = require_applicability(); var dataType_2 = require_dataType(); var defaults_1 = require_defaults(); var keyword_1 = require_keyword(); var subschema_1 = require_subschema(); var codegen_1 = require_codegen(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util(); var errors_1 = require_errors3(); function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults } } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts, t) { return ts.includes(t) || t === "integer" && ts.includes("number"); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } var KeywordCxt = class { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment of segments) { if (segment) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports.getData = getData; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/validation_error.js var require_validation_error = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/validation_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports.default = ValidationError; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/ref_error.js var require_ref_error = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/ref_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var resolve_1 = require_resolve(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports.default = MissingRefError; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/compile/index.js var require_compile = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/compile/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; var codegen_1 = require_codegen(); var validation_error_1 = require_validation_error(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { constructor(env) { var _a; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e; } finally { this._compilations.delete(sch); } } exports.compileSchema = compileSchema; function resolveRef(root, baseId, ref) { var _a; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === void 0) { const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports.resolveRef = resolveRef; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a; if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/refs/data.json var require_data = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/refs/data.json"(exports, module2) { module2.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/uri-js/dist/es5/uri.all.js var require_uri_all = __commonJS({ "node_modules/uri-js/dist/es5/uri.all.js"(exports, module2) { (function(global2, factory) { typeof exports === "object" && typeof module2 !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.URI = global2.URI || {}); })(exports, function(exports2) { "use strict"; function merge() { for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { sets[_key] = arguments[_key]; } if (sets.length > 1) { sets[0] = sets[0].slice(0, -1); var xl = sets.length - 1; for (var x = 1; x < xl; ++x) { sets[x] = sets[x].slice(1, -1); } sets[xl] = sets[xl].slice(1); return sets.join(""); } else { return sets[0]; } } function subexp(str) { return "(?:" + str + ")"; } function typeOf(o) { return o === void 0 ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); } function toUpperCase(str) { return str.toUpperCase(); } function toArray(obj) { return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; } function assign(target, source) { var obj = target; if (source) { for (var key in source) { obj[key] = source[key]; } } return obj; } function buildExps(isIRI2) { var ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$2 = merge(DIGIT$$, "[A-Fa-f]"), LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI2 ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI2 ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$2 + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$2 + "|" + PCT_ENCODED$2) + "+"), IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + ZONEID$), IPVFUTURE$ = subexp("[vV]" + HEXDIG$$2 + "+\\." + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), REG_NAME$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), PATH_EMPTY$ = "(?!" + PCHAR$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; return { NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"), NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"), NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"), NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"), NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), ESCAPE: new RegExp(merge("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"), UNRESERVED: new RegExp(UNRESERVED$$2, "g"), OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"), PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"), IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules }; } var URI_PROTOCOL = buildExps(false); var IRI_PROTOCOL = buildExps(true); var slicedToArray = function() { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = void 0; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var toConsumableArray = function(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; var maxInt = 2147483647; var base = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; var delimiter = "-"; var regexPunycode = /^xn--/; var regexNonASCII = /[^\0-\x7E]/; var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; var errors = { "overflow": "Overflow: input needs wider integers to process", "not-basic": "Illegal input >= 0x80 (not a basic code point)", "invalid-input": "Invalid input" }; var baseMinusTMin = base - tMin; var floor = Math.floor; var stringFromCharCode = String.fromCharCode; function error$1(type) { throw new RangeError(errors[type]); } function map(array, fn) { var result = []; var length = array.length; while (length--) { result[length] = fn(array[length]); } return result; } function mapDomain(string, fn) { var parts = string.split("@"); var result = ""; if (parts.length > 1) { result = parts[0] + "@"; string = parts[1]; } string = string.replace(regexSeparators, "."); var labels = string.split("."); var encoded = map(labels, fn).join("."); return result + encoded; } function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; while (counter < length) { var value = string.charCodeAt(counter++); if (value >= 55296 && value <= 56319 && counter < length) { var extra = string.charCodeAt(counter++); if ((extra & 64512) == 56320) { output.push(((value & 1023) << 10) + (extra & 1023) + 65536); } else { output.push(value); counter--; } } else { output.push(value); } } return output; } var ucs2encode = function ucs2encode2(array) { return String.fromCodePoint.apply(String, toConsumableArray(array)); }; var basicToDigit = function basicToDigit2(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; }; var digitToBasic = function digitToBasic2(digit, flag) { return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; var adapt = function adapt2(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for ( ; /* no initialization */ delta > baseMinusTMin * tMax >> 1; k += base ) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; var decode = function decode2(input) { var output = []; var inputLength = input.length; var i = 0; var n = initialN; var bias = initialBias; var basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (var j = 0; j < basic; ++j) { if (input.charCodeAt(j) >= 128) { error$1("not-basic"); } output.push(input.charCodeAt(j)); } for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; ) { var oldi = i; for ( var w = 1, k = base; ; /* no condition */ k += base ) { if (index >= inputLength) { error$1("invalid-input"); } var digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error$1("overflow"); } i += digit * w; var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } var baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error$1("overflow"); } w *= baseMinusT; } var out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); if (floor(i / out) > maxInt - n) { error$1("overflow"); } n += floor(i / out); i %= out; output.splice(i++, 0, n); } return String.fromCodePoint.apply(String, output); }; var encode = function encode2(input) { var output = []; input = ucs2decode(input); var inputLength = input.length; var n = initialN; var delta = 0; var bias = initialBias; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = void 0; try { for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _currentValue2 = _step.value; if (_currentValue2 < 128) { output.push(stringFromCharCode(_currentValue2)); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var basicLength = output.length; var handledCPCount = basicLength; if (basicLength) { output.push(delimiter); } while (handledCPCount < inputLength) { var m = maxInt; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = void 0; try { for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var currentValue = _step2.value; if (currentValue >= n && currentValue < m) { m = currentValue; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error$1("overflow"); } delta += (m - n) * handledCPCountPlusOne; n = m; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = void 0; try { for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _currentValue = _step3.value; if (_currentValue < n && ++delta > maxInt) { error$1("overflow"); } if (_currentValue == n) { var q = delta; for ( var k = base; ; /* no condition */ k += base ) { var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } var qMinusT = q - t; var baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } ++delta; ++n; } return output.join(""); }; var toUnicode = function toUnicode2(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }; var toASCII = function toASCII2(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? "xn--" + encode(string) : string; }); }; var punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ "version": "2.1.0", /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ "ucs2": { "decode": ucs2decode, "encode": ucs2encode }, "decode": decode, "encode": encode, "toASCII": toASCII, "toUnicode": toUnicode }; var SCHEMES = {}; function pctEncChar(chr) { var c = chr.charCodeAt(0); var e = void 0; if (c < 16) e = "%0" + c.toString(16).toUpperCase(); else if (c < 128) e = "%" + c.toString(16).toUpperCase(); else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); return e; } function pctDecChars(str) { var newStr = ""; var i = 0; var il = str.length; while (i < il) { var c = parseInt(str.substr(i + 1, 2), 16); if (c < 128) { newStr += String.fromCharCode(c); i += 3; } else if (c >= 194 && c < 224) { if (il - i >= 6) { var c2 = parseInt(str.substr(i + 4, 2), 16); newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); } else { newStr += str.substr(i, 6); } i += 6; } else if (c >= 224) { if (il - i >= 9) { var _c = parseInt(str.substr(i + 4, 2), 16); var c3 = parseInt(str.substr(i + 7, 2), 16); newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); } else { newStr += str.substr(i, 9); } i += 9; } else { newStr += str.substr(i, 3); i += 3; } } return newStr; } function _normalizeComponentEncoding(components, protocol) { function decodeUnreserved2(str) { var decStr = pctDecChars(str); return !decStr.match(protocol.UNRESERVED) ? str : decStr; } if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, ""); if (components.userinfo !== void 0) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.host !== void 0) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.path !== void 0) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.query !== void 0) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.fragment !== void 0) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); return components; } function _stripLeadingZeros(str) { return str.replace(/^0*(.*)/, "$1") || "0"; } function _normalizeIPv4(host, protocol) { var matches = host.match(protocol.IPV4ADDRESS) || []; var _matches = slicedToArray(matches, 2), address = _matches[1]; if (address) { return address.split(".").map(_stripLeadingZeros).join("."); } else { return host; } } function _normalizeIPv6(host, protocol) { var matches = host.match(protocol.IPV6ADDRESS) || []; var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2]; if (address) { var _address$toLowerCase$ = address.toLowerCase().split("::").reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last = _address$toLowerCase$2[0], first = _address$toLowerCase$2[1]; var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; var lastFields = last.split(":").map(_stripLeadingZeros); var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); var fieldCount = isLastFieldIPv4Address ? 7 : 8; var lastFieldsStart = lastFields.length - fieldCount; var fields = Array(fieldCount); for (var x = 0; x < fieldCount; ++x) { fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ""; } if (isLastFieldIPv4Address) { fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); } var allZeroFields = fields.reduce(function(acc, field, index) { if (!field || field === "0") { var lastLongest = acc[acc.length - 1]; if (lastLongest && lastLongest.index + lastLongest.length === index) { lastLongest.length++; } else { acc.push({ index, length: 1 }); } } return acc; }, []); var longestZeroFields = allZeroFields.sort(function(a, b) { return b.length - a.length; })[0]; var newHost = void 0; if (longestZeroFields && longestZeroFields.length > 1) { var newFirst = fields.slice(0, longestZeroFields.index); var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); newHost = newFirst.join(":") + "::" + newLast.join(":"); } else { newHost = fields.join(":"); } if (zone) { newHost += "%" + zone; } return newHost; } else { return host; } } var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0; function parse(uriString) { var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var components = {}; var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; var matches = uriString.match(URI_PARSE); if (matches) { if (NO_MATCH_IS_UNDEFINED) { components.scheme = matches[1]; components.userinfo = matches[3]; components.host = matches[4]; components.port = parseInt(matches[5], 10); components.path = matches[6] || ""; components.query = matches[7]; components.fragment = matches[8]; if (isNaN(components.port)) { components.port = matches[5]; } } else { components.scheme = matches[1] || void 0; components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : void 0; components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0; components.port = parseInt(matches[5], 10); components.path = matches[6] || ""; components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0; components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : void 0; if (isNaN(components.port)) { components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0; } } if (components.host) { components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); } if (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) { components.reference = "same-document"; } else if (components.scheme === void 0) { components.reference = "relative"; } else if (components.fragment === void 0) { components.reference = "absolute"; } else { components.reference = "uri"; } if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { components.error = components.error || "URI is not a " + options.reference + " reference."; } var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { try { components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); } catch (e) { components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; } } _normalizeComponentEncoding(components, URI_PROTOCOL); } else { _normalizeComponentEncoding(components, protocol); } if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(components, options); } } else { components.error = components.error || "URI can not be parsed."; } return components; } function _recomposeAuthority(components, options) { var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; var uriTokens = []; if (components.userinfo !== void 0) { uriTokens.push(components.userinfo); uriTokens.push("@"); } if (components.host !== void 0) { uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_, $1, $2) { return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; })); } if (typeof components.port === "number" || typeof components.port === "string") { uriTokens.push(":"); uriTokens.push(String(components.port)); } return uriTokens.length ? uriTokens.join("") : void 0; } var RDS1 = /^\.\.?\//; var RDS2 = /^\/\.(\/|$)/; var RDS3 = /^\/\.\.(\/|$)/; var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; function removeDotSegments(input) { var output = []; while (input.length) { if (input.match(RDS1)) { input = input.replace(RDS1, ""); } else if (input.match(RDS2)) { input = input.replace(RDS2, "/"); } else if (input.match(RDS3)) { input = input.replace(RDS3, "/"); output.pop(); } else if (input === "." || input === "..") { input = ""; } else { var im = input.match(RDS5); if (im) { var s = im[0]; input = input.slice(s.length); output.push(s); } else { throw new Error("Unexpected dot segment condition"); } } } return output.join(""); } function serialize(components) { var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; var uriTokens = []; var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); if (components.host) { if (protocol.IPV6ADDRESS.test(components.host)) { } else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { try { components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); } catch (e) { components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; } } } _normalizeComponentEncoding(components, protocol); if (options.reference !== "suffix" && components.scheme) { uriTokens.push(components.scheme); uriTokens.push(":"); } var authority = _recomposeAuthority(components, options); if (authority !== void 0) { if (options.reference !== "suffix") { uriTokens.push("//"); } uriTokens.push(authority); if (components.path && components.path.charAt(0) !== "/") { uriTokens.push("/"); } } if (components.path !== void 0) { var s = components.path; if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s = removeDotSegments(s); } if (authority === void 0) { s = s.replace(/^\/\//, "/%2F"); } uriTokens.push(s); } if (components.query !== void 0) { uriTokens.push("?"); uriTokens.push(components.query); } if (components.fragment !== void 0) { uriTokens.push("#"); uriTokens.push(components.fragment); } return uriTokens.join(""); } function resolveComponents(base2, relative) { var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; var skipNormalization = arguments[3]; var target = {}; if (!skipNormalization) { base2 = parse(serialize(base2, options), options); relative = parse(serialize(relative, options), options); } options = options || {}; if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (!relative.path) { target.path = base2.path; if (relative.query !== void 0) { target.query = relative.query; } else { target.query = base2.query; } } else { if (relative.path.charAt(0) === "/") { target.path = removeDotSegments(relative.path); } else { if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) { target.path = "/" + relative.path; } else if (!base2.path) { target.path = relative.path; } else { target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative.path; } target.path = removeDotSegments(target.path); } target.query = relative.query; } target.userinfo = base2.userinfo; target.host = base2.host; target.port = base2.port; } target.scheme = base2.scheme; } target.fragment = relative.fragment; return target; } function resolve(baseURI, relativeURI, options) { var schemelessOptions = assign({ scheme: "null" }, options); return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); } function normalize(uri, options) { if (typeof uri === "string") { uri = serialize(parse(uri, options), options); } else if (typeOf(uri) === "object") { uri = parse(serialize(uri, options), options); } return uri; } function equal(uriA, uriB, options) { if (typeof uriA === "string") { uriA = serialize(parse(uriA, options), options); } else if (typeOf(uriA) === "object") { uriA = serialize(uriA, options); } if (typeof uriB === "string") { uriB = serialize(parse(uriB, options), options); } else if (typeOf(uriB) === "object") { uriB = serialize(uriB, options); } return uriA === uriB; } function escapeComponent(str, options) { return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); } function unescapeComponent(str, options) { return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); } var handler = { scheme: "http", domainHost: true, parse: function parse2(components, options) { if (!components.host) { components.error = components.error || "HTTP URIs must have a host."; } return components; }, serialize: function serialize2(components, options) { var secure = String(components.scheme).toLowerCase() === "https"; if (components.port === (secure ? 443 : 80) || components.port === "") { components.port = void 0; } if (!components.path) { components.path = "/"; } return components; } }; var handler$1 = { scheme: "https", domainHost: handler.domainHost, parse: handler.parse, serialize: handler.serialize }; function isSecure(wsComponents) { return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; } var handler$2 = { scheme: "ws", domainHost: true, parse: function parse2(components, options) { var wsComponents = components; wsComponents.secure = isSecure(wsComponents); wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : ""); wsComponents.path = void 0; wsComponents.query = void 0; return wsComponents; }, serialize: function serialize2(wsComponents, options) { if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { wsComponents.port = void 0; } if (typeof wsComponents.secure === "boolean") { wsComponents.scheme = wsComponents.secure ? "wss" : "ws"; wsComponents.secure = void 0; } if (wsComponents.resourceName) { var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1]; wsComponents.path = path && path !== "/" ? path : void 0; wsComponents.query = query; wsComponents.resourceName = void 0; } wsComponents.fragment = void 0; return wsComponents; } }; var handler$3 = { scheme: "wss", domainHost: handler$2.domainHost, parse: handler$2.parse, serialize: handler$2.serialize }; var O = {}; var isIRI = true; var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; var HEXDIG$$ = "[0-9A-Fa-f]"; var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; var VCHAR$$ = merge(QTEXT$$, '[\\"\\\\]'); var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; var UNRESERVED = new RegExp(UNRESERVED$$, "g"); var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); var NOT_HFVALUE = NOT_HFNAME; function decodeUnreserved(str) { var decStr = pctDecChars(str); return !decStr.match(UNRESERVED) ? str : decStr; } var handler$4 = { scheme: "mailto", parse: function parse$$1(components, options) { var mailtoComponents = components; var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; mailtoComponents.path = void 0; if (mailtoComponents.query) { var unknownHeaders = false; var headers = {}; var hfields = mailtoComponents.query.split("&"); for (var x = 0, xl = hfields.length; x < xl; ++x) { var hfield = hfields[x].split("="); switch (hfield[0]) { case "to": var toAddrs = hfield[1].split(","); for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { to.push(toAddrs[_x]); } break; case "subject": mailtoComponents.subject = unescapeComponent(hfield[1], options); break; case "body": mailtoComponents.body = unescapeComponent(hfield[1], options); break; default: unknownHeaders = true; headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); break; } } if (unknownHeaders) mailtoComponents.headers = headers; } mailtoComponents.query = void 0; for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { var addr = to[_x2].split("@"); addr[0] = unescapeComponent(addr[0]); if (!options.unicodeSupport) { try { addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); } catch (e) { mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; } } else { addr[1] = unescapeComponent(addr[1], options).toLowerCase(); } to[_x2] = addr.join("@"); } return mailtoComponents; }, serialize: function serialize$$1(mailtoComponents, options) { var components = mailtoComponents; var to = toArray(mailtoComponents.to); if (to) { for (var x = 0, xl = to.length; x < xl; ++x) { var toAddr = String(to[x]); var atIdx = toAddr.lastIndexOf("@"); var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); var domain = toAddr.slice(atIdx + 1); try { domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); } catch (e) { components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; } to[x] = localPart + "@" + domain; } components.path = to.join(","); } var headers = mailtoComponents.headers = mailtoComponents.headers || {}; if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; if (mailtoComponents.body) headers["body"] = mailtoComponents.body; var fields = []; for (var name in headers) { if (headers[name] !== O[name]) { fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); } } if (fields.length) { components.query = fields.join("&"); } return components; } }; var URN_PARSE = /^([^\:]+)\:(.*)/; var handler$5 = { scheme: "urn", parse: function parse$$1(components, options) { var matches = components.path && components.path.match(URN_PARSE); var urnComponents = components; if (matches) { var scheme = options.scheme || urnComponents.scheme || "urn"; var nid = matches[1].toLowerCase(); var nss = matches[2]; var urnScheme = scheme + ":" + (options.nid || nid); var schemeHandler = SCHEMES[urnScheme]; urnComponents.nid = nid; urnComponents.nss = nss; urnComponents.path = void 0; if (schemeHandler) { urnComponents = schemeHandler.parse(urnComponents, options); } } else { urnComponents.error = urnComponents.error || "URN can not be parsed."; } return urnComponents; }, serialize: function serialize$$1(urnComponents, options) { var scheme = options.scheme || urnComponents.scheme || "urn"; var nid = urnComponents.nid; var urnScheme = scheme + ":" + (options.nid || nid); var schemeHandler = SCHEMES[urnScheme]; if (schemeHandler) { urnComponents = schemeHandler.serialize(urnComponents, options); } var uriComponents = urnComponents; var nss = urnComponents.nss; uriComponents.path = (nid || options.nid) + ":" + nss; return uriComponents; } }; var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; var handler$6 = { scheme: "urn:uuid", parse: function parse2(urnComponents, options) { var uuidComponents = urnComponents; uuidComponents.uuid = uuidComponents.nss; uuidComponents.nss = void 0; if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { uuidComponents.error = uuidComponents.error || "UUID is not valid."; } return uuidComponents; }, serialize: function serialize2(uuidComponents, options) { var urnComponents = uuidComponents; urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); return urnComponents; } }; SCHEMES[handler.scheme] = handler; SCHEMES[handler$1.scheme] = handler$1; SCHEMES[handler$2.scheme] = handler$2; SCHEMES[handler$3.scheme] = handler$3; SCHEMES[handler$4.scheme] = handler$4; SCHEMES[handler$5.scheme] = handler$5; SCHEMES[handler$6.scheme] = handler$6; exports2.SCHEMES = SCHEMES; exports2.pctEncChar = pctEncChar; exports2.pctDecChars = pctDecChars; exports2.parse = parse; exports2.removeDotSegments = removeDotSegments; exports2.serialize = serialize; exports2.resolveComponents = resolveComponents; exports2.resolve = resolve; exports2.normalize = normalize; exports2.equal = equal; exports2.escapeComponent = escapeComponent; exports2.unescapeComponent = unescapeComponent; Object.defineProperty(exports2, "__esModule", { value: true }); }); } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/uri.js var require_uri = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/uri.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var uri = require_uri_all(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports.default = uri; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/core.js var require_core = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/core.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; var validate_1 = require_validate(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); var ref_error_1 = require_ref_error(); var rules_1 = require_rules(); var compile_1 = require_compile(); var codegen_2 = require_codegen(); var resolve_1 = require_resolve(); var dataType_1 = require_dataType(); var util_1 = require_util(); var $dataRefSchema = require_data(); var uri_1 = require_uri(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = {}; this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; } validate(schemaKeyRef, data) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv.ValidationError = validation_error_1.default; Ajv.MissingRefError = ref_error_1.default; exports.default = Ajv; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/core/id.js var require_id = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/core/ref.js var require_ref = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.callRef = exports.getValidate = void 0; var ref_error_1 = require_ref_error(); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var compile_1 = require_compile(); var util_1 = require_util(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a; if (!it.opts.unevaluated) return; const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports.callRef = callRef; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/core/index.js var require_core2 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var id_1 = require_id(); var ref_1 = require_ref(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports.default = core; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error, code(cxt) { const { data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/required.js var require_required = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); var error = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/equal.js var require_equal = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/runtime/equal.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var equal = require_fast_deep_equal(); equal.code = 'require("ajv/dist/runtime/equal").default'; exports.default = equal; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var dataType_1 = require_dataType(); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._)`${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/const.js var require_const = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/index.js var require_validation2 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber(); var multipleOf_1 = require_multipleOf(); var limitLength_1 = require_limitLength(); var pattern_1 = require_pattern(); var limitProperties_1 = require_limitProperties(); var required_1 = require_required(); var limitItems_1 = require_limitItems(); var uniqueItems_1 = require_uniqueItems(); var const_1 = require_const(); var enum_1 = require_enum(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports.default = validation; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var error = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports.validateAdditionalItems = validateAdditionalItems; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/items.js var require_items = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateTuple = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports.validateTuple = validateTuple; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = require_items(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items2020 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); var error = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === void 0 ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max }); if (max === void 0 && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== void 0 && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); exports.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports.validateSchemaDeps = validateSchemaDeps; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); var error = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var validate_1 = require_validate(); var code_1 = require_code2(); var util_1 = require_util(); var additionalProperties_1 = require_additionalProperties(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); var util_2 = require_util(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/not.js var require_not = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true }, schValid); } if (i > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/if.js var require_if = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); } exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems(); var prefixItems_1 = require_prefixItems(); var items_1 = require_items(); var items2020_1 = require_items2020(); var contains_1 = require_contains(); var dependencies_1 = require_dependencies(); var propertyNames_1 = require_propertyNames(); var additionalProperties_1 = require_additionalProperties(); var properties_1 = require_properties(); var patternProperties_1 = require_patternProperties(); var not_1 = require_not(); var anyOf_1 = require_anyOf(); var oneOf_1 = require_oneOf(); var allOf_1 = require_allOf(); var if_1 = require_if(); var thenElse_1 = require_thenElse(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports.default = getApplicator; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/format/format.js var require_format = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/format/index.js var require_format2 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var format_1 = require_format(); var format = [format_1.default]; exports.default = format; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/metadata.js var require_metadata = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.contentVocabulary = exports.metadataVocabulary = void 0; exports.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/draft7.js var require_draft7 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require_core2(); var validation_1 = require_validation2(); var applicator_1 = require_applicator(); var format_1 = require_format2(); var metadata_1 = require_metadata(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports.default = draft7Vocabularies; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports.DiscrError = DiscrError = {})); } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var types_1 = require_types(); var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); var error = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required }) { return Array.isArray(required) && required.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } } }; exports.default = def; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_07 = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module2) { module2.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/fast-json-stringify/node_modules/ajv/dist/ajv.js var require_ajv = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv/dist/ajv.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; var core_1 = require_core(); var draft7_1 = require_draft7(); var discriminator_1 = require_discriminator(); var draft7MetaSchema = require_json_schema_draft_07(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports.Ajv = Ajv; module2.exports = exports = Ajv; module2.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv; var validate_1 = require_validate(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error(); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/fast-uri/lib/scopedChars.js var require_scopedChars = __commonJS({ "node_modules/fast-uri/lib/scopedChars.js"(exports, module2) { "use strict"; var HEX = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, a: 10, A: 10, b: 11, B: 11, c: 12, C: 12, d: 13, D: 13, e: 14, E: 14, f: 15, F: 15 }; module2.exports = { HEX }; } }); // node_modules/fast-uri/lib/utils.js var require_utils = __commonJS({ "node_modules/fast-uri/lib/utils.js"(exports, module2) { "use strict"; var { HEX } = require_scopedChars(); function normalizeIPv4(host) { if (findToken(host, ".") < 3) { return { host, isIPV4: false }; } const matches = host.match(/^(\b[01]?\d{1,2}|\b2[0-4]\d|\b25[0-5])(\.([01]?\d{1,2}|2[0-4]\d|25[0-5])){3}$/u) || []; const [address] = matches; if (address) { return { host: stripLeadingZeros(address, "."), isIPV4: true }; } else { return { host, isIPV4: false }; } } function stringToHexStripped(input) { let acc = ""; let strip = true; for (const c of input) { if (c !== "0" && strip === true) strip = false; if (HEX[c] === void 0) return void 0; if (!strip) acc += c; } return acc; } function getIPV6(input) { let tokenCount = 0; const output = { error: false, address: "", zone: "" }; const address = []; const buffer = []; let isZone = false; let endipv6Encountered = false; let endIpv6 = false; function consume() { if (buffer.length) { if (isZone === false) { const hex = stringToHexStripped(buffer.join("")); if (hex !== void 0) { address.push(hex); } else { output.error = true; return false; } } buffer.length = 0; } return true; } for (let i = 0; i < input.length; i++) { const cursor = input[i]; if (cursor === "[" || cursor === "]") { continue; } if (cursor === ":") { if (endipv6Encountered === true) { endIpv6 = true; } if (!consume()) { break; } tokenCount++; address.push(":"); if (tokenCount > 7) { output.error = true; break; } if (i - 1 >= 0 && input[i - 1] === ":") { endipv6Encountered = true; } continue; } else if (cursor === "%") { if (!consume()) { break; } isZone = true; } else { buffer.push(cursor); continue; } } if (buffer.length) { if (isZone) { output.zone = buffer.join(""); } else if (endIpv6) { address.push(buffer.join("")); } else { address.push(stringToHexStripped(buffer.join(""))); } } output.address = address.join(""); return output; } function normalizeIPv6(host, opts = {}) { if (findToken(host, ":") < 2) { return { host, isIPV6: false }; } const ipv6 = getIPV6(host); if (!ipv6.error) { let newHost = ipv6.address; let escapedHost = ipv6.address; if (ipv6.zone) { newHost += "%" + ipv6.zone; escapedHost += "%25" + ipv6.zone; } return { host: newHost, escapedHost, isIPV6: true }; } else { return { host, isIPV6: false }; } } function stripLeadingZeros(str, token) { let out = ""; let skip = true; const l = str.length; for (let i = 0; i < l; i++) { const c = str[i]; if (c === "0" && skip) { if (i + 1 <= l && str[i + 1] === token || i + 1 === l) { out += c; skip = false; } } else { if (c === token) { skip = true; } else { skip = false; } out += c; } } return out; } function findToken(str, token) { let ind = 0; for (let i = 0; i < str.length; i++) { if (str[i] === token) ind++; } return ind; } var RDS1 = /^\.\.?\//u; var RDS2 = /^\/\.(?:\/|$)/u; var RDS3 = /^\/\.\.(?:\/|$)/u; var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u; function removeDotSegments(input) { const output = []; while (input.length) { if (input.match(RDS1)) { input = input.replace(RDS1, ""); } else if (input.match(RDS2)) { input = input.replace(RDS2, "/"); } else if (input.match(RDS3)) { input = input.replace(RDS3, "/"); output.pop(); } else if (input === "." || input === "..") { input = ""; } else { const im = input.match(RDS5); if (im) { const s = im[0]; input = input.slice(s.length); output.push(s); } else { throw new Error("Unexpected dot segment condition"); } } } return output.join(""); } function normalizeComponentEncoding(components, esc) { const func = esc !== true ? escape : unescape; if (components.scheme !== void 0) { components.scheme = func(components.scheme); } if (components.userinfo !== void 0) { components.userinfo = func(components.userinfo); } if (components.host !== void 0) { components.host = func(components.host); } if (components.path !== void 0) { components.path = func(components.path); } if (components.query !== void 0) { components.query = func(components.query); } if (components.fragment !== void 0) { components.fragment = func(components.fragment); } return components; } function recomposeAuthority(components, options) { const uriTokens = []; if (components.userinfo !== void 0) { uriTokens.push(components.userinfo); uriTokens.push("@"); } if (components.host !== void 0) { let host = unescape(components.host); const ipV4res = normalizeIPv4(host); if (ipV4res.isIPV4) { host = ipV4res.host; } else { const ipV6res = normalizeIPv6(ipV4res.host, { isIPV4: false }); if (ipV6res.isIPV6 === true) { host = `[${ipV6res.escapedHost}]`; } else { host = components.host; } } uriTokens.push(host); } if (typeof components.port === "number" || typeof components.port === "string") { uriTokens.push(":"); uriTokens.push(String(components.port)); } return uriTokens.length ? uriTokens.join("") : void 0; } module2.exports = { recomposeAuthority, normalizeComponentEncoding, removeDotSegments, normalizeIPv4, normalizeIPv6, stringToHexStripped }; } }); // node_modules/fast-uri/lib/schemes.js var require_schemes = __commonJS({ "node_modules/fast-uri/lib/schemes.js"(exports, module2) { "use strict"; var UUID_REG = /^[\da-f]{8}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{12}$/iu; var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; function isSecure(wsComponents) { return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; } function httpParse(components) { if (!components.host) { components.error = components.error || "HTTP URIs must have a host."; } return components; } function httpSerialize(components) { const secure = String(components.scheme).toLowerCase() === "https"; if (components.port === (secure ? 443 : 80) || components.port === "") { components.port = void 0; } if (!components.path) { components.path = "/"; } return components; } function wsParse(wsComponents) { wsComponents.secure = isSecure(wsComponents); wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : ""); wsComponents.path = void 0; wsComponents.query = void 0; return wsComponents; } function wsSerialize(wsComponents) { if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { wsComponents.port = void 0; } if (typeof wsComponents.secure === "boolean") { wsComponents.scheme = wsComponents.secure ? "wss" : "ws"; wsComponents.secure = void 0; } if (wsComponents.resourceName) { const [path, query] = wsComponents.resourceName.split("?"); wsComponents.path = path && path !== "/" ? path : void 0; wsComponents.query = query; wsComponents.resourceName = void 0; } wsComponents.fragment = void 0; return wsComponents; } function urnParse(urnComponents, options) { if (!urnComponents.path) { urnComponents.error = "URN can not be parsed"; return urnComponents; } const matches = urnComponents.path.match(URN_REG); if (matches) { const scheme = options.scheme || urnComponents.scheme || "urn"; urnComponents.nid = matches[1].toLowerCase(); urnComponents.nss = matches[2]; const urnScheme = `${scheme}:${options.nid || urnComponents.nid}`; const schemeHandler = SCHEMES[urnScheme]; urnComponents.path = void 0; if (schemeHandler) { urnComponents = schemeHandler.parse(urnComponents, options); } } else { urnComponents.error = urnComponents.error || "URN can not be parsed."; } return urnComponents; } function urnSerialize(urnComponents, options) { const scheme = options.scheme || urnComponents.scheme || "urn"; const nid = urnComponents.nid.toLowerCase(); const urnScheme = `${scheme}:${options.nid || nid}`; const schemeHandler = SCHEMES[urnScheme]; if (schemeHandler) { urnComponents = schemeHandler.serialize(urnComponents, options); } const uriComponents = urnComponents; const nss = urnComponents.nss; uriComponents.path = `${nid || options.nid}:${nss}`; options.skipEscape = true; return uriComponents; } function urnuuidParse(urnComponents, options) { const uuidComponents = urnComponents; uuidComponents.uuid = uuidComponents.nss; uuidComponents.nss = void 0; if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) { uuidComponents.error = uuidComponents.error || "UUID is not valid."; } return uuidComponents; } function urnuuidSerialize(uuidComponents) { const urnComponents = uuidComponents; urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); return urnComponents; } var http = { scheme: "http", domainHost: true, parse: httpParse, serialize: httpSerialize }; var https = { scheme: "https", domainHost: http.domainHost, parse: httpParse, serialize: httpSerialize }; var ws = { scheme: "ws", domainHost: true, parse: wsParse, serialize: wsSerialize }; var wss = { scheme: "wss", domainHost: ws.domainHost, parse: ws.parse, serialize: ws.serialize }; var urn = { scheme: "urn", parse: urnParse, serialize: urnSerialize, skipNormalize: true }; var urnuuid = { scheme: "urn:uuid", parse: urnuuidParse, serialize: urnuuidSerialize, skipNormalize: true }; var SCHEMES = { http, https, ws, wss, urn, "urn:uuid": urnuuid }; module2.exports = SCHEMES; } }); // node_modules/fast-uri/index.js var require_fast_uri = __commonJS({ "node_modules/fast-uri/index.js"(exports, module2) { "use strict"; var { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require_utils(); var SCHEMES = require_schemes(); function normalize(uri, options) { if (typeof uri === "string") { uri = serialize(parse(uri, options), options); } else if (typeof uri === "object") { uri = parse(serialize(uri, options), options); } return uri; } function resolve(baseURI, relativeURI, options) { const schemelessOptions = Object.assign({ scheme: "null" }, options); const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); return serialize(resolved, { ...schemelessOptions, skipEscape: true }); } function resolveComponents(base, relative, options, skipNormalization) { const target = {}; if (!skipNormalization) { base = parse(serialize(base, options), options); relative = parse(serialize(relative, options), options); } options = options || {}; if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (!relative.path) { target.path = base.path; if (relative.query !== void 0) { target.query = relative.query; } else { target.query = base.query; } } else { if (relative.path.charAt(0) === "/") { target.path = removeDotSegments(relative.path); } else { if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { target.path = "/" + relative.path; } else if (!base.path) { target.path = relative.path; } else { target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; } target.path = removeDotSegments(target.path); } target.query = relative.query; } target.userinfo = base.userinfo; target.host = base.host; target.port = base.port; } target.scheme = base.scheme; } target.fragment = relative.fragment; return target; } function equal(uriA, uriB, options) { if (typeof uriA === "string") { uriA = unescape(uriA); uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true }); } else if (typeof uriA === "object") { uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); } if (typeof uriB === "string") { uriB = unescape(uriB); uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true }); } else if (typeof uriB === "object") { uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); } return uriA.toLowerCase() === uriB.toLowerCase(); } function serialize(cmpts, opts) { const components = { host: cmpts.host, scheme: cmpts.scheme, userinfo: cmpts.userinfo, port: cmpts.port, path: cmpts.path, query: cmpts.query, nid: cmpts.nid, nss: cmpts.nss, uuid: cmpts.uuid, fragment: cmpts.fragment, reference: cmpts.reference, resourceName: cmpts.resourceName, secure: cmpts.secure, error: "" }; const options = Object.assign({}, opts); const uriTokens = []; const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); if (components.path !== void 0) { if (!options.skipEscape) { components.path = escape(components.path); if (components.scheme !== void 0) { components.path = components.path.split("%3A").join(":"); } } else { components.path = unescape(components.path); } } if (options.reference !== "suffix" && components.scheme) { uriTokens.push(components.scheme); uriTokens.push(":"); } const authority = recomposeAuthority(components, options); if (authority !== void 0) { if (options.reference !== "suffix") { uriTokens.push("//"); } uriTokens.push(authority); if (components.path && components.path.charAt(0) !== "/") { uriTokens.push("/"); } } if (components.path !== void 0) { let s = components.path; if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s = removeDotSegments(s); } if (authority === void 0) { s = s.replace(/^\/\//u, "/%2F"); } uriTokens.push(s); } if (components.query !== void 0) { uriTokens.push("?"); uriTokens.push(components.query); } if (components.fragment !== void 0) { uriTokens.push("#"); uriTokens.push(components.fragment); } return uriTokens.join(""); } var hexLookUp = Array.from({ length: 127 }, (v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k))); function nonSimpleDomain(value) { let code = 0; for (let i = 0, len = value.length; i < len; ++i) { code = value.charCodeAt(i); if (code > 126 || hexLookUp[code]) { return true; } } return false; } var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; function parse(uri, opts) { const options = Object.assign({}, opts); const parsed = { scheme: void 0, userinfo: void 0, host: "", port: void 0, path: "", query: void 0, fragment: void 0 }; const gotEncoding = uri.indexOf("%") !== -1; if (options.reference === "suffix") uri = (options.scheme ? options.scheme + ":" : "") + "//" + uri; const matches = uri.match(URI_PARSE); if (matches) { parsed.scheme = matches[1]; parsed.userinfo = matches[3]; parsed.host = matches[4]; parsed.port = parseInt(matches[5], 10); parsed.path = matches[6] || ""; parsed.query = matches[7]; parsed.fragment = matches[8]; if (isNaN(parsed.port)) { parsed.port = matches[5]; } if (parsed.host) { const ipv4result = normalizeIPv4(parsed.host); if (ipv4result.isIPV4 === false) { parsed.host = normalizeIPv6(ipv4result.host, { isIPV4: false }).host.toLowerCase(); } else { parsed.host = ipv4result.host; } } if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && !parsed.path && parsed.query === void 0) { parsed.reference = "same-document"; } else if (parsed.scheme === void 0) { parsed.reference = "relative"; } else if (parsed.fragment === void 0) { parsed.reference = "absolute"; } else { parsed.reference = "uri"; } if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; } const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || "").toLowerCase()]; if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && nonSimpleDomain(parsed.host)) { try { parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); } catch (e) { parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; } } } if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { if (gotEncoding && parsed.scheme !== void 0) { parsed.scheme = unescape(parsed.scheme); } if (gotEncoding && parsed.userinfo !== void 0) { parsed.userinfo = unescape(parsed.userinfo); } if (gotEncoding && parsed.host !== void 0) { parsed.host = unescape(parsed.host); } if (parsed.path !== void 0 && parsed.path.length) { parsed.path = escape(unescape(parsed.path)); } if (parsed.fragment !== void 0 && parsed.fragment.length) { parsed.fragment = encodeURI(decodeURI(parsed.fragment)); } } if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(parsed, options); } } else { parsed.error = parsed.error || "URI can not be parsed."; } return parsed; } var fastUri = { normalize, resolve, resolveComponents, equal, serialize, parse }; module2.exports = fastUri; module2.exports.default = fastUri; module2.exports.fastUri = fastUri; } }); // node_modules/fast-json-stringify/node_modules/ajv-formats/dist/formats.js var require_formats = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv-formats/dist/formats.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; function fmtDef(validate, compare) { return { validate, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true }; exports.fastFormats = { ...exports.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i }; exports.formatNames = Object.keys(exports.fullFormats); function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date(str) { const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); } function compareDate(d1, d2) { if (!(d1 && d2)) return void 0; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; function getTime(strictTimeZone) { return function time(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tz = matches[4]; const tzSign = matches[5] === "-" ? -1 : 1; const tzH = +(matches[6] || 0); const tzM = +(matches[7] || 0); if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; if (hr <= 23 && min <= 59 && sec < 60) return true; const utcMin = min - tzM * tzSign; const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; }; } function compareTime(s1, s2) { if (!(s1 && s2)) return void 0; const t1 = new Date("2020-01-01T" + s1).valueOf(); const t2 = new Date("2020-01-01T" + s2).valueOf(); if (!(t1 && t2)) return void 0; return t1 - t2; } function compareIsoTime(t1, t2) { if (!(t1 && t2)) return void 0; const a1 = TIME.exec(t1); const a2 = TIME.exec(t2); if (!(a1 && a2)) return void 0; t1 = a1[1] + a1[2] + a1[3]; t2 = a2[1] + a2[2] + a2[3]; if (t1 > t2) return 1; if (t1 < t2) return -1; return 0; } var DATE_TIME_SEPARATOR = /t|\s/i; function getDateTime(strictTimeZone) { const time = getTime(strictTimeZone); return function date_time(str) { const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); }; } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const d1 = new Date(dt1).valueOf(); const d2 = new Date(dt2).valueOf(); if (!(d1 && d2)) return void 0; return d1 - d2; } function compareIsoDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === void 0) return void 0; return res || compareTime(t1, t2); } var NOT_URI_FRAGMENT = /\/|:/; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } var MIN_INT32 = -(2 ** 31); var MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { return Number.isInteger(value); } function validateNumber() { return true; } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e) { return false; } } } }); // node_modules/fast-json-stringify/node_modules/ajv-formats/dist/limit.js var require_limit = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv-formats/dist/limit.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatLimitDefinition = void 0; var ajv_1 = require_ajv(); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; exports.formatLimitDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self } = it; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 }); cxt.fail$data(compareCode(fmt)); } function compareCode(fmt) { return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"] }; var formatLimitPlugin = (ajv) => { ajv.addKeyword(exports.formatLimitDefinition); return ajv; }; exports.default = formatLimitPlugin; } }); // node_modules/fast-json-stringify/node_modules/ajv-formats/dist/index.js var require_dist = __commonJS({ "node_modules/fast-json-stringify/node_modules/ajv-formats/dist/index.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var formats_1 = require_formats(); var limit_1 = require_limit(); var codegen_1 = require_codegen(); var fullName = new codegen_1.Name("fullFormats"); var fastName = new codegen_1.Name("fastFormats"); var formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) (0, limit_1.default)(ajv); return ajv; }; formatsPlugin.get = (name, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f = formats[name]; if (!f) throw new Error(`Unknown format "${name}"`); return f; }; function addFormats(ajv, list, fs, exportName) { var _a; var _b; (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) ajv.addFormat(f, fs[f]); } module2.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = formatsPlugin; } }); // node_modules/fast-json-stringify/lib/validator.js var require_validator2 = __commonJS({ "node_modules/fast-json-stringify/lib/validator.js"(exports, module2) { "use strict"; var Ajv = require_ajv(); var fastUri = require_fast_uri(); var ajvFormats = require_dist(); var clone = require_rfdc()({ proto: true }); var Validator = class { constructor(ajvOptions) { this.ajv = new Ajv({ ...ajvOptions, strictSchema: false, validateSchema: false, allowUnionTypes: true, uriResolver: fastUri }); ajvFormats(this.ajv); this.ajv.addKeyword({ keyword: "fjs_type", type: "object", errors: false, validate: (type, date) => { return date instanceof Date; } }); this._ajvSchemas = {}; this._ajvOptions = ajvOptions || {}; } addSchema(schema, schemaName) { let schemaKey = schema.$id || schemaName; if (schema.$id !== void 0 && schema.$id[0] === "#") { schemaKey = schemaName + schema.$id; } if (this.ajv.refs[schemaKey] === void 0 && this.ajv.schemas[schemaKey] === void 0) { const ajvSchema = clone(schema); this.convertSchemaToAjvFormat(ajvSchema); this.ajv.addSchema(ajvSchema, schemaKey); this._ajvSchemas[schemaKey] = schema; } } validate(schemaRef, data) { return this.ajv.validate(schemaRef, data); } // Ajv does not support js date format. In order to properly validate objects containing a date, // it needs to replace all occurrences of the string date format with a custom keyword fjs_type. // (see https://github.com/fastify/fast-json-stringify/pull/441) convertSchemaToAjvFormat(schema) { if (schema === null) return; if (schema.type === "string") { schema.fjs_type = "string"; schema.type = ["string", "object"]; } else if (Array.isArray(schema.type) && schema.type.includes("string") && !schema.type.includes("object")) { schema.fjs_type = "string"; schema.type.push("object"); } for (const property in schema) { if (typeof schema[property] === "object") { this.convertSchemaToAjvFormat(schema[property]); } } } getState() { return { ajvOptions: this._ajvOptions, ajvSchemas: this._ajvSchemas }; } static restoreFromState(state) { const validator = new Validator(state.ajvOptions); for (const [id, ajvSchema] of Object.entries(state.ajvSchemas)) { validator.ajv.addSchema(ajvSchema, id); } return validator; } }; module2.exports = Validator; } }); // node_modules/fast-json-stringify/lib/location.js var require_location = __commonJS({ "node_modules/fast-json-stringify/lib/location.js"(exports, module2) { "use strict"; var Location = class { constructor(schema, schemaId, jsonPointer = "#") { this.schema = schema; this.schemaId = schemaId; this.jsonPointer = jsonPointer; } getPropertyLocation(propertyName) { const propertyLocation = new Location( this.schema[propertyName], this.schemaId, this.jsonPointer + "/" + propertyName ); return propertyLocation; } getSchemaRef() { return this.schemaId + this.jsonPointer; } }; module2.exports = Location; } }); // node_modules/fast-json-stringify/lib/schema-validator.js var require_schema_validator = __commonJS({ "node_modules/fast-json-stringify/lib/schema-validator.js"(exports, module2) { "use strict"; module2.exports = validate10; module2.exports.default = validate10; var schema11 = { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://json-schema.org/draft-07/schema#", "title": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": { "$ref": "#" } }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": { "type": "string" }, "uniqueItems": true, "default": [] } }, "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "$comment": { "type": "string" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "readOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "pattern": { "type": "string", "format": "regex" }, "additionalItems": { "$ref": "#" }, "items": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], "default": true }, "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "uniqueItems": { "type": "boolean", "default": false }, "contains": { "$ref": "#" }, "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "required": { "$ref": "#/definitions/stringArray" }, "additionalProperties": { "$ref": "#" }, "definitions": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "properties": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": { "$ref": "#" }, "propertyNames": { "format": "regex" }, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } }, "propertyNames": { "$ref": "#" }, "const": true, "enum": { "type": "array", "items": true, "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { "type": "array", "items": { "$ref": "#/definitions/simpleTypes" }, "minItems": 1, "uniqueItems": true }] }, "format": { "type": "string" }, "contentMediaType": { "type": "string" }, "contentEncoding": { "type": "string" }, "if": { "$ref": "#" }, "then": { "$ref": "#" }, "else": { "$ref": "#" }, "allOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" }, "oneOf": { "$ref": "#/definitions/schemaArray" }, "not": { "$ref": "#" } }, "default": true }; var schema20 = { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }; var formats0 = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; var formats2 = require_formats().fullFormats.uri; var formats6 = require_formats().fullFormats.regex; function validate11(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { let vErrors = null; let errors = 0; const _errs1 = errors; if (!(typeof data == "number" && (!(data % 1) && !isNaN(data)) && isFinite(data))) { validate11.errors = [{ instancePath, schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } if (errors === _errs1) { if (typeof data == "number" && isFinite(data)) { if (data < 0 || isNaN(data)) { validate11.errors = [{ instancePath, schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; return false; } } } validate11.errors = vErrors; return errors === 0; } var root1 = { validate: validate10 }; function validate13(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { let vErrors = null; let errors = 0; if (errors === 0) { if (Array.isArray(data)) { if (data.length < 1) { validate13.errors = [{ instancePath, schemaPath: "#/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid0 = true; const len0 = data.length; for (let i0 = 0; i0 < len0; i0++) { const _errs1 = errors; if (!root1.validate(data[i0], { instancePath: instancePath + "/" + i0, parentData: data, parentDataProperty: i0, rootData })) { vErrors = vErrors === null ? root1.validate.errors : vErrors.concat(root1.validate.errors); errors = vErrors.length; } var valid0 = _errs1 === errors; if (!valid0) { break; } } } } else { validate13.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } validate13.errors = vErrors; return errors === 0; } var func0 = require_equal().default; function validate10(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { ; let vErrors = null; let errors = 0; if (!(data && typeof data == "object" && !Array.isArray(data)) && typeof data !== "boolean") { validate10.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema11.type }, message: "must be object,boolean" }]; return false; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.$id !== void 0) { let data0 = data.$id; const _errs1 = errors; if (errors === _errs1) { if (errors === _errs1) { if (typeof data0 === "string") { if (!formats0.test(data0)) { validate10.errors = [{ instancePath: instancePath + "/$id", schemaPath: "#/properties/%24id/format", keyword: "format", params: { format: "uri-reference" }, message: 'must match format "uri-reference"' }]; return false; } } else { validate10.errors = [{ instancePath: instancePath + "/$id", schemaPath: "#/properties/%24id/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } } var valid0 = _errs1 === errors; } else { var valid0 = true; } if (valid0) { if (data.$schema !== void 0) { let data1 = data.$schema; const _errs3 = errors; if (errors === _errs3) { if (errors === _errs3) { if (typeof data1 === "string") { if (!formats2(data1)) { validate10.errors = [{ instancePath: instancePath + "/$schema", schemaPath: "#/properties/%24schema/format", keyword: "format", params: { format: "uri" }, message: 'must match format "uri"' }]; return false; } } else { validate10.errors = [{ instancePath: instancePath + "/$schema", schemaPath: "#/properties/%24schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } } var valid0 = _errs3 === errors; } else { var valid0 = true; } if (valid0) { if (data.$ref !== void 0) { let data2 = data.$ref; const _errs5 = errors; if (errors === _errs5) { if (errors === _errs5) { if (typeof data2 === "string") { if (!formats0.test(data2)) { validate10.errors = [{ instancePath: instancePath + "/$ref", schemaPath: "#/properties/%24ref/format", keyword: "format", params: { format: "uri-reference" }, message: 'must match format "uri-reference"' }]; return false; } } else { validate10.errors = [{ instancePath: instancePath + "/$ref", schemaPath: "#/properties/%24ref/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } } var valid0 = _errs5 === errors; } else { var valid0 = true; } if (valid0) { if (data.$comment !== void 0) { const _errs7 = errors; if (typeof data.$comment !== "string") { validate10.errors = [{ instancePath: instancePath + "/$comment", schemaPath: "#/properties/%24comment/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs7 === errors; } else { var valid0 = true; } if (valid0) { if (data.title !== void 0) { const _errs9 = errors; if (typeof data.title !== "string") { validate10.errors = [{ instancePath: instancePath + "/title", schemaPath: "#/properties/title/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs9 === errors; } else { var valid0 = true; } if (valid0) { if (data.description !== void 0) { const _errs11 = errors; if (typeof data.description !== "string") { validate10.errors = [{ instancePath: instancePath + "/description", schemaPath: "#/properties/description/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs11 === errors; } else { var valid0 = true; } if (valid0) { if (data.readOnly !== void 0) { const _errs13 = errors; if (typeof data.readOnly !== "boolean") { validate10.errors = [{ instancePath: instancePath + "/readOnly", schemaPath: "#/properties/readOnly/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid0 = _errs13 === errors; } else { var valid0 = true; } if (valid0) { if (data.examples !== void 0) { const _errs15 = errors; if (errors === _errs15) { if (!Array.isArray(data.examples)) { validate10.errors = [{ instancePath: instancePath + "/examples", schemaPath: "#/properties/examples/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid0 = _errs15 === errors; } else { var valid0 = true; } if (valid0) { if (data.multipleOf !== void 0) { let data8 = data.multipleOf; const _errs17 = errors; if (errors === _errs17) { if (typeof data8 == "number" && isFinite(data8)) { if (data8 <= 0 || isNaN(data8)) { validate10.errors = [{ instancePath: instancePath + "/multipleOf", schemaPath: "#/properties/multipleOf/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; return false; } } else { validate10.errors = [{ instancePath: instancePath + "/multipleOf", schemaPath: "#/properties/multipleOf/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } } var valid0 = _errs17 === errors; } else { var valid0 = true; } if (valid0) { if (data.maximum !== void 0) { let data9 = data.maximum; const _errs19 = errors; if (!(typeof data9 == "number" && isFinite(data9))) { validate10.errors = [{ instancePath: instancePath + "/maximum", schemaPath: "#/properties/maximum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid0 = _errs19 === errors; } else { var valid0 = true; } if (valid0) { if (data.exclusiveMaximum !== void 0) { let data10 = data.exclusiveMaximum; const _errs21 = errors; if (!(typeof data10 == "number" && isFinite(data10))) { validate10.errors = [{ instancePath: instancePath + "/exclusiveMaximum", schemaPath: "#/properties/exclusiveMaximum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid0 = _errs21 === errors; } else { var valid0 = true; } if (valid0) { if (data.minimum !== void 0) { let data11 = data.minimum; const _errs23 = errors; if (!(typeof data11 == "number" && isFinite(data11))) { validate10.errors = [{ instancePath: instancePath + "/minimum", schemaPath: "#/properties/minimum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid0 = _errs23 === errors; } else { var valid0 = true; } if (valid0) { if (data.exclusiveMinimum !== void 0) { let data12 = data.exclusiveMinimum; const _errs25 = errors; if (!(typeof data12 == "number" && isFinite(data12))) { validate10.errors = [{ instancePath: instancePath + "/exclusiveMinimum", schemaPath: "#/properties/exclusiveMinimum/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid0 = _errs25 === errors; } else { var valid0 = true; } if (valid0) { if (data.maxLength !== void 0) { let data13 = data.maxLength; const _errs27 = errors; const _errs28 = errors; if (!(typeof data13 == "number" && (!(data13 % 1) && !isNaN(data13)) && isFinite(data13))) { validate10.errors = [{ instancePath: instancePath + "/maxLength", schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } if (errors === _errs28) { if (typeof data13 == "number" && isFinite(data13)) { if (data13 < 0 || isNaN(data13)) { validate10.errors = [{ instancePath: instancePath + "/maxLength", schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; return false; } } } var valid0 = _errs27 === errors; } else { var valid0 = true; } if (valid0) { if (data.minLength !== void 0) { const _errs30 = errors; if (!validate11(data.minLength, { instancePath: instancePath + "/minLength", parentData: data, parentDataProperty: "minLength", rootData })) { vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors); errors = vErrors.length; } var valid0 = _errs30 === errors; } else { var valid0 = true; } if (valid0) { if (data.pattern !== void 0) { let data15 = data.pattern; const _errs31 = errors; if (errors === _errs31) { if (errors === _errs31) { if (typeof data15 === "string") { if (!formats6(data15)) { validate10.errors = [{ instancePath: instancePath + "/pattern", schemaPath: "#/properties/pattern/format", keyword: "format", params: { format: "regex" }, message: 'must match format "regex"' }]; return false; } } else { validate10.errors = [{ instancePath: instancePath + "/pattern", schemaPath: "#/properties/pattern/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } } var valid0 = _errs31 === errors; } else { var valid0 = true; } if (valid0) { if (data.additionalItems !== void 0) { const _errs33 = errors; if (!validate10(data.additionalItems, { instancePath: instancePath + "/additionalItems", parentData: data, parentDataProperty: "additionalItems", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs33 === errors; } else { var valid0 = true; } if (valid0) { if (data.items !== void 0) { let data17 = data.items; const _errs34 = errors; const _errs35 = errors; let valid2 = false; const _errs36 = errors; if (!validate10(data17, { instancePath: instancePath + "/items", parentData: data, parentDataProperty: "items", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var _valid0 = _errs36 === errors; valid2 = valid2 || _valid0; if (!valid2) { const _errs37 = errors; if (!validate13(data17, { instancePath: instancePath + "/items", parentData: data, parentDataProperty: "items", rootData })) { vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); errors = vErrors.length; } var _valid0 = _errs37 === errors; valid2 = valid2 || _valid0; } if (!valid2) { const err0 = { instancePath: instancePath + "/items", schemaPath: "#/properties/items/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs35; if (vErrors !== null) { if (_errs35) { vErrors.length = _errs35; } else { vErrors = null; } } } var valid0 = _errs34 === errors; } else { var valid0 = true; } if (valid0) { if (data.maxItems !== void 0) { let data18 = data.maxItems; const _errs38 = errors; const _errs39 = errors; if (!(typeof data18 == "number" && (!(data18 % 1) && !isNaN(data18)) && isFinite(data18))) { validate10.errors = [{ instancePath: instancePath + "/maxItems", schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } if (errors === _errs39) { if (typeof data18 == "number" && isFinite(data18)) { if (data18 < 0 || isNaN(data18)) { validate10.errors = [{ instancePath: instancePath + "/maxItems", schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; return false; } } } var valid0 = _errs38 === errors; } else { var valid0 = true; } if (valid0) { if (data.minItems !== void 0) { const _errs41 = errors; if (!validate11(data.minItems, { instancePath: instancePath + "/minItems", parentData: data, parentDataProperty: "minItems", rootData })) { vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors); errors = vErrors.length; } var valid0 = _errs41 === errors; } else { var valid0 = true; } if (valid0) { if (data.uniqueItems !== void 0) { const _errs42 = errors; if (typeof data.uniqueItems !== "boolean") { validate10.errors = [{ instancePath: instancePath + "/uniqueItems", schemaPath: "#/properties/uniqueItems/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid0 = _errs42 === errors; } else { var valid0 = true; } if (valid0) { if (data.contains !== void 0) { const _errs44 = errors; if (!validate10(data.contains, { instancePath: instancePath + "/contains", parentData: data, parentDataProperty: "contains", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs44 === errors; } else { var valid0 = true; } if (valid0) { if (data.maxProperties !== void 0) { let data22 = data.maxProperties; const _errs45 = errors; const _errs46 = errors; if (!(typeof data22 == "number" && (!(data22 % 1) && !isNaN(data22)) && isFinite(data22))) { validate10.errors = [{ instancePath: instancePath + "/maxProperties", schemaPath: "#/definitions/nonNegativeInteger/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } if (errors === _errs46) { if (typeof data22 == "number" && isFinite(data22)) { if (data22 < 0 || isNaN(data22)) { validate10.errors = [{ instancePath: instancePath + "/maxProperties", schemaPath: "#/definitions/nonNegativeInteger/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; return false; } } } var valid0 = _errs45 === errors; } else { var valid0 = true; } if (valid0) { if (data.minProperties !== void 0) { const _errs48 = errors; if (!validate11(data.minProperties, { instancePath: instancePath + "/minProperties", parentData: data, parentDataProperty: "minProperties", rootData })) { vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors); errors = vErrors.length; } var valid0 = _errs48 === errors; } else { var valid0 = true; } if (valid0) { if (data.required !== void 0) { let data24 = data.required; const _errs49 = errors; const _errs50 = errors; if (errors === _errs50) { if (Array.isArray(data24)) { var valid6 = true; const len0 = data24.length; for (let i0 = 0; i0 < len0; i0++) { const _errs52 = errors; if (typeof data24[i0] !== "string") { validate10.errors = [{ instancePath: instancePath + "/required/" + i0, schemaPath: "#/definitions/stringArray/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs52 === errors; if (!valid6) { break; } } if (valid6) { let i1 = data24.length; let j0; if (i1 > 1) { const indices0 = {}; for (; i1--; ) { let item0 = data24[i1]; if (typeof item0 !== "string") { continue; } if (typeof indices0[item0] == "number") { j0 = indices0[item0]; validate10.errors = [{ instancePath: instancePath + "/required", schemaPath: "#/definitions/stringArray/uniqueItems", keyword: "uniqueItems", params: { i: i1, j: j0 }, message: "must NOT have duplicate items (items ## " + j0 + " and " + i1 + " are identical)" }]; return false; break; } indices0[item0] = i1; } } } } else { validate10.errors = [{ instancePath: instancePath + "/required", schemaPath: "#/definitions/stringArray/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid0 = _errs49 === errors; } else { var valid0 = true; } if (valid0) { if (data.additionalProperties !== void 0) { const _errs54 = errors; if (!validate10(data.additionalProperties, { instancePath: instancePath + "/additionalProperties", parentData: data, parentDataProperty: "additionalProperties", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs54 === errors; } else { var valid0 = true; } if (valid0) { if (data.definitions !== void 0) { let data27 = data.definitions; const _errs55 = errors; if (errors === _errs55) { if (data27 && typeof data27 == "object" && !Array.isArray(data27)) { for (const key0 in data27) { const _errs58 = errors; if (!validate10(data27[key0], { instancePath: instancePath + "/definitions/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data27, parentDataProperty: key0, rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid8 = _errs58 === errors; if (!valid8) { break; } } } else { validate10.errors = [{ instancePath: instancePath + "/definitions", schemaPath: "#/properties/definitions/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs55 === errors; } else { var valid0 = true; } if (valid0) { if (data.properties !== void 0) { let data29 = data.properties; const _errs59 = errors; if (errors === _errs59) { if (data29 && typeof data29 == "object" && !Array.isArray(data29)) { for (const key1 in data29) { const _errs62 = errors; if (!validate10(data29[key1], { instancePath: instancePath + "/properties/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data29, parentDataProperty: key1, rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid9 = _errs62 === errors; if (!valid9) { break; } } } else { validate10.errors = [{ instancePath: instancePath + "/properties", schemaPath: "#/properties/properties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs59 === errors; } else { var valid0 = true; } if (valid0) { if (data.patternProperties !== void 0) { let data31 = data.patternProperties; const _errs63 = errors; if (errors === _errs63) { if (data31 && typeof data31 == "object" && !Array.isArray(data31)) { for (const key2 in data31) { const _errs65 = errors; if (errors === _errs65) { if (typeof key2 === "string") { if (!formats6(key2)) { const err1 = { instancePath: instancePath + "/patternProperties", schemaPath: "#/properties/patternProperties/propertyNames/format", keyword: "format", params: { format: "regex" }, message: 'must match format "regex"', propertyName: key2 }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } } var valid10 = _errs65 === errors; if (!valid10) { const err2 = { instancePath: instancePath + "/patternProperties", schemaPath: "#/properties/patternProperties/propertyNames", keyword: "propertyNames", params: { propertyName: key2 }, message: "property name must be valid" }; if (vErrors === null) { vErrors = [err2]; } else { vErrors.push(err2); } errors++; validate10.errors = vErrors; return false; break; } } if (valid10) { for (const key3 in data31) { const _errs67 = errors; if (!validate10(data31[key3], { instancePath: instancePath + "/patternProperties/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data31, parentDataProperty: key3, rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid11 = _errs67 === errors; if (!valid11) { break; } } } } else { validate10.errors = [{ instancePath: instancePath + "/patternProperties", schemaPath: "#/properties/patternProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs63 === errors; } else { var valid0 = true; } if (valid0) { if (data.dependencies !== void 0) { let data33 = data.dependencies; const _errs68 = errors; if (errors === _errs68) { if (data33 && typeof data33 == "object" && !Array.isArray(data33)) { for (const key4 in data33) { let data34 = data33[key4]; const _errs71 = errors; const _errs72 = errors; let valid13 = false; const _errs73 = errors; if (!validate10(data34, { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data33, parentDataProperty: key4, rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var _valid1 = _errs73 === errors; valid13 = valid13 || _valid1; if (!valid13) { const _errs74 = errors; const _errs75 = errors; if (errors === _errs75) { if (Array.isArray(data34)) { var valid15 = true; const len1 = data34.length; for (let i2 = 0; i2 < len1; i2++) { const _errs77 = errors; if (typeof data34[i2] !== "string") { const err3 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/" + i2, schemaPath: "#/definitions/stringArray/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } var valid15 = _errs77 === errors; if (!valid15) { break; } } if (valid15) { let i3 = data34.length; let j1; if (i3 > 1) { const indices1 = {}; for (; i3--; ) { let item1 = data34[i3]; if (typeof item1 !== "string") { continue; } if (typeof indices1[item1] == "number") { j1 = indices1[item1]; const err4 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/definitions/stringArray/uniqueItems", keyword: "uniqueItems", params: { i: i3, j: j1 }, message: "must NOT have duplicate items (items ## " + j1 + " and " + i3 + " are identical)" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; break; } indices1[item1] = i3; } } } } else { const err5 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/definitions/stringArray/type", keyword: "type", params: { type: "array" }, message: "must be array" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } } var _valid1 = _errs74 === errors; valid13 = valid13 || _valid1; } if (!valid13) { const err6 = { instancePath: instancePath + "/dependencies/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/dependencies/additionalProperties/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs72; if (vErrors !== null) { if (_errs72) { vErrors.length = _errs72; } else { vErrors = null; } } } var valid12 = _errs71 === errors; if (!valid12) { break; } } } else { validate10.errors = [{ instancePath: instancePath + "/dependencies", schemaPath: "#/properties/dependencies/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs68 === errors; } else { var valid0 = true; } if (valid0) { if (data.propertyNames !== void 0) { const _errs79 = errors; if (!validate10(data.propertyNames, { instancePath: instancePath + "/propertyNames", parentData: data, parentDataProperty: "propertyNames", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs79 === errors; } else { var valid0 = true; } if (valid0) { if (data.enum !== void 0) { let data37 = data.enum; const _errs80 = errors; if (errors === _errs80) { if (Array.isArray(data37)) { if (data37.length < 1) { validate10.errors = [{ instancePath: instancePath + "/enum", schemaPath: "#/properties/enum/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { let i4 = data37.length; let j2; if (i4 > 1) { outer0: for (; i4--; ) { for (j2 = i4; j2--; ) { if (func0(data37[i4], data37[j2])) { validate10.errors = [{ instancePath: instancePath + "/enum", schemaPath: "#/properties/enum/uniqueItems", keyword: "uniqueItems", params: { i: i4, j: j2 }, message: "must NOT have duplicate items (items ## " + j2 + " and " + i4 + " are identical)" }]; return false; break outer0; } } } } } } else { validate10.errors = [{ instancePath: instancePath + "/enum", schemaPath: "#/properties/enum/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid0 = _errs80 === errors; } else { var valid0 = true; } if (valid0) { if (data.type !== void 0) { let data38 = data.type; const _errs82 = errors; const _errs83 = errors; let valid18 = false; const _errs84 = errors; if (!(data38 === "array" || data38 === "boolean" || data38 === "integer" || data38 === "null" || data38 === "number" || data38 === "object" || data38 === "string")) { const err7 = { instancePath: instancePath + "/type", schemaPath: "#/definitions/simpleTypes/enum", keyword: "enum", params: { allowedValues: schema20.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var _valid2 = _errs84 === errors; valid18 = valid18 || _valid2; if (!valid18) { const _errs86 = errors; if (errors === _errs86) { if (Array.isArray(data38)) { if (data38.length < 1) { const err8 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf/1/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } else { var valid20 = true; const len2 = data38.length; for (let i5 = 0; i5 < len2; i5++) { let data39 = data38[i5]; const _errs88 = errors; if (!(data39 === "array" || data39 === "boolean" || data39 === "integer" || data39 === "null" || data39 === "number" || data39 === "object" || data39 === "string")) { const err9 = { instancePath: instancePath + "/type/" + i5, schemaPath: "#/definitions/simpleTypes/enum", keyword: "enum", params: { allowedValues: schema20.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } var valid20 = _errs88 === errors; if (!valid20) { break; } } if (valid20) { let i6 = data38.length; let j3; if (i6 > 1) { outer1: for (; i6--; ) { for (j3 = i6; j3--; ) { if (func0(data38[i6], data38[j3])) { const err10 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf/1/uniqueItems", keyword: "uniqueItems", params: { i: i6, j: j3 }, message: "must NOT have duplicate items (items ## " + j3 + " and " + i6 + " are identical)" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; break outer1; } } } } } } } else { const err11 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf/1/type", keyword: "type", params: { type: "array" }, message: "must be array" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } } var _valid2 = _errs86 === errors; valid18 = valid18 || _valid2; } if (!valid18) { const err12 = { instancePath: instancePath + "/type", schemaPath: "#/properties/type/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs83; if (vErrors !== null) { if (_errs83) { vErrors.length = _errs83; } else { vErrors = null; } } } var valid0 = _errs82 === errors; } else { var valid0 = true; } if (valid0) { if (data.format !== void 0) { const _errs90 = errors; if (typeof data.format !== "string") { validate10.errors = [{ instancePath: instancePath + "/format", schemaPath: "#/properties/format/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs90 === errors; } else { var valid0 = true; } if (valid0) { if (data.contentMediaType !== void 0) { const _errs92 = errors; if (typeof data.contentMediaType !== "string") { validate10.errors = [{ instancePath: instancePath + "/contentMediaType", schemaPath: "#/properties/contentMediaType/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs92 === errors; } else { var valid0 = true; } if (valid0) { if (data.contentEncoding !== void 0) { const _errs94 = errors; if (typeof data.contentEncoding !== "string") { validate10.errors = [{ instancePath: instancePath + "/contentEncoding", schemaPath: "#/properties/contentEncoding/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs94 === errors; } else { var valid0 = true; } if (valid0) { if (data.if !== void 0) { const _errs96 = errors; if (!validate10(data.if, { instancePath: instancePath + "/if", parentData: data, parentDataProperty: "if", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs96 === errors; } else { var valid0 = true; } if (valid0) { if (data.then !== void 0) { const _errs97 = errors; if (!validate10(data.then, { instancePath: instancePath + "/then", parentData: data, parentDataProperty: "then", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs97 === errors; } else { var valid0 = true; } if (valid0) { if (data.else !== void 0) { const _errs98 = errors; if (!validate10(data.else, { instancePath: instancePath + "/else", parentData: data, parentDataProperty: "else", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs98 === errors; } else { var valid0 = true; } if (valid0) { if (data.allOf !== void 0) { const _errs99 = errors; if (!validate13(data.allOf, { instancePath: instancePath + "/allOf", parentData: data, parentDataProperty: "allOf", rootData })) { vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); errors = vErrors.length; } var valid0 = _errs99 === errors; } else { var valid0 = true; } if (valid0) { if (data.anyOf !== void 0) { const _errs100 = errors; if (!validate13(data.anyOf, { instancePath: instancePath + "/anyOf", parentData: data, parentDataProperty: "anyOf", rootData })) { vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); errors = vErrors.length; } var valid0 = _errs100 === errors; } else { var valid0 = true; } if (valid0) { if (data.oneOf !== void 0) { const _errs101 = errors; if (!validate13(data.oneOf, { instancePath: instancePath + "/oneOf", parentData: data, parentDataProperty: "oneOf", rootData })) { vErrors = vErrors === null ? validate13.errors : vErrors.concat(validate13.errors); errors = vErrors.length; } var valid0 = _errs101 === errors; } else { var valid0 = true; } if (valid0) { if (data.not !== void 0) { const _errs102 = errors; if (!validate10(data.not, { instancePath: instancePath + "/not", parentData: data, parentDataProperty: "not", rootData })) { vErrors = vErrors === null ? validate10.errors : vErrors.concat(validate10.errors); errors = vErrors.length; } var valid0 = _errs102 === errors; } else { var valid0 = true; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } validate10.errors = vErrors; return errors === 0; } } }); // node_modules/@fastify/merge-json-schemas/lib/errors.js var require_errors4 = __commonJS({ "node_modules/@fastify/merge-json-schemas/lib/errors.js"(exports, module2) { "use strict"; var MergeError = class extends Error { constructor(keyword, schemas) { super(); this.name = "JsonSchemaMergeError"; this.code = "JSON_SCHEMA_MERGE_ERROR"; this.message = `Failed to merge "${keyword}" keyword schemas.`; this.schemas = schemas; } }; var ResolverNotFoundError = class extends Error { constructor(keyword, schemas) { super(); this.name = "JsonSchemaMergeError"; this.code = "JSON_SCHEMA_MERGE_ERROR"; this.message = `Resolver for "${keyword}" keyword not found.`; this.schemas = schemas; } }; var InvalidOnConflictOptionError = class extends Error { constructor(onConflict) { super(); this.name = "JsonSchemaMergeError"; this.code = "JSON_SCHEMA_MERGE_ERROR"; this.message = `Invalid "onConflict" option: "${onConflict}".`; } }; module2.exports = { MergeError, ResolverNotFoundError, InvalidOnConflictOptionError }; } }); // node_modules/@fastify/merge-json-schemas/lib/resolvers.js var require_resolvers = __commonJS({ "node_modules/@fastify/merge-json-schemas/lib/resolvers.js"(exports, module2) { "use strict"; var deepEqual = require_fast_deep_equal(); var { MergeError } = require_errors4(); function _arraysIntersection(arrays) { let intersection = arrays[0]; for (let i = 1; i < arrays.length; i++) { intersection = intersection.filter( (value) => arrays[i].includes(value) ); } return intersection; } function arraysIntersection(keyword, values, mergedSchema) { const intersection = _arraysIntersection(values); if (intersection.length === 0) { throw new MergeError(keyword, values); } mergedSchema[keyword] = intersection; } function hybridArraysIntersection(keyword, values, mergedSchema) { for (let i = 0; i < values.length; i++) { if (!Array.isArray(values[i])) { values[i] = [values[i]]; } } const intersection = _arraysIntersection(values); if (intersection.length === 0) { throw new MergeError(keyword, values); } if (intersection.length === 1) { mergedSchema[keyword] = intersection[0]; } else { mergedSchema[keyword] = intersection; } } function arraysUnion(keyword, values, mergedSchema) { const union = []; for (const array of values) { for (const value of array) { if (!union.includes(value)) { union.push(value); } } } mergedSchema[keyword] = union; } function minNumber(keyword, values, mergedSchema) { mergedSchema[keyword] = Math.min(...values); } function maxNumber(keyword, values, mergedSchema) { mergedSchema[keyword] = Math.max(...values); } function commonMultiple(keyword, values, mergedSchema) { const gcd = (a, b) => !b ? a : gcd(b, a % b); const lcm = (a, b) => a * b / gcd(a, b); let scale = 1; for (const value of values) { while (value * scale % 1 !== 0) { scale *= 10; } } let multiple = values[0] * scale; for (const value of values) { multiple = lcm(multiple, value * scale); } mergedSchema[keyword] = multiple / scale; } function allEqual(keyword, values, mergedSchema) { const firstValue = values[0]; for (let i = 1; i < values.length; i++) { if (!deepEqual(values[i], firstValue)) { throw new MergeError(keyword, values); } } mergedSchema[keyword] = firstValue; } function skip() { } function booleanAnd(keyword, values, mergedSchema) { for (const value of values) { if (value === false) { mergedSchema[keyword] = false; return; } } mergedSchema[keyword] = true; } function booleanOr(keyword, values, mergedSchema) { for (const value of values) { if (value === true) { mergedSchema[keyword] = true; return; } } mergedSchema[keyword] = false; } module2.exports = { arraysIntersection, hybridArraysIntersection, arraysUnion, minNumber, maxNumber, commonMultiple, allEqual, booleanAnd, booleanOr, skip }; } }); // node_modules/@fastify/merge-json-schemas/index.js var require_merge_json_schemas = __commonJS({ "node_modules/@fastify/merge-json-schemas/index.js"(exports, module2) { "use strict"; var deepEqual = require_fast_deep_equal(); var resolvers = require_resolvers(); var errors = require_errors4(); var keywordsResolvers = { $id: resolvers.skip, type: resolvers.hybridArraysIntersection, enum: resolvers.arraysIntersection, minLength: resolvers.maxNumber, maxLength: resolvers.minNumber, minimum: resolvers.maxNumber, maximum: resolvers.minNumber, multipleOf: resolvers.commonMultiple, exclusiveMinimum: resolvers.maxNumber, exclusiveMaximum: resolvers.minNumber, minItems: resolvers.maxNumber, maxItems: resolvers.minNumber, maxProperties: resolvers.minNumber, minProperties: resolvers.maxNumber, const: resolvers.allEqual, default: resolvers.allEqual, format: resolvers.allEqual, required: resolvers.arraysUnion, properties: mergeProperties, patternProperties: mergeObjects, additionalProperties: mergeSchemasResolver, items: mergeItems, additionalItems: mergeAdditionalItems, definitions: mergeObjects, $defs: mergeObjects, nullable: resolvers.booleanAnd, oneOf: mergeOneOf, anyOf: mergeOneOf, allOf: resolvers.arraysUnion, not: mergeSchemasResolver, if: mergeIfThenElseSchemas, then: resolvers.skip, else: resolvers.skip, dependencies: mergeDependencies, dependentRequired: mergeDependencies, dependentSchemas: mergeObjects, propertyNames: mergeSchemasResolver, uniqueItems: resolvers.booleanOr, contains: mergeSchemasResolver }; function mergeSchemasResolver(keyword, values, mergedSchema, schemas, options) { mergedSchema[keyword] = _mergeSchemas(values, options); } function cartesianProduct(arrays) { let result = [[]]; for (const array of arrays) { const temp = []; for (const x of result) { for (const y of array) { temp.push([...x, y]); } } result = temp; } return result; } function mergeOneOf(keyword, values, mergedSchema, schemas, options) { if (values.length === 1) { mergedSchema[keyword] = values[0]; return; } const product = cartesianProduct(values); const mergedOneOf = []; for (const combination of product) { try { const mergedSchema2 = _mergeSchemas(combination, options); if (mergedSchema2 !== void 0) { mergedOneOf.push(mergedSchema2); } } catch (error) { if (error instanceof errors.MergeError) continue; throw error; } } mergedSchema[keyword] = mergedOneOf; } function getSchemaForItem(schema, index) { const { items, additionalItems } = schema; if (Array.isArray(items)) { if (index < items.length) { return items[index]; } return additionalItems; } if (items !== void 0) { return items; } return additionalItems; } function mergeItems(keyword, values, mergedSchema, schemas, options) { let maxArrayItemsLength = 0; for (const itemsSchema of values) { if (Array.isArray(itemsSchema)) { maxArrayItemsLength = Math.max(maxArrayItemsLength, itemsSchema.length); } } if (maxArrayItemsLength === 0) { mergedSchema[keyword] = _mergeSchemas(values, options); return; } const mergedItemsSchemas = []; for (let i = 0; i < maxArrayItemsLength; i++) { const indexItemSchemas = []; for (const schema of schemas) { const itemSchema = getSchemaForItem(schema, i); if (itemSchema !== void 0) { indexItemSchemas.push(itemSchema); } } mergedItemsSchemas[i] = _mergeSchemas(indexItemSchemas, options); } mergedSchema[keyword] = mergedItemsSchemas; } function mergeAdditionalItems(keyword, values, mergedSchema, schemas, options) { let hasArrayItems = false; for (const schema of schemas) { if (Array.isArray(schema.items)) { hasArrayItems = true; break; } } if (!hasArrayItems) { mergedSchema[keyword] = _mergeSchemas(values, options); return; } const mergedAdditionalItemsSchemas = []; for (const schema of schemas) { let additionalItemsSchema = schema.additionalItems; if (additionalItemsSchema === void 0 && !Array.isArray(schema.items)) { additionalItemsSchema = schema.items; } if (additionalItemsSchema !== void 0) { mergedAdditionalItemsSchemas.push(additionalItemsSchema); } } mergedSchema[keyword] = _mergeSchemas(mergedAdditionalItemsSchemas, options); } function getSchemaForProperty(schema, propertyName) { const { properties, patternProperties, additionalProperties } = schema; if ((properties == null ? void 0 : properties[propertyName]) !== void 0) { return properties[propertyName]; } for (const pattern of Object.keys(patternProperties != null ? patternProperties : {})) { const regexp = new RegExp(pattern); if (regexp.test(propertyName)) { return patternProperties[pattern]; } } return additionalProperties; } function mergeProperties(keyword, values, mergedSchema, schemas, options) { var _a; const foundProperties = {}; for (const currentSchema of schemas) { const properties = (_a = currentSchema.properties) != null ? _a : {}; for (const propertyName of Object.keys(properties)) { if (foundProperties[propertyName] !== void 0) continue; const propertySchema = properties[propertyName]; foundProperties[propertyName] = [propertySchema]; for (const anotherSchema of schemas) { if (currentSchema === anotherSchema) continue; const propertySchema2 = getSchemaForProperty(anotherSchema, propertyName); if (propertySchema2 !== void 0) { foundProperties[propertyName].push(propertySchema2); } } } } const mergedProperties = {}; for (const property of Object.keys(foundProperties)) { const propertySchemas = foundProperties[property]; mergedProperties[property] = _mergeSchemas(propertySchemas, options); } mergedSchema[keyword] = mergedProperties; } function mergeObjects(keyword, values, mergedSchema, schemas, options) { const objectsProperties = {}; for (const properties of values) { for (const propertyName of Object.keys(properties)) { if (objectsProperties[propertyName] === void 0) { objectsProperties[propertyName] = []; } objectsProperties[propertyName].push(properties[propertyName]); } } const mergedProperties = {}; for (const propertyName of Object.keys(objectsProperties)) { const propertySchemas = objectsProperties[propertyName]; const mergedPropertySchema = _mergeSchemas(propertySchemas, options); mergedProperties[propertyName] = mergedPropertySchema; } mergedSchema[keyword] = mergedProperties; } function mergeIfThenElseSchemas(keyword, values, mergedSchema, schemas, options) { for (let i = 0; i < schemas.length; i++) { const subSchema = { if: schemas[i].if, then: schemas[i].then, else: schemas[i].else }; if (subSchema.if === void 0) continue; if (mergedSchema.if === void 0) { mergedSchema.if = subSchema.if; if (subSchema.then !== void 0) { mergedSchema.then = subSchema.then; } if (subSchema.else !== void 0) { mergedSchema.else = subSchema.else; } continue; } if (mergedSchema.then !== void 0) { mergedSchema.then = _mergeSchemas([mergedSchema.then, subSchema], options); } if (mergedSchema.else !== void 0) { mergedSchema.else = _mergeSchemas([mergedSchema.else, subSchema], options); } } } function mergeDependencies(keyword, values, mergedSchema) { const mergedDependencies = {}; for (const dependencies of values) { for (const propertyName of Object.keys(dependencies)) { if (mergedDependencies[propertyName] === void 0) { mergedDependencies[propertyName] = []; } const mergedPropertyDependencies = mergedDependencies[propertyName]; for (const propertyDependency of dependencies[propertyName]) { if (!mergedPropertyDependencies.includes(propertyDependency)) { mergedPropertyDependencies.push(propertyDependency); } } } } mergedSchema[keyword] = mergedDependencies; } function _mergeSchemas(schemas, options) { var _a; if (schemas.length === 0) return {}; if (schemas.length === 1) return schemas[0]; const mergedSchema = {}; const keywords = {}; let allSchemasAreTrue = true; for (const schema of schemas) { if (schema === false) return false; if (schema === true) continue; allSchemasAreTrue = false; for (const keyword of Object.keys(schema)) { if (keywords[keyword] === void 0) { keywords[keyword] = []; } keywords[keyword].push(schema[keyword]); } } if (allSchemasAreTrue) return true; for (const keyword of Object.keys(keywords)) { const keywordValues = keywords[keyword]; const resolver = (_a = options.resolvers[keyword]) != null ? _a : options.defaultResolver; resolver(keyword, keywordValues, mergedSchema, schemas, options); } return mergedSchema; } function defaultResolver(keyword, values, mergedSchema, schemas, options) { var _a; const onConflict = (_a = options.onConflict) != null ? _a : "throw"; if (values.length === 1 || onConflict === "first") { mergedSchema[keyword] = values[0]; return; } let allValuesEqual = true; for (let i = 1; i < values.length; i++) { if (!deepEqual(values[i], values[0])) { allValuesEqual = false; break; } } if (allValuesEqual) { mergedSchema[keyword] = values[0]; return; } if (onConflict === "throw") { throw new errors.ResolverNotFoundError(keyword, values); } if (onConflict === "skip") { return; } throw new errors.InvalidOnConflictOptionError(onConflict); } function mergeSchemas(schemas, options = {}) { if (options.defaultResolver === void 0) { options.defaultResolver = defaultResolver; } options.resolvers = { ...keywordsResolvers, ...options.resolvers }; const mergedSchema = _mergeSchemas(schemas, options); return mergedSchema; } module2.exports = { mergeSchemas, keywordsResolvers, defaultResolver, ...errors }; } }); // node_modules/fast-json-stringify/lib/merge-schemas.js var require_merge_schemas = __commonJS({ "node_modules/fast-json-stringify/lib/merge-schemas.js"(exports, module2) { "use strict"; var { mergeSchemas: _mergeSchemas } = require_merge_json_schemas(); function mergeSchemas(schemas) { return _mergeSchemas(schemas, { onConflict: "skip" }); } module2.exports = mergeSchemas; } }); // node_modules/fast-json-stringify/lib/standalone.js var require_standalone = __commonJS({ "node_modules/fast-json-stringify/lib/standalone.js"(exports, module2) { "use strict"; function buildStandaloneCode(contextFunc, context, serializer, validator) { let ajvDependencyCode = ""; if (context.validatorSchemasIds.size > 0) { ajvDependencyCode += "const Validator = require('fast-json-stringify/lib/validator')\n"; ajvDependencyCode += `const validatorState = ${JSON.stringify(validator.getState())} `; ajvDependencyCode += "const validator = Validator.restoreFromState(validatorState)\n"; } else { ajvDependencyCode += "const validator = null\n"; } const { schema, ...serializerState } = serializer.getState(); return ` 'use strict' const Serializer = require('fast-json-stringify/lib/serializer') const serializerState = ${JSON.stringify(serializerState)} const serializer = Serializer.restoreFromState(serializerState) ${ajvDependencyCode} module.exports = ${contextFunc.toString()}(validator, serializer)`; } module2.exports = buildStandaloneCode; module2.exports.dependencies = { Serializer: require_serializer(), Validator: require_validator2() }; } }); // node_modules/fast-json-stringify/index.js var require_fast_json_stringify = __commonJS({ "node_modules/fast-json-stringify/index.js"(exports, module2) { "use strict"; var { RefResolver } = require_json_schema_ref_resolver(); var Serializer = require_serializer(); var Validator = require_validator2(); var Location = require_location(); var validate = require_schema_validator(); var mergeSchemas = require_merge_schemas(); var SINGLE_TICK = /'/g; var largeArraySize = 2e4; var largeArrayMechanism = "default"; var validRoundingMethods = [ "floor", "ceil", "round", "trunc" ]; var validLargeArrayMechanisms = [ "default", "json-stringify" ]; var schemaIdCounter = 0; function isValidSchema(schema, name) { if (!validate(schema)) { if (name) { name = `"${name}" `; } else { name = ""; } const first = validate.errors[0]; const err = new Error(`${name}schema is invalid: data${first.instancePath} ${first.message}`); err.errors = isValidSchema.errors; throw err; } } function resolveRef(context, location) { const ref = location.schema.$ref; let hashIndex = ref.indexOf("#"); if (hashIndex === -1) { hashIndex = ref.length; } const schemaId = ref.slice(0, hashIndex) || location.schemaId; const jsonPointer = ref.slice(hashIndex) || "#"; const schema = context.refResolver.getSchema(schemaId, jsonPointer); if (schema === null) { throw new Error(`Cannot find reference "${ref}"`); } const newLocation = new Location(schema, schemaId, jsonPointer); if (schema.$ref !== void 0) { return resolveRef(context, newLocation); } return newLocation; } function getMergedLocation(context, mergedSchemaId) { const mergedSchema = context.refResolver.getSchema(mergedSchemaId, "#"); return new Location(mergedSchema, mergedSchemaId, "#"); } function getSchemaId(schema, rootSchemaId) { if (schema.$id && schema.$id.charAt(0) !== "#") { return schema.$id; } return rootSchemaId; } function build(schema, options) { isValidSchema(schema); options = options || {}; const context = { functions: [], functionsCounter: 0, functionsNamesBySchema: /* @__PURE__ */ new Map(), options, refResolver: new RefResolver(), rootSchemaId: schema.$id || `__fjs_root_${schemaIdCounter++}`, validatorSchemasIds: /* @__PURE__ */ new Set(), mergedSchemasIds: /* @__PURE__ */ new Map() }; const schemaId = getSchemaId(schema, context.rootSchemaId); if (!context.refResolver.hasSchema(schemaId)) { context.refResolver.addSchema(schema, context.rootSchemaId); } if (options.schema) { for (const key in options.schema) { const schema2 = options.schema[key]; const schemaId2 = getSchemaId(schema2, key); if (!context.refResolver.hasSchema(schemaId2)) { isValidSchema(schema2, key); context.refResolver.addSchema(schema2, key); } } } if (options.rounding) { if (!validRoundingMethods.includes(options.rounding)) { throw new Error(`Unsupported integer rounding method ${options.rounding}`); } } if (options.largeArrayMechanism) { if (validLargeArrayMechanisms.includes(options.largeArrayMechanism)) { largeArrayMechanism = options.largeArrayMechanism; } else { throw new Error(`Unsupported large array mechanism ${options.largeArrayMechanism}`); } } if (options.largeArraySize) { if (typeof options.largeArraySize === "string" && Number.isFinite(Number.parseInt(options.largeArraySize, 10))) { largeArraySize = Number.parseInt(options.largeArraySize, 10); } else if (typeof options.largeArraySize === "number" && Number.isInteger(options.largeArraySize)) { largeArraySize = options.largeArraySize; } else if (typeof options.largeArraySize === "bigint") { largeArraySize = Number(options.largeArraySize); } else { throw new Error(`Unsupported large array size. Expected integer-like, got ${typeof options.largeArraySize} with value ${options.largeArraySize}`); } } const location = new Location(schema, context.rootSchemaId); const code = buildValue(context, location, "input"); let contextFunctionCode = ` const JSON_STR_BEGIN_OBJECT = '{' const JSON_STR_END_OBJECT = '}' const JSON_STR_BEGIN_ARRAY = '[' const JSON_STR_END_ARRAY = ']' const JSON_STR_COMMA = ',' const JSON_STR_COLONS = ':' const JSON_STR_QUOTE = '"' const JSON_STR_EMPTY_OBJECT = JSON_STR_BEGIN_OBJECT + JSON_STR_END_OBJECT const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE const JSON_STR_NULL = 'null' `; if (code === "json += anonymous0(input)") { contextFunctionCode += ` ${context.functions.join("\n")} const main = anonymous0 return main `; } else { contextFunctionCode += ` function main (input) { let json = '' ${code} return json } ${context.functions.join("\n")} return main `; } const serializer = new Serializer(options); const validator = new Validator(options.ajv); for (const schemaId2 of context.validatorSchemasIds) { const schema2 = context.refResolver.getSchema(schemaId2); validator.addSchema(schema2, schemaId2); const dependencies = context.refResolver.getSchemaDependencies(schemaId2); for (const [schemaId3, schema3] of Object.entries(dependencies)) { validator.addSchema(schema3, schemaId3); } } if (options.debugMode) { options.mode = "debug"; } if (options.mode === "debug") { return { validator, serializer, code: `validator serializer ${contextFunctionCode}`, ajv: validator.ajv }; } const contextFunc = new Function("validator", "serializer", contextFunctionCode); if (options.mode === "standalone") { const buildStandaloneCode = require_standalone(); return buildStandaloneCode(contextFunc, context, serializer, validator); } return contextFunc(validator, serializer); } var objectKeywords = [ "properties", "required", "additionalProperties", "patternProperties", "maxProperties", "minProperties", "dependencies" ]; var arrayKeywords = [ "items", "additionalItems", "maxItems", "minItems", "uniqueItems", "contains" ]; var stringKeywords = [ "maxLength", "minLength", "pattern" ]; var numberKeywords = [ "multipleOf", "maximum", "exclusiveMaximum", "minimum", "exclusiveMinimum" ]; function inferTypeByKeyword(schema) { for (var keyword of objectKeywords) { if (keyword in schema) return "object"; } for (var keyword of arrayKeywords) { if (keyword in schema) return "array"; } for (var keyword of stringKeywords) { if (keyword in schema) return "string"; } for (var keyword of numberKeywords) { if (keyword in schema) return "number"; } return schema.type; } function buildExtraObjectPropertiesSerializer(context, location, addComma) { const schema = location.schema; const propertiesKeys = Object.keys(schema.properties || {}); let code = ` const propertiesKeys = ${JSON.stringify(propertiesKeys)} for (const [key, value] of Object.entries(obj)) { if ( propertiesKeys.includes(key) || value === undefined || typeof value === 'function' || typeof value === 'symbol' ) continue `; const patternPropertiesLocation = location.getPropertyLocation("patternProperties"); const patternPropertiesSchema = patternPropertiesLocation.schema; if (patternPropertiesSchema !== void 0) { for (const propertyKey in patternPropertiesSchema) { const propertyLocation = patternPropertiesLocation.getPropertyLocation(propertyKey); code += ` if (/${propertyKey.replace(/\\*\//g, "\\/")}/.test(key)) { ${addComma} json += serializer.asString(key) + JSON_STR_COLONS ${buildValue(context, propertyLocation, "value")} continue } `; } } const additionalPropertiesLocation = location.getPropertyLocation("additionalProperties"); const additionalPropertiesSchema = additionalPropertiesLocation.schema; if (additionalPropertiesSchema !== void 0) { if (additionalPropertiesSchema === true) { code += ` ${addComma} json += serializer.asString(key) + JSON_STR_COLONS + JSON.stringify(value) `; } else { const propertyLocation = location.getPropertyLocation("additionalProperties"); code += ` ${addComma} json += serializer.asString(key) + JSON_STR_COLONS ${buildValue(context, propertyLocation, "value")} `; } } code += ` } `; return code; } function buildInnerObject(context, location) { const schema = location.schema; const propertiesLocation = location.getPropertyLocation("properties"); const requiredProperties = schema.required || []; const propertiesKeys = Object.keys(schema.properties || {}).sort( (key1, key2) => { const required1 = requiredProperties.includes(key1); const required2 = requiredProperties.includes(key2); return required1 === required2 ? 0 : required1 ? -1 : 1; } ); const hasRequiredProperties = requiredProperties.includes(propertiesKeys[0]); let code = "let value\n"; for (const key of requiredProperties) { if (!propertiesKeys.includes(key)) { const sanitizedKey = JSON.stringify(key); code += `if (obj[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, "\\'")} is required!') `; } } code += "let json = JSON_STR_BEGIN_OBJECT\n"; let addComma = ""; if (!hasRequiredProperties) { code += "let addComma = false\n"; addComma = "!addComma && (addComma = true) || (json += JSON_STR_COMMA)"; } for (const key of propertiesKeys) { let propertyLocation = propertiesLocation.getPropertyLocation(key); if (propertyLocation.schema.$ref) { propertyLocation = resolveRef(context, propertyLocation); } const sanitizedKey = JSON.stringify(key); const defaultValue = propertyLocation.schema.default; const isRequired = requiredProperties.includes(key); code += ` value = obj[${sanitizedKey}] if (value !== undefined) { ${addComma} json += ${JSON.stringify(sanitizedKey + ":")} ${buildValue(context, propertyLocation, "value")} }`; if (defaultValue !== void 0) { code += ` else { ${addComma} json += ${JSON.stringify(sanitizedKey + ":" + JSON.stringify(defaultValue))} } `; } else if (isRequired) { code += ` else { throw new Error('${sanitizedKey.replace(/'/g, "\\'")} is required!') } `; } else { code += "\n"; } if (hasRequiredProperties) { addComma = "json += ','"; } } if (schema.patternProperties || schema.additionalProperties) { code += buildExtraObjectPropertiesSerializer(context, location, addComma); } code += ` return json + JSON_STR_END_OBJECT `; return code; } function mergeLocations(context, mergedSchemaId, mergedLocations) { for (let i = 0; i < mergedLocations.length; i++) { const location = mergedLocations[i]; const schema = location.schema; if (schema.$ref) { mergedLocations[i] = resolveRef(context, location); } } const mergedSchemas = []; for (const location of mergedLocations) { const schema = cloneOriginSchema(context, location.schema, location.schemaId); delete schema.$id; mergedSchemas.push(schema); } const mergedSchema = mergeSchemas(mergedSchemas); const mergedLocation = new Location(mergedSchema, mergedSchemaId); context.refResolver.addSchema(mergedSchema, mergedSchemaId); return mergedLocation; } function cloneOriginSchema(context, schema, schemaId) { const clonedSchema = Array.isArray(schema) ? [] : {}; if (schema.$id !== void 0 && schema.$id.charAt(0) !== "#") { schemaId = schema.$id; } const mergedSchemaRef = context.mergedSchemasIds.get(schema); if (mergedSchemaRef) { context.mergedSchemasIds.set(clonedSchema, mergedSchemaRef); } for (const key in schema) { let value = schema[key]; if (key === "$ref" && typeof value === "string" && value.charAt(0) === "#") { value = schemaId + value; } if (typeof value === "object" && value !== null) { value = cloneOriginSchema(context, value, schemaId); } clonedSchema[key] = value; } return clonedSchema; } function toJSON(variableName) { return `(${variableName} && typeof ${variableName}.toJSON === 'function') ? ${variableName}.toJSON() : ${variableName} `; } function buildObject(context, location) { const schema = location.schema; if (context.functionsNamesBySchema.has(schema)) { return context.functionsNamesBySchema.get(schema); } const functionName = generateFuncName(context); context.functionsNamesBySchema.set(schema, functionName); let schemaRef = location.getSchemaRef(); if (schemaRef.startsWith(context.rootSchemaId)) { schemaRef = schemaRef.replace(context.rootSchemaId, ""); } let functionCode = ` `; const nullable = schema.nullable === true; functionCode += ` // ${schemaRef} function ${functionName} (input) { const obj = ${toJSON("input")} ${!nullable ? "if (obj === null) return JSON_STR_EMPTY_OBJECT" : ""} ${buildInnerObject(context, location)} } `; context.functions.push(functionCode); return functionName; } function buildArray(context, location) { const schema = location.schema; let itemsLocation = location.getPropertyLocation("items"); itemsLocation.schema = itemsLocation.schema || {}; if (itemsLocation.schema.$ref) { itemsLocation = resolveRef(context, itemsLocation); } const itemsSchema = itemsLocation.schema; if (context.functionsNamesBySchema.has(schema)) { return context.functionsNamesBySchema.get(schema); } const functionName = generateFuncName(context); context.functionsNamesBySchema.set(schema, functionName); let schemaRef = location.getSchemaRef(); if (schemaRef.startsWith(context.rootSchemaId)) { schemaRef = schemaRef.replace(context.rootSchemaId, ""); } let functionCode = ` function ${functionName} (obj) { // ${schemaRef} `; const nullable = schema.nullable === true; functionCode += ` ${!nullable ? "if (obj === null) return JSON_STR_EMPTY_ARRAY" : ""} if (!Array.isArray(obj)) { throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`) } const arrayLength = obj.length `; if (!schema.additionalItems && Array.isArray(itemsSchema)) { functionCode += ` if (arrayLength > ${itemsSchema.length}) { throw new Error(\`Item at ${itemsSchema.length} does not match schema definition.\`) } `; } if (largeArrayMechanism === "json-stringify") { functionCode += `if (arrayLength >= ${largeArraySize}) return JSON.stringify(obj) `; } functionCode += ` const arrayEnd = arrayLength - 1 let value let json = '' `; if (Array.isArray(itemsSchema)) { for (let i = 0; i < itemsSchema.length; i++) { const item = itemsSchema[i]; functionCode += `value = obj[${i}]`; const tmpRes = buildValue(context, itemsLocation.getPropertyLocation(i), "value"); functionCode += ` if (${i} < arrayLength) { if (${buildArrayTypeCondition(item.type, `[${i}]`)}) { ${tmpRes} if (${i} < arrayEnd) { json += JSON_STR_COMMA } } else { throw new Error(\`Item at ${i} does not match schema definition.\`) } } `; } if (schema.additionalItems) { functionCode += ` for (let i = ${itemsSchema.length}; i < arrayLength; i++) { json += JSON.stringify(obj[i]) if (i < arrayEnd) { json += JSON_STR_COMMA } }`; } } else { const code = buildValue(context, itemsLocation, "obj[i]"); functionCode += ` for (let i = 0; i < arrayLength; i++) { ${code} if (i < arrayEnd) { json += JSON_STR_COMMA } }`; } functionCode += ` return JSON_STR_BEGIN_ARRAY + json + JSON_STR_END_ARRAY }`; context.functions.push(functionCode); return functionName; } function buildArrayTypeCondition(type, accessor) { let condition; switch (type) { case "null": condition = "value === null"; break; case "string": condition = `typeof value === 'string' || value === null || value instanceof Date || value instanceof RegExp || ( typeof value === "object" && typeof value.toString === "function" && value.toString !== Object.prototype.toString )`; break; case "integer": condition = "Number.isInteger(value)"; break; case "number": condition = "Number.isFinite(value)"; break; case "boolean": condition = "typeof value === 'boolean'"; break; case "object": condition = "value && typeof value === 'object' && value.constructor === Object"; break; case "array": condition = "Array.isArray(value)"; break; default: if (Array.isArray(type)) { const conditions = type.map((subType) => { return buildArrayTypeCondition(subType, accessor); }); condition = `(${conditions.join(" || ")})`; } } return condition; } function generateFuncName(context) { return "anonymous" + context.functionsCounter++; } function buildMultiTypeSerializer(context, location, input) { const schema = location.schema; const types = schema.type.sort((t1) => t1 === "null" ? -1 : 1); let code = ""; types.forEach((type, index) => { location.schema = { ...location.schema, type }; const nestedResult = buildSingleTypeSerializer(context, location, input); const statement = index === 0 ? "if" : "else if"; switch (type) { case "null": code += ` ${statement} (${input} === null) ${nestedResult} `; break; case "string": { code += ` ${statement}( typeof ${input} === "string" || ${input} === null || ${input} instanceof Date || ${input} instanceof RegExp || ( typeof ${input} === "object" && typeof ${input}.toString === "function" && ${input}.toString !== Object.prototype.toString ) ) ${nestedResult} `; break; } case "array": { code += ` ${statement}(Array.isArray(${input})) ${nestedResult} `; break; } case "integer": { code += ` ${statement}(Number.isInteger(${input}) || ${input} === null) ${nestedResult} `; break; } default: { code += ` ${statement}(typeof ${input} === "${type}" || ${input} === null) ${nestedResult} `; break; } } }); let schemaRef = location.getSchemaRef(); if (schemaRef.startsWith(context.rootSchemaId)) { schemaRef = schemaRef.replace(context.rootSchemaId, ""); } code += ` else throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`) `; return code; } function buildSingleTypeSerializer(context, location, input) { const schema = location.schema; switch (schema.type) { case "null": return "json += JSON_STR_NULL"; case "string": { if (schema.format === "date-time") { return `json += serializer.asDateTime(${input})`; } else if (schema.format === "date") { return `json += serializer.asDate(${input})`; } else if (schema.format === "time") { return `json += serializer.asTime(${input})`; } else if (schema.format === "unsafe") { return `json += serializer.asUnsafeString(${input})`; } else { return ` if (typeof ${input} !== 'string') { if (${input} === null) { json += JSON_STR_EMPTY_STRING } else if (${input} instanceof Date) { json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE } else if (${input} instanceof RegExp) { json += serializer.asString(${input}.source) } else { json += serializer.asString(${input}.toString()) } } else { json += serializer.asString(${input}) } `; } } case "integer": return `json += serializer.asInteger(${input})`; case "number": return `json += serializer.asNumber(${input})`; case "boolean": return `json += serializer.asBoolean(${input})`; case "object": { const funcName = buildObject(context, location); return `json += ${funcName}(${input})`; } case "array": { const funcName = buildArray(context, location); return `json += ${funcName}(${input})`; } case void 0: return `json += JSON.stringify(${input})`; default: throw new Error(`${schema.type} unsupported`); } } function buildConstSerializer(location, input) { const schema = location.schema; const type = schema.type; const hasNullType = Array.isArray(type) && type.includes("null"); let code = ""; if (hasNullType) { code += ` if (${input} === null) { json += JSON_STR_NULL } else { `; } code += `json += '${JSON.stringify(schema.const).replace(SINGLE_TICK, "\\'")}'`; if (hasNullType) { code += ` } `; } return code; } function buildAllOf(context, location, input) { const schema = location.schema; let mergedSchemaId = context.mergedSchemasIds.get(schema); if (mergedSchemaId) { const mergedLocation2 = getMergedLocation(context, mergedSchemaId); return buildValue(context, mergedLocation2, input); } mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context.mergedSchemasIds.set(schema, mergedSchemaId); const { allOf, ...schemaWithoutAllOf } = location.schema; const locations = [ new Location( schemaWithoutAllOf, location.schemaId, location.jsonPointer ) ]; const allOfsLocation = location.getPropertyLocation("allOf"); for (let i = 0; i < allOf.length; i++) { locations.push(allOfsLocation.getPropertyLocation(i)); } const mergedLocation = mergeLocations(context, mergedSchemaId, locations); return buildValue(context, mergedLocation, input); } function buildOneOf(context, location, input) { context.validatorSchemasIds.add(location.schemaId); const schema = location.schema; const type = schema.anyOf ? "anyOf" : "oneOf"; const { [type]: oneOfs, ...schemaWithoutAnyOf } = location.schema; const locationWithoutOneOf = new Location( schemaWithoutAnyOf, location.schemaId, location.jsonPointer ); const oneOfsLocation = location.getPropertyLocation(type); let code = ""; for (let index = 0; index < oneOfs.length; index++) { const optionLocation = oneOfsLocation.getPropertyLocation(index); const optionSchema = optionLocation.schema; let mergedSchemaId = context.mergedSchemasIds.get(optionSchema); let mergedLocation = null; if (mergedSchemaId) { mergedLocation = getMergedLocation(context, mergedSchemaId); } else { mergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context.mergedSchemasIds.set(optionSchema, mergedSchemaId); mergedLocation = mergeLocations(context, mergedSchemaId, [ locationWithoutOneOf, optionLocation ]); } const nestedResult = buildValue(context, mergedLocation, input); const schemaRef2 = optionLocation.getSchemaRef(); code += ` ${index === 0 ? "if" : "else if"}(validator.validate("${schemaRef2}", ${input})) ${nestedResult} `; } let schemaRef = location.getSchemaRef(); if (schemaRef.startsWith(context.rootSchemaId)) { schemaRef = schemaRef.replace(context.rootSchemaId, ""); } code += ` else throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`) `; return code; } function buildIfThenElse(context, location, input) { context.validatorSchemasIds.add(location.schemaId); const { if: ifSchema, then: thenSchema, else: elseSchema, ...schemaWithoutIfThenElse } = location.schema; const rootLocation = new Location( schemaWithoutIfThenElse, location.schemaId, location.jsonPointer ); const ifLocation = location.getPropertyLocation("if"); const ifSchemaRef = ifLocation.getSchemaRef(); const thenLocation = location.getPropertyLocation("then"); let thenMergedSchemaId = context.mergedSchemasIds.get(thenSchema); let thenMergedLocation = null; if (thenMergedSchemaId) { thenMergedLocation = getMergedLocation(context, thenMergedSchemaId); } else { thenMergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context.mergedSchemasIds.set(thenSchema, thenMergedSchemaId); thenMergedLocation = mergeLocations(context, thenMergedSchemaId, [ rootLocation, thenLocation ]); } if (!elseSchema) { return ` if (validator.validate("${ifSchemaRef}", ${input})) { ${buildValue(context, thenMergedLocation, input)} } else { ${buildValue(context, rootLocation, input)} } `; } const elseLocation = location.getPropertyLocation("else"); let elseMergedSchemaId = context.mergedSchemasIds.get(elseSchema); let elseMergedLocation = null; if (elseMergedSchemaId) { elseMergedLocation = getMergedLocation(context, elseMergedSchemaId); } else { elseMergedSchemaId = `__fjs_merged_${schemaIdCounter++}`; context.mergedSchemasIds.set(elseSchema, elseMergedSchemaId); elseMergedLocation = mergeLocations(context, elseMergedSchemaId, [ rootLocation, elseLocation ]); } return ` if (validator.validate("${ifSchemaRef}", ${input})) { ${buildValue(context, thenMergedLocation, input)} } else { ${buildValue(context, elseMergedLocation, input)} } `; } function buildValue(context, location, input) { let schema = location.schema; if (typeof schema === "boolean") { return `json += JSON.stringify(${input})`; } if (schema.$ref) { location = resolveRef(context, location); schema = location.schema; } if (schema.allOf) { return buildAllOf(context, location, input); } if (schema.anyOf || schema.oneOf) { return buildOneOf(context, location, input); } if (schema.if && schema.then) { return buildIfThenElse(context, location, input); } if (schema.type === void 0) { const inferredType = inferTypeByKeyword(schema); if (inferredType) { schema.type = inferredType; } } let code = ""; const type = schema.type; const nullable = schema.nullable === true; if (nullable) { code += ` if (${input} === null) { json += JSON_STR_NULL } else { `; } if (schema.const !== void 0) { code += buildConstSerializer(location, input); } else if (Array.isArray(type)) { code += buildMultiTypeSerializer(context, location, input); } else { code += buildSingleTypeSerializer(context, location, input); } if (nullable) { code += ` } `; } return code; } module2.exports = build; module2.exports.default = build; module2.exports.build = build; module2.exports.validLargeArrayMechanisms = validLargeArrayMechanisms; module2.exports.restore = function({ code, validator, serializer }) { return Function.apply(null, ["validator", "serializer", code]).apply(null, [validator, serializer]); }; } }); // node_modules/@fastify/fast-json-stringify-compiler/standalone.js var require_standalone2 = __commonJS({ "node_modules/@fastify/fast-json-stringify-compiler/standalone.js"(exports, module2) { "use strict"; var SerializerSelector = require_fast_json_stringify_compiler(); function StandaloneSerializer(options = { readMode: true }) { if (options.readMode === true && typeof options.restoreFunction !== "function") { throw new Error("You must provide a function for the restoreFunction-option when readMode ON"); } if (options.readMode !== true && typeof options.storeFunction !== "function") { throw new Error("You must provide a function for the storeFunction-option when readMode OFF"); } if (options.readMode === true) { return function wrapper() { return function(opts) { return options.restoreFunction(opts); }; }; } const factory = SerializerSelector(); return function wrapper(externalSchemas, serializerOpts = {}) { serializerOpts.mode = "standalone"; const compiler = factory(externalSchemas, serializerOpts); return function(opts) { const serializeFuncCode = compiler(opts); options.storeFunction(opts, serializeFuncCode); return new Function(serializeFuncCode); }; }; } module2.exports = StandaloneSerializer; module2.exports.default = StandaloneSerializer; } }); // node_modules/@fastify/fast-json-stringify-compiler/index.js var require_fast_json_stringify_compiler = __commonJS({ "node_modules/@fastify/fast-json-stringify-compiler/index.js"(exports, module2) { "use strict"; var fastJsonStringify = require_fast_json_stringify(); function SerializerSelector() { return function buildSerializerFactory(externalSchemas, serializerOpts) { const fjsOpts = Object.assign({}, serializerOpts, { schema: externalSchemas }); return responseSchemaCompiler.bind(null, fjsOpts); }; } function responseSchemaCompiler(fjsOpts, { schema /* method, url, httpStatus */ }) { if (fjsOpts.schema && schema.$id && fjsOpts.schema[schema.$id]) { fjsOpts.schema = { ...fjsOpts.schema }; delete fjsOpts.schema[schema.$id]; } return fastJsonStringify(schema, fjsOpts); } module2.exports = SerializerSelector; module2.exports.default = SerializerSelector; module2.exports.SerializerSelector = SerializerSelector; module2.exports.StandaloneSerializer = require_standalone2(); } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/codegen/code.js var require_code3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/codegen/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; var _CodeOrName = class { }; exports._CodeOrName = _CodeOrName; exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s) { super(); if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a; return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); } get names() { var _a; return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}); } }; exports._Code = _Code; exports.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports._ = _; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== void 0) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports.strConcat = strConcat; function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports.stringify = stringify; function safeStringify(x) { return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; } exports.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports.regexpCode = regexpCode; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/codegen/scope.js var require_scope2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; var code_1 = require_code3(); var ValueError = class extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a, _b; if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports.ValueScopeName = ValueScopeName; var line = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = /* @__PURE__ */ new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._)`${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } }; exports.ValueScope = ValueScope; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/codegen/index.js var require_codegen2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/codegen/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; var code_1 = require_code3(); var scope_1 = require_scope2(); var code_2 = require_code3(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope2(); Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } }; var Label = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } }; var Break = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } }; var Throw = class extends Node { constructor(error) { super(); this.error = error; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } }; var AnyCode = class extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof If ? e : e.nodes; if (this.nodes.length) return this; return new If(not(cond), e instanceof If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a; this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a, _b; super.optimizeNodes(); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a, _b; super.optimizeNames(names, constants); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error) { super(); this.error = error; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { this.var(name, (0, code_1._)`${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error = this.name("e"); this._currNode = node.catch = new Catch(error); catchCode(error); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error) { return this._leafNode(new Throw(error)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || N2 && n instanceof N2) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } }; exports.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === void 0 || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; } exports.not = not; var andCode = mappend(exports.operators.AND); function and(...args) { return args.reduce(andCode); } exports.and = and; var orCode = mappend(exports.operators.OR); function or(...args) { return args.reduce(orCode); } exports.or = or; function mappend(op) { return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/util.js var require_util2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/util.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; var codegen_1 = require_codegen2(); var code_1 = require_code3(); function toHash(arr) { const hash = {}; for (const item of arr) hash[item] = true; return hash; } exports.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps !== void 0) setEvaluated(gen, props, ps); return props; } exports.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); } exports.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports.checkStrictMode = checkStrictMode; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/names.js var require_names2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/names.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports.default = names; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/errors.js var require_errors5 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/errors.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); var names_1 = require_names2(); exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._)`[${errObj}]`); } } exports.reportError = reportError; function reportExtraError(cxt, error = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err}.data`, data); } }); } exports.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error, errorPaths); } function errorObject(cxt, error, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; var errors_1 = require_errors5(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); falseSchemaError(it); } else { gen.var(valid, true); } } exports.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/rules.js var require_rules2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/rules.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRules = exports.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports.getRules = getRules; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/applicability.js var require_applicability2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a; return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); } exports.shouldUseRule = shouldUseRule; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/dataType.js var require_dataType2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; var rules_1 = require_rules2(); var applicability_1 = require_applicability2(); var errors_1 = require_errors5(); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it }; } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/defaults.js var require_defaults2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assignDefaults = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/code.js var require_code4 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); var names_1 = require_names2(); var util_2 = require_util2(); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); } exports.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports.validateUnion = validateUnion; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/keyword.js var require_keyword2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; var codegen_1 = require_codegen2(); var names_1 = require_names2(); var code_1 = require_code4(); var errors_1 = require_errors5(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a2; gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors); } } exports.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); } exports.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/subschema.js var require_subschema2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/@fastify/ajv-compiler/node_modules/json-schema-traverse/index.js var require_json_schema_traverse2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/json-schema-traverse/index.js"(exports, module2) { "use strict"; var traverse = module2.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/resolve.js var require_resolve2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/resolve.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; var util_1 = require_util2(); var equal = require_fast_deep_equal(); var traverse = require_json_schema_traverse2(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports.getSchemaRefs = getSchemaRefs; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/index.js var require_validate2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/validate/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema2(); var dataType_1 = require_dataType2(); var applicability_1 = require_applicability2(); var dataType_2 = require_dataType2(); var defaults_1 = require_defaults2(); var keyword_1 = require_keyword2(); var subschema_1 = require_subschema2(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var resolve_1 = require_resolve2(); var util_1 = require_util2(); var errors_1 = require_errors5(); function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults } } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts, t) { return ts.includes(t) || t === "integer" && ts.includes("number"); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } var KeywordCxt = class { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment of segments) { if (segment) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports.getData = getData; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/validation_error.js var require_validation_error2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/validation_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports.default = ValidationError; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/ref_error.js var require_ref_error2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/ref_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var resolve_1 = require_resolve2(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports.default = MissingRefError; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/index.js var require_compile2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; var codegen_1 = require_codegen2(); var validation_error_1 = require_validation_error2(); var names_1 = require_names2(); var resolve_1 = require_resolve2(); var util_1 = require_util2(); var validate_1 = require_validate2(); var SchemaEnv = class { constructor(env) { var _a; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e; } finally { this._compilations.delete(sch); } } exports.compileSchema = compileSchema; function resolveRef(root, baseId, ref) { var _a; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === void 0) { const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports.resolveRef = resolveRef; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a; if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/refs/data.json var require_data2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/refs/data.json"(exports, module2) { module2.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/uri.js var require_uri2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/uri.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var uri = require_uri_all(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports.default = uri; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/core.js var require_core3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/core.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; var validate_1 = require_validate2(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen2(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error2(); var ref_error_1 = require_ref_error2(); var rules_1 = require_rules2(); var compile_1 = require_compile2(); var codegen_2 = require_codegen2(); var resolve_1 = require_resolve2(); var dataType_1 = require_dataType2(); var util_1 = require_util2(); var $dataRefSchema = require_data2(); var uri_1 = require_uri2(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = {}; this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; } validate(schemaKeyRef, data) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv.ValidationError = validation_error_1.default; Ajv.MissingRefError = ref_error_1.default; exports.default = Ajv; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/core/id.js var require_id2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/core/ref.js var require_ref2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.callRef = exports.getValidate = void 0; var ref_error_1 = require_ref_error2(); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var compile_1 = require_compile2(); var util_1 = require_util2(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a; if (!it.opts.unevaluated) return; const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports.callRef = callRef; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/core/index.js var require_core4 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var id_1 = require_id2(); var ref_1 = require_ref2(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports.default = core; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var ucs2length_1 = require_ucs2length2(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error, code(cxt) { const { data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/required.js var require_required2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var error = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/equal.js var require_equal2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/equal.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var equal = require_fast_deep_equal(); equal.code = 'require("ajv/dist/runtime/equal").default'; exports.default = equal; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var dataType_1 = require_dataType2(); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var equal_1 = require_equal2(); var error = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._)`${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/const.js var require_const2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var equal_1 = require_equal2(); var error = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var equal_1 = require_equal2(); var error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/index.js var require_validation3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber2(); var multipleOf_1 = require_multipleOf2(); var limitLength_1 = require_limitLength2(); var pattern_1 = require_pattern2(); var limitProperties_1 = require_limitProperties2(); var required_1 = require_required2(); var limitItems_1 = require_limitItems2(); var uniqueItems_1 = require_uniqueItems2(); var const_1 = require_const2(); var enum_1 = require_enum2(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports.default = validation; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); var error = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports.validateAdditionalItems = validateAdditionalItems; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/items.js var require_items2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateTuple = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); var code_1 = require_code4(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports.validateTuple = validateTuple; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = require_items2(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items20202 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var code_1 = require_code4(); var additionalItems_1 = require_additionalItems2(); var error = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var error = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === void 0 ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max }); if (max === void 0 && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== void 0 && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util2(); var code_1 = require_code4(); exports.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports.validateSchemaDeps = validateSchemaDeps; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var error = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var util_1 = require_util2(); var error = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var validate_1 = require_validate2(); var code_1 = require_code4(); var util_1 = require_util2(); var additionalProperties_1 = require_additionalProperties2(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var util_2 = require_util2(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/not.js var require_not2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util2(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code4(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var error = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true }, schValid); } if (i > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util2(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/if.js var require_if2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util2(); var error = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); } exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util2(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems2(); var prefixItems_1 = require_prefixItems2(); var items_1 = require_items2(); var items2020_1 = require_items20202(); var contains_1 = require_contains2(); var dependencies_1 = require_dependencies2(); var propertyNames_1 = require_propertyNames2(); var additionalProperties_1 = require_additionalProperties2(); var properties_1 = require_properties2(); var patternProperties_1 = require_patternProperties2(); var not_1 = require_not2(); var anyOf_1 = require_anyOf2(); var oneOf_1 = require_oneOf2(); var allOf_1 = require_allOf2(); var if_1 = require_if2(); var thenElse_1 = require_thenElse2(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports.default = getApplicator; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/format/format.js var require_format3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/format/index.js var require_format4 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var format_1 = require_format3(); var format = [format_1.default]; exports.default = format; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/metadata.js var require_metadata2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.contentVocabulary = exports.metadataVocabulary = void 0; exports.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/draft7.js var require_draft72 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require_core4(); var validation_1 = require_validation3(); var applicator_1 = require_applicator2(); var format_1 = require_format4(); var metadata_1 = require_metadata2(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports.default = draft7Vocabularies; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports.DiscrError = DiscrError = {})); } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var types_1 = require_types2(); var compile_1 = require_compile2(); var ref_error_1 = require_ref_error2(); var util_1 = require_util2(); var error = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required }) { return Array.isArray(required) && required.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_072 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module2) { module2.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/ajv.js var require_ajv2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/ajv.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; var core_1 = require_core3(); var draft7_1 = require_draft72(); var discriminator_1 = require_discriminator2(); var draft7MetaSchema = require_json_schema_draft_072(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports.Ajv = Ajv; module2.exports = exports = Ajv; module2.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv; var validate_1 = require_validate2(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen2(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error2(); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error2(); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/metadata.js var require_metadata3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/metadata.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkMetadata = void 0; var util_1 = require_util2(); var def = { keyword: "metadata", schemaType: "object", code(cxt) { checkMetadata(cxt); const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid); cxt.ok(valid); } }; function checkMetadata({ it, keyword }, metadata) { if (it.jtdMetadata !== metadata) { throw new Error(`JTD: "${keyword}" cannot be used in this schema location`); } } exports.checkMetadata = checkMetadata; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/ref.js var require_ref3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/ref.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hasRef = void 0; var compile_1 = require_compile2(); var codegen_1 = require_codegen2(); var ref_error_1 = require_ref_error2(); var names_1 = require_names2(); var ref_1 = require_ref2(); var metadata_1 = require_metadata3(); var def = { keyword: "ref", schemaType: "string", code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema: ref, parentSchema, it } = cxt; const { schemaEnv: { root } } = it; const valid = gen.name("valid"); if (parentSchema.nullable) { gen.var(valid, (0, codegen_1._)`${data} === null`); gen.if((0, codegen_1.not)(valid), validateJtdRef); } else { gen.var(valid, false); validateJtdRef(); } cxt.ok(valid); function validateJtdRef() { var _a; const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref]; if (!refSchema) { throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`); } if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema); else inlineRefSchema(refSchema); } function callValidate(schema) { const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` })); const v = (0, ref_1.getValidate)(cxt, sch); const errsCount = gen.const("_errs", names_1.default.errors); (0, ref_1.callRef)(cxt, v, sch, sch.$async); gen.assign(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function inlineRefSchema(schema) { const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema }); cxt.subschema({ schema, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: `/definitions/${ref}` }, valid); } } }; function hasRef(schema) { for (const key in schema) { let sch; if (key === "ref" || typeof (sch = schema[key]) == "object" && hasRef(sch)) return true; } return false; } exports.hasRef = hasRef; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/timestamp.js var require_timestamp = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/timestamp.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DT_SEPARATOR = /t|\s/i; var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i; var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function validTimestamp(str, allowDate) { const dt = str.split(DT_SEPARATOR); return dt.length === 2 && validDate(dt[0]) && validTime(dt[1]) || allowDate && dt.length === 1 && validDate(dt[0]); } exports.default = validTimestamp; function validDate(str) { const matches = DATE.exec(str); if (!matches) return false; const y = +matches[1]; const m = +matches[2]; const d = +matches[3]; return m >= 1 && m <= 12 && d >= 1 && (d <= DAYS[m] || // leap year: https://tools.ietf.org/html/rfc3339#appendix-C m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)); } function validTime(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tzH = +(matches[4] || 0); const tzM = +(matches[5] || 0); return hr <= 23 && min <= 59 && sec <= 59 || // leap second hr - tzH === 23 && min - tzM === 59 && sec === 60; } validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/error.js var require_error2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0; var codegen_1 = require_codegen2(); function typeError(t) { return { message: (cxt) => typeErrorMessage(cxt, t), params: (cxt) => typeErrorParams(cxt, t) }; } exports.typeError = typeError; function typeErrorMessage({ parentSchema }, t) { return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`; } exports.typeErrorMessage = typeErrorMessage; function typeErrorParams({ parentSchema }, t) { return (0, codegen_1._)`{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`; } exports.typeErrorParams = typeErrorParams; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/type.js var require_type = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/type.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.intRange = void 0; var codegen_1 = require_codegen2(); var timestamp_1 = require_timestamp(); var util_1 = require_util2(); var metadata_1 = require_metadata3(); var error_1 = require_error2(); exports.intRange = { int8: [-128, 127, 3], uint8: [0, 255, 3], int16: [-32768, 32767, 5], uint16: [0, 65535, 5], int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10] }; var error = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema) }; function timestampCode(cxt) { const { gen, data, it } = cxt; const { timestamp, allowDate } = it.opts; if (timestamp === "date") return (0, codegen_1._)`${data} instanceof Date `; const vts = (0, util_1.useFunc)(gen, timestamp_1.default); const allowDateArg = allowDate ? (0, codegen_1._)`, true` : codegen_1.nil; const validString = (0, codegen_1._)`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`; return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._)`${data} instanceof Date`, validString); } var def = { keyword: "type", schemaType: "string", error, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; let cond; switch (schema) { case "boolean": case "string": cond = (0, codegen_1._)`typeof ${data} == ${schema}`; break; case "timestamp": { cond = timestampCode(cxt); break; } case "float32": case "float64": cond = (0, codegen_1._)`typeof ${data} == "number"`; break; default: { const sch = schema; cond = (0, codegen_1._)`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`; if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { if (sch === "uint32") cond = (0, codegen_1._)`${cond} && ${data} >= 0`; } else { const [min, max] = exports.intRange[sch]; cond = (0, codegen_1._)`${cond} && ${data} >= ${min} && ${data} <= ${max}`; } } } cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._)`${data} === null`, cond) : cond); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/nullable.js var require_nullable = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/nullable.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkNullableObject = exports.checkNullable = void 0; var codegen_1 = require_codegen2(); function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) { const valid = gen.name("valid"); if (parentSchema.nullable) { gen.let(valid, (0, codegen_1._)`${data} === null`); cond = (0, codegen_1.not)(valid); } else { gen.let(valid, false); } return [valid, cond]; } exports.checkNullable = checkNullable; function checkNullableObject(cxt, cond) { const [valid, cond_] = checkNullable(cxt, cond); return [valid, (0, codegen_1._)`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]; } exports.checkNullableObject = checkNullableObject; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/enum.js var require_enum3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/enum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var metadata_1 = require_metadata3(); var nullable_1 = require_nullable(); var error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", error, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; if (schema.length === 0) throw new Error("enum must have non-empty array"); if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique"); let valid; const isString = (0, codegen_1._)`typeof ${data} == "string"`; if (schema.length >= it.opts.loopEnum) { let cond; [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString); gen.if(cond, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._)`${data} === ${value}`))); if (parentSchema.nullable) valid = (0, codegen_1.or)((0, codegen_1._)`${data} === null`, valid); } cxt.pass(valid); function loopEnum() { gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._)`${valid} = ${data} === ${v}`, () => gen.break())); } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/elements.js var require_elements = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/elements.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util2(); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var metadata_1 = require_metadata3(); var nullable_1 = require_nullable(); var error_1 = require_error2(); var def = { keyword: "elements", schemaType: "object", error: (0, error_1.typeError)("array"), code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const [valid] = (0, nullable_1.checkNullable)(cxt); gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._)`Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error())); cxt.ok(valid); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/properties.js var require_properties3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/properties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateProperties = exports.error = void 0; var code_1 = require_code4(); var util_1 = require_util2(); var codegen_1 = require_codegen2(); var metadata_1 = require_metadata3(); var nullable_1 = require_nullable(); var error_1 = require_error2(); var PropError; (function(PropError2) { PropError2["Additional"] = "additional"; PropError2["Missing"] = "missing"; })(PropError || (PropError = {})); exports.error = { message: (cxt) => { const { params } = cxt; return params.propError ? params.propError === PropError.Additional ? "must NOT have additional properties" : `must have property '${params.missingProperty}'` : (0, error_1.typeErrorMessage)(cxt, "object"); }, params: (cxt) => { const { params } = cxt; return params.propError ? params.propError === PropError.Additional ? (0, codegen_1._)`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` : (0, codegen_1._)`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` : (0, error_1.typeErrorParams)(cxt, "object"); } }; var def = { keyword: "properties", schemaType: "object", error: exports.error, code: validateProperties }; function validateProperties(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, parentSchema, it } = cxt; const { additionalProperties, nullable } = parentSchema; if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping"); if (commonProperties()) { throw new Error("JTD: properties and optionalProperties have common members"); } const [allProps, properties] = schemaProperties("properties"); const [allOptProps, optProperties] = schemaProperties("optionalProperties"); if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { return; } const [valid, cond] = it.jtdDiscriminator === void 0 ? (0, nullable_1.checkNullableObject)(cxt, data) : [gen.let("valid", false), true]; gen.if(cond, () => gen.assign(valid, true).block(() => { validateProps(properties, "properties", true); validateProps(optProperties, "optionalProperties"); if (!additionalProperties) validateAdditional(); })); cxt.pass(valid); function commonProperties() { const props = parentSchema.properties; const optProps = parentSchema.optionalProperties; if (!(props && optProps)) return false; for (const p in props) { if (Object.prototype.hasOwnProperty.call(optProps, p)) return true; } return false; } function schemaProperties(keyword) { const schema = parentSchema[keyword]; const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : []; if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { throw new Error(`JTD: discriminator tag used in ${keyword}`); } const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); return [allPs, ps]; } function validateProps(props, keyword, required) { const _valid = gen.var("valid"); for (const prop of props) { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop)); cxt.ok(_valid); } function missingProperty(prop) { if (required) { gen.assign(_valid, false); cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop }); } else { gen.assign(_valid, true); } } } function applyPropertySchema(prop, keyword, _valid) { cxt.subschema({ keyword, schemaProp: prop, dataProp: prop }, _valid); } function validateAdditional() { gen.forIn("key", data, (key) => { const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator); const addOptProp = isAdditional(key, allOptProps, "optionalProperties"); const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp); gen.if(extra, () => { if (it.opts.removeAdditional) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } else { cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true }); if (!it.opts.allErrors) gen.break(); } }); }); } function isAdditional(key, props, keyword, jtdDiscriminator) { let additional; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword); additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key)); if (jtdDiscriminator !== void 0) { additional = (0, codegen_1.and)(additional, (0, codegen_1._)`${key} !== ${jtdDiscriminator}`); } } else if (props.length || jtdDiscriminator !== void 0) { const ps = jtdDiscriminator === void 0 ? props : [jtdDiscriminator].concat(props); additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._)`${key} !== ${p}`)); } else { additional = true; } return additional; } } exports.validateProperties = validateProperties; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js var require_optionalProperties = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var properties_1 = require_properties3(); var def = { keyword: "optionalProperties", schemaType: "object", error: properties_1.error, code(cxt) { if (cxt.parentSchema.properties) return; (0, properties_1.validateProperties)(cxt); } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/discriminator.js var require_discriminator3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/discriminator.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var metadata_1 = require_metadata3(); var nullable_1 = require_nullable(); var error_1 = require_error2(); var types_1 = require_types2(); var error = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); }, params: (cxt) => { const { schema, params } = cxt; return params.discrError ? (0, codegen_1._)`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` : (0, error_1.typeErrorParams)(cxt, "object"); } }; var def = { keyword: "discriminator", schemaType: "string", implements: ["mapping"], error, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); gen.if(cond); validateDiscriminator(); gen.elseIf((0, codegen_1.not)(valid)); cxt.error(); gen.endIf(); cxt.ok(valid); function validateDiscriminator() { const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(schema)}`); gen.if((0, codegen_1._)`${tag} === undefined`); cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }); gen.elseIf((0, codegen_1._)`typeof ${tag} == "string"`); validateMapping(tag); gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema }); gen.endIf(); } function validateMapping(tag) { gen.if(false); for (const tagValue in parentSchema.mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(tagValue)); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); cxt.subschema({ keyword: "mapping", schemaProp, jtdDiscriminator: schema }, _valid); return _valid; } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/values.js var require_values = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/values.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util2(); var codegen_1 = require_codegen2(); var metadata_1 = require_metadata3(); var nullable_1 = require_nullable(); var error_1 = require_error2(); var def = { keyword: "values", schemaType: "object", error: (0, error_1.typeError)("object"), code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, it } = cxt; const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); if ((0, util_1.alwaysValidSchema)(it, schema)) { gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error()); } else { gen.if(cond); gen.assign(valid, validateMap()); gen.elseIf((0, codegen_1.not)(valid)); cxt.error(); gen.endIf(); } cxt.ok(valid); function validateMap() { const _valid = gen.name("valid"); if (it.allErrors) { const validMap = gen.let("valid", true); validateValues(() => gen.assign(validMap, false)); return validMap; } gen.var(_valid, true); validateValues(() => gen.break()); return _valid; function validateValues(notValid) { gen.forIn("key", data, (key) => { cxt.subschema({ keyword: "values", dataProp: key, dataPropType: util_1.Type.Str }, _valid); gen.if((0, codegen_1.not)(_valid), notValid); }); } } } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/union.js var require_union = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/union.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code4(); var def = { keyword: "union", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in union" } }; exports.default = def; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/index.js var require_jtd = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/vocabularies/jtd/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ref_1 = require_ref3(); var type_1 = require_type(); var enum_1 = require_enum3(); var elements_1 = require_elements(); var properties_1 = require_properties3(); var optionalProperties_1 = require_optionalProperties(); var discriminator_1 = require_discriminator3(); var values_1 = require_values(); var union_1 = require_union(); var metadata_1 = require_metadata3(); var jtdVocabulary = [ "definitions", ref_1.default, type_1.default, enum_1.default, elements_1.default, properties_1.default, optionalProperties_1.default, discriminator_1.default, values_1.default, union_1.default, metadata_1.default, { keyword: "additionalProperties", schemaType: "boolean" }, { keyword: "nullable", schemaType: "boolean" } ]; exports.default = jtdVocabulary; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/refs/jtd-schema.js var require_jtd_schema = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/refs/jtd-schema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var shared = (root) => { const sch = { nullable: { type: "boolean" }, metadata: { optionalProperties: { union: { elements: { ref: "schema" } } }, additionalProperties: true } }; if (root) sch.definitions = { values: { ref: "schema" } }; return sch; }; var emptyForm = (root) => ({ optionalProperties: shared(root) }); var refForm = (root) => ({ properties: { ref: { type: "string" } }, optionalProperties: shared(root) }); var typeForm = (root) => ({ properties: { type: { enum: [ "boolean", "timestamp", "string", "float32", "float64", "int8", "uint8", "int16", "uint16", "int32", "uint32" ] } }, optionalProperties: shared(root) }); var enumForm = (root) => ({ properties: { enum: { elements: { type: "string" } } }, optionalProperties: shared(root) }); var elementsForm = (root) => ({ properties: { elements: { ref: "schema" } }, optionalProperties: shared(root) }); var propertiesForm = (root) => ({ properties: { properties: { values: { ref: "schema" } } }, optionalProperties: { optionalProperties: { values: { ref: "schema" } }, additionalProperties: { type: "boolean" }, ...shared(root) } }); var optionalPropertiesForm = (root) => ({ properties: { optionalProperties: { values: { ref: "schema" } } }, optionalProperties: { additionalProperties: { type: "boolean" }, ...shared(root) } }); var discriminatorForm = (root) => ({ properties: { discriminator: { type: "string" }, mapping: { values: { metadata: { union: [propertiesForm(false), optionalPropertiesForm(false)] } } } }, optionalProperties: shared(root) }); var valuesForm = (root) => ({ properties: { values: { ref: "schema" } }, optionalProperties: shared(root) }); var schema = (root) => ({ metadata: { union: [ emptyForm, refForm, typeForm, enumForm, elementsForm, propertiesForm, optionalPropertiesForm, discriminatorForm, valuesForm ].map((s) => s(root)) } }); var jtdMetaSchema = { definitions: { schema: schema(false) }, ...schema(true) }; exports.default = jtdMetaSchema; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/jtd/types.js var require_types3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/jtd/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jtdForms = void 0; exports.jtdForms = [ "elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref" ]; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/quote.js var require_quote = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/quote.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rxEscapable = ( // eslint-disable-next-line no-control-regex, no-misleading-character-class /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g ); var escaped = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\" }; function quote(s) { rxEscapable.lastIndex = 0; return '"' + (rxEscapable.test(s) ? s.replace(rxEscapable, (a) => { const c = escaped[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) : s) + '"'; } exports.default = quote; quote.code = 'require("ajv/dist/runtime/quote").default'; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/jtd/serialize.js var require_serialize = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/jtd/serialize.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = require_types3(); var __1 = require_compile2(); var codegen_1 = require_codegen2(); var ref_error_1 = require_ref_error2(); var names_1 = require_names2(); var code_1 = require_code4(); var ref_1 = require_ref3(); var util_1 = require_util2(); var quote_1 = require_quote(); var genSerialize = { elements: serializeElements, values: serializeValues, discriminator: serializeDiscriminator, properties: serializeProperties, optionalProperties: serializeProperties, enum: serializeString, type: serializeType, ref: serializeRef }; function compileSerializer(sch, definitions) { const _sch = __1.getCompilingSchema.call(this, sch); if (_sch) return _sch; const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); const serializeName = gen.scopeName("serialize"); const cxt = { self: this, gen, schema: sch.schema, schemaEnv: sch, definitions, data: names_1.default.data }; let sourceCode; try { this._compilations.add(sch); sch.serializeName = serializeName; gen.func(serializeName, names_1.default.data, false, () => { gen.let(names_1.default.json, (0, codegen_1.str)``); serializeCode(cxt); gen.return(names_1.default.json); }); gen.optimize(this.opts.code.optimize); const serializeFuncCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`; const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode); const serialize = makeSerialize(this.scope.get()); this.scope.value(serializeName, { ref: serialize }); sch.serialize = serialize; } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode); delete sch.serialize; delete sch.serializeName; throw e; } finally { this._compilations.delete(sch); } return sch; } exports.default = compileSerializer; function serializeCode(cxt) { let form; for (const key of types_1.jtdForms) { if (key in cxt.schema) { form = key; break; } } serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty); } function serializeNullable(cxt, serializeForm) { const { gen, schema, data } = cxt; if (!schema.nullable) return serializeForm(cxt); gen.if((0, codegen_1._)`${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._)`"null"`), () => serializeForm(cxt)); } function serializeElements(cxt) { const { gen, schema, data } = cxt; gen.add(names_1.default.json, (0, codegen_1.str)`[`); const first = gen.let("first", true); gen.forOf("el", data, (el) => { addComma(cxt, first); serializeCode({ ...cxt, schema: schema.elements, data: el }); }); gen.add(names_1.default.json, (0, codegen_1.str)`]`); } function serializeValues(cxt) { const { gen, schema, data } = cxt; gen.add(names_1.default.json, (0, codegen_1.str)`{`); const first = gen.let("first", true); gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)); gen.add(names_1.default.json, (0, codegen_1.str)`}`); } function serializeKeyValue(cxt, key, schema, first) { const { gen, data } = cxt; addComma(cxt, first); serializeString({ ...cxt, data: key }); gen.add(names_1.default.json, (0, codegen_1.str)`:`); const value = gen.const("value", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(key)}`); serializeCode({ ...cxt, schema, data: value }); } function serializeDiscriminator(cxt) { const { gen, schema, data } = cxt; const { discriminator } = schema; gen.add(names_1.default.json, (0, codegen_1.str)`{${JSON.stringify(discriminator)}:`); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(discriminator)}`); serializeString({ ...cxt, data: tag }); gen.if(false); for (const tagValue in schema.mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); const sch = schema.mapping[tagValue]; serializeSchemaProperties({ ...cxt, schema: sch }, discriminator); } gen.endIf(); gen.add(names_1.default.json, (0, codegen_1.str)`}`); } function serializeProperties(cxt) { const { gen } = cxt; gen.add(names_1.default.json, (0, codegen_1.str)`{`); serializeSchemaProperties(cxt); gen.add(names_1.default.json, (0, codegen_1.str)`}`); } function serializeSchemaProperties(cxt, discriminator) { const { gen, schema, data } = cxt; const { properties, optionalProperties } = schema; const props = keys(properties); const optProps = keys(optionalProperties); const allProps = allProperties(props.concat(optProps)); let first = !discriminator; let firstProp; for (const key of props) { if (first) first = false; else gen.add(names_1.default.json, (0, codegen_1.str)`,`); serializeProperty(key, properties[key], keyValue(key)); } if (first) firstProp = gen.let("first", true); for (const key of optProps) { const value = keyValue(key); gen.if((0, codegen_1.and)((0, codegen_1._)`${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => { addComma(cxt, firstProp); serializeProperty(key, optionalProperties[key], value); }); } if (schema.additionalProperties) { gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))); } function keys(ps) { return ps ? Object.keys(ps) : []; } function allProperties(ps) { if (discriminator) ps.push(discriminator); if (new Set(ps).size !== ps.length) { throw new Error("JTD: properties/optionalProperties/disciminator overlap"); } return ps; } function keyValue(key) { return gen.const("value", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(key)}`); } function serializeProperty(key, propSchema, value) { gen.add(names_1.default.json, (0, codegen_1.str)`${JSON.stringify(key)}:`); serializeCode({ ...cxt, schema: propSchema, data: value }); } function isAdditional(key, ps) { return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._)`${key} !== ${p}`)) : true; } } function serializeType(cxt) { const { gen, schema, data } = cxt; switch (schema.type) { case "boolean": gen.add(names_1.default.json, (0, codegen_1._)`${data} ? "true" : "false"`); break; case "string": serializeString(cxt); break; case "timestamp": gen.if((0, codegen_1._)`${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._)`'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt)); break; default: serializeNumber(cxt); } } function serializeString({ gen, data }) { gen.add(names_1.default.json, (0, codegen_1._)`${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`); } function serializeNumber({ gen, data }) { gen.add(names_1.default.json, (0, codegen_1._)`"" + ${data}`); } function serializeRef(cxt) { const { gen, self, data, definitions, schema, schemaEnv } = cxt; const { ref } = schema; const refSchema = definitions[ref]; if (!refSchema) throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); if (!(0, ref_1.hasRef)(refSchema)) return serializeCode({ ...cxt, schema: refSchema }); const { root } = schemaEnv; const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); gen.add(names_1.default.json, (0, codegen_1._)`${getSerialize(gen, sch)}(${data})`); } function getSerialize(gen, sch) { return sch.serialize ? gen.scopeValue("serialize", { ref: sch.serialize }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.serialize`; } function serializeEmpty({ gen, data }) { gen.add(names_1.default.json, (0, codegen_1._)`JSON.stringify(${data})`); } function addComma({ gen }, first) { if (first) { gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str)`,`)); } else { gen.add(names_1.default.json, (0, codegen_1.str)`,`); } } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/parseJson.js var require_parseJson = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/runtime/parseJson.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0; var rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/; function parseJson(s, pos) { let endPos; parseJson.message = void 0; let matches; if (pos) s = s.slice(pos); try { parseJson.position = pos + s.length; return JSON.parse(s); } catch (e) { matches = rxParseJson.exec(e.message); if (!matches) { parseJson.message = "unexpected end"; return void 0; } endPos = +matches[1]; const c = s[endPos]; s = s.slice(0, endPos); parseJson.position = pos + endPos; try { return JSON.parse(s); } catch (e1) { parseJson.message = `unexpected token ${c}`; return void 0; } } } exports.parseJson = parseJson; parseJson.message = void 0; parseJson.position = 0; parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'; function parseJsonNumber(s, pos, maxDigits) { let numStr = ""; let c; parseJsonNumber.message = void 0; if (s[pos] === "-") { numStr += "-"; pos++; } if (s[pos] === "0") { numStr += "0"; pos++; } else { if (!parseDigits(maxDigits)) { errorMessage(); return void 0; } } if (maxDigits) { parseJsonNumber.position = pos; return +numStr; } if (s[pos] === ".") { numStr += "."; pos++; if (!parseDigits()) { errorMessage(); return void 0; } } if (c = s[pos], c === "e" || c === "E") { numStr += "e"; pos++; if (c = s[pos], c === "+" || c === "-") { numStr += c; pos++; } if (!parseDigits()) { errorMessage(); return void 0; } } parseJsonNumber.position = pos; return +numStr; function parseDigits(maxLen) { let digit = false; while (c = s[pos], c >= "0" && c <= "9" && (maxLen === void 0 || maxLen-- > 0)) { digit = true; numStr += c; pos++; } return digit; } function errorMessage() { parseJsonNumber.position = pos; parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"; } } exports.parseJsonNumber = parseJsonNumber; parseJsonNumber.message = void 0; parseJsonNumber.position = 0; parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'; var escapedChars = { b: "\b", f: "\f", n: "\n", r: "\r", t: " ", '"': '"', "/": "/", "\\": "\\" }; var CODE_A = "a".charCodeAt(0); var CODE_0 = "0".charCodeAt(0); function parseJsonString(s, pos) { let str = ""; let c; parseJsonString.message = void 0; while (true) { c = s[pos++]; if (c === '"') break; if (c === "\\") { c = s[pos]; if (c in escapedChars) { str += escapedChars[c]; pos++; } else if (c === "u") { pos++; let count = 4; let code = 0; while (count--) { code <<= 4; c = s[pos]; if (c === void 0) { errorMessage("unexpected end"); return void 0; } c = c.toLowerCase(); if (c >= "a" && c <= "f") { code += c.charCodeAt(0) - CODE_A + 10; } else if (c >= "0" && c <= "9") { code += c.charCodeAt(0) - CODE_0; } else { errorMessage(`unexpected token ${c}`); return void 0; } pos++; } str += String.fromCharCode(code); } else { errorMessage(`unexpected token ${c}`); return void 0; } } else if (c === void 0) { errorMessage("unexpected end"); return void 0; } else { if (c.charCodeAt(0) >= 32) { str += c; } else { errorMessage(`unexpected token ${c}`); return void 0; } } } parseJsonString.position = pos; return str; function errorMessage(msg) { parseJsonString.position = pos; parseJsonString.message = msg; } } exports.parseJsonString = parseJsonString; parseJsonString.message = void 0; parseJsonString.position = 0; parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/jtd/parse.js var require_parse3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/compile/jtd/parse.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = require_types3(); var __1 = require_compile2(); var codegen_1 = require_codegen2(); var ref_error_1 = require_ref_error2(); var names_1 = require_names2(); var code_1 = require_code4(); var ref_1 = require_ref3(); var type_1 = require_type(); var parseJson_1 = require_parseJson(); var util_1 = require_util2(); var timestamp_1 = require_timestamp(); var genParse = { elements: parseElements, values: parseValues, discriminator: parseDiscriminator, properties: parseProperties, optionalProperties: parseProperties, enum: parseEnum, type: parseType, ref: parseRef }; function compileParser(sch, definitions) { const _sch = __1.getCompilingSchema.call(this, sch); if (_sch) return _sch; const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); const parseName = gen.scopeName("parse"); const cxt = { self: this, gen, schema: sch.schema, schemaEnv: sch, definitions, data: names_1.default.data, parseName, char: gen.name("c") }; let sourceCode; try { this._compilations.add(sch); sch.parseName = parseName; parserFunction(cxt); gen.optimize(this.opts.code.optimize); const parseFuncCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`; const makeParse = new Function(`${names_1.default.scope}`, sourceCode); const parse = makeParse(this.scope.get()); this.scope.value(parseName, { ref: parse }); sch.parse = parse; } catch (e) { if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode); delete sch.parse; delete sch.parseName; throw e; } finally { this._compilations.delete(sch); } return sch; } exports.default = compileParser; var undef = (0, codegen_1._)`undefined`; function parserFunction(cxt) { const { gen, parseName, char } = cxt; gen.func(parseName, (0, codegen_1._)`${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => { gen.let(names_1.default.data); gen.let(char); gen.assign((0, codegen_1._)`${parseName}.message`, undef); gen.assign((0, codegen_1._)`${parseName}.position`, undef); gen.assign(names_1.default.jsonPos, (0, codegen_1._)`${names_1.default.jsonPos} || 0`); gen.const(names_1.default.jsonLen, (0, codegen_1._)`${names_1.default.json}.length`); parseCode(cxt); skipWhitespace(cxt); gen.if(names_1.default.jsonPart, () => { gen.assign((0, codegen_1._)`${parseName}.position`, names_1.default.jsonPos); gen.return(names_1.default.data); }); gen.if((0, codegen_1._)`${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data)); jsonSyntaxError(cxt); }); } function parseCode(cxt) { let form; for (const key of types_1.jtdForms) { if (key in cxt.schema) { form = key; break; } } if (form) parseNullable(cxt, genParse[form]); else parseEmpty(cxt); } var parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)); function parseNullable(cxt, parseForm) { const { gen, schema, data } = cxt; if (!schema.nullable) return parseForm(cxt); tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)); } function parseElements(cxt) { const { gen, schema, data } = cxt; parseToken(cxt, "["); const ix = gen.let("i", 0); gen.assign(data, (0, codegen_1._)`[]`); parseItems(cxt, "]", () => { const el = gen.let("el"); parseCode({ ...cxt, schema: schema.elements, data: el }); gen.assign((0, codegen_1._)`${data}[${ix}++]`, el); }); } function parseValues(cxt) { const { gen, schema, data } = cxt; parseToken(cxt, "{"); gen.assign(data, (0, codegen_1._)`{}`); parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)); } function parseItems(cxt, endToken, block) { tryParseItems(cxt, endToken, block); parseToken(cxt, endToken); } function tryParseItems(cxt, endToken, block) { const { gen } = cxt; gen.for((0, codegen_1._)`;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { block(); tryParseToken(cxt, ",", () => gen.break(), hasItem); }); function hasItem() { tryParseToken(cxt, endToken, () => { }, jsonSyntaxError); } } function parseKeyValue(cxt, schema) { const { gen } = cxt; const key = gen.let("key"); parseString({ ...cxt, data: key }); parseToken(cxt, ":"); parsePropertyValue(cxt, key, schema); } function parseDiscriminator(cxt) { const { gen, data, schema } = cxt; const { discriminator, mapping } = schema; parseToken(cxt, "{"); gen.assign(data, (0, codegen_1._)`{}`); const startPos = gen.const("pos", names_1.default.jsonPos); const value = gen.let("value"); const tag = gen.let("tag"); tryParseItems(cxt, "}", () => { const key = gen.let("key"); parseString({ ...cxt, data: key }); parseToken(cxt, ":"); gen.if( (0, codegen_1._)`${key} === ${discriminator}`, () => { parseString({ ...cxt, data: tag }); gen.assign((0, codegen_1._)`${data}[${key}]`, tag); gen.break(); }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped ); }); gen.assign(names_1.default.jsonPos, startPos); gen.if((0, codegen_1._)`${tag} === undefined`); parsingError(cxt, (0, codegen_1.str)`discriminator tag not found`); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator); } gen.else(); parsingError(cxt, (0, codegen_1.str)`discriminator value not in schema`); gen.endIf(); } function parseProperties(cxt) { const { gen, data } = cxt; parseToken(cxt, "{"); gen.assign(data, (0, codegen_1._)`{}`); parseSchemaProperties(cxt); } function parseSchemaProperties(cxt, discriminator) { const { gen, schema, data } = cxt; const { properties, optionalProperties, additionalProperties } = schema; parseItems(cxt, "}", () => { const key = gen.let("key"); parseString({ ...cxt, data: key }); parseToken(cxt, ":"); gen.if(false); parseDefinedProperty(cxt, key, properties); parseDefinedProperty(cxt, key, optionalProperties); if (discriminator) { gen.elseIf((0, codegen_1._)`${key} === ${discriminator}`); const tag = gen.let("tag"); parseString({ ...cxt, data: tag }); } gen.else(); if (additionalProperties) { parseEmpty({ ...cxt, data: (0, codegen_1._)`${data}[${key}]` }); } else { parsingError(cxt, (0, codegen_1.str)`property ${key} not allowed`); } gen.endIf(); }); if (properties) { const hasProp = (0, code_1.hasPropFunc)(gen); const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._)`${hasProp}.call(${data}, ${p})`)); gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str)`missing required properties`)); } } function parseDefinedProperty(cxt, key, schemas = {}) { const { gen } = cxt; for (const prop in schemas) { gen.elseIf((0, codegen_1._)`${key} === ${prop}`); parsePropertyValue(cxt, key, schemas[prop]); } } function parsePropertyValue(cxt, key, schema) { parseCode({ ...cxt, schema, data: (0, codegen_1._)`${cxt.data}[${key}]` }); } function parseType(cxt) { const { gen, schema, data, self } = cxt; switch (schema.type) { case "boolean": parseBoolean(cxt); break; case "string": parseString(cxt); break; case "timestamp": { parseString(cxt); const vts = (0, util_1.useFunc)(gen, timestamp_1.default); const { allowDate, parseDate } = self.opts; const notValid = allowDate ? (0, codegen_1._)`!${vts}(${data}, true)` : (0, codegen_1._)`!${vts}(${data})`; const fail = parseDate ? (0, codegen_1.or)(notValid, (0, codegen_1._)`(${data} = new Date(${data}), false)`, (0, codegen_1._)`isNaN(${data}.valueOf())`) : notValid; gen.if(fail, () => parsingError(cxt, (0, codegen_1.str)`invalid timestamp`)); break; } case "float32": case "float64": parseNumber(cxt); break; default: { const t = schema.type; if (!self.opts.int32range && (t === "int32" || t === "uint32")) { parseNumber(cxt, 16); if (t === "uint32") { gen.if((0, codegen_1._)`${data} < 0`, () => parsingError(cxt, (0, codegen_1.str)`integer out of range`)); } } else { const [min, max, maxDigits] = type_1.intRange[t]; parseNumber(cxt, maxDigits); gen.if((0, codegen_1._)`${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str)`integer out of range`)); } } } } function parseString(cxt) { parseToken(cxt, '"'); parseWith(cxt, parseJson_1.parseJsonString); } function parseEnum(cxt) { const { gen, data, schema } = cxt; const enumSch = schema.enum; parseToken(cxt, '"'); gen.if(false); for (const value of enumSch) { const valueStr = JSON.stringify(value).slice(1); gen.elseIf((0, codegen_1._)`${jsonSlice(valueStr.length)} === ${valueStr}`); gen.assign(data, (0, codegen_1.str)`${value}`); gen.add(names_1.default.jsonPos, valueStr.length); } gen.else(); jsonSyntaxError(cxt); gen.endIf(); } function parseNumber(cxt, maxDigits) { const { gen } = cxt; skipWhitespace(cxt); gen.if((0, codegen_1._)`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits)); } function parseBooleanToken(bool, fail) { return (cxt) => { const { gen, data } = cxt; tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool)); }; } function parseRef(cxt) { const { gen, self, definitions, schema, schemaEnv } = cxt; const { ref } = schema; const refSchema = definitions[ref]; if (!refSchema) throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); if (!(0, ref_1.hasRef)(refSchema)) return parseCode({ ...cxt, schema: refSchema }); const { root } = schemaEnv; const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); partialParse(cxt, getParser(gen, sch), true); } function getParser(gen, sch) { return sch.parse ? gen.scopeValue("parse", { ref: sch.parse }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.parse`; } function parseEmpty(cxt) { parseWith(cxt, parseJson_1.parseJson); } function parseWith(cxt, parseFunc, args) { partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args); } function partialParse(cxt, parseFunc, args) { const { gen, data } = cxt; gen.assign(data, (0, codegen_1._)`${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._)`, ${args}` : codegen_1.nil})`); gen.assign(names_1.default.jsonPos, (0, codegen_1._)`${parseFunc}.position`); gen.if((0, codegen_1._)`${data} === undefined`, () => parsingError(cxt, (0, codegen_1._)`${parseFunc}.message`)); } function parseToken(cxt, tok) { tryParseToken(cxt, tok, jsonSyntaxError); } function tryParseToken(cxt, tok, fail, success) { const { gen } = cxt; const n = tok.length; skipWhitespace(cxt); gen.if((0, codegen_1._)`${jsonSlice(n)} === ${tok}`, () => { gen.add(names_1.default.jsonPos, n); success === null || success === void 0 ? void 0 : success(cxt); }, () => fail(cxt)); } function skipWhitespace({ gen, char: c }) { gen.code((0, codegen_1._)`while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`); } function jsonSlice(len) { return len === 1 ? (0, codegen_1._)`${names_1.default.json}[${names_1.default.jsonPos}]` : (0, codegen_1._)`${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`; } function jsonSyntaxError(cxt) { parsingError(cxt, (0, codegen_1._)`"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`); } function parsingError({ gen, parseName }, msg) { gen.assign((0, codegen_1._)`${parseName}.message`, msg); gen.assign((0, codegen_1._)`${parseName}.position`, names_1.default.jsonPos); gen.return(undef); } } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/jtd.js var require_jtd2 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/jtd.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; var core_1 = require_core3(); var jtd_1 = require_jtd(); var jtd_schema_1 = require_jtd_schema(); var serialize_1 = require_serialize(); var parse_1 = require_parse3(); var META_SCHEMA_ID = "JTD-meta-schema"; var Ajv = class extends core_1.default { constructor(opts = {}) { super({ ...opts, jtd: true }); } _addVocabularies() { super._addVocabularies(); this.addVocabulary(jtd_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false); } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } compileSerializer(schema) { const sch = this._addSchema(schema); return sch.serialize || this._compileSerializer(sch); } compileParser(schema) { const sch = this._addSchema(schema); return sch.parse || this._compileParser(sch); } _compileSerializer(sch) { serialize_1.default.call(this, sch, sch.schema.definitions || {}); if (!sch.serialize) throw new Error("ajv implementation error"); return sch.serialize; } _compileParser(sch) { parse_1.default.call(this, sch, sch.schema.definitions || {}); if (!sch.parse) throw new Error("ajv implementation error"); return sch.parse; } }; exports.Ajv = Ajv; module2.exports = exports = Ajv; module2.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv; var validate_1 = require_validate2(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen2(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error2(); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error2(); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js var require_default_ajv_options = __commonJS({ "node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js"(exports, module2) { "use strict"; var fastUri = require_fast_uri(); module2.exports = Object.freeze({ coerceTypes: "array", useDefaults: true, removeAdditional: true, uriResolver: fastUri, addUsedSchema: false, // Explicitly set allErrors to `false`. // When set to `true`, a DoS attack is possible. allErrors: false }); } }); // node_modules/ajv-formats/dist/formats.js var require_formats2 = __commonJS({ "node_modules/ajv-formats/dist/formats.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; function fmtDef(validate, compare) { return { validate, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(time, compareTime), "date-time": fmtDef(date_time, compareDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true }; exports.fastFormats = { ...exports.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i }; exports.formatNames = Object.keys(exports.fullFormats); function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date(str) { const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); } function compareDate(d1, d2) { if (!(d1 && d2)) return void 0; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; function time(str, withTimeZone) { const matches = TIME.exec(str); if (!matches) return false; const hour = +matches[1]; const minute = +matches[2]; const second = +matches[3]; const timeZone = matches[5]; return (hour <= 23 && minute <= 59 && second <= 59 || hour === 23 && minute === 59 && second === 60) && (!withTimeZone || timeZone !== ""); } function compareTime(t1, t2) { if (!(t1 && t2)) return void 0; const a1 = TIME.exec(t1); const a2 = TIME.exec(t2); if (!(a1 && a2)) return void 0; t1 = a1[1] + a1[2] + a1[3] + (a1[4] || ""); t2 = a2[1] + a2[2] + a2[3] + (a2[4] || ""); if (t1 > t2) return 1; if (t1 < t2) return -1; return 0; } var DATE_TIME_SEPARATOR = /t|\s/i; function date_time(str) { const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1], true); } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === void 0) return void 0; return res || compareTime(t1, t2); } var NOT_URI_FRAGMENT = /\/|:/; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } var MIN_INT32 = -(2 ** 31); var MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { return Number.isInteger(value); } function validateNumber() { return true; } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e) { return false; } } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js var require_code5 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; var _CodeOrName = class { }; exports._CodeOrName = _CodeOrName; exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s) { super(); if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a; return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); } get names() { var _a; return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}); } }; exports._Code = _Code; exports.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports._ = _; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== void 0) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports.strConcat = strConcat; function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports.stringify = stringify; function safeStringify(x) { return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; } exports.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports.regexpCode = regexpCode; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js var require_scope3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; var code_1 = require_code5(); var ValueError = class extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a, _b; if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports.ValueScopeName = ValueScopeName; var line = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = /* @__PURE__ */ new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._)`${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } }; exports.ValueScope = ValueScope; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js var require_codegen3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; var code_1 = require_code5(); var scope_1 = require_scope3(); var code_2 = require_code5(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope3(); Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } }; var Label = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } }; var Break = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } }; var Throw = class extends Node { constructor(error) { super(); this.error = error; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } }; var AnyCode = class extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof If ? e : e.nodes; if (this.nodes.length) return this; return new If(not(cond), e instanceof If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a; this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a, _b; super.optimizeNodes(); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a, _b; super.optimizeNames(names, constants); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error) { super(); this.error = error; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { this.var(name, (0, code_1._)`${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error = this.name("e"); this._currNode = node.catch = new Catch(error); catchCode(error); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error) { return this._leafNode(new Throw(error)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || N2 && n instanceof N2) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } }; exports.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === void 0 || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; } exports.not = not; var andCode = mappend(exports.operators.AND); function and(...args) { return args.reduce(andCode); } exports.and = and; var orCode = mappend(exports.operators.OR); function or(...args) { return args.reduce(orCode); } exports.or = or; function mappend(op) { return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js var require_util3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; var codegen_1 = require_codegen3(); var code_1 = require_code5(); function toHash(arr) { const hash = {}; for (const item of arr) hash[item] = true; return hash; } exports.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps !== void 0) setEvaluated(gen, props, ps); return props; } exports.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); } exports.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports.checkStrictMode = checkStrictMode; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js var require_names3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports.default = names; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js var require_errors6 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); var names_1 = require_names3(); exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._)`[${errObj}]`); } } exports.reportError = reportError; function reportExtraError(cxt, error = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err}.data`, data); } }); } exports.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error, errorPaths); } function errorObject(cxt, error, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; var errors_1 = require_errors6(); var codegen_1 = require_codegen3(); var names_1 = require_names3(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); falseSchemaError(it); } else { gen.var(valid, true); } } exports.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js var require_rules3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRules = exports.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports.getRules = getRules; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js var require_applicability3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a; return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); } exports.shouldUseRule = shouldUseRule; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js var require_dataType3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; var rules_1 = require_rules3(); var applicability_1 = require_applicability3(); var errors_1 = require_errors6(); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it }; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js var require_defaults3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assignDefaults = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js var require_code6 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); var names_1 = require_names3(); var util_2 = require_util3(); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); } exports.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports.validateUnion = validateUnion; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js var require_keyword3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; var codegen_1 = require_codegen3(); var names_1 = require_names3(); var code_1 = require_code6(); var errors_1 = require_errors6(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a2; gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors); } } exports.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); } exports.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js var require_subschema3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/ajv-formats/node_modules/json-schema-traverse/index.js var require_json_schema_traverse3 = __commonJS({ "node_modules/ajv-formats/node_modules/json-schema-traverse/index.js"(exports, module2) { "use strict"; var traverse = module2.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js var require_resolve3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; var util_1 = require_util3(); var equal = require_fast_deep_equal(); var traverse = require_json_schema_traverse3(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports.getSchemaRefs = getSchemaRefs; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js var require_validate3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema3(); var dataType_1 = require_dataType3(); var applicability_1 = require_applicability3(); var dataType_2 = require_dataType3(); var defaults_1 = require_defaults3(); var keyword_1 = require_keyword3(); var subschema_1 = require_subschema3(); var codegen_1 = require_codegen3(); var names_1 = require_names3(); var resolve_1 = require_resolve3(); var util_1 = require_util3(); var errors_1 = require_errors6(); function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults } } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts, t) { return ts.includes(t) || t === "integer" && ts.includes("number"); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } var KeywordCxt = class { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment of segments) { if (segment) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports.getData = getData; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js var require_validation_error3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports.default = ValidationError; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js var require_ref_error3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var resolve_1 = require_resolve3(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports.default = MissingRefError; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js var require_compile3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; var codegen_1 = require_codegen3(); var validation_error_1 = require_validation_error3(); var names_1 = require_names3(); var resolve_1 = require_resolve3(); var util_1 = require_util3(); var validate_1 = require_validate3(); var SchemaEnv = class { constructor(env) { var _a; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e; } finally { this._compilations.delete(sch); } } exports.compileSchema = compileSchema; function resolveRef(root, baseId, ref) { var _a; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === void 0) { const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports.resolveRef = resolveRef; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a; if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json var require_data3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json"(exports, module2) { module2.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js var require_uri3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var uri = require_uri_all(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports.default = uri; } }); // node_modules/ajv-formats/node_modules/ajv/dist/core.js var require_core5 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/core.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; var validate_1 = require_validate3(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen3(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error3(); var ref_error_1 = require_ref_error3(); var rules_1 = require_rules3(); var compile_1 = require_compile3(); var codegen_2 = require_codegen3(); var resolve_1 = require_resolve3(); var dataType_1 = require_dataType3(); var util_1 = require_util3(); var $dataRefSchema = require_data3(); var uri_1 = require_uri3(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = {}; this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; } validate(schemaKeyRef, data) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv.ValidationError = validation_error_1.default; Ajv.MissingRefError = ref_error_1.default; exports.default = Ajv; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js var require_id3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js var require_ref4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.callRef = exports.getValidate = void 0; var ref_error_1 = require_ref_error3(); var code_1 = require_code6(); var codegen_1 = require_codegen3(); var names_1 = require_names3(); var compile_1 = require_compile3(); var util_1 = require_util3(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a; if (!it.opts.unevaluated) return; const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports.callRef = callRef; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js var require_core6 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var id_1 = require_id3(); var ref_1 = require_ref4(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports.default = core; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var ucs2length_1 = require_ucs2length3(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code6(); var codegen_1 = require_codegen3(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error, code(cxt) { const { data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js var require_required3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code6(); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var error = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var error = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js var require_equal3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var equal = require_fast_deep_equal(); equal.code = 'require("ajv/dist/runtime/equal").default'; exports.default = equal; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var dataType_1 = require_dataType3(); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var equal_1 = require_equal3(); var error = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._)`${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js var require_const3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var equal_1 = require_equal3(); var error = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var equal_1 = require_equal3(); var error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js var require_validation4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber3(); var multipleOf_1 = require_multipleOf3(); var limitLength_1 = require_limitLength3(); var pattern_1 = require_pattern3(); var limitProperties_1 = require_limitProperties3(); var required_1 = require_required3(); var limitItems_1 = require_limitItems3(); var uniqueItems_1 = require_uniqueItems3(); var const_1 = require_const3(); var enum_1 = require_enum4(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports.default = validation; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); var error = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports.validateAdditionalItems = validateAdditionalItems; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js var require_items3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateTuple = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); var code_1 = require_code6(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports.validateTuple = validateTuple; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = require_items3(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items20203 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var code_1 = require_code6(); var additionalItems_1 = require_additionalItems3(); var error = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var error = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === void 0 ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max }); if (max === void 0 && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== void 0 && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; var codegen_1 = require_codegen3(); var util_1 = require_util3(); var code_1 = require_code6(); exports.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports.validateSchemaDeps = validateSchemaDeps; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var error = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code6(); var codegen_1 = require_codegen3(); var names_1 = require_names3(); var util_1 = require_util3(); var error = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var validate_1 = require_validate3(); var code_1 = require_code6(); var util_1 = require_util3(); var additionalProperties_1 = require_additionalProperties3(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code6(); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var util_2 = require_util3(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js var require_not3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util3(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code6(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var error = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true }, schValid); } if (i > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util3(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js var require_if3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var util_1 = require_util3(); var error = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); } exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util3(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems3(); var prefixItems_1 = require_prefixItems3(); var items_1 = require_items3(); var items2020_1 = require_items20203(); var contains_1 = require_contains3(); var dependencies_1 = require_dependencies3(); var propertyNames_1 = require_propertyNames3(); var additionalProperties_1 = require_additionalProperties3(); var properties_1 = require_properties4(); var patternProperties_1 = require_patternProperties3(); var not_1 = require_not3(); var anyOf_1 = require_anyOf3(); var oneOf_1 = require_oneOf3(); var allOf_1 = require_allOf3(); var if_1 = require_if3(); var thenElse_1 = require_thenElse3(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports.default = getApplicator; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js var require_format5 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var error = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js var require_format6 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var format_1 = require_format5(); var format = [format_1.default]; exports.default = format; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js var require_metadata4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.contentVocabulary = exports.metadataVocabulary = void 0; exports.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js var require_draft73 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require_core6(); var validation_1 = require_validation4(); var applicator_1 = require_applicator3(); var format_1 = require_format6(); var metadata_1 = require_metadata4(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports.default = draft7Vocabularies; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports.DiscrError = DiscrError = {})); } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen3(); var types_1 = require_types4(); var compile_1 = require_compile3(); var ref_error_1 = require_ref_error3(); var util_1 = require_util3(); var error = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required }) { return Array.isArray(required) && required.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } } }; exports.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_073 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module2) { module2.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/ajv-formats/node_modules/ajv/dist/ajv.js var require_ajv3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/ajv.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; var core_1 = require_core5(); var draft7_1 = require_draft73(); var discriminator_1 = require_discriminator4(); var draft7MetaSchema = require_json_schema_draft_073(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports.Ajv = Ajv; module2.exports = exports = Ajv; module2.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv; var validate_1 = require_validate3(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen3(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error3(); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error3(); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/ajv-formats/dist/limit.js var require_limit2 = __commonJS({ "node_modules/ajv-formats/dist/limit.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatLimitDefinition = void 0; var ajv_1 = require_ajv3(); var codegen_1 = require_codegen3(); var ops = codegen_1.operators; var KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error = { message: ({ keyword, schemaCode }) => codegen_1.str`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => codegen_1._`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; exports.formatLimitDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self } = it; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fmt = gen.const("fmt", codegen_1._`${fmts}[${fCxt.schemaCode}]`); cxt.fail$data(codegen_1.or(codegen_1._`typeof ${fmt} != "object"`, codegen_1._`${fmt} instanceof RegExp`, codegen_1._`typeof ${fmt}.compare != "function"`, compareCode(fmt))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? codegen_1._`${opts.code.formats}${codegen_1.getProperty(format)}` : void 0 }); cxt.fail$data(compareCode(fmt)); } function compareCode(fmt) { return codegen_1._`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"] }; var formatLimitPlugin = (ajv) => { ajv.addKeyword(exports.formatLimitDefinition); return ajv; }; exports.default = formatLimitPlugin; } }); // node_modules/ajv-formats/dist/index.js var require_dist2 = __commonJS({ "node_modules/ajv-formats/dist/index.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var formats_1 = require_formats2(); var limit_1 = require_limit2(); var codegen_1 = require_codegen3(); var fullName = new codegen_1.Name("fullFormats"); var fastName = new codegen_1.Name("fastFormats"); var formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) limit_1.default(ajv); return ajv; }; formatsPlugin.get = (name, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f = formats[name]; if (!f) throw new Error(`Unknown format "${name}"`); return f; }; function addFormats(ajv, list, fs, exportName) { var _a; var _b; (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = codegen_1._`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) ajv.addFormat(f, fs[f]); } module2.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = formatsPlugin; } }); // node_modules/@fastify/ajv-compiler/lib/validator-compiler.js var require_validator_compiler = __commonJS({ "node_modules/@fastify/ajv-compiler/lib/validator-compiler.js"(exports, module2) { "use strict"; var Ajv = require_ajv2().default; var AjvJTD = require_jtd2(); var defaultAjvOptions = require_default_ajv_options(); var ValidatorCompiler = class { constructor(externalSchemas, options) { if (options.mode === "JTD") { this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options.customOptions)); } else { this.ajv = new Ajv(Object.assign({}, defaultAjvOptions, options.customOptions)); } let addFormatPlugin = true; if (options.plugins && options.plugins.length > 0) { for (const plugin of options.plugins) { if (Array.isArray(plugin)) { addFormatPlugin = addFormatPlugin && plugin[0].name !== "formatsPlugin"; plugin[0](this.ajv, plugin[1]); } else { addFormatPlugin = addFormatPlugin && plugin.name !== "formatsPlugin"; plugin(this.ajv); } } } if (addFormatPlugin) { require_dist2()(this.ajv); } const sourceSchemas = Object.values(externalSchemas); for (const extSchema of sourceSchemas) { this.ajv.addSchema(extSchema); } } buildValidatorFunction({ schema /*, method, url, httpPart */ }) { if (schema.$id) { const stored = this.ajv.getSchema(schema.$id); if (stored) { return stored; } } return this.ajv.compile(schema); } }; module2.exports = ValidatorCompiler; } }); // node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js var require_serializer_compiler = __commonJS({ "node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js"(exports, module2) { "use strict"; var AjvJTD = require_jtd2(); var defaultAjvOptions = require_default_ajv_options(); var SerializerCompiler = class { constructor(externalSchemas, options) { this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options)); } buildSerializerFunction({ schema /*, method, url, httpStatus */ }) { return this.ajv.compileSerializer(schema); } }; module2.exports = SerializerCompiler; } }); // node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/standalone/index.js var require_standalone3 = __commonJS({ "node_modules/@fastify/ajv-compiler/node_modules/ajv/dist/standalone/index.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var scope_1 = require_scope2(); var code_1 = require_code3(); function standaloneCode(ajv, refsOrFunc) { if (!ajv.opts.code.source) { throw new Error("moduleCode: ajv instance must have code.source option"); } const { _n } = ajv.scope.opts; return typeof refsOrFunc == "function" ? funcExportCode(refsOrFunc.source) : refsOrFunc !== void 0 ? multiExportsCode(refsOrFunc, getValidate) : multiExportsCode(ajv.schemas, (sch) => sch.meta ? void 0 : ajv.compile(sch.schema)); function getValidate(id) { const v = ajv.getSchema(id); if (!v) throw new Error(`moduleCode: no schema with id ${id}`); return v; } function funcExportCode(source) { const usedValues = {}; const n = source === null || source === void 0 ? void 0 : source.validateName; const vCode = validateCode(usedValues, source); if (ajv.opts.code.esm) { return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`; } return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`; } function multiExportsCode(schemas, getValidateFunc) { var _a; const usedValues = {}; let code = (0, code_1._)`"use strict";`; for (const name in schemas) { const v = getValidateFunc(schemas[name]); if (v) { const vCode = validateCode(usedValues, v.source); const exportSyntax = ajv.opts.code.esm ? (0, code_1._)`export const ${(0, code_1.getEsmExportName)(name)}` : (0, code_1._)`exports${(0, code_1.getProperty)(name)}`; code = (0, code_1._)`${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`; } } return `${code}`; } function validateCode(usedValues, s) { if (!s) throw new Error('moduleCode: function does not have "source" property'); if (usedState(s.validateName) === scope_1.UsedValueState.Completed) return code_1.nil; setUsedState(s.validateName, scope_1.UsedValueState.Started); const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode); const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`); return s.evaluated ? (0, code_1._)`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code; function refValidateCode(n) { var _a; const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref; if (n.prefix === "validate" && typeof vRef == "function") { const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { const { validate, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._)`${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); return (0, code_1._)`${wrapper}${_n}${vCode}`; } return void 0; } function usedState(name) { var _a; return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name); } function setUsedState(name, state) { const { prefix } = name; const names = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); names.set(name, state); } } } module2.exports = exports = standaloneCode; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = standaloneCode; } }); // node_modules/@fastify/ajv-compiler/standalone.js var require_standalone4 = __commonJS({ "node_modules/@fastify/ajv-compiler/standalone.js"(exports, module2) { "use strict"; var ValidatorSelector = require_ajv_compiler(); var standaloneCode = require_standalone3().default; function StandaloneValidator(options = { readMode: true }) { if (options.readMode === true && !options.restoreFunction) { throw new Error("You must provide a restoreFunction options when readMode ON"); } if (options.readMode !== true && !options.storeFunction) { throw new Error("You must provide a storeFunction options when readMode OFF"); } if (options.readMode === true) { return function wrapper() { return function(opts) { return options.restoreFunction(opts); }; }; } const factory = ValidatorSelector(); return function wrapper(externalSchemas, ajvOptions = {}) { if (!ajvOptions.customOptions || !ajvOptions.customOptions.code) { ajvOptions.customOptions = Object.assign({}, ajvOptions.customOptions, { code: { source: true } }); } const compiler = factory(externalSchemas, ajvOptions); return function(opts) { const validationFunc = compiler(opts); const schemaValidationCode = standaloneCode(compiler[ValidatorSelector.AjvReference].ajv, validationFunc); options.storeFunction(opts, schemaValidationCode); return validationFunc; }; }; } module2.exports = StandaloneValidator; } }); // node_modules/@fastify/ajv-compiler/index.js var require_ajv_compiler = __commonJS({ "node_modules/@fastify/ajv-compiler/index.js"(exports, module2) { "use strict"; var AjvReference = Symbol.for("fastify.ajv-compiler.reference"); var ValidatorCompiler = require_validator_compiler(); var SerializerCompiler = require_serializer_compiler(); function AjvCompiler(opts) { const validatorPool = /* @__PURE__ */ new Map(); const serializerPool = /* @__PURE__ */ new Map(); if (opts && opts.jtdSerializer === true) { return function buildSerializerFromPool(externalSchemas, serializerOpts) { const uniqueAjvKey = getPoolKey({}, serializerOpts); if (serializerPool.has(uniqueAjvKey)) { return serializerPool.get(uniqueAjvKey); } const compiler = new SerializerCompiler(externalSchemas, serializerOpts); const ret = compiler.buildSerializerFunction.bind(compiler); serializerPool.set(uniqueAjvKey, ret); return ret; }; } return function buildCompilerFromPool(externalSchemas, options) { const uniqueAjvKey = getPoolKey(externalSchemas, options.customOptions); if (validatorPool.has(uniqueAjvKey)) { return validatorPool.get(uniqueAjvKey); } const compiler = new ValidatorCompiler(externalSchemas, options); const ret = compiler.buildValidatorFunction.bind(compiler); validatorPool.set(uniqueAjvKey, ret); if (options.customOptions.code !== void 0) { ret[AjvReference] = compiler; } return ret; }; } function getPoolKey(externalSchemas, options) { const externals = JSON.stringify(externalSchemas); const ajvConfig = JSON.stringify(options); return `${externals}${ajvConfig}`; } module2.exports = AjvCompiler; module2.exports.default = AjvCompiler; module2.exports.AjvCompiler = AjvCompiler; module2.exports.AjvReference = AjvReference; module2.exports.StandaloneValidator = require_standalone4(); } }); // node_modules/fastify/lib/schema-controller.js var require_schema_controller = __commonJS({ "node_modules/fastify/lib/schema-controller.js"(exports, module2) { "use strict"; var { buildSchemas } = require_schemas(); var SerializerSelector = require_fast_json_stringify_compiler(); var ValidatorSelector = require_ajv_compiler(); function buildSchemaController(parentSchemaCtrl, opts) { var _a, _b; if (parentSchemaCtrl) { return new SchemaController(parentSchemaCtrl, opts); } const compilersFactory = Object.assign({ buildValidator: null, buildSerializer: null }, opts == null ? void 0 : opts.compilersFactory); if (!compilersFactory.buildValidator) { compilersFactory.buildValidator = ValidatorSelector(); } if (!compilersFactory.buildSerializer) { compilersFactory.buildSerializer = SerializerSelector(); } const option = { bucket: opts && opts.bucket || buildSchemas, compilersFactory, isCustomValidatorCompiler: typeof ((_a = opts == null ? void 0 : opts.compilersFactory) == null ? void 0 : _a.buildValidator) === "function", isCustomSerializerCompiler: typeof ((_b = opts == null ? void 0 : opts.compilersFactory) == null ? void 0 : _b.buildValidator) === "function" }; return new SchemaController(void 0, option); } var SchemaController = class { constructor(parent, options) { this.opts = options || (parent == null ? void 0 : parent.opts); this.addedSchemas = false; this.compilersFactory = this.opts.compilersFactory; if (parent) { this.schemaBucket = this.opts.bucket(parent.getSchemas()); this.validatorCompiler = parent.getValidatorCompiler(); this.serializerCompiler = parent.getSerializerCompiler(); this.isCustomValidatorCompiler = parent.isCustomValidatorCompiler; this.isCustomSerializerCompiler = parent.isCustomSerializerCompiler; this.parent = parent; } else { this.schemaBucket = this.opts.bucket(); this.isCustomValidatorCompiler = this.opts.isCustomValidatorCompiler || false; this.isCustomSerializerCompiler = this.opts.isCustomSerializerCompiler || false; } } // Bucket interface add(schema) { this.addedSchemas = true; return this.schemaBucket.add(schema); } getSchema(schemaId) { return this.schemaBucket.getSchema(schemaId); } getSchemas() { return this.schemaBucket.getSchemas(); } setValidatorCompiler(validatorCompiler) { this.compilersFactory = Object.assign( {}, this.compilersFactory, { buildValidator: () => validatorCompiler } ); this.validatorCompiler = validatorCompiler; this.isCustomValidatorCompiler = true; } setSerializerCompiler(serializerCompiler) { this.compilersFactory = Object.assign( {}, this.compilersFactory, { buildSerializer: () => serializerCompiler } ); this.serializerCompiler = serializerCompiler; this.isCustomSerializerCompiler = true; } getValidatorCompiler() { return this.validatorCompiler || this.parent && this.parent.getValidatorCompiler(); } getSerializerCompiler() { return this.serializerCompiler || this.parent && this.parent.getSerializerCompiler(); } getSerializerBuilder() { return this.compilersFactory.buildSerializer || this.parent && this.parent.getSerializerBuilder(); } getValidatorBuilder() { return this.compilersFactory.buildValidator || this.parent && this.parent.getValidatorBuilder(); } /** * This method will be called when a validator must be setup. * Do not setup the compiler more than once * @param {object} serverOptions the fastify server options */ setupValidator(serverOptions) { const isReady = this.validatorCompiler !== void 0 && !this.addedSchemas; if (isReady) { return; } this.validatorCompiler = this.getValidatorBuilder()(this.schemaBucket.getSchemas(), serverOptions.ajv); } /** * This method will be called when a serializer must be setup. * Do not setup the compiler more than once * @param {object} serverOptions the fastify server options */ setupSerializer(serverOptions) { const isReady = this.serializerCompiler !== void 0 && !this.addedSchemas; if (isReady) { return; } this.serializerCompiler = this.getSerializerBuilder()(this.schemaBucket.getSchemas(), serverOptions.serializerOpts); } }; SchemaController.buildSchemaController = buildSchemaController; module2.exports = SchemaController; } }); // node_modules/fastify/lib/pluginUtils.js var require_pluginUtils = __commonJS({ "node_modules/fastify/lib/pluginUtils.js"(exports, module2) { "use strict"; var semver = require_semver2(); var assert = require("assert"); var kRegisteredPlugins = Symbol.for("registered-plugin"); var { kTestInternals } = require_symbols2(); var { exist, existReply, existRequest } = require_decorate(); var { FST_ERR_PLUGIN_VERSION_MISMATCH, FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE } = require_errors2(); var { FSTWRN002 } = require_warnings(); function getMeta(fn) { return fn[Symbol.for("plugin-meta")]; } function getPluginName(func) { const display = getDisplayName(func); if (display) { return display; } const cache = require.cache; if (cache) { const keys = Object.keys(cache); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (cache[key].exports === func) { return key; } } } if (func.name) { return func.name; } return null; } function getFuncPreview(func) { return func.toString().split("\n").slice(0, 2).map((s) => s.trim()).join(" -- "); } function getDisplayName(fn) { return fn[Symbol.for("fastify.display-name")]; } function shouldSkipOverride(fn) { return !!fn[Symbol.for("skip-override")]; } function checkDependencies(fn) { const meta = getMeta(fn); if (!meta) return; const dependencies = meta.dependencies; if (!dependencies) return; assert(Array.isArray(dependencies), "The dependencies should be an array of strings"); dependencies.forEach((dependency) => { assert( this[kRegisteredPlugins].indexOf(dependency) > -1, `The dependency '${dependency}' of plugin '${meta.name}' is not registered` ); }); } function checkDecorators(fn) { const meta = getMeta(fn); if (!meta) return; const { decorators, name } = meta; if (!decorators) return; if (decorators.fastify) _checkDecorators(this, "Fastify", decorators.fastify, name); if (decorators.reply) _checkDecorators(this, "Reply", decorators.reply, name); if (decorators.request) _checkDecorators(this, "Request", decorators.request, name); } var checks = { Fastify: exist, Request: existRequest, Reply: existReply }; function _checkDecorators(that, instance, decorators, name) { assert(Array.isArray(decorators), "The decorators should be an array of strings"); decorators.forEach((decorator) => { const withPluginName = typeof name === "string" ? ` required by '${name}'` : ""; if (!checks[instance].call(that, decorator)) { throw new FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE(decorator, withPluginName, instance); } }); } function checkVersion(fn) { const meta = getMeta(fn); if (!meta) return; const requiredVersion = meta.fastify; const fastifyRc = /-rc.+$/.test(this.version); if (fastifyRc === true && semver.gt(this.version, semver.coerce(requiredVersion)) === true) { return; } if (requiredVersion && semver.satisfies(this.version, requiredVersion, { includePrerelease: fastifyRc }) === false) { throw new FST_ERR_PLUGIN_VERSION_MISMATCH(meta.name, requiredVersion, this.version); } } function registerPluginName(fn) { const meta = getMeta(fn); if (!meta) return; const name = meta.name; if (!name) return; this[kRegisteredPlugins].push(name); return name; } function checkPluginHealthiness(fn, pluginName) { if (fn.constructor.name === "AsyncFunction" && fn.length === 3) { FSTWRN002(pluginName || "anonymous"); } } function registerPlugin(fn) { const pluginName = registerPluginName.call(this, fn) || getPluginName(fn); checkPluginHealthiness.call(this, fn, pluginName); checkVersion.call(this, fn); checkDecorators.call(this, fn); checkDependencies.call(this, fn); return shouldSkipOverride(fn); } module2.exports = { getPluginName, getFuncPreview, kRegisteredPlugins, getDisplayName, registerPlugin }; module2.exports[kTestInternals] = { shouldSkipOverride, getMeta, checkDecorators, checkDependencies }; } }); // node_modules/fastify/lib/reqIdGenFactory.js var require_reqIdGenFactory = __commonJS({ "node_modules/fastify/lib/reqIdGenFactory.js"(exports, module2) { "use strict"; function reqIdGenFactory(requestIdHeader, optGenReqId) { const genReqId = optGenReqId || buildDefaultGenReqId(); if (requestIdHeader) { return buildOptionalHeaderReqId(requestIdHeader, genReqId); } return genReqId; } function getGenReqId(contextServer, req) { return contextServer.genReqId(req); } function buildDefaultGenReqId() { const maxInt = 2147483647; let nextReqId = 0; return function defaultGenReqId() { nextReqId = nextReqId + 1 & maxInt; return `req-${nextReqId.toString(36)}`; }; } function buildOptionalHeaderReqId(requestIdHeader, genReqId) { return function(req) { return req.headers[requestIdHeader] || genReqId(req); }; } module2.exports = { getGenReqId, reqIdGenFactory }; } }); // node_modules/fast-decode-uri-component/index.js var require_fast_decode_uri_component = __commonJS({ "node_modules/fast-decode-uri-component/index.js"(exports, module2) { "use strict"; var UTF8_ACCEPT = 12; var UTF8_REJECT = 0; var UTF8_DATA = [ // The first part of the table maps bytes to character to a transition. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 7, 10, 9, 9, 9, 11, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // The second part of the table maps a state to a new state when adding a // transition. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 24, 36, 48, 60, 72, 84, 96, 0, 12, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // The third part maps the current transition to a mask that needs to apply // to the byte. 127, 63, 63, 63, 0, 31, 15, 15, 15, 7, 7, 7 ]; function decodeURIComponent2(uri) { var percentPosition = uri.indexOf("%"); if (percentPosition === -1) return uri; var length = uri.length; var decoded = ""; var last = 0; var codepoint = 0; var startOfOctets = percentPosition; var state = UTF8_ACCEPT; while (percentPosition > -1 && percentPosition < length) { var high = hexCodeToInt(uri[percentPosition + 1], 4); var low = hexCodeToInt(uri[percentPosition + 2], 0); var byte = high | low; var type = UTF8_DATA[byte]; state = UTF8_DATA[256 + state + type]; codepoint = codepoint << 6 | byte & UTF8_DATA[364 + type]; if (state === UTF8_ACCEPT) { decoded += uri.slice(last, startOfOctets); decoded += codepoint <= 65535 ? String.fromCharCode(codepoint) : String.fromCharCode( 55232 + (codepoint >> 10), 56320 + (codepoint & 1023) ); codepoint = 0; last = percentPosition + 3; percentPosition = startOfOctets = uri.indexOf("%", last); } else if (state === UTF8_REJECT) { return null; } else { percentPosition += 3; if (percentPosition < length && uri.charCodeAt(percentPosition) === 37) continue; return null; } } return decoded + uri.slice(last); } var HEX = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "a": 10, "A": 10, "b": 11, "B": 11, "c": 12, "C": 12, "d": 13, "D": 13, "e": 14, "E": 14, "f": 15, "F": 15 }; function hexCodeToInt(c, shift) { var i = HEX[c]; return i === void 0 ? 255 : i << shift; } module2.exports = decodeURIComponent2; } }); // node_modules/fast-querystring/lib/parse.js var require_parse4 = __commonJS({ "node_modules/fast-querystring/lib/parse.js"(exports, module2) { "use strict"; var fastDecode = require_fast_decode_uri_component(); var plusRegex = /\+/g; var Empty = function() { }; Empty.prototype = /* @__PURE__ */ Object.create(null); function parse(input) { const result = new Empty(); if (typeof input !== "string") { return result; } let inputLength = input.length; let key = ""; let value = ""; let startingIndex = -1; let equalityIndex = -1; let shouldDecodeKey = false; let shouldDecodeValue = false; let keyHasPlus = false; let valueHasPlus = false; let hasBothKeyValuePair = false; let c = 0; for (let i = 0; i < inputLength + 1; i++) { c = i !== inputLength ? input.charCodeAt(i) : 38; if (c === 38) { hasBothKeyValuePair = equalityIndex > startingIndex; if (!hasBothKeyValuePair) { equalityIndex = i; } key = input.slice(startingIndex + 1, equalityIndex); if (hasBothKeyValuePair || key.length > 0) { if (keyHasPlus) { key = key.replace(plusRegex, " "); } if (shouldDecodeKey) { key = fastDecode(key) || key; } if (hasBothKeyValuePair) { value = input.slice(equalityIndex + 1, i); if (valueHasPlus) { value = value.replace(plusRegex, " "); } if (shouldDecodeValue) { value = fastDecode(value) || value; } } const currentValue = result[key]; if (currentValue === void 0) { result[key] = value; } else { if (currentValue.pop) { currentValue.push(value); } else { result[key] = [currentValue, value]; } } } value = ""; startingIndex = i; equalityIndex = i; shouldDecodeKey = false; shouldDecodeValue = false; keyHasPlus = false; valueHasPlus = false; } else if (c === 61) { if (equalityIndex <= startingIndex) { equalityIndex = i; } else { shouldDecodeValue = true; } } else if (c === 43) { if (equalityIndex > startingIndex) { valueHasPlus = true; } else { keyHasPlus = true; } } else if (c === 37) { if (equalityIndex > startingIndex) { shouldDecodeValue = true; } else { shouldDecodeKey = true; } } } return result; } module2.exports = parse; } }); // node_modules/fast-querystring/lib/internals/querystring.js var require_querystring = __commonJS({ "node_modules/fast-querystring/lib/internals/querystring.js"(exports, module2) { var hexTable = Array.from( { length: 256 }, (_, i) => "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase() ); var noEscape = new Int8Array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 80 - 95 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 // 112 - 127 ]); function encodeString(str) { const len = str.length; if (len === 0) return ""; let out = ""; let lastPos = 0; let i = 0; outer: for (; i < len; i++) { let c = str.charCodeAt(i); while (c < 128) { if (noEscape[c] !== 1) { if (lastPos < i) out += str.slice(lastPos, i); lastPos = i + 1; out += hexTable[c]; } if (++i === len) break outer; c = str.charCodeAt(i); } if (lastPos < i) out += str.slice(lastPos, i); if (c < 2048) { lastPos = i + 1; out += hexTable[192 | c >> 6] + hexTable[128 | c & 63]; continue; } if (c < 55296 || c >= 57344) { lastPos = i + 1; out += hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; continue; } ++i; if (i >= len) { throw new Error("URI malformed"); } const c2 = str.charCodeAt(i) & 1023; lastPos = i + 1; c = 65536 + ((c & 1023) << 10 | c2); out += hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; } if (lastPos === 0) return str; if (lastPos < len) return out + str.slice(lastPos); return out; } module2.exports = { encodeString }; } }); // node_modules/fast-querystring/lib/stringify.js var require_stringify = __commonJS({ "node_modules/fast-querystring/lib/stringify.js"(exports, module2) { "use strict"; var { encodeString } = require_querystring(); function getAsPrimitive(value) { const type = typeof value; if (type === "string") { return encodeString(value); } else if (type === "bigint") { return value.toString(); } else if (type === "boolean") { return value ? "true" : "false"; } else if (type === "number" && Number.isFinite(value)) { return value < 1e21 ? "" + value : encodeString("" + value); } return ""; } function stringify(input) { let result = ""; if (input === null || typeof input !== "object") { return result; } const separator = "&"; const keys = Object.keys(input); const keyLength = keys.length; let valueLength = 0; for (let i = 0; i < keyLength; i++) { const key = keys[i]; const value = input[key]; const encodedKey = encodeString(key) + "="; if (i) { result += separator; } if (Array.isArray(value)) { valueLength = value.length; for (let j = 0; j < valueLength; j++) { if (j) { result += separator; } result += encodedKey; result += getAsPrimitive(value[j]); } } else { result += encodedKey; result += getAsPrimitive(value); } } return result; } module2.exports = stringify; } }); // node_modules/fast-querystring/lib/index.js var require_lib = __commonJS({ "node_modules/fast-querystring/lib/index.js"(exports, module2) { "use strict"; var parse = require_parse4(); var stringify = require_stringify(); var fastQuerystring = { parse, stringify }; module2.exports = fastQuerystring; module2.exports.default = fastQuerystring; module2.exports.parse = parse; module2.exports.stringify = stringify; } }); // node_modules/ret/dist/types/tokens.js var require_tokens = __commonJS({ "node_modules/ret/dist/types/tokens.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); } }); // node_modules/ret/dist/types/types.js var require_types5 = __commonJS({ "node_modules/ret/dist/types/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.types = void 0; var types; (function(types2) { types2[types2["ROOT"] = 0] = "ROOT"; types2[types2["GROUP"] = 1] = "GROUP"; types2[types2["POSITION"] = 2] = "POSITION"; types2[types2["SET"] = 3] = "SET"; types2[types2["RANGE"] = 4] = "RANGE"; types2[types2["REPETITION"] = 5] = "REPETITION"; types2[types2["REFERENCE"] = 6] = "REFERENCE"; types2[types2["CHAR"] = 7] = "CHAR"; })(types = exports.types || (exports.types = {})); } }); // node_modules/ret/dist/types/set-lookup.js var require_set_lookup = __commonJS({ "node_modules/ret/dist/types/set-lookup.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); } }); // node_modules/ret/dist/types/index.js var require_types6 = __commonJS({ "node_modules/ret/dist/types/index.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(require_tokens(), exports); __exportStar(require_types5(), exports); __exportStar(require_set_lookup(), exports); } }); // node_modules/ret/dist/sets.js var require_sets = __commonJS({ "node_modules/ret/dist/sets.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.anyChar = exports.notWhitespace = exports.whitespace = exports.notInts = exports.ints = exports.notWords = exports.words = void 0; var types_1 = require_types6(); var INTS = () => [{ type: types_1.types.RANGE, from: 48, to: 57 }]; var WORDS = () => [ { type: types_1.types.CHAR, value: 95 }, { type: types_1.types.RANGE, from: 97, to: 122 }, { type: types_1.types.RANGE, from: 65, to: 90 }, { type: types_1.types.RANGE, from: 48, to: 57 } ]; var WHITESPACE = () => [ { type: types_1.types.CHAR, value: 9 }, { type: types_1.types.CHAR, value: 10 }, { type: types_1.types.CHAR, value: 11 }, { type: types_1.types.CHAR, value: 12 }, { type: types_1.types.CHAR, value: 13 }, { type: types_1.types.CHAR, value: 32 }, { type: types_1.types.CHAR, value: 160 }, { type: types_1.types.CHAR, value: 5760 }, { type: types_1.types.RANGE, from: 8192, to: 8202 }, { type: types_1.types.CHAR, value: 8232 }, { type: types_1.types.CHAR, value: 8233 }, { type: types_1.types.CHAR, value: 8239 }, { type: types_1.types.CHAR, value: 8287 }, { type: types_1.types.CHAR, value: 12288 }, { type: types_1.types.CHAR, value: 65279 } ]; var NOTANYCHAR = () => [ { type: types_1.types.CHAR, value: 10 }, { type: types_1.types.CHAR, value: 13 }, { type: types_1.types.CHAR, value: 8232 }, { type: types_1.types.CHAR, value: 8233 } ]; exports.words = () => ({ type: types_1.types.SET, set: WORDS(), not: false }); exports.notWords = () => ({ type: types_1.types.SET, set: WORDS(), not: true }); exports.ints = () => ({ type: types_1.types.SET, set: INTS(), not: false }); exports.notInts = () => ({ type: types_1.types.SET, set: INTS(), not: true }); exports.whitespace = () => ({ type: types_1.types.SET, set: WHITESPACE(), not: false }); exports.notWhitespace = () => ({ type: types_1.types.SET, set: WHITESPACE(), not: true }); exports.anyChar = () => ({ type: types_1.types.SET, set: NOTANYCHAR(), not: true }); } }); // node_modules/ret/dist/util.js var require_util4 = __commonJS({ "node_modules/ret/dist/util.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.tokenizeClass = exports.strToChars = void 0; var types_1 = require_types6(); var sets = __importStar(require_sets()); var CTRL = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?"; exports.strToChars = (str) => { const charsRegex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g; return str.replace(charsRegex, (s, b, lbs, a16, b16, dctrl, eslsh) => { if (lbs) { return s; } let code = b ? 8 : a16 ? parseInt(a16, 16) : b16 ? parseInt(b16, 16) : dctrl ? CTRL.indexOf(dctrl) : { 0: 0, t: 9, n: 10, v: 11, f: 12, r: 13 }[eslsh]; let c = String.fromCharCode(code); return /[[\]{}^$.|?*+()]/.test(c) ? `\\${c}` : c; }); }; exports.tokenizeClass = (str, regexpStr) => { var _a, _b, _c, _d, _e, _f, _g; let tokens = [], rs, c; const regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g; while ((rs = regexp.exec(str)) !== null) { const p = (_g = (_f = (_e = (_d = (_c = (_b = (_a = rs[1] && sets.words()) !== null && _a !== void 0 ? _a : rs[2] && sets.ints()) !== null && _b !== void 0 ? _b : rs[3] && sets.whitespace()) !== null && _c !== void 0 ? _c : rs[4] && sets.notWords()) !== null && _d !== void 0 ? _d : rs[5] && sets.notInts()) !== null && _e !== void 0 ? _e : rs[6] && sets.notWhitespace()) !== null && _f !== void 0 ? _f : rs[7] && { type: types_1.types.RANGE, from: (rs[8] || rs[9]).charCodeAt(0), to: (c = rs[10]).charCodeAt(c.length - 1) }) !== null && _g !== void 0 ? _g : (c = rs[16]) && { type: types_1.types.CHAR, value: c.charCodeAt(0) }; if (p) { tokens.push(p); } else { return [tokens, regexp.lastIndex]; } } throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unterminated character class`); }; } }); // node_modules/ret/dist/tokenizer.js var require_tokenizer = __commonJS({ "node_modules/ret/dist/tokenizer.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.tokenizer = void 0; var util = __importStar(require_util4()); var types_1 = require_types6(); var sets = __importStar(require_sets()); exports.tokenizer = (regexpStr) => { let i = 0, c; let start = { type: types_1.types.ROOT, stack: [] }; let lastGroup = start; let last = start.stack; let groupStack = []; let referenceQueue = []; let groupCount = 0; const repeatErr = (col) => { throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Nothing to repeat at column ${col - 1}`); }; let str = util.strToChars(regexpStr); while (i < str.length) { switch (c = str[i++]) { case "\\": if (i === str.length) { throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: \\ at end of pattern`); } switch (c = str[i++]) { case "b": last.push({ type: types_1.types.POSITION, value: "b" }); break; case "B": last.push({ type: types_1.types.POSITION, value: "B" }); break; case "w": last.push(sets.words()); break; case "W": last.push(sets.notWords()); break; case "d": last.push(sets.ints()); break; case "D": last.push(sets.notInts()); break; case "s": last.push(sets.whitespace()); break; case "S": last.push(sets.notWhitespace()); break; default: if (/\d/.test(c)) { let digits = c; while (i < str.length && /\d/.test(str[i])) { digits += str[i++]; } let value = parseInt(digits, 10); const reference = { type: types_1.types.REFERENCE, value }; last.push(reference); referenceQueue.push({ reference, stack: last, index: last.length - 1 }); } else { last.push({ type: types_1.types.CHAR, value: c.charCodeAt(0) }); } } break; case "^": last.push({ type: types_1.types.POSITION, value: "^" }); break; case "$": last.push({ type: types_1.types.POSITION, value: "$" }); break; case "[": { let not; if (str[i] === "^") { not = true; i++; } else { not = false; } let classTokens = util.tokenizeClass(str.slice(i), regexpStr); i += classTokens[1]; last.push({ type: types_1.types.SET, set: classTokens[0], not }); break; } case ".": last.push(sets.anyChar()); break; case "(": { let group = { type: types_1.types.GROUP, stack: [], remember: true }; if (str[i] === "?") { c = str[i + 1]; i += 2; if (c === "=") { group.followedBy = true; } else if (c === "!") { group.notFollowedBy = true; } else if (c !== ":") { throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Invalid group, character '${c}' after '?' at column ${i - 1}`); } group.remember = false; } else { groupCount += 1; } last.push(group); groupStack.push(lastGroup); lastGroup = group; last = group.stack; break; } case ")": if (groupStack.length === 0) { throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unmatched ) at column ${i - 1}`); } lastGroup = groupStack.pop(); last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; break; case "|": { if (!lastGroup.options) { lastGroup.options = [lastGroup.stack]; delete lastGroup.stack; } let stack = []; lastGroup.options.push(stack); last = stack; break; } case "{": { let rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; if (rs !== null) { if (last.length === 0) { repeatErr(i); } min = parseInt(rs[1], 10); max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; i += rs[0].length; last.push({ type: types_1.types.REPETITION, min, max, value: last.pop() }); } else { last.push({ type: types_1.types.CHAR, value: 123 }); } break; } case "?": if (last.length === 0) { repeatErr(i); } last.push({ type: types_1.types.REPETITION, min: 0, max: 1, value: last.pop() }); break; case "+": if (last.length === 0) { repeatErr(i); } last.push({ type: types_1.types.REPETITION, min: 1, max: Infinity, value: last.pop() }); break; case "*": if (last.length === 0) { repeatErr(i); } last.push({ type: types_1.types.REPETITION, min: 0, max: Infinity, value: last.pop() }); break; default: last.push({ type: types_1.types.CHAR, value: c.charCodeAt(0) }); } } if (groupStack.length !== 0) { throw new SyntaxError(`Invalid regular expression: /${regexpStr}/: Unterminated group`); } updateReferences(referenceQueue, groupCount); return start; }; function updateReferences(referenceQueue, groupCount) { for (const elem of referenceQueue.reverse()) { if (groupCount < elem.reference.value) { elem.reference.type = types_1.types.CHAR; const valueString = elem.reference.value.toString(); elem.reference.value = parseInt(valueString, 8); if (!/^[0-7]+$/.test(valueString)) { let i = 0; while (valueString[i] !== "8" && valueString[i] !== "9") { i += 1; } if (i === 0) { elem.reference.value = valueString.charCodeAt(0); i += 1; } else { elem.reference.value = parseInt(valueString.slice(0, i), 8); } if (valueString.length > i) { const tail = elem.stack.splice(elem.index + 1); for (const char of valueString.slice(i)) { elem.stack.push({ type: types_1.types.CHAR, value: char.charCodeAt(0) }); } elem.stack.push(...tail); } } } } } } }); // node_modules/ret/dist/sets-lookup.js var require_sets_lookup = __commonJS({ "node_modules/ret/dist/sets-lookup.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NOTANYCHAR = exports.WHITESPACE = exports.WORDS = exports.INTS = void 0; var Sets = __importStar(require_sets()); var types_1 = require_types6(); function setToLookup(tokens) { let lookup = {}; let len = 0; for (const token of tokens) { if (token.type === types_1.types.CHAR) { lookup[token.value] = true; } if (token.type === types_1.types.RANGE) { lookup[`${token.from}-${token.to}`] = true; } len += 1; } return { lookup: () => Object.assign({}, lookup), len }; } exports.INTS = setToLookup(Sets.ints().set); exports.WORDS = setToLookup(Sets.words().set); exports.WHITESPACE = setToLookup(Sets.whitespace().set); exports.NOTANYCHAR = setToLookup(Sets.anyChar().set); } }); // node_modules/ret/dist/write-set-tokens.js var require_write_set_tokens = __commonJS({ "node_modules/ret/dist/write-set-tokens.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.writeSetTokens = exports.setChar = void 0; var types_1 = require_types6(); var sets = __importStar(require_sets_lookup()); function setChar(charCode) { return charCode === 94 ? "\\^" : charCode === 92 ? "\\\\" : charCode === 93 ? "\\]" : charCode === 45 ? "\\-" : String.fromCharCode(charCode); } exports.setChar = setChar; function isSameSet(set, { lookup, len }) { if (len !== set.length) { return false; } const map = lookup(); for (const elem of set) { if (elem.type === types_1.types.SET) { return false; } const key = elem.type === types_1.types.CHAR ? elem.value : `${elem.from}-${elem.to}`; if (map[key]) { map[key] = false; } else { return false; } } return true; } function writeSetTokens(set, isNested = false) { if (isSameSet(set.set, sets.INTS)) { return set.not ? "\\D" : "\\d"; } if (isSameSet(set.set, sets.WORDS)) { return set.not ? "\\W" : "\\w"; } if (set.not && isSameSet(set.set, sets.NOTANYCHAR)) { return "."; } if (isSameSet(set.set, sets.WHITESPACE)) { return set.not ? "\\S" : "\\s"; } let tokenString = ""; for (let i = 0; i < set.set.length; i++) { const subset = set.set[i]; tokenString += writeSetToken(subset); } const contents = `${set.not ? "^" : ""}${tokenString}`; return isNested ? contents : `[${contents}]`; } exports.writeSetTokens = writeSetTokens; function writeSetToken(set) { if (set.type === types_1.types.CHAR) { return setChar(set.value); } else if (set.type === types_1.types.RANGE) { return `${setChar(set.from)}-${setChar(set.to)}`; } return writeSetTokens(set, true); } } }); // node_modules/ret/dist/reconstruct.js var require_reconstruct = __commonJS({ "node_modules/ret/dist/reconstruct.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reconstruct = void 0; var types_1 = require_types6(); var write_set_tokens_1 = require_write_set_tokens(); var reduceStack = (stack) => stack.map(exports.reconstruct).join(""); var createAlternate = (token) => { if ("options" in token) { return token.options.map(reduceStack).join("|"); } else if ("stack" in token) { return reduceStack(token.stack); } else { throw new Error(`options or stack must be Root or Group token`); } }; exports.reconstruct = (token) => { switch (token.type) { case types_1.types.ROOT: return createAlternate(token); case types_1.types.CHAR: { const c = String.fromCharCode(token.value); return (/[[\\{}$^.|?*+()]/.test(c) ? "\\" : "") + c; } case types_1.types.POSITION: if (token.value === "^" || token.value === "$") { return token.value; } else { return `\\${token.value}`; } case types_1.types.REFERENCE: return `\\${token.value}`; case types_1.types.SET: return write_set_tokens_1.writeSetTokens(token); case types_1.types.GROUP: { const prefix = token.remember ? "" : token.followedBy ? "?=" : token.notFollowedBy ? "?!" : "?:"; return `(${prefix}${createAlternate(token)})`; } case types_1.types.REPETITION: { const { min, max } = token; let endWith; if (min === 0 && max === 1) { endWith = "?"; } else if (min === 1 && max === Infinity) { endWith = "+"; } else if (min === 0 && max === Infinity) { endWith = "*"; } else if (max === Infinity) { endWith = `{${min},}`; } else if (min === max) { endWith = `{${min}}`; } else { endWith = `{${min},${max}}`; } return `${exports.reconstruct(token.value)}${endWith}`; } case types_1.types.RANGE: return `${write_set_tokens_1.setChar(token.from)}-${write_set_tokens_1.setChar(token.to)}`; default: throw new Error(`Invalid token type ${token}`); } }; } }); // node_modules/ret/dist/index.js var require_dist3 = __commonJS({ "node_modules/ret/dist/index.js"(exports, module2) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.types = void 0; var types_1 = require_types6(); Object.defineProperty(exports, "types", { enumerable: true, get: function() { return types_1.types; } }); __exportStar(require_tokenizer(), exports); __exportStar(require_reconstruct(), exports); var tokenizer_1 = require_tokenizer(); var reconstruct_1 = require_reconstruct(); __exportStar(require_types6(), exports); exports.default = tokenizer_1.tokenizer; module2.exports = tokenizer_1.tokenizer; module2.exports.types = types_1.types; module2.exports.reconstruct = reconstruct_1.reconstruct; } }); // node_modules/safe-regex2/index.js var require_safe_regex2 = __commonJS({ "node_modules/safe-regex2/index.js"(exports, module2) { "use strict"; var parse = require_dist3(); var types = parse.types; function safeRegex(re, opts) { if (!opts) opts = {}; const replimit = opts.limit === void 0 ? 25 : opts.limit; if (isRegExp(re)) re = re.source; else if (typeof re !== "string") re = String(re); try { re = parse(re); } catch (err) { return false; } let reps = 0; return function walk(node, starHeight) { let i; let ok; let len; if (node.type === types.REPETITION) { starHeight++; reps++; if (starHeight > 1) return false; if (reps > replimit) return false; } if (node.options) { for (i = 0, len = node.options.length; i < len; i++) { ok = walk({ stack: node.options[i] }, starHeight); if (!ok) return false; } } const stack = node.stack || node.value && node.value.stack; if (!stack) return true; for (i = 0; i < stack.length; i++) { ok = walk(stack[i], starHeight); if (!ok) return false; } return true; }(re, 0); } function isRegExp(x) { return {}.toString.call(x) === "[object RegExp]"; } module2.exports = safeRegex; module2.exports.default = safeRegex; module2.exports.safeRegex = safeRegex; } }); // node_modules/find-my-way/lib/strategies/http-method.js var require_http_method = __commonJS({ "node_modules/find-my-way/lib/strategies/http-method.js"(exports, module2) { "use strict"; module2.exports = { name: "__fmw_internal_strategy_merged_tree_http_method__", storage: function() { const handlers = {}; return { get: (type) => { return handlers[type] || null; }, set: (type, store) => { handlers[type] = store; } }; }, deriveConstraint: ( /* istanbul ignore next */ (req) => req.method ), mustMatchWhenDerived: true }; } }); // node_modules/find-my-way/lib/pretty-print.js var require_pretty_print = __commonJS({ "node_modules/find-my-way/lib/pretty-print.js"(exports, module2) { "use strict"; var deepEqual = require_fast_deep_equal(); var httpMethodStrategy = require_http_method(); var treeDataSymbol = Symbol("treeData"); function printObjectTree(obj, parentPrefix = "") { let tree = ""; const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = obj[key]; const isLast = i === keys.length - 1; const nodePrefix = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "; const childPrefix = isLast ? " " : "\u2502 "; const nodeData = value[treeDataSymbol] || ""; const prefixedNodeData = nodeData.split("\n").join("\n" + parentPrefix + childPrefix); tree += parentPrefix + nodePrefix + key + prefixedNodeData + "\n"; tree += printObjectTree(value, parentPrefix + childPrefix); } return tree; } function parseFunctionName(fn) { let fName = fn.name || ""; fName = fName.replace("bound", "").trim(); fName = (fName || "anonymous") + "()"; return fName; } function parseMeta(meta) { if (Array.isArray(meta)) return meta.map((m) => parseMeta(m)); if (typeof meta === "symbol") return meta.toString(); if (typeof meta === "function") return parseFunctionName(meta); return meta; } function getRouteMetaData(route, options) { if (!options.includeMeta) return {}; const metaDataObject = options.buildPrettyMeta(route); const filteredMetaData = {}; let includeMetaKeys = options.includeMeta; if (!Array.isArray(includeMetaKeys)) { includeMetaKeys = Reflect.ownKeys(metaDataObject); } for (const metaKey of includeMetaKeys) { if (!Object.prototype.hasOwnProperty.call(metaDataObject, metaKey)) continue; const serializedKey = metaKey.toString(); const metaValue = metaDataObject[metaKey]; if (metaValue !== void 0 && metaValue !== null) { const serializedValue = JSON.stringify(parseMeta(metaValue)); filteredMetaData[serializedKey] = serializedValue; } } return filteredMetaData; } function serializeMetaData(metaData) { let serializedMetaData = ""; for (const [key, value] of Object.entries(metaData)) { serializedMetaData += ` \u2022 (${key}) ${value}`; } return serializedMetaData; } function normalizeRoute(route) { const constraints = { ...route.opts.constraints }; const method = constraints[httpMethodStrategy.name]; delete constraints[httpMethodStrategy.name]; return { ...route, method, opts: { constraints } }; } function serializeRoute(route) { let serializedRoute = ` (${route.method})`; const constraints = route.opts.constraints || {}; if (Object.keys(constraints).length !== 0) { serializedRoute += " " + JSON.stringify(constraints); } serializedRoute += serializeMetaData(route.metaData); return serializedRoute; } function mergeSimilarRoutes(routes) { return routes.reduce((mergedRoutes, route) => { for (const nodeRoute of mergedRoutes) { if (deepEqual(route.opts.constraints, nodeRoute.opts.constraints) && deepEqual(route.metaData, nodeRoute.metaData)) { nodeRoute.method += ", " + route.method; return mergedRoutes; } } mergedRoutes.push(route); return mergedRoutes; }, []); } function serializeNode(node, prefix, options) { let routes = node.routes; if (options.method === void 0) { routes = routes.map(normalizeRoute); } routes = routes.map((route) => { route.metaData = getRouteMetaData(route, options); return route; }); if (options.method === void 0) { routes = mergeSimilarRoutes(routes); } return routes.map(serializeRoute).join(` ${prefix}`); } function buildObjectTree(node, tree, prefix, options) { if (node.isLeafNode || options.commonPrefix !== false) { prefix = prefix || "(empty root node)"; tree = tree[prefix] = {}; if (node.isLeafNode) { tree[treeDataSymbol] = serializeNode(node, prefix, options); } prefix = ""; } if (node.staticChildren) { for (const child of Object.values(node.staticChildren)) { buildObjectTree(child, tree, prefix + child.prefix, options); } } if (node.parametricChildren) { for (const child of Object.values(node.parametricChildren)) { const childPrefix = Array.from(child.nodePaths).join("|"); buildObjectTree(child, tree, prefix + childPrefix, options); } } if (node.wildcardChild) { buildObjectTree(node.wildcardChild, tree, "*", options); } } function prettyPrintTree(root, options) { const objectTree = {}; buildObjectTree(root, objectTree, root.prefix, options); return printObjectTree(objectTree); } module2.exports = { prettyPrintTree }; } }); // node_modules/find-my-way/lib/handler-storage.js var require_handler_storage = __commonJS({ "node_modules/find-my-way/lib/handler-storage.js"(exports, module2) { "use strict"; var httpMethodStrategy = require_http_method(); var HandlerStorage = class { constructor() { this.unconstrainedHandler = null; this.constraints = []; this.handlers = []; this.constrainedHandlerStores = null; } // This is the hot path for node handler finding -- change with care! getMatchingHandler(derivedConstraints) { if (derivedConstraints === void 0) { return this.unconstrainedHandler; } return this._getHandlerMatchingConstraints(derivedConstraints); } addHandler(constrainer, route) { const params = route.params; const constraints = route.opts.constraints || {}; const handlerObject = { params, constraints, handler: route.handler, store: route.store || null, _createParamsObject: this._compileCreateParamsObject(params) }; const constraintsNames = Object.keys(constraints); if (constraintsNames.length === 0) { this.unconstrainedHandler = handlerObject; } for (const constraint of constraintsNames) { if (!this.constraints.includes(constraint)) { if (constraint === "version") { this.constraints.unshift(constraint); } else { this.constraints.push(constraint); } } } const isMergedTree = constraintsNames.includes(httpMethodStrategy.name); if (!isMergedTree && this.handlers.length >= 31) { throw new Error("find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached"); } this.handlers.push(handlerObject); this.handlers.sort((a, b) => Object.keys(a.constraints).length - Object.keys(b.constraints).length); if (!isMergedTree) { this._compileGetHandlerMatchingConstraints(constrainer, constraints); } } _compileCreateParamsObject(params) { const lines = []; for (let i = 0; i < params.length; i++) { lines.push(`'${params[i]}': paramsArray[${i}]`); } return new Function("paramsArray", `return {${lines.join(",")}}`); } _getHandlerMatchingConstraints() { return null; } // Builds a store object that maps from constraint values to a bitmap of handler indexes which pass the constraint for a value // So for a host constraint, this might look like { "fastify.io": 0b0010, "google.ca": 0b0101 }, meaning the 3rd handler is constrainted to fastify.io, and the 2nd and 4th handlers are constrained to google.ca. // The store's implementation comes from the strategies provided to the Router. _buildConstraintStore(store, constraint) { for (let i = 0; i < this.handlers.length; i++) { const handler = this.handlers[i]; const constraintValue = handler.constraints[constraint]; if (constraintValue !== void 0) { let indexes = store.get(constraintValue) || 0; indexes |= 1 << i; store.set(constraintValue, indexes); } } } // Builds a bitmask for a given constraint that has a bit for each handler index that is 0 when that handler *is* constrained and 1 when the handler *isnt* constrainted. This is opposite to what might be obvious, but is just for convienience when doing the bitwise operations. _constrainedIndexBitmask(constraint) { let mask = 0; for (let i = 0; i < this.handlers.length; i++) { const handler = this.handlers[i]; const constraintValue = handler.constraints[constraint]; if (constraintValue !== void 0) { mask |= 1 << i; } } return ~mask; } // Compile a fast function to match the handlers for this node // The function implements a general case multi-constraint matching algorithm. // The general idea is this: we have a bunch of handlers, each with a potentially different set of constraints, and sometimes none at all. We're given a list of constraint values and we have to use the constraint-value-comparison strategies to see which handlers match the constraint values passed in. // We do this by asking each constraint store which handler indexes match the given constraint value for each store. Trickily, the handlers that a store says match are the handlers constrained by that store, but handlers that aren't constrained at all by that store could still match just fine. So, each constraint store can only describe matches for it, and it won't have any bearing on the handlers it doesn't care about. For this reason, we have to ask each stores which handlers match and track which have been matched (or not cared about) by all of them. // We use bitmaps to represent these lists of matches so we can use bitwise operations to implement this efficiently. Bitmaps are cheap to allocate, let us implement this masking behaviour in one CPU instruction, and are quite compact in memory. We start with a bitmap set to all 1s representing every handler that is a match candidate, and then for each constraint, see which handlers match using the store, and then mask the result by the mask of handlers that that store applies to, and bitwise AND with the candidate list. Phew. // We consider all this compiling function complexity to be worth it, because the naive implementation that just loops over the handlers asking which stores match is quite a bit slower. _compileGetHandlerMatchingConstraints(constrainer) { this.constrainedHandlerStores = {}; for (const constraint of this.constraints) { const store = constrainer.newStoreForConstraint(constraint); this.constrainedHandlerStores[constraint] = store; this._buildConstraintStore(store, constraint); } const lines = []; lines.push(` let candidates = ${(1 << this.handlers.length) - 1} let mask, matches `); for (const constraint of this.constraints) { lines.push(` mask = ${this._constrainedIndexBitmask(constraint)} value = derivedConstraints.${constraint} `); const strategy = constrainer.strategies[constraint]; const matchMask = strategy.mustMatchWhenDerived ? "matches" : "(matches | mask)"; lines.push(` if (value === undefined) { candidates &= mask } else { matches = this.constrainedHandlerStores.${constraint}.get(value) || 0 candidates &= ${matchMask} } if (candidates === 0) return null; `); } for (const constraint in constrainer.strategies) { const strategy = constrainer.strategies[constraint]; if (strategy.mustMatchWhenDerived && !this.constraints.includes(constraint)) { lines.push(`if (derivedConstraints.${constraint} !== undefined) return null`); } } lines.push("return this.handlers[Math.floor(Math.log2(candidates))]"); this._getHandlerMatchingConstraints = new Function("derivedConstraints", lines.join("\n")); } }; module2.exports = HandlerStorage; } }); // node_modules/find-my-way/lib/node.js var require_node = __commonJS({ "node_modules/find-my-way/lib/node.js"(exports, module2) { "use strict"; var HandlerStorage = require_handler_storage(); var NODE_TYPES = { STATIC: 0, PARAMETRIC: 1, WILDCARD: 2 }; var Node = class { constructor() { this.isLeafNode = false; this.routes = null; this.handlerStorage = null; } addRoute(route, constrainer) { if (this.routes === null) { this.routes = []; } if (this.handlerStorage === null) { this.handlerStorage = new HandlerStorage(); } this.isLeafNode = true; this.routes.push(route); this.handlerStorage.addHandler(constrainer, route); } }; var ParentNode = class extends Node { constructor() { super(); this.staticChildren = {}; } findStaticMatchingChild(path, pathIndex) { const staticChild = this.staticChildren[path.charAt(pathIndex)]; if (staticChild === void 0 || !staticChild.matchPrefix(path, pathIndex)) { return null; } return staticChild; } getStaticChild(path, pathIndex = 0) { if (path.length === pathIndex) { return this; } const staticChild = this.findStaticMatchingChild(path, pathIndex); if (staticChild) { return staticChild.getStaticChild(path, pathIndex + staticChild.prefix.length); } return null; } createStaticChild(path) { if (path.length === 0) { return this; } let staticChild = this.staticChildren[path.charAt(0)]; if (staticChild) { let i = 1; for (; i < staticChild.prefix.length; i++) { if (path.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) { staticChild = staticChild.split(this, i); break; } } return staticChild.createStaticChild(path.slice(i)); } const label = path.charAt(0); this.staticChildren[label] = new StaticNode(path); return this.staticChildren[label]; } }; var StaticNode = class extends ParentNode { constructor(prefix) { super(); this.prefix = prefix; this.wildcardChild = null; this.parametricChildren = []; this.kind = NODE_TYPES.STATIC; this._compilePrefixMatch(); } getParametricChild(regex) { const regexpSource = regex && regex.source; const parametricChild = this.parametricChildren.find((child) => { const childRegexSource = child.regex && child.regex.source; return childRegexSource === regexpSource; }); if (parametricChild) { return parametricChild; } return null; } createParametricChild(regex, staticSuffix, nodePath) { let parametricChild = this.getParametricChild(regex); if (parametricChild) { parametricChild.nodePaths.add(nodePath); return parametricChild; } parametricChild = new ParametricNode(regex, staticSuffix, nodePath); this.parametricChildren.push(parametricChild); this.parametricChildren.sort((child1, child2) => { if (!child1.isRegex) return 1; if (!child2.isRegex) return -1; if (child1.staticSuffix === null) return 1; if (child2.staticSuffix === null) return -1; if (child2.staticSuffix.endsWith(child1.staticSuffix)) return 1; if (child1.staticSuffix.endsWith(child2.staticSuffix)) return -1; return 0; }); return parametricChild; } getWildcardChild() { return this.wildcardChild; } createWildcardChild() { this.wildcardChild = this.getWildcardChild() || new WildcardNode(); return this.wildcardChild; } split(parentNode, length) { const parentPrefix = this.prefix.slice(0, length); const childPrefix = this.prefix.slice(length); this.prefix = childPrefix; this._compilePrefixMatch(); const staticNode = new StaticNode(parentPrefix); staticNode.staticChildren[childPrefix.charAt(0)] = this; parentNode.staticChildren[parentPrefix.charAt(0)] = staticNode; return staticNode; } getNextNode(path, pathIndex, nodeStack, paramsCount) { let node = this.findStaticMatchingChild(path, pathIndex); let parametricBrotherNodeIndex = 0; if (node === null) { if (this.parametricChildren.length === 0) { return this.wildcardChild; } node = this.parametricChildren[0]; parametricBrotherNodeIndex = 1; } if (this.wildcardChild !== null) { nodeStack.push({ paramsCount, brotherPathIndex: pathIndex, brotherNode: this.wildcardChild }); } for (let i = this.parametricChildren.length - 1; i >= parametricBrotherNodeIndex; i--) { nodeStack.push({ paramsCount, brotherPathIndex: pathIndex, brotherNode: this.parametricChildren[i] }); } return node; } _compilePrefixMatch() { if (this.prefix.length === 1) { this.matchPrefix = () => true; return; } const lines = []; for (let i = 1; i < this.prefix.length; i++) { const charCode = this.prefix.charCodeAt(i); lines.push(`path.charCodeAt(i + ${i}) === ${charCode}`); } this.matchPrefix = new Function("path", "i", `return ${lines.join(" && ")}`); } }; var ParametricNode = class extends ParentNode { constructor(regex, staticSuffix, nodePath) { super(); this.isRegex = !!regex; this.regex = regex || null; this.staticSuffix = staticSuffix || null; this.kind = NODE_TYPES.PARAMETRIC; this.nodePaths = /* @__PURE__ */ new Set([nodePath]); } getNextNode(path, pathIndex) { return this.findStaticMatchingChild(path, pathIndex); } }; var WildcardNode = class extends Node { constructor() { super(); this.kind = NODE_TYPES.WILDCARD; } getNextNode() { return null; } }; module2.exports = { StaticNode, ParametricNode, WildcardNode, NODE_TYPES }; } }); // node_modules/find-my-way/lib/strategies/accept-version.js var require_accept_version = __commonJS({ "node_modules/find-my-way/lib/strategies/accept-version.js"(exports, module2) { "use strict"; var assert = require("assert"); function SemVerStore() { if (!(this instanceof SemVerStore)) { return new SemVerStore(); } this.store = {}; this.maxMajor = 0; this.maxMinors = {}; this.maxPatches = {}; } SemVerStore.prototype.set = function(version, store) { if (typeof version !== "string") { throw new TypeError("Version should be a string"); } let [major, minor, patch] = version.split("."); if (isNaN(major)) { throw new TypeError("Major version must be a numeric value"); } major = Number(major); minor = Number(minor) || 0; patch = Number(patch) || 0; if (major >= this.maxMajor) { this.maxMajor = major; this.store.x = store; this.store["*"] = store; this.store["x.x"] = store; this.store["x.x.x"] = store; } if (minor >= (this.maxMinors[major] || 0)) { this.maxMinors[major] = minor; this.store[`${major}.x`] = store; this.store[`${major}.x.x`] = store; } if (patch >= (this.maxPatches[`${major}.${minor}`] || 0)) { this.maxPatches[`${major}.${minor}`] = patch; this.store[`${major}.${minor}.x`] = store; } this.store[`${major}.${minor}.${patch}`] = store; return this; }; SemVerStore.prototype.get = function(version) { return this.store[version]; }; module2.exports = { name: "version", mustMatchWhenDerived: true, storage: SemVerStore, validate(value) { assert(typeof value === "string", "Version should be a string"); } }; } }); // node_modules/find-my-way/lib/strategies/accept-host.js var require_accept_host = __commonJS({ "node_modules/find-my-way/lib/strategies/accept-host.js"(exports, module2) { "use strict"; var assert = require("assert"); function HostStorage() { const hosts = {}; const regexHosts = []; return { get: (host) => { const exact = hosts[host]; if (exact) { return exact; } for (const regex of regexHosts) { if (regex.host.test(host)) { return regex.value; } } }, set: (host, value) => { if (host instanceof RegExp) { regexHosts.push({ host, value }); } else { hosts[host] = value; } } }; } module2.exports = { name: "host", mustMatchWhenDerived: false, storage: HostStorage, validate(value) { assert(typeof value === "string" || Object.prototype.toString.call(value) === "[object RegExp]", "Host should be a string or a RegExp"); } }; } }); // node_modules/find-my-way/lib/constrainer.js var require_constrainer = __commonJS({ "node_modules/find-my-way/lib/constrainer.js"(exports, module2) { "use strict"; var acceptVersionStrategy = require_accept_version(); var acceptHostStrategy = require_accept_host(); var assert = require("assert"); var Constrainer = class { constructor(customStrategies) { this.strategies = { version: acceptVersionStrategy, host: acceptHostStrategy }; this.strategiesInUse = /* @__PURE__ */ new Set(); this.asyncStrategiesInUse = /* @__PURE__ */ new Set(); if (customStrategies) { for (const strategy of Object.values(customStrategies)) { this.addConstraintStrategy(strategy); } } } isStrategyUsed(strategyName) { return this.strategiesInUse.has(strategyName) || this.asyncStrategiesInUse.has(strategyName); } hasConstraintStrategy(strategyName) { const customConstraintStrategy = this.strategies[strategyName]; if (customConstraintStrategy !== void 0) { return customConstraintStrategy.isCustom || this.isStrategyUsed(strategyName); } return false; } addConstraintStrategy(strategy) { assert(typeof strategy.name === "string" && strategy.name !== "", "strategy.name is required."); assert(strategy.storage && typeof strategy.storage === "function", "strategy.storage function is required."); assert(strategy.deriveConstraint && typeof strategy.deriveConstraint === "function", "strategy.deriveConstraint function is required."); if (this.strategies[strategy.name] && this.strategies[strategy.name].isCustom) { throw new Error(`There already exists a custom constraint with the name ${strategy.name}.`); } if (this.isStrategyUsed(strategy.name)) { throw new Error(`There already exists a route with ${strategy.name} constraint.`); } strategy.isCustom = true; strategy.isAsync = strategy.deriveConstraint.length === 3; this.strategies[strategy.name] = strategy; if (strategy.mustMatchWhenDerived) { this.noteUsage({ [strategy.name]: strategy }); } } deriveConstraints(req, ctx, done) { const constraints = this.deriveSyncConstraints(req, ctx); if (done === void 0) { return constraints; } this.deriveAsyncConstraints(constraints, req, ctx, done); } deriveSyncConstraints(req, ctx) { return void 0; } // When new constraints start getting used, we need to rebuild the deriver to derive them. Do so if we see novel constraints used. noteUsage(constraints) { if (constraints) { const beforeSize = this.strategiesInUse.size; for (const key in constraints) { const strategy = this.strategies[key]; if (strategy.isAsync) { this.asyncStrategiesInUse.add(key); } else { this.strategiesInUse.add(key); } } if (beforeSize !== this.strategiesInUse.size) { this._buildDeriveConstraints(); } } } newStoreForConstraint(constraint) { if (!this.strategies[constraint]) { throw new Error(`No strategy registered for constraint key ${constraint}`); } return this.strategies[constraint].storage(); } validateConstraints(constraints) { for (const key in constraints) { const value = constraints[key]; if (typeof value === "undefined") { throw new Error("Can't pass an undefined constraint value, must pass null or no key at all"); } const strategy = this.strategies[key]; if (!strategy) { throw new Error(`No strategy registered for constraint key ${key}`); } if (strategy.validate) { strategy.validate(value); } } } deriveAsyncConstraints(constraints, req, ctx, done) { let asyncConstraintsCount = this.asyncStrategiesInUse.size; if (asyncConstraintsCount === 0) { done(null, constraints); return; } constraints = constraints || {}; for (const key of this.asyncStrategiesInUse) { const strategy = this.strategies[key]; strategy.deriveConstraint(req, ctx, (err, constraintValue) => { if (err !== null) { done(err); return; } constraints[key] = constraintValue; if (--asyncConstraintsCount === 0) { done(null, constraints); } }); } } // Optimization: build a fast function for deriving the constraints for all the strategies at once. We inline the definitions of the version constraint and the host constraint for performance. // If no constraining strategies are in use (no routes constrain on host, or version, or any custom strategies) then we don't need to derive constraints for each route match, so don't do anything special, and just return undefined // This allows us to not allocate an object to hold constraint values if no constraints are defined. _buildDeriveConstraints() { if (this.strategiesInUse.size === 0) return; const lines = ["return {"]; for (const key of this.strategiesInUse) { const strategy = this.strategies[key]; if (!strategy.isCustom) { if (key === "version") { lines.push(" version: req.headers['accept-version'],"); } else { lines.push(" host: req.headers.host || req.headers[':authority'],"); } } else { lines.push(` ${strategy.name}: this.strategies.${key}.deriveConstraint(req, ctx),`); } } lines.push("}"); this.deriveSyncConstraints = new Function("req", "ctx", lines.join("\n")).bind(this); } }; module2.exports = Constrainer; } }); // node_modules/find-my-way/lib/http-methods.js var require_http_methods = __commonJS({ "node_modules/find-my-way/lib/http-methods.js"(exports, module2) { "use strict"; var httpMethods = [ "ACL", "BIND", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LINK", "LOCK", "M-SEARCH", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKCOL", "MOVE", "NOTIFY", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PURGE", "PUT", "REBIND", "REPORT", "SEARCH", "SOURCE", "SUBSCRIBE", "TRACE", "UNBIND", "UNLINK", "UNLOCK", "UNSUBSCRIBE" ]; module2.exports = httpMethods; } }); // node_modules/find-my-way/lib/url-sanitizer.js var require_url_sanitizer = __commonJS({ "node_modules/find-my-way/lib/url-sanitizer.js"(exports, module2) { "use strict"; function decodeComponentChar(highCharCode, lowCharCode) { if (highCharCode === 50) { if (lowCharCode === 53) return "%"; if (lowCharCode === 51) return "#"; if (lowCharCode === 52) return "$"; if (lowCharCode === 54) return "&"; if (lowCharCode === 66) return "+"; if (lowCharCode === 98) return "+"; if (lowCharCode === 67) return ","; if (lowCharCode === 99) return ","; if (lowCharCode === 70) return "/"; if (lowCharCode === 102) return "/"; return null; } if (highCharCode === 51) { if (lowCharCode === 65) return ":"; if (lowCharCode === 97) return ":"; if (lowCharCode === 66) return ";"; if (lowCharCode === 98) return ";"; if (lowCharCode === 68) return "="; if (lowCharCode === 100) return "="; if (lowCharCode === 70) return "?"; if (lowCharCode === 102) return "?"; return null; } if (highCharCode === 52 && lowCharCode === 48) { return "@"; } return null; } function safeDecodeURI(path, useSemicolonDelimiter) { let shouldDecode = false; let shouldDecodeParam = false; let querystring = ""; for (let i = 1; i < path.length; i++) { const charCode = path.charCodeAt(i); if (charCode === 37) { const highCharCode = path.charCodeAt(i + 1); const lowCharCode = path.charCodeAt(i + 2); if (decodeComponentChar(highCharCode, lowCharCode) === null) { shouldDecode = true; } else { shouldDecodeParam = true; if (highCharCode === 50 && lowCharCode === 53) { shouldDecode = true; path = path.slice(0, i + 1) + "25" + path.slice(i + 1); i += 2; } i += 2; } } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) { querystring = path.slice(i + 1); path = path.slice(0, i); break; } } const decodedPath = shouldDecode ? decodeURI(path) : path; return { path: decodedPath, querystring, shouldDecodeParam }; } function safeDecodeURIComponent(uriComponent) { const startIndex = uriComponent.indexOf("%"); if (startIndex === -1) return uriComponent; let decoded = ""; let lastIndex = startIndex; for (let i = startIndex; i < uriComponent.length; i++) { if (uriComponent.charCodeAt(i) === 37) { const highCharCode = uriComponent.charCodeAt(i + 1); const lowCharCode = uriComponent.charCodeAt(i + 2); const decodedChar = decodeComponentChar(highCharCode, lowCharCode); decoded += uriComponent.slice(lastIndex, i) + decodedChar; lastIndex = i + 3; } } return uriComponent.slice(0, startIndex) + decoded + uriComponent.slice(lastIndex); } module2.exports = { safeDecodeURI, safeDecodeURIComponent }; } }); // node_modules/find-my-way/index.js var require_find_my_way = __commonJS({ "node_modules/find-my-way/index.js"(exports, module2) { "use strict"; var assert = require("assert"); var querystring = require_lib(); var isRegexSafe = require_safe_regex2(); var deepEqual = require_fast_deep_equal(); var { prettyPrintTree } = require_pretty_print(); var { StaticNode, NODE_TYPES } = require_node(); var Constrainer = require_constrainer(); var httpMethods = require_http_methods(); var httpMethodStrategy = require_http_method(); var { safeDecodeURI, safeDecodeURIComponent } = require_url_sanitizer(); var FULL_PATH_REGEXP = /^https?:\/\/.*?\//; var OPTIONAL_PARAM_REGEXP = /(\/:[^/()]*?)\?(\/?)/; if (!isRegexSafe(FULL_PATH_REGEXP)) { throw new Error("the FULL_PATH_REGEXP is not safe, update this module"); } if (!isRegexSafe(OPTIONAL_PARAM_REGEXP)) { throw new Error("the OPTIONAL_PARAM_REGEXP is not safe, update this module"); } function Router(opts) { if (!(this instanceof Router)) { return new Router(opts); } opts = opts || {}; this._opts = opts; if (opts.defaultRoute) { assert(typeof opts.defaultRoute === "function", "The default route must be a function"); this.defaultRoute = opts.defaultRoute; } else { this.defaultRoute = null; } if (opts.onBadUrl) { assert(typeof opts.onBadUrl === "function", "The bad url handler must be a function"); this.onBadUrl = opts.onBadUrl; } else { this.onBadUrl = null; } if (opts.buildPrettyMeta) { assert(typeof opts.buildPrettyMeta === "function", "buildPrettyMeta must be a function"); this.buildPrettyMeta = opts.buildPrettyMeta; } else { this.buildPrettyMeta = defaultBuildPrettyMeta; } if (opts.querystringParser) { assert(typeof opts.querystringParser === "function", "querystringParser must be a function"); this.querystringParser = opts.querystringParser; } else { this.querystringParser = (query) => query === "" ? {} : querystring.parse(query); } this.caseSensitive = opts.caseSensitive === void 0 ? true : opts.caseSensitive; this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false; this.ignoreDuplicateSlashes = opts.ignoreDuplicateSlashes || false; this.maxParamLength = opts.maxParamLength || 100; this.allowUnsafeRegex = opts.allowUnsafeRegex || false; this.constrainer = new Constrainer(opts.constraints); this.useSemicolonDelimiter = opts.useSemicolonDelimiter || false; this.routes = []; this.trees = {}; } Router.prototype.on = function on(method, path, opts, handler, store) { if (typeof opts === "function") { if (handler !== void 0) { store = handler; } handler = opts; opts = {}; } assert(typeof path === "string", "Path should be a string"); assert(path.length > 0, "The path could not be empty"); assert(path[0] === "/" || path[0] === "*", "The first character of a path should be `/` or `*`"); assert(typeof handler === "function", "Handler should be a function"); const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP); if (optionalParamMatch) { assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path"); const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, "$1$2"); const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/"; this.on(method, pathFull, opts, handler, store); this.on(method, pathOptional, opts, handler, store); return; } const route = path; if (this.ignoreDuplicateSlashes) { path = removeDuplicateSlashes(path); } if (this.ignoreTrailingSlash) { path = trimLastSlash(path); } const methods = Array.isArray(method) ? method : [method]; for (const method2 of methods) { assert(typeof method2 === "string", "Method should be a string"); assert(httpMethods.includes(method2), `Method '${method2}' is not an http method.`); this._on(method2, path, opts, handler, store, route); } }; Router.prototype._on = function _on(method, path, opts, handler, store) { let constraints = {}; if (opts.constraints !== void 0) { assert(typeof opts.constraints === "object" && opts.constraints !== null, "Constraints should be an object"); if (Object.keys(opts.constraints).length !== 0) { constraints = opts.constraints; } } this.constrainer.validateConstraints(constraints); this.constrainer.noteUsage(constraints); if (this.trees[method] === void 0) { this.trees[method] = new StaticNode("/"); } let pattern = path; if (pattern === "*" && this.trees[method].prefix.length !== 0) { const currentRoot = this.trees[method]; this.trees[method] = new StaticNode(""); this.trees[method].staticChildren["/"] = currentRoot; } let currentNode = this.trees[method]; let parentNodePathIndex = currentNode.prefix.length; const params = []; for (let i = 0; i <= pattern.length; i++) { if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) { i++; continue; } const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58; const isWildcardNode = pattern.charCodeAt(i) === 42; if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) { let staticNodePath = pattern.slice(parentNodePathIndex, i); if (!this.caseSensitive) { staticNodePath = staticNodePath.toLowerCase(); } staticNodePath = staticNodePath.split("::").join(":"); staticNodePath = staticNodePath.split("%").join("%25"); currentNode = currentNode.createStaticChild(staticNodePath); } if (isParametricNode) { let isRegexNode = false; const regexps = []; let lastParamStartIndex = i + 1; for (let j = lastParamStartIndex; ; j++) { const charCode = pattern.charCodeAt(j); const isRegexParam = charCode === 40; const isStaticPart = charCode === 45 || charCode === 46; const isEndOfNode = charCode === 47 || j === pattern.length; if (isRegexParam || isStaticPart || isEndOfNode) { const paramName = pattern.slice(lastParamStartIndex, j); params.push(paramName); isRegexNode = isRegexNode || isRegexParam || isStaticPart; if (isRegexParam) { const endOfRegexIndex = getClosingParenthensePosition(pattern, j); const regexString = pattern.slice(j, endOfRegexIndex + 1); if (!this.allowUnsafeRegex) { assert(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`); } regexps.push(trimRegExpStartAndEnd(regexString)); j = endOfRegexIndex + 1; } else { regexps.push("(.*?)"); } const staticPartStartIndex = j; for (; j < pattern.length; j++) { const charCode2 = pattern.charCodeAt(j); if (charCode2 === 47) break; if (charCode2 === 58) { const nextCharCode = pattern.charCodeAt(j + 1); if (nextCharCode === 58) j++; else break; } } let staticPart = pattern.slice(staticPartStartIndex, j); if (staticPart) { staticPart = staticPart.split("::").join(":"); staticPart = staticPart.split("%").join("%25"); regexps.push(escapeRegExp(staticPart)); } lastParamStartIndex = j + 1; if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) { const nodePattern = isRegexNode ? "()" + staticPart : staticPart; const nodePath = pattern.slice(i, j); pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j); i += nodePattern.length; const regex = isRegexNode ? new RegExp("^" + regexps.join("") + "$") : null; currentNode = currentNode.createParametricChild(regex, staticPart || null, nodePath); parentNodePathIndex = i + 1; break; } } } } else if (isWildcardNode) { params.push("*"); currentNode = currentNode.createWildcardChild(); parentNodePathIndex = i + 1; if (i !== pattern.length - 1) { throw new Error("Wildcard must be the last character in the route"); } } } if (!this.caseSensitive) { pattern = pattern.toLowerCase(); } if (pattern === "*") { pattern = "/*"; } for (const existRoute of this.routes) { const routeConstraints = existRoute.opts.constraints || {}; if (existRoute.method === method && existRoute.pattern === pattern && deepEqual(routeConstraints, constraints)) { throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`); } } const route = { method, path, pattern, params, opts, handler, store }; this.routes.push(route); currentNode.addRoute(route, this.constrainer); }; Router.prototype.hasRoute = function hasRoute(method, path, constraints) { const route = this.findRoute(method, path, constraints); return route !== null; }; Router.prototype.findRoute = function findNode(method, path, constraints = {}) { if (this.trees[method] === void 0) { return null; } let pattern = path; let currentNode = this.trees[method]; let parentNodePathIndex = currentNode.prefix.length; const params = []; for (let i = 0; i <= pattern.length; i++) { if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) { i++; continue; } const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58; const isWildcardNode = pattern.charCodeAt(i) === 42; if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) { let staticNodePath = pattern.slice(parentNodePathIndex, i); if (!this.caseSensitive) { staticNodePath = staticNodePath.toLowerCase(); } staticNodePath = staticNodePath.split("::").join(":"); staticNodePath = staticNodePath.split("%").join("%25"); currentNode = currentNode.getStaticChild(staticNodePath); if (currentNode === null) { return null; } } if (isParametricNode) { let isRegexNode = false; const regexps = []; let lastParamStartIndex = i + 1; for (let j = lastParamStartIndex; ; j++) { const charCode = pattern.charCodeAt(j); const isRegexParam = charCode === 40; const isStaticPart = charCode === 45 || charCode === 46; const isEndOfNode = charCode === 47 || j === pattern.length; if (isRegexParam || isStaticPart || isEndOfNode) { const paramName = pattern.slice(lastParamStartIndex, j); params.push(paramName); isRegexNode = isRegexNode || isRegexParam || isStaticPart; if (isRegexParam) { const endOfRegexIndex = getClosingParenthensePosition(pattern, j); const regexString = pattern.slice(j, endOfRegexIndex + 1); if (!this.allowUnsafeRegex) { assert(isRegexSafe(new RegExp(regexString)), `The regex '${regexString}' is not safe!`); } regexps.push(trimRegExpStartAndEnd(regexString)); j = endOfRegexIndex + 1; } else { regexps.push("(.*?)"); } const staticPartStartIndex = j; for (; j < pattern.length; j++) { const charCode2 = pattern.charCodeAt(j); if (charCode2 === 47) break; if (charCode2 === 58) { const nextCharCode = pattern.charCodeAt(j + 1); if (nextCharCode === 58) j++; else break; } } let staticPart = pattern.slice(staticPartStartIndex, j); if (staticPart) { staticPart = staticPart.split("::").join(":"); staticPart = staticPart.split("%").join("%25"); regexps.push(escapeRegExp(staticPart)); } lastParamStartIndex = j + 1; if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) { const nodePattern = isRegexNode ? "()" + staticPart : staticPart; const nodePath = pattern.slice(i, j); pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j); i += nodePattern.length; const regex = isRegexNode ? new RegExp("^" + regexps.join("") + "$") : null; currentNode = currentNode.getParametricChild(regex, staticPart || null, nodePath); if (currentNode === null) { return null; } parentNodePathIndex = i + 1; break; } } } } else if (isWildcardNode) { params.push("*"); currentNode = currentNode.getWildcardChild(); parentNodePathIndex = i + 1; if (i !== pattern.length - 1) { throw new Error("Wildcard must be the last character in the route"); } } } if (!this.caseSensitive) { pattern = pattern.toLowerCase(); } for (const existRoute of this.routes) { const routeConstraints = existRoute.opts.constraints || {}; if (existRoute.method === method && existRoute.pattern === pattern && deepEqual(routeConstraints, constraints)) { return { handler: existRoute.handler, store: existRoute.store, params: existRoute.params }; } } return null; }; Router.prototype.hasConstraintStrategy = function(strategyName) { return this.constrainer.hasConstraintStrategy(strategyName); }; Router.prototype.addConstraintStrategy = function(constraints) { this.constrainer.addConstraintStrategy(constraints); this._rebuild(this.routes); }; Router.prototype.reset = function reset() { this.trees = {}; this.routes = []; }; Router.prototype.off = function off(method, path, constraints) { assert(typeof path === "string", "Path should be a string"); assert(path.length > 0, "The path could not be empty"); assert(path[0] === "/" || path[0] === "*", "The first character of a path should be `/` or `*`"); assert( typeof constraints === "undefined" || typeof constraints === "object" && !Array.isArray(constraints) && constraints !== null, "Constraints should be an object or undefined." ); const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP); if (optionalParamMatch) { assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path"); const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, "$1$2"); const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, "$2"); this.off(method, pathFull, constraints); this.off(method, pathOptional, constraints); return; } if (this.ignoreDuplicateSlashes) { path = removeDuplicateSlashes(path); } if (this.ignoreTrailingSlash) { path = trimLastSlash(path); } const methods = Array.isArray(method) ? method : [method]; for (const method2 of methods) { this._off(method2, path, constraints); } }; Router.prototype._off = function _off(method, path, constraints) { assert(typeof method === "string", "Method should be a string"); assert(httpMethods.includes(method), `Method '${method}' is not an http method.`); function matcherWithoutConstraints(route) { return method !== route.method || path !== route.path; } function matcherWithConstraints(route) { return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {}); } const predicate = constraints ? matcherWithConstraints : matcherWithoutConstraints; const newRoutes = this.routes.filter(predicate); this._rebuild(newRoutes); }; Router.prototype.lookup = function lookup(req, res, ctx, done) { if (typeof ctx === "function") { done = ctx; ctx = void 0; } if (done === void 0) { const constraints = this.constrainer.deriveConstraints(req, ctx); const handle = this.find(req.method, req.url, constraints); return this.callHandler(handle, req, res, ctx); } this.constrainer.deriveConstraints(req, ctx, (err, constraints) => { if (err !== null) { done(err); return; } try { const handle = this.find(req.method, req.url, constraints); const result = this.callHandler(handle, req, res, ctx); done(null, result); } catch (err2) { done(err2); } }); }; Router.prototype.callHandler = function callHandler(handle, req, res, ctx) { if (handle === null) return this._defaultRoute(req, res, ctx); return ctx === void 0 ? handle.handler(req, res, handle.params, handle.store, handle.searchParams) : handle.handler.call(ctx, req, res, handle.params, handle.store, handle.searchParams); }; Router.prototype.find = function find(method, path, derivedConstraints) { let currentNode = this.trees[method]; if (currentNode === void 0) return null; if (path.charCodeAt(0) !== 47) { path = path.replace(FULL_PATH_REGEXP, "/"); } if (this.ignoreDuplicateSlashes) { path = removeDuplicateSlashes(path); } let sanitizedUrl; let querystring2; let shouldDecodeParam; try { sanitizedUrl = safeDecodeURI(path, this.useSemicolonDelimiter); path = sanitizedUrl.path; querystring2 = sanitizedUrl.querystring; shouldDecodeParam = sanitizedUrl.shouldDecodeParam; } catch (error) { return this._onBadUrl(path); } if (this.ignoreTrailingSlash) { path = trimLastSlash(path); } const originPath = path; if (this.caseSensitive === false) { path = path.toLowerCase(); } const maxParamLength = this.maxParamLength; let pathIndex = currentNode.prefix.length; const params = []; const pathLen = path.length; const brothersNodesStack = []; while (true) { if (pathIndex === pathLen && currentNode.isLeafNode) { const handle = currentNode.handlerStorage.getMatchingHandler(derivedConstraints); if (handle !== null) { return { handler: handle.handler, store: handle.store, params: handle._createParamsObject(params), searchParams: this.querystringParser(querystring2) }; } } let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length); if (node === null) { if (brothersNodesStack.length === 0) { return null; } const brotherNodeState = brothersNodesStack.pop(); pathIndex = brotherNodeState.brotherPathIndex; params.splice(brotherNodeState.paramsCount); node = brotherNodeState.brotherNode; } currentNode = node; if (currentNode.kind === NODE_TYPES.STATIC) { pathIndex += currentNode.prefix.length; continue; } if (currentNode.kind === NODE_TYPES.WILDCARD) { let param2 = originPath.slice(pathIndex); if (shouldDecodeParam) { param2 = safeDecodeURIComponent(param2); } params.push(param2); pathIndex = pathLen; continue; } let paramEndIndex = originPath.indexOf("/", pathIndex); if (paramEndIndex === -1) { paramEndIndex = pathLen; } let param = originPath.slice(pathIndex, paramEndIndex); if (shouldDecodeParam) { param = safeDecodeURIComponent(param); } if (currentNode.isRegex) { const matchedParameters = currentNode.regex.exec(param); if (matchedParameters === null) continue; for (let i = 1; i < matchedParameters.length; i++) { const matchedParam = matchedParameters[i]; if (matchedParam.length > maxParamLength) { return null; } params.push(matchedParam); } } else { if (param.length > maxParamLength) { return null; } params.push(param); } pathIndex = paramEndIndex; } }; Router.prototype._rebuild = function(routes) { this.reset(); for (const route of routes) { const { method, path, opts, handler, store } = route; this._on(method, path, opts, handler, store); } }; Router.prototype._defaultRoute = function(req, res, ctx) { if (this.defaultRoute !== null) { return ctx === void 0 ? this.defaultRoute(req, res) : this.defaultRoute.call(ctx, req, res); } else { res.statusCode = 404; res.end(); } }; Router.prototype._onBadUrl = function(path) { if (this.onBadUrl === null) { return null; } const onBadUrl = this.onBadUrl; return { handler: (req, res, ctx) => onBadUrl(path, req, res), params: {}, store: null }; }; Router.prototype.prettyPrint = function(options = {}) { const method = options.method; options.buildPrettyMeta = this.buildPrettyMeta.bind(this); let tree = null; if (method === void 0) { const { version, host, ...constraints } = this.constrainer.strategies; constraints[httpMethodStrategy.name] = httpMethodStrategy; const mergedRouter = new Router({ ...this._opts, constraints }); const mergedRoutes = this.routes.map((route) => { const constraints2 = { ...route.opts.constraints, [httpMethodStrategy.name]: route.method }; return { ...route, method: "MERGED", opts: { constraints: constraints2 } }; }); mergedRouter._rebuild(mergedRoutes); tree = mergedRouter.trees.MERGED; } else { tree = this.trees[method]; } if (tree == null) return "(empty tree)"; return prettyPrintTree(tree, options); }; for (const i in httpMethods) { if (!httpMethods.hasOwnProperty(i)) continue; const m = httpMethods[i]; const methodName = m.toLowerCase(); Router.prototype[methodName] = function(path, handler, store) { return this.on(m, path, handler, store); }; } Router.prototype.all = function(path, handler, store) { this.on(httpMethods, path, handler, store); }; module2.exports = Router; function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function removeDuplicateSlashes(path) { return path.replace(/\/\/+/g, "/"); } function trimLastSlash(path) { if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) { return path.slice(0, -1); } return path; } function trimRegExpStartAndEnd(regexString) { if (regexString.charCodeAt(1) === 94) { regexString = regexString.slice(0, 1) + regexString.slice(2); } if (regexString.charCodeAt(regexString.length - 2) === 36) { regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1); } return regexString; } function getClosingParenthensePosition(path, idx) { let parentheses = 1; while (idx < path.length) { idx++; if (path[idx] === "\\") { idx++; continue; } if (path[idx] === ")") { parentheses--; } else if (path[idx] === "(") { parentheses++; } if (!parentheses) return idx; } throw new TypeError('Invalid regexp expression in "' + path + '"'); } function defaultBuildPrettyMeta(route) { if (!route) return {}; if (!route.store) return {}; return Object.assign({}, route.store); } } }); // node_modules/fastify/lib/headRoute.js var require_headRoute = __commonJS({ "node_modules/fastify/lib/headRoute.js"(exports, module2) { "use strict"; function headRouteOnSendHandler(req, reply, payload, done) { if (payload === void 0) { reply.header("content-length", "0"); return done(null, null); } if (typeof payload.resume === "function") { payload.on("error", (err) => { reply.log.error({ err }, "Error on Stream found for HEAD route"); }); payload.resume(); return done(null, null); } const size = "" + Buffer.byteLength(payload); reply.header("content-length", size); done(null, null); } function parseHeadOnSendHandlers(onSendHandlers) { if (onSendHandlers == null) return headRouteOnSendHandler; return Array.isArray(onSendHandlers) ? [...onSendHandlers, headRouteOnSendHandler] : [onSendHandlers, headRouteOnSendHandler]; } module2.exports = { parseHeadOnSendHandlers }; } }); // node_modules/fastify/lib/route.js var require_route = __commonJS({ "node_modules/fastify/lib/route.js"(exports, module2) { "use strict"; var FindMyWay = require_find_my_way(); var Context = require_context(); var handleRequest = require_handleRequest(); var { onRequestAbortHookRunner, lifecycleHooks, preParsingHookRunner, onTimeoutHookRunner, onRequestHookRunner } = require_hooks(); var { supportedMethods } = require_httpMethods(); var { normalizeSchema } = require_schemas(); var { parseHeadOnSendHandlers } = require_headRoute(); var { FSTDEP007, FSTDEP008, FSTDEP014 } = require_warnings(); var { compileSchemasForValidation, compileSchemasForSerialization } = require_validation(); var { FST_ERR_SCH_VALIDATION_BUILD, FST_ERR_SCH_SERIALIZATION_BUILD, FST_ERR_DEFAULT_ROUTE_INVALID_TYPE, FST_ERR_DUPLICATED_ROUTE, FST_ERR_INVALID_URL, FST_ERR_HOOK_INVALID_HANDLER, FST_ERR_ROUTE_OPTIONS_NOT_OBJ, FST_ERR_ROUTE_DUPLICATED_HANDLER, FST_ERR_ROUTE_HANDLER_NOT_FN, FST_ERR_ROUTE_MISSING_HANDLER, FST_ERR_ROUTE_METHOD_NOT_SUPPORTED, FST_ERR_ROUTE_METHOD_INVALID, FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED, FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT, FST_ERR_HOOK_INVALID_ASYNC_HANDLER } = require_errors2(); var { kRoutePrefix, kLogLevel, kLogSerializers, kHooks, kSchemaController, kOptions, kReplySerializerDefault, kReplyIsError, kRequestPayloadStream, kDisableRequestLogging, kSchemaErrorFormatter, kErrorHandler, kHasBeenDecorated, kRequestAcceptVersion, kRouteByFastify, kRouteContext } = require_symbols2(); var { buildErrorHandler } = require_error_handler(); var { createChildLogger } = require_logger(); var { getGenReqId } = require_reqIdGenFactory(); function buildRouting(options) { const router = FindMyWay(options.config); let avvio; let fourOhFour; let logger; let hasLogger; let setupResponseListeners; let throwIfAlreadyStarted; let disableRequestLogging; let ignoreTrailingSlash; let ignoreDuplicateSlashes; let return503OnClosing; let globalExposeHeadRoutes; let validateHTTPVersion; let keepAliveConnections; let closing = false; return { /** * @param {import('../fastify').FastifyServerOptions} options * @param {*} fastifyArgs */ setup(options2, fastifyArgs) { avvio = fastifyArgs.avvio; fourOhFour = fastifyArgs.fourOhFour; logger = fastifyArgs.logger; hasLogger = fastifyArgs.hasLogger; setupResponseListeners = fastifyArgs.setupResponseListeners; throwIfAlreadyStarted = fastifyArgs.throwIfAlreadyStarted; validateHTTPVersion = fastifyArgs.validateHTTPVersion; globalExposeHeadRoutes = options2.exposeHeadRoutes; disableRequestLogging = options2.disableRequestLogging; ignoreTrailingSlash = options2.ignoreTrailingSlash; ignoreDuplicateSlashes = options2.ignoreDuplicateSlashes; return503OnClosing = Object.prototype.hasOwnProperty.call(options2, "return503OnClosing") ? options2.return503OnClosing : true; keepAliveConnections = fastifyArgs.keepAliveConnections; }, routing: router.lookup.bind(router), // router func to find the right handler to call route, // configure a route in the fastify instance hasRoute, prepareRoute, getDefaultRoute: function() { FSTDEP014(); return router.defaultRoute; }, setDefaultRoute: function(defaultRoute) { FSTDEP014(); if (typeof defaultRoute !== "function") { throw new FST_ERR_DEFAULT_ROUTE_INVALID_TYPE(); } router.defaultRoute = defaultRoute; }, routeHandler, closeRoutes: () => { closing = true; }, printRoutes: router.prettyPrint.bind(router), addConstraintStrategy, hasConstraintStrategy, isAsyncConstraint, findRoute }; function addConstraintStrategy(strategy) { throwIfAlreadyStarted("Cannot add constraint strategy!"); return router.addConstraintStrategy(strategy); } function hasConstraintStrategy(strategyName) { return router.hasConstraintStrategy(strategyName); } function isAsyncConstraint() { return router.constrainer.asyncStrategiesInUse.size > 0; } function prepareRoute({ method, url, options: options2, handler, isFastify }) { if (typeof url !== "string") { throw new FST_ERR_INVALID_URL(typeof url); } if (!handler && typeof options2 === "function") { handler = options2; options2 = {}; } else if (handler && typeof handler === "function") { if (Object.prototype.toString.call(options2) !== "[object Object]") { throw new FST_ERR_ROUTE_OPTIONS_NOT_OBJ(method, url); } else if (options2.handler) { if (typeof options2.handler === "function") { throw new FST_ERR_ROUTE_DUPLICATED_HANDLER(method, url); } else { throw new FST_ERR_ROUTE_HANDLER_NOT_FN(method, url); } } } options2 = Object.assign({}, options2, { method, url, path: url, handler: handler || options2 && options2.handler }); return route.call(this, { options: options2, isFastify }); } function hasRoute({ options: options2 }) { var _a, _b; const normalizedMethod = (_b = (_a = options2.method) == null ? void 0 : _a.toUpperCase()) != null ? _b : ""; return findRoute({ ...options2, method: normalizedMethod }) !== null; } function findRoute(options2) { const route2 = router.find( options2.method, options2.url || "", options2.constraints ); if (route2) { return { handler: route2.handler, params: route2.params, searchParams: route2.searchParams }; } else { return null; } } function route({ options: options2, isFastify }) { const opts = { ...options2 }; const { exposeHeadRoute } = opts; const hasRouteExposeHeadRouteFlag = exposeHeadRoute != null; const shouldExposeHead = hasRouteExposeHeadRouteFlag ? exposeHeadRoute : globalExposeHeadRoutes; const isGetRoute = opts.method === "GET" || Array.isArray(opts.method) && opts.method.includes("GET"); const isHeadRoute = opts.method === "HEAD" || Array.isArray(opts.method) && opts.method.includes("HEAD"); const headOpts = shouldExposeHead && isGetRoute ? { ...options2 } : null; throwIfAlreadyStarted("Cannot add route!"); const path = opts.url || opts.path || ""; if (Array.isArray(opts.method)) { for (var i = 0; i < opts.method.length; ++i) { opts.method[i] = normalizeAndValidateMethod(opts.method[i]); validateSchemaBodyOption(opts.method[i], path, opts.schema); } } else { opts.method = normalizeAndValidateMethod(opts.method); validateSchemaBodyOption(opts.method, path, opts.schema); } if (!opts.handler) { throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path); } if (opts.errorHandler !== void 0 && typeof opts.errorHandler !== "function") { throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path); } validateBodyLimitOption(opts.bodyLimit); const prefix = this[kRoutePrefix]; if (path === "/" && prefix.length > 0 && opts.method !== "HEAD") { switch (opts.prefixTrailingSlash) { case "slash": addNewRoute.call(this, { path, isFastify }); break; case "no-slash": addNewRoute.call(this, { path: "", isFastify }); break; case "both": default: addNewRoute.call(this, { path: "", isFastify }); if (ignoreTrailingSlash !== true && (ignoreDuplicateSlashes !== true || !prefix.endsWith("/"))) { addNewRoute.call(this, { path, prefixing: true, isFastify }); } } } else if (path[0] === "/" && prefix.endsWith("/")) { addNewRoute.call(this, { path: path.slice(1), isFastify }); } else { addNewRoute.call(this, { path, isFastify }); } return this; function addNewRoute({ path: path2, prefixing = false, isFastify: isFastify2 = false }) { const url = prefix + path2; opts.url = url; opts.path = url; opts.routePath = path2; opts.prefix = prefix; opts.logLevel = opts.logLevel || this[kLogLevel]; if (this[kLogSerializers] || opts.logSerializers) { opts.logSerializers = Object.assign(Object.create(this[kLogSerializers]), opts.logSerializers); } if (opts.attachValidation == null) { opts.attachValidation = false; } if (prefixing === false) { for (const hook of this[kHooks].onRoute) { hook.call(this, opts); } } for (const hook of lifecycleHooks) { if (opts && hook in opts) { if (Array.isArray(opts[hook])) { for (const func of opts[hook]) { if (typeof func !== "function") { throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(func)); } if (hook === "onSend" || hook === "preSerialization" || hook === "onError" || hook === "preParsing") { if (func.constructor.name === "AsyncFunction" && func.length === 4) { throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } else if (hook === "onRequestAbort") { if (func.constructor.name === "AsyncFunction" && func.length !== 1) { throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } else { if (func.constructor.name === "AsyncFunction" && func.length === 3) { throw new FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } } } else if (opts[hook] !== void 0 && typeof opts[hook] !== "function") { throw new FST_ERR_HOOK_INVALID_HANDLER(hook, Object.prototype.toString.call(opts[hook])); } } } const constraints = opts.constraints || {}; const config = { ...opts.config, url, method: opts.method }; const context = new Context({ schema: opts.schema, handler: opts.handler.bind(this), config, errorHandler: opts.errorHandler, childLoggerFactory: opts.childLoggerFactory, bodyLimit: opts.bodyLimit, logLevel: opts.logLevel, logSerializers: opts.logSerializers, attachValidation: opts.attachValidation, schemaErrorFormatter: opts.schemaErrorFormatter, replySerializer: this[kReplySerializerDefault], validatorCompiler: opts.validatorCompiler, serializerCompiler: opts.serializerCompiler, exposeHeadRoute: shouldExposeHead, prefixTrailingSlash: opts.prefixTrailingSlash || "both", server: this, isFastify: isFastify2 }); if (opts.version) { FSTDEP008(); constraints.version = opts.version; } const headHandler = router.findRoute("HEAD", opts.url, constraints); const hasHEADHandler = headHandler !== null; if (isHeadRoute && hasHEADHandler && !context[kRouteByFastify] && headHandler.store[kRouteByFastify]) { router.off("HEAD", opts.url, constraints); } try { router.on(opts.method, opts.url, { constraints }, routeHandler, context); } catch (error) { if (!context[kRouteByFastify]) { const isDuplicatedRoute = error.message.includes(`Method '${opts.method}' already declared for route '${opts.url}'`); if (isDuplicatedRoute) { throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url); } throw error; } } this.after((notHandledErr, done) => { context.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler]; context._parserOptions.limit = opts.bodyLimit || null; context.logLevel = opts.logLevel; context.logSerializers = opts.logSerializers; context.attachValidation = opts.attachValidation; context[kReplySerializerDefault] = this[kReplySerializerDefault]; context.schemaErrorFormatter = opts.schemaErrorFormatter || this[kSchemaErrorFormatter] || context.schemaErrorFormatter; avvio.once("preReady", () => { for (const hook of lifecycleHooks) { const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h) => h.bind(this)); context[hook] = toSet.length ? toSet : null; } while (!context.Request[kHasBeenDecorated] && context.Request.parent) { context.Request = context.Request.parent; } while (!context.Reply[kHasBeenDecorated] && context.Reply.parent) { context.Reply = context.Reply.parent; } fourOhFour.setContext(this, context); if (opts.schema) { context.schema = normalizeSchema(context.schema, this.initialConfig); const schemaController = this[kSchemaController]; if (!opts.validatorCompiler && (opts.schema.body || opts.schema.headers || opts.schema.querystring || opts.schema.params)) { schemaController.setupValidator(this[kOptions]); } try { const isCustom = typeof (opts == null ? void 0 : opts.validatorCompiler) === "function" || schemaController.isCustomValidatorCompiler; compileSchemasForValidation(context, opts.validatorCompiler || schemaController.validatorCompiler, isCustom); } catch (error) { throw new FST_ERR_SCH_VALIDATION_BUILD(opts.method, url, error.message); } if (opts.schema.response && !opts.serializerCompiler) { schemaController.setupSerializer(this[kOptions]); } try { compileSchemasForSerialization(context, opts.serializerCompiler || schemaController.serializerCompiler); } catch (error) { throw new FST_ERR_SCH_SERIALIZATION_BUILD(opts.method, url, error.message); } } }); done(notHandledErr); }); if (shouldExposeHead && isGetRoute && !isHeadRoute && !hasHEADHandler) { const onSendHandlers = parseHeadOnSendHandlers(headOpts.onSend); prepareRoute.call(this, { method: "HEAD", url: path2, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true }); } else if (hasHEADHandler && exposeHeadRoute) { FSTDEP007(); } } } function routeHandler(req, res, params, context, query) { const id = getGenReqId(context.server, req); const loggerOpts = { level: context.logLevel }; if (context.logSerializers) { loggerOpts.serializers = context.logSerializers; } const childLogger = createChildLogger(context, logger, req, id, loggerOpts); childLogger[kDisableRequestLogging] = disableRequestLogging; if (!validateHTTPVersion(req.httpVersion)) { childLogger.info({ res: { statusCode: 505 } }, "request aborted - invalid HTTP version"); const message = '{"error":"HTTP Version Not Supported","message":"HTTP Version Not Supported","statusCode":505}'; const headers = { "Content-Type": "application/json", "Content-Length": message.length }; res.writeHead(505, headers); res.end(message); return; } if (closing === true) { if (req.httpVersionMajor !== 2) { res.setHeader("Connection", "close"); } if (return503OnClosing) { const headers = { "Content-Type": "application/json", "Content-Length": "80" }; res.writeHead(503, headers); res.end('{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}'); childLogger.info({ res: { statusCode: 503 } }, "request aborted - refusing to accept new requests as server is closing"); return; } } const connHeader = String.prototype.toLowerCase.call(req.headers.connection || ""); if (connHeader === "keep-alive") { if (keepAliveConnections.has(req.socket) === false) { keepAliveConnections.add(req.socket); req.socket.on("close", removeTrackedSocket.bind({ keepAliveConnections, socket: req.socket })); } } if (req.headers[kRequestAcceptVersion] !== void 0) { req.headers["accept-version"] = req.headers[kRequestAcceptVersion]; req.headers[kRequestAcceptVersion] = void 0; } const request = new context.Request(id, params, req, query, childLogger, context); const reply = new context.Reply(res, request, childLogger); if (disableRequestLogging === false) { childLogger.info({ req: request }, "incoming request"); } if (hasLogger === true || context.onResponse !== null) { setupResponseListeners(reply); } if (context.onRequest !== null) { onRequestHookRunner( context.onRequest, request, reply, runPreParsing ); } else { runPreParsing(null, request, reply); } if (context.onRequestAbort !== null) { req.on("close", () => { if (req.aborted) { onRequestAbortHookRunner( context.onRequestAbort, request, handleOnRequestAbortHooksErrors.bind(null, reply) ); } }); } if (context.onTimeout !== null) { if (!request.raw.socket._meta) { request.raw.socket.on("timeout", handleTimeout); } request.raw.socket._meta = { context, request, reply }; } } } function handleOnRequestAbortHooksErrors(reply, err) { if (err) { reply.log.error({ err }, "onRequestAborted hook failed"); } } function handleTimeout() { const { context, request, reply } = this._meta; onTimeoutHookRunner( context.onTimeout, request, reply, noop ); } function normalizeAndValidateMethod(method) { if (typeof method !== "string") { throw new FST_ERR_ROUTE_METHOD_INVALID(); } method = method.toUpperCase(); if (supportedMethods.indexOf(method) === -1) { throw new FST_ERR_ROUTE_METHOD_NOT_SUPPORTED(method); } return method; } function validateSchemaBodyOption(method, path, schema) { if ((method === "GET" || method === "HEAD") && schema && schema.body) { throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path); } } function validateBodyLimitOption(bodyLimit) { if (bodyLimit === void 0) return; if (!Number.isInteger(bodyLimit) || bodyLimit <= 0) { throw new FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT(bodyLimit); } } function runPreParsing(err, request, reply) { if (reply.sent === true) return; if (err != null) { reply[kReplyIsError] = true; reply.send(err); return; } request[kRequestPayloadStream] = request.raw; if (request[kRouteContext].preParsing !== null) { preParsingHookRunner(request[kRouteContext].preParsing, request, reply, handleRequest); } else { handleRequest(null, request, reply); } } function removeTrackedSocket() { this.keepAliveConnections.delete(this.socket); } function noop() { } module2.exports = { buildRouting, validateBodyLimitOption }; } }); // node_modules/fastify/lib/fourOhFour.js var require_fourOhFour = __commonJS({ "node_modules/fastify/lib/fourOhFour.js"(exports, module2) { "use strict"; var FindMyWay = require_find_my_way(); var Reply = require_reply(); var Request = require_request(); var Context = require_context(); var { kRoutePrefix, kCanSetNotFoundHandler, kFourOhFourLevelInstance, kFourOhFourContext, kHooks, kErrorHandler } = require_symbols2(); var { lifecycleHooks } = require_hooks(); var { buildErrorHandler } = require_error_handler(); var { FST_ERR_NOT_FOUND } = require_errors2(); var { createChildLogger } = require_logger(); var { getGenReqId } = require_reqIdGenFactory(); function fourOhFour(options) { const { logger, disableRequestLogging } = options; const router = FindMyWay({ onBadUrl: createOnBadUrl(), defaultRoute: fourOhFourFallBack }); let _onBadUrlHandler = null; return { router, setNotFoundHandler, setContext, arrange404 }; function arrange404(instance) { instance[kFourOhFourLevelInstance] = instance; instance[kCanSetNotFoundHandler] = true; router.onBadUrl = router.onBadUrl.bind(instance); router.defaultRoute = router.defaultRoute.bind(instance); } function basic404(request, reply) { const { url, method } = request.raw; const message = `Route ${method}:${url} not found`; if (!disableRequestLogging) { request.log.info(message); } reply.code(404).send({ message, error: "Not Found", statusCode: 404 }); } function createOnBadUrl() { return function onBadUrl(path, req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); const childLogger = createChildLogger(fourOhFourContext, logger, req, id); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); _onBadUrlHandler(request, reply); }; } function setContext(instance, context) { const _404Context = Object.assign({}, instance[kFourOhFourContext]); _404Context.onSend = context.onSend; context[kFourOhFourContext] = _404Context; } function setNotFoundHandler(opts, handler, avvio, routeHandler) { if (this[kCanSetNotFoundHandler] === void 0) { this[kCanSetNotFoundHandler] = true; } if (this[kFourOhFourContext] === void 0) { this[kFourOhFourContext] = null; } const _fastify = this; const prefix = this[kRoutePrefix] || "/"; if (this[kCanSetNotFoundHandler] === false) { throw new Error(`Not found handler already set for Fastify instance with prefix: '${prefix}'`); } if (typeof opts === "object") { if (opts.preHandler) { if (Array.isArray(opts.preHandler)) { opts.preHandler = opts.preHandler.map((hook) => hook.bind(_fastify)); } else { opts.preHandler = opts.preHandler.bind(_fastify); } } if (opts.preValidation) { if (Array.isArray(opts.preValidation)) { opts.preValidation = opts.preValidation.map((hook) => hook.bind(_fastify)); } else { opts.preValidation = opts.preValidation.bind(_fastify); } } } if (typeof opts === "function") { handler = opts; opts = void 0; } opts = opts || {}; if (handler) { this[kFourOhFourLevelInstance][kCanSetNotFoundHandler] = false; handler = handler.bind(this); _onBadUrlHandler = handler; } else { handler = basic404; _onBadUrlHandler = basic404; } this.after((notHandledErr, done) => { _setNotFoundHandler.call(this, prefix, opts, handler, avvio, routeHandler); done(notHandledErr); }); } function _setNotFoundHandler(prefix, opts, handler, avvio, routeHandler) { const context = new Context({ schema: opts.schema, handler, config: opts.config || {}, server: this }); avvio.once("preReady", () => { const context2 = this[kFourOhFourContext]; for (const hook of lifecycleHooks) { const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h) => h.bind(this)); context2[hook] = toSet.length ? toSet : null; } context2.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler]; }); if (this[kFourOhFourContext] !== null && prefix === "/") { Object.assign(this[kFourOhFourContext], context); return; } this[kFourOhFourLevelInstance][kFourOhFourContext] = context; router.all(prefix + (prefix.endsWith("/") ? "*" : "/*"), routeHandler, context); router.all(prefix, routeHandler, context); } function fourOhFourFallBack(req, res) { const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext]; const id = getGenReqId(fourOhFourContext.server, req); const childLogger = createChildLogger(fourOhFourContext, logger, req, id); childLogger.info({ req }, "incoming request"); const request = new Request(id, null, req, null, childLogger, fourOhFourContext); const reply = new Reply(res, request, childLogger); request.log.warn("the default handler for 404 did not catch this, this is likely a fastify bug, please report it"); request.log.warn(router.prettyPrint()); reply.code(404).send(new FST_ERR_NOT_FOUND()); } } module2.exports = fourOhFour; } }); // node_modules/fastify/lib/configValidator.js var require_configValidator = __commonJS({ "node_modules/fastify/lib/configValidator.js"(exports, module2) { "use strict"; module2.exports = validate10; module2.exports.default = validate10; var schema11 = { "type": "object", "additionalProperties": false, "properties": { "connectionTimeout": { "type": "integer", "default": 0 }, "keepAliveTimeout": { "type": "integer", "default": 72e3 }, "forceCloseConnections": { "oneOf": [{ "type": "string", "pattern": "idle" }, { "type": "boolean" }] }, "maxRequestsPerSocket": { "type": "integer", "default": 0, "nullable": true }, "requestTimeout": { "type": "integer", "default": 0 }, "bodyLimit": { "type": "integer", "default": 1048576 }, "caseSensitive": { "type": "boolean", "default": true }, "allowUnsafeRegex": { "type": "boolean", "default": false }, "http2": { "type": "boolean" }, "https": { "if": { "not": { "oneOf": [{ "type": "boolean" }, { "type": "null" }, { "type": "object", "additionalProperties": false, "required": ["allowHTTP1"], "properties": { "allowHTTP1": { "type": "boolean" } } }] } }, "then": { "setDefaultValue": true } }, "ignoreTrailingSlash": { "type": "boolean", "default": false }, "ignoreDuplicateSlashes": { "type": "boolean", "default": false }, "disableRequestLogging": { "type": "boolean", "default": false }, "jsonShorthand": { "type": "boolean", "default": true }, "maxParamLength": { "type": "integer", "default": 100 }, "onProtoPoisoning": { "type": "string", "default": "error" }, "onConstructorPoisoning": { "type": "string", "default": "error" }, "pluginTimeout": { "type": "integer", "default": 1e4 }, "requestIdHeader": { "anyOf": [{ "enum": [false] }, { "type": "string" }], "default": "request-id" }, "requestIdLogLabel": { "type": "string", "default": "reqId" }, "http2SessionTimeout": { "type": "integer", "default": 72e3 }, "exposeHeadRoutes": { "type": "boolean", "default": true }, "useSemicolonDelimiter": { "type": "boolean", "default": true }, "versioning": { "type": "object", "additionalProperties": true, "required": ["storage", "deriveVersion"], "properties": { "storage": {}, "deriveVersion": {} } }, "constraints": { "type": "object", "additionalProperties": { "type": "object", "required": ["name", "storage", "validate", "deriveConstraint"], "additionalProperties": true, "properties": { "name": { "type": "string" }, "storage": {}, "validate": {}, "deriveConstraint": {} } } } } }; var func2 = Object.prototype.hasOwnProperty; var pattern0 = new RegExp("idle", "u"); function validate10(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { let vErrors = null; let errors = 0; if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.connectionTimeout === void 0) { data.connectionTimeout = 0; } if (data.keepAliveTimeout === void 0) { data.keepAliveTimeout = 72e3; } if (data.maxRequestsPerSocket === void 0) { data.maxRequestsPerSocket = 0; } if (data.requestTimeout === void 0) { data.requestTimeout = 0; } if (data.bodyLimit === void 0) { data.bodyLimit = 1048576; } if (data.caseSensitive === void 0) { data.caseSensitive = true; } if (data.allowUnsafeRegex === void 0) { data.allowUnsafeRegex = false; } if (data.ignoreTrailingSlash === void 0) { data.ignoreTrailingSlash = false; } if (data.ignoreDuplicateSlashes === void 0) { data.ignoreDuplicateSlashes = false; } if (data.disableRequestLogging === void 0) { data.disableRequestLogging = false; } if (data.jsonShorthand === void 0) { data.jsonShorthand = true; } if (data.maxParamLength === void 0) { data.maxParamLength = 100; } if (data.onProtoPoisoning === void 0) { data.onProtoPoisoning = "error"; } if (data.onConstructorPoisoning === void 0) { data.onConstructorPoisoning = "error"; } if (data.pluginTimeout === void 0) { data.pluginTimeout = 1e4; } if (data.requestIdHeader === void 0) { data.requestIdHeader = "request-id"; } if (data.requestIdLogLabel === void 0) { data.requestIdLogLabel = "reqId"; } if (data.http2SessionTimeout === void 0) { data.http2SessionTimeout = 72e3; } if (data.exposeHeadRoutes === void 0) { data.exposeHeadRoutes = true; } if (data.useSemicolonDelimiter === void 0) { data.useSemicolonDelimiter = true; } const _errs1 = errors; for (const key0 in data) { if (!func2.call(schema11.properties, key0)) { delete data[key0]; } } if (_errs1 === errors) { let data0 = data.connectionTimeout; const _errs2 = errors; if (!(typeof data0 == "number" && (!(data0 % 1) && !isNaN(data0)) && isFinite(data0))) { let dataType0 = typeof data0; let coerced0 = void 0; if (!(coerced0 !== void 0)) { if (dataType0 === "boolean" || data0 === null || dataType0 === "string" && data0 && data0 == +data0 && !(data0 % 1)) { coerced0 = +data0; } else { validate10.errors = [{ instancePath: instancePath + "/connectionTimeout", schemaPath: "#/properties/connectionTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced0 !== void 0) { data0 = coerced0; if (data !== void 0) { data["connectionTimeout"] = coerced0; } } } var valid0 = _errs2 === errors; if (valid0) { let data1 = data.keepAliveTimeout; const _errs4 = errors; if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1)) && isFinite(data1))) { let dataType1 = typeof data1; let coerced1 = void 0; if (!(coerced1 !== void 0)) { if (dataType1 === "boolean" || data1 === null || dataType1 === "string" && data1 && data1 == +data1 && !(data1 % 1)) { coerced1 = +data1; } else { validate10.errors = [{ instancePath: instancePath + "/keepAliveTimeout", schemaPath: "#/properties/keepAliveTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced1 !== void 0) { data1 = coerced1; if (data !== void 0) { data["keepAliveTimeout"] = coerced1; } } } var valid0 = _errs4 === errors; if (valid0) { if (data.forceCloseConnections !== void 0) { let data2 = data.forceCloseConnections; const _errs6 = errors; const _errs7 = errors; let valid1 = false; let passing0 = null; const _errs8 = errors; if (typeof data2 !== "string") { let dataType2 = typeof data2; let coerced2 = void 0; if (!(coerced2 !== void 0)) { if (dataType2 == "number" || dataType2 == "boolean") { coerced2 = "" + data2; } else if (data2 === null) { coerced2 = ""; } else { const err0 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } } if (coerced2 !== void 0) { data2 = coerced2; if (data !== void 0) { data["forceCloseConnections"] = coerced2; } } } if (errors === _errs8) { if (typeof data2 === "string") { if (!pattern0.test(data2)) { const err1 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf/0/pattern", keyword: "pattern", params: { pattern: "idle" }, message: 'must match pattern "idle"' }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } } var _valid0 = _errs8 === errors; if (_valid0) { valid1 = true; passing0 = 0; } const _errs10 = errors; if (typeof data2 !== "boolean") { let coerced3 = void 0; if (!(coerced3 !== void 0)) { if (data2 === "false" || data2 === 0 || data2 === null) { coerced3 = false; } else if (data2 === "true" || data2 === 1) { coerced3 = true; } else { const err2 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf/1/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; if (vErrors === null) { vErrors = [err2]; } else { vErrors.push(err2); } errors++; } } if (coerced3 !== void 0) { data2 = coerced3; if (data !== void 0) { data["forceCloseConnections"] = coerced3; } } } var _valid0 = _errs10 === errors; if (_valid0 && valid1) { valid1 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid1 = true; passing0 = 1; } } if (!valid1) { const err3 = { instancePath: instancePath + "/forceCloseConnections", schemaPath: "#/properties/forceCloseConnections/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs7; if (vErrors !== null) { if (_errs7) { vErrors.length = _errs7; } else { vErrors = null; } } } var valid0 = _errs6 === errors; } else { var valid0 = true; } if (valid0) { let data3 = data.maxRequestsPerSocket; const _errs12 = errors; if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3)) && isFinite(data3)) && data3 !== null) { let dataType4 = typeof data3; let coerced4 = void 0; if (!(coerced4 !== void 0)) { if (dataType4 === "boolean" || data3 === null || dataType4 === "string" && data3 && data3 == +data3 && !(data3 % 1)) { coerced4 = +data3; } else if (data3 === "" || data3 === 0 || data3 === false) { coerced4 = null; } else { validate10.errors = [{ instancePath: instancePath + "/maxRequestsPerSocket", schemaPath: "#/properties/maxRequestsPerSocket/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced4 !== void 0) { data3 = coerced4; if (data !== void 0) { data["maxRequestsPerSocket"] = coerced4; } } } var valid0 = _errs12 === errors; if (valid0) { let data4 = data.requestTimeout; const _errs15 = errors; if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { let dataType5 = typeof data4; let coerced5 = void 0; if (!(coerced5 !== void 0)) { if (dataType5 === "boolean" || data4 === null || dataType5 === "string" && data4 && data4 == +data4 && !(data4 % 1)) { coerced5 = +data4; } else { validate10.errors = [{ instancePath: instancePath + "/requestTimeout", schemaPath: "#/properties/requestTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced5 !== void 0) { data4 = coerced5; if (data !== void 0) { data["requestTimeout"] = coerced5; } } } var valid0 = _errs15 === errors; if (valid0) { let data5 = data.bodyLimit; const _errs17 = errors; if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { let dataType6 = typeof data5; let coerced6 = void 0; if (!(coerced6 !== void 0)) { if (dataType6 === "boolean" || data5 === null || dataType6 === "string" && data5 && data5 == +data5 && !(data5 % 1)) { coerced6 = +data5; } else { validate10.errors = [{ instancePath: instancePath + "/bodyLimit", schemaPath: "#/properties/bodyLimit/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced6 !== void 0) { data5 = coerced6; if (data !== void 0) { data["bodyLimit"] = coerced6; } } } var valid0 = _errs17 === errors; if (valid0) { let data6 = data.caseSensitive; const _errs19 = errors; if (typeof data6 !== "boolean") { let coerced7 = void 0; if (!(coerced7 !== void 0)) { if (data6 === "false" || data6 === 0 || data6 === null) { coerced7 = false; } else if (data6 === "true" || data6 === 1) { coerced7 = true; } else { validate10.errors = [{ instancePath: instancePath + "/caseSensitive", schemaPath: "#/properties/caseSensitive/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced7 !== void 0) { data6 = coerced7; if (data !== void 0) { data["caseSensitive"] = coerced7; } } } var valid0 = _errs19 === errors; if (valid0) { let data7 = data.allowUnsafeRegex; const _errs21 = errors; if (typeof data7 !== "boolean") { let coerced8 = void 0; if (!(coerced8 !== void 0)) { if (data7 === "false" || data7 === 0 || data7 === null) { coerced8 = false; } else if (data7 === "true" || data7 === 1) { coerced8 = true; } else { validate10.errors = [{ instancePath: instancePath + "/allowUnsafeRegex", schemaPath: "#/properties/allowUnsafeRegex/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced8 !== void 0) { data7 = coerced8; if (data !== void 0) { data["allowUnsafeRegex"] = coerced8; } } } var valid0 = _errs21 === errors; if (valid0) { if (data.http2 !== void 0) { let data8 = data.http2; const _errs23 = errors; if (typeof data8 !== "boolean") { let coerced9 = void 0; if (!(coerced9 !== void 0)) { if (data8 === "false" || data8 === 0 || data8 === null) { coerced9 = false; } else if (data8 === "true" || data8 === 1) { coerced9 = true; } else { validate10.errors = [{ instancePath: instancePath + "/http2", schemaPath: "#/properties/http2/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced9 !== void 0) { data8 = coerced9; if (data !== void 0) { data["http2"] = coerced9; } } } var valid0 = _errs23 === errors; } else { var valid0 = true; } if (valid0) { if (data.https !== void 0) { let data9 = data.https; const _errs25 = errors; const _errs26 = errors; let valid2 = true; const _errs27 = errors; const _errs28 = errors; const _errs29 = errors; const _errs30 = errors; let valid4 = false; let passing1 = null; const _errs31 = errors; if (typeof data9 !== "boolean") { let coerced10 = void 0; if (!(coerced10 !== void 0)) { if (data9 === "false" || data9 === 0 || data9 === null) { coerced10 = false; } else if (data9 === "true" || data9 === 1) { coerced10 = true; } else { const err4 = {}; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } } if (coerced10 !== void 0) { data9 = coerced10; if (data !== void 0) { data["https"] = coerced10; } } } var _valid2 = _errs31 === errors; if (_valid2) { valid4 = true; passing1 = 0; } const _errs33 = errors; if (data9 !== null) { let coerced11 = void 0; if (!(coerced11 !== void 0)) { if (data9 === "" || data9 === 0 || data9 === false) { coerced11 = null; } else { const err5 = {}; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } } if (coerced11 !== void 0) { data9 = coerced11; if (data !== void 0) { data["https"] = coerced11; } } } var _valid2 = _errs33 === errors; if (_valid2 && valid4) { valid4 = false; passing1 = [passing1, 1]; } else { if (_valid2) { valid4 = true; passing1 = 1; } const _errs35 = errors; if (errors === _errs35) { if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing0; if (data9.allowHTTP1 === void 0 && (missing0 = "allowHTTP1")) { const err6 = {}; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } else { const _errs37 = errors; for (const key1 in data9) { if (!(key1 === "allowHTTP1")) { delete data9[key1]; } } if (_errs37 === errors) { if (data9.allowHTTP1 !== void 0) { let data10 = data9.allowHTTP1; if (typeof data10 !== "boolean") { let coerced12 = void 0; if (!(coerced12 !== void 0)) { if (data10 === "false" || data10 === 0 || data10 === null) { coerced12 = false; } else if (data10 === "true" || data10 === 1) { coerced12 = true; } else { const err7 = {}; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } } if (coerced12 !== void 0) { data10 = coerced12; if (data9 !== void 0) { data9["allowHTTP1"] = coerced12; } } } } } } } else { const err8 = {}; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } } var _valid2 = _errs35 === errors; if (_valid2 && valid4) { valid4 = false; passing1 = [passing1, 2]; } else { if (_valid2) { valid4 = true; passing1 = 2; } } } if (!valid4) { const err9 = {}; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } else { errors = _errs30; if (vErrors !== null) { if (_errs30) { vErrors.length = _errs30; } else { vErrors = null; } } } var valid3 = _errs29 === errors; if (valid3) { const err10 = {}; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } else { errors = _errs28; if (vErrors !== null) { if (_errs28) { vErrors.length = _errs28; } else { vErrors = null; } } } var _valid1 = _errs27 === errors; errors = _errs26; if (vErrors !== null) { if (_errs26) { vErrors.length = _errs26; } else { vErrors = null; } } if (_valid1) { const _errs40 = errors; data["https"] = true; var _valid1 = _errs40 === errors; valid2 = _valid1; } if (!valid2) { const err11 = { instancePath: instancePath + "/https", schemaPath: "#/properties/https/if", keyword: "if", params: { failingKeyword: "then" }, message: 'must match "then" schema' }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; validate10.errors = vErrors; return false; } var valid0 = _errs25 === errors; } else { var valid0 = true; } if (valid0) { let data11 = data.ignoreTrailingSlash; const _errs41 = errors; if (typeof data11 !== "boolean") { let coerced13 = void 0; if (!(coerced13 !== void 0)) { if (data11 === "false" || data11 === 0 || data11 === null) { coerced13 = false; } else if (data11 === "true" || data11 === 1) { coerced13 = true; } else { validate10.errors = [{ instancePath: instancePath + "/ignoreTrailingSlash", schemaPath: "#/properties/ignoreTrailingSlash/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced13 !== void 0) { data11 = coerced13; if (data !== void 0) { data["ignoreTrailingSlash"] = coerced13; } } } var valid0 = _errs41 === errors; if (valid0) { let data12 = data.ignoreDuplicateSlashes; const _errs43 = errors; if (typeof data12 !== "boolean") { let coerced14 = void 0; if (!(coerced14 !== void 0)) { if (data12 === "false" || data12 === 0 || data12 === null) { coerced14 = false; } else if (data12 === "true" || data12 === 1) { coerced14 = true; } else { validate10.errors = [{ instancePath: instancePath + "/ignoreDuplicateSlashes", schemaPath: "#/properties/ignoreDuplicateSlashes/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced14 !== void 0) { data12 = coerced14; if (data !== void 0) { data["ignoreDuplicateSlashes"] = coerced14; } } } var valid0 = _errs43 === errors; if (valid0) { let data13 = data.disableRequestLogging; const _errs45 = errors; if (typeof data13 !== "boolean") { let coerced15 = void 0; if (!(coerced15 !== void 0)) { if (data13 === "false" || data13 === 0 || data13 === null) { coerced15 = false; } else if (data13 === "true" || data13 === 1) { coerced15 = true; } else { validate10.errors = [{ instancePath: instancePath + "/disableRequestLogging", schemaPath: "#/properties/disableRequestLogging/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced15 !== void 0) { data13 = coerced15; if (data !== void 0) { data["disableRequestLogging"] = coerced15; } } } var valid0 = _errs45 === errors; if (valid0) { let data14 = data.jsonShorthand; const _errs47 = errors; if (typeof data14 !== "boolean") { let coerced16 = void 0; if (!(coerced16 !== void 0)) { if (data14 === "false" || data14 === 0 || data14 === null) { coerced16 = false; } else if (data14 === "true" || data14 === 1) { coerced16 = true; } else { validate10.errors = [{ instancePath: instancePath + "/jsonShorthand", schemaPath: "#/properties/jsonShorthand/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced16 !== void 0) { data14 = coerced16; if (data !== void 0) { data["jsonShorthand"] = coerced16; } } } var valid0 = _errs47 === errors; if (valid0) { let data15 = data.maxParamLength; const _errs49 = errors; if (!(typeof data15 == "number" && (!(data15 % 1) && !isNaN(data15)) && isFinite(data15))) { let dataType17 = typeof data15; let coerced17 = void 0; if (!(coerced17 !== void 0)) { if (dataType17 === "boolean" || data15 === null || dataType17 === "string" && data15 && data15 == +data15 && !(data15 % 1)) { coerced17 = +data15; } else { validate10.errors = [{ instancePath: instancePath + "/maxParamLength", schemaPath: "#/properties/maxParamLength/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced17 !== void 0) { data15 = coerced17; if (data !== void 0) { data["maxParamLength"] = coerced17; } } } var valid0 = _errs49 === errors; if (valid0) { let data16 = data.onProtoPoisoning; const _errs51 = errors; if (typeof data16 !== "string") { let dataType18 = typeof data16; let coerced18 = void 0; if (!(coerced18 !== void 0)) { if (dataType18 == "number" || dataType18 == "boolean") { coerced18 = "" + data16; } else if (data16 === null) { coerced18 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/onProtoPoisoning", schemaPath: "#/properties/onProtoPoisoning/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced18 !== void 0) { data16 = coerced18; if (data !== void 0) { data["onProtoPoisoning"] = coerced18; } } } var valid0 = _errs51 === errors; if (valid0) { let data17 = data.onConstructorPoisoning; const _errs53 = errors; if (typeof data17 !== "string") { let dataType19 = typeof data17; let coerced19 = void 0; if (!(coerced19 !== void 0)) { if (dataType19 == "number" || dataType19 == "boolean") { coerced19 = "" + data17; } else if (data17 === null) { coerced19 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/onConstructorPoisoning", schemaPath: "#/properties/onConstructorPoisoning/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced19 !== void 0) { data17 = coerced19; if (data !== void 0) { data["onConstructorPoisoning"] = coerced19; } } } var valid0 = _errs53 === errors; if (valid0) { let data18 = data.pluginTimeout; const _errs55 = errors; if (!(typeof data18 == "number" && (!(data18 % 1) && !isNaN(data18)) && isFinite(data18))) { let dataType20 = typeof data18; let coerced20 = void 0; if (!(coerced20 !== void 0)) { if (dataType20 === "boolean" || data18 === null || dataType20 === "string" && data18 && data18 == +data18 && !(data18 % 1)) { coerced20 = +data18; } else { validate10.errors = [{ instancePath: instancePath + "/pluginTimeout", schemaPath: "#/properties/pluginTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced20 !== void 0) { data18 = coerced20; if (data !== void 0) { data["pluginTimeout"] = coerced20; } } } var valid0 = _errs55 === errors; if (valid0) { let data19 = data.requestIdHeader; const _errs57 = errors; const _errs58 = errors; let valid6 = false; const _errs59 = errors; if (!(data19 === false)) { const err12 = { instancePath: instancePath + "/requestIdHeader", schemaPath: "#/properties/requestIdHeader/anyOf/0/enum", keyword: "enum", params: { allowedValues: schema11.properties.requestIdHeader.anyOf[0].enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } var _valid3 = _errs59 === errors; valid6 = valid6 || _valid3; if (!valid6) { const _errs60 = errors; if (typeof data19 !== "string") { let dataType21 = typeof data19; let coerced21 = void 0; if (!(coerced21 !== void 0)) { if (dataType21 == "number" || dataType21 == "boolean") { coerced21 = "" + data19; } else if (data19 === null) { coerced21 = ""; } else { const err13 = { instancePath: instancePath + "/requestIdHeader", schemaPath: "#/properties/requestIdHeader/anyOf/1/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } } if (coerced21 !== void 0) { data19 = coerced21; if (data !== void 0) { data["requestIdHeader"] = coerced21; } } } var _valid3 = _errs60 === errors; valid6 = valid6 || _valid3; } if (!valid6) { const err14 = { instancePath: instancePath + "/requestIdHeader", schemaPath: "#/properties/requestIdHeader/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs58; if (vErrors !== null) { if (_errs58) { vErrors.length = _errs58; } else { vErrors = null; } } } var valid0 = _errs57 === errors; if (valid0) { let data20 = data.requestIdLogLabel; const _errs62 = errors; if (typeof data20 !== "string") { let dataType22 = typeof data20; let coerced22 = void 0; if (!(coerced22 !== void 0)) { if (dataType22 == "number" || dataType22 == "boolean") { coerced22 = "" + data20; } else if (data20 === null) { coerced22 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/requestIdLogLabel", schemaPath: "#/properties/requestIdLogLabel/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced22 !== void 0) { data20 = coerced22; if (data !== void 0) { data["requestIdLogLabel"] = coerced22; } } } var valid0 = _errs62 === errors; if (valid0) { let data21 = data.http2SessionTimeout; const _errs64 = errors; if (!(typeof data21 == "number" && (!(data21 % 1) && !isNaN(data21)) && isFinite(data21))) { let dataType23 = typeof data21; let coerced23 = void 0; if (!(coerced23 !== void 0)) { if (dataType23 === "boolean" || data21 === null || dataType23 === "string" && data21 && data21 == +data21 && !(data21 % 1)) { coerced23 = +data21; } else { validate10.errors = [{ instancePath: instancePath + "/http2SessionTimeout", schemaPath: "#/properties/http2SessionTimeout/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }]; return false; } } if (coerced23 !== void 0) { data21 = coerced23; if (data !== void 0) { data["http2SessionTimeout"] = coerced23; } } } var valid0 = _errs64 === errors; if (valid0) { let data22 = data.exposeHeadRoutes; const _errs66 = errors; if (typeof data22 !== "boolean") { let coerced24 = void 0; if (!(coerced24 !== void 0)) { if (data22 === "false" || data22 === 0 || data22 === null) { coerced24 = false; } else if (data22 === "true" || data22 === 1) { coerced24 = true; } else { validate10.errors = [{ instancePath: instancePath + "/exposeHeadRoutes", schemaPath: "#/properties/exposeHeadRoutes/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced24 !== void 0) { data22 = coerced24; if (data !== void 0) { data["exposeHeadRoutes"] = coerced24; } } } var valid0 = _errs66 === errors; if (valid0) { let data23 = data.useSemicolonDelimiter; const _errs68 = errors; if (typeof data23 !== "boolean") { let coerced25 = void 0; if (!(coerced25 !== void 0)) { if (data23 === "false" || data23 === 0 || data23 === null) { coerced25 = false; } else if (data23 === "true" || data23 === 1) { coerced25 = true; } else { validate10.errors = [{ instancePath: instancePath + "/useSemicolonDelimiter", schemaPath: "#/properties/useSemicolonDelimiter/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced25 !== void 0) { data23 = coerced25; if (data !== void 0) { data["useSemicolonDelimiter"] = coerced25; } } } var valid0 = _errs68 === errors; if (valid0) { if (data.versioning !== void 0) { let data24 = data.versioning; const _errs70 = errors; if (errors === _errs70) { if (data24 && typeof data24 == "object" && !Array.isArray(data24)) { let missing1; if (data24.storage === void 0 && (missing1 = "storage") || data24.deriveVersion === void 0 && (missing1 = "deriveVersion")) { validate10.errors = [{ instancePath: instancePath + "/versioning", schemaPath: "#/properties/versioning/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } } else { validate10.errors = [{ instancePath: instancePath + "/versioning", schemaPath: "#/properties/versioning/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs70 === errors; } else { var valid0 = true; } if (valid0) { if (data.constraints !== void 0) { let data25 = data.constraints; const _errs73 = errors; if (errors === _errs73) { if (data25 && typeof data25 == "object" && !Array.isArray(data25)) { for (const key2 in data25) { let data26 = data25[key2]; const _errs76 = errors; if (errors === _errs76) { if (data26 && typeof data26 == "object" && !Array.isArray(data26)) { let missing2; if (data26.name === void 0 && (missing2 = "name") || data26.storage === void 0 && (missing2 = "storage") || data26.validate === void 0 && (missing2 = "validate") || data26.deriveConstraint === void 0 && (missing2 = "deriveConstraint")) { validate10.errors = [{ instancePath: instancePath + "/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/constraints/additionalProperties/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }]; return false; } else { if (data26.name !== void 0) { let data27 = data26.name; if (typeof data27 !== "string") { let dataType26 = typeof data27; let coerced26 = void 0; if (!(coerced26 !== void 0)) { if (dataType26 == "number" || dataType26 == "boolean") { coerced26 = "" + data27; } else if (data27 === null) { coerced26 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1") + "/name", schemaPath: "#/properties/constraints/additionalProperties/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced26 !== void 0) { data27 = coerced26; if (data26 !== void 0) { data26["name"] = coerced26; } } } } } } else { validate10.errors = [{ instancePath: instancePath + "/constraints/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/constraints/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid7 = _errs76 === errors; if (!valid7) { break; } } } else { validate10.errors = [{ instancePath: instancePath + "/constraints", schemaPath: "#/properties/constraints/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs73 === errors; } else { var valid0 = true; } } } } } } } } } } } } } } } } } } } } } } } } } } } else { validate10.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate10.errors = vErrors; return errors === 0; } module2.exports.defaultInitOptions = { "connectionTimeout": 0, "keepAliveTimeout": 72e3, "maxRequestsPerSocket": 0, "requestTimeout": 0, "bodyLimit": 1048576, "caseSensitive": true, "allowUnsafeRegex": false, "disableRequestLogging": false, "jsonShorthand": true, "ignoreTrailingSlash": false, "ignoreDuplicateSlashes": false, "maxParamLength": 100, "onProtoPoisoning": "error", "onConstructorPoisoning": "error", "pluginTimeout": 1e4, "requestIdHeader": "request-id", "requestIdLogLabel": "reqId", "http2SessionTimeout": 72e3, "exposeHeadRoutes": true, "useSemicolonDelimiter": true }; } }); // node_modules/fastify/lib/initialConfigValidation.js var require_initialConfigValidation = __commonJS({ "node_modules/fastify/lib/initialConfigValidation.js"(exports, module2) { "use strict"; var validate = require_configValidator(); var deepClone = require_rfdc()({ circles: true, proto: false }); var { FST_ERR_INIT_OPTS_INVALID } = require_errors2(); function validateInitialConfig(options) { const opts = deepClone(options); if (!validate(opts)) { const error = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map((e) => e.message))); error.errors = validate.errors; throw error; } return deepFreezeObject(opts); } function deepFreezeObject(object) { const properties = Object.getOwnPropertyNames(object); for (const name of properties) { const value = object[name]; if (ArrayBuffer.isView(value) && !(value instanceof DataView)) { continue; } object[name] = value && typeof value === "object" ? deepFreezeObject(value) : value; } return Object.freeze(object); } module2.exports = validateInitialConfig; module2.exports.defaultInitOptions = validate.defaultInitOptions; module2.exports.utils = { deepFreezeObject }; } }); // node_modules/fastify/lib/pluginOverride.js var require_pluginOverride = __commonJS({ "node_modules/fastify/lib/pluginOverride.js"(exports, module2) { "use strict"; var { kAvvioBoot, kChildren, kRoutePrefix, kLogLevel, kLogSerializers, kHooks, kSchemaController, kContentTypeParser, kReply, kRequest, kFourOhFour, kPluginNameChain } = require_symbols2(); var Reply = require_reply(); var Request = require_request(); var SchemaController = require_schema_controller(); var ContentTypeParser = require_contentTypeParser(); var { buildHooks } = require_hooks(); var pluginUtils = require_pluginUtils(); module2.exports = function override(old, fn, opts) { const shouldSkipOverride = pluginUtils.registerPlugin.call(old, fn); const fnName = pluginUtils.getPluginName(fn) || pluginUtils.getFuncPreview(fn); if (shouldSkipOverride) { old[kPluginNameChain].push(fnName); return old; } const instance = Object.create(old); old[kChildren].push(instance); instance.ready = old[kAvvioBoot].bind(instance); instance[kChildren] = []; instance[kReply] = Reply.buildReply(instance[kReply]); instance[kRequest] = Request.buildRequest(instance[kRequest]); instance[kContentTypeParser] = ContentTypeParser.helpers.buildContentTypeParser(instance[kContentTypeParser]); instance[kHooks] = buildHooks(instance[kHooks]); instance[kRoutePrefix] = buildRoutePrefix(instance[kRoutePrefix], opts.prefix); instance[kLogLevel] = opts.logLevel || instance[kLogLevel]; instance[kSchemaController] = SchemaController.buildSchemaController(old[kSchemaController]); instance.getSchema = instance[kSchemaController].getSchema.bind(instance[kSchemaController]); instance.getSchemas = instance[kSchemaController].getSchemas.bind(instance[kSchemaController]); instance[pluginUtils.kRegisteredPlugins] = Object.create(instance[pluginUtils.kRegisteredPlugins]); instance[kPluginNameChain] = [fnName]; if (instance[kLogSerializers] || opts.logSerializers) { instance[kLogSerializers] = Object.assign(Object.create(instance[kLogSerializers]), opts.logSerializers); } if (opts.prefix) { instance[kFourOhFour].arrange404(instance); } for (const hook of instance[kHooks].onRegister) hook.call(this, instance, opts); return instance; }; function buildRoutePrefix(instancePrefix, pluginPrefix) { if (!pluginPrefix) { return instancePrefix; } if (instancePrefix.endsWith("/") && pluginPrefix[0] === "/") { pluginPrefix = pluginPrefix.slice(1); } else if (pluginPrefix[0] !== "/") { pluginPrefix = "/" + pluginPrefix; } return instancePrefix + pluginPrefix; } } }); // node_modules/fastify/lib/noop-set.js var require_noop_set = __commonJS({ "node_modules/fastify/lib/noop-set.js"(exports, module2) { "use strict"; module2.exports = function noopSet() { return { [Symbol.iterator]: function* () { }, add() { }, delete() { }, has() { return true; } }; }; } }); // node_modules/cookie/index.js var require_cookie = __commonJS({ "node_modules/cookie/index.js"(exports) { "use strict"; exports.parse = parse; exports.serialize = serialize; var __toString = Object.prototype.toString; var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; function parse(str, options) { if (typeof str !== "string") { throw new TypeError("argument str must be a string"); } var obj = {}; var opt = options || {}; var dec = opt.decode || decode; var index = 0; while (index < str.length) { var eqIdx = str.indexOf("=", index); if (eqIdx === -1) { break; } var endIdx = str.indexOf(";", index); if (endIdx === -1) { endIdx = str.length; } else if (endIdx < eqIdx) { index = str.lastIndexOf(";", eqIdx - 1) + 1; continue; } var key = str.slice(index, eqIdx).trim(); if (void 0 === obj[key]) { var val = str.slice(eqIdx + 1, endIdx).trim(); if (val.charCodeAt(0) === 34) { val = val.slice(1, -1); } obj[key] = tryDecode(val, dec); } index = endIdx + 1; } return obj; } function serialize(name, val, options) { var opt = options || {}; var enc = opt.encode || encode; if (typeof enc !== "function") { throw new TypeError("option encode is invalid"); } if (!fieldContentRegExp.test(name)) { throw new TypeError("argument name is invalid"); } var value = enc(val); if (value && !fieldContentRegExp.test(value)) { throw new TypeError("argument val is invalid"); } var str = name + "=" + value; if (null != opt.maxAge) { var maxAge = opt.maxAge - 0; if (isNaN(maxAge) || !isFinite(maxAge)) { throw new TypeError("option maxAge is invalid"); } str += "; Max-Age=" + Math.floor(maxAge); } if (opt.domain) { if (!fieldContentRegExp.test(opt.domain)) { throw new TypeError("option domain is invalid"); } str += "; Domain=" + opt.domain; } if (opt.path) { if (!fieldContentRegExp.test(opt.path)) { throw new TypeError("option path is invalid"); } str += "; Path=" + opt.path; } if (opt.expires) { var expires = opt.expires; if (!isDate(expires) || isNaN(expires.valueOf())) { throw new TypeError("option expires is invalid"); } str += "; Expires=" + expires.toUTCString(); } if (opt.httpOnly) { str += "; HttpOnly"; } if (opt.secure) { str += "; Secure"; } if (opt.partitioned) { str += "; Partitioned"; } if (opt.priority) { var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; switch (priority) { case "low": str += "; Priority=Low"; break; case "medium": str += "; Priority=Medium"; break; case "high": str += "; Priority=High"; break; default: throw new TypeError("option priority is invalid"); } } if (opt.sameSite) { var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; switch (sameSite) { case true: str += "; SameSite=Strict"; break; case "lax": str += "; SameSite=Lax"; break; case "strict": str += "; SameSite=Strict"; break; case "none": str += "; SameSite=None"; break; default: throw new TypeError("option sameSite is invalid"); } } return str; } function decode(str) { return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; } function encode(val) { return encodeURIComponent(val); } function isDate(val) { return __toString.call(val) === "[object Date]" || val instanceof Date; } function tryDecode(str, decode2) { try { return decode2(str); } catch (e) { return str; } } } }); // node_modules/light-my-request/lib/parse-url.js var require_parse_url = __commonJS({ "node_modules/light-my-request/lib/parse-url.js"(exports, module2) { "use strict"; var { URL: URL2 } = require("url"); var BASE_URL = "http://localhost"; module2.exports = function parseURL(url, query) { if ((typeof url === "string" || Object.prototype.toString.call(url) === "[object String]") && url.startsWith("//")) { url = BASE_URL + url; } const result = typeof url === "object" ? Object.assign(new URL2(BASE_URL), url) : new URL2(url, BASE_URL); if (typeof query === "string") { query = new URLSearchParams(query); for (const key of query.keys()) { result.searchParams.delete(key); for (const value of query.getAll(key)) { result.searchParams.append(key, value); } } } else { const merged = Object.assign({}, url.query, query); for (const key in merged) { const value = merged[key]; if (Array.isArray(value)) { result.searchParams.delete(key); for (const param of value) { result.searchParams.append(key, param); } } else { result.searchParams.set(key, value); } } } return result; }; } }); // node_modules/light-my-request/lib/form-data.js var require_form_data = __commonJS({ "node_modules/light-my-request/lib/form-data.js"(exports, module2) { "use strict"; var { randomUUID } = require("crypto"); var { Readable } = require("stream"); var textEncoder; function isFormDataLike(payload) { return payload && typeof payload === "object" && typeof payload.append === "function" && typeof payload.delete === "function" && typeof payload.get === "function" && typeof payload.getAll === "function" && typeof payload.has === "function" && typeof payload.set === "function" && payload[Symbol.toStringTag] === "FormData"; } function formDataToStream(formdata) { textEncoder = textEncoder != null ? textEncoder : new TextEncoder(); const boundary = `----formdata-${randomUUID()}`; const prefix = `--${boundary}\r Content-Disposition: form-data`; const escape2 = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n"); const linebreak = new Uint8Array([13, 10]); async function* asyncIterator() { for (const [name, value] of formdata) { if (typeof value === "string") { yield textEncoder.encode(`${prefix}; name="${escape2(normalizeLinefeeds(name))}"\r \r `); yield textEncoder.encode(`${normalizeLinefeeds(value)}\r `); } else { let header = `${prefix}; name="${escape2(normalizeLinefeeds(name))}"`; value.name && (header += `; filename="${escape2(value.name)}"`); header += `\r Content-Type: ${value.type || "application/octet-stream"}\r \r `; yield textEncoder.encode(header); if (value.stream) { yield* value.stream(); } else { yield value; } yield linebreak; } } yield textEncoder.encode(`--${boundary}--`); } const stream = Readable.from(asyncIterator()); return { stream, contentType: `multipart/form-data; boundary=${boundary}` }; } module2.exports.isFormDataLike = isFormDataLike; module2.exports.formDataToStream = formDataToStream; } }); // node_modules/light-my-request/lib/request.js var require_request2 = __commonJS({ "node_modules/light-my-request/lib/request.js"(exports, module2) { "use strict"; var { Readable, addAbortSignal } = require("stream"); var util = require("util"); var cookie = require_cookie(); var assert = require("assert"); var { createDeprecation } = require_process_warning(); var parseURL = require_parse_url(); var { isFormDataLike, formDataToStream } = require_form_data(); var { EventEmitter } = require("events"); var FST_LIGHTMYREQUEST_DEP01 = createDeprecation({ name: "FastifyDeprecationLightMyRequest", code: "FST_LIGHTMYREQUEST_DEP01", message: 'You are accessing "request.connection", use "request.socket" instead.' }); function hostHeaderFromURL(parsedURL) { return parsedURL.port ? parsedURL.host : parsedURL.hostname + (parsedURL.protocol === "https:" ? ":443" : ":80"); } var MockSocket = class extends EventEmitter { constructor(remoteAddress) { super(); this.remoteAddress = remoteAddress; } }; function CustomRequest(options) { return new _CustomLMRRequest(this); function _CustomLMRRequest(obj) { Request.call(obj, { ...options, Request: void 0 }); Object.assign(this, obj); for (const fn of Object.keys(Request.prototype)) { this.constructor.prototype[fn] = Request.prototype[fn]; } util.inherits(this.constructor, options.Request); return this; } } function Request(options) { Readable.call(this, { autoDestroy: false }); const parsedURL = parseURL(options.url || options.path, options.query); this.url = parsedURL.pathname + parsedURL.search; this.aborted = false; this.httpVersionMajor = 1; this.httpVersionMinor = 1; this.httpVersion = "1.1"; this.method = options.method ? options.method.toUpperCase() : "GET"; this.headers = {}; this.rawHeaders = []; const headers = options.headers || {}; for (const field in headers) { const fieldLowerCase = field.toLowerCase(); if ((fieldLowerCase === "user-agent" || fieldLowerCase === "content-type") && headers[field] === void 0) { this.headers[fieldLowerCase] = void 0; continue; } const value = headers[field]; assert(value !== void 0, 'invalid value "undefined" for header ' + field); this.headers[fieldLowerCase] = "" + value; } if ("user-agent" in this.headers === false) { this.headers["user-agent"] = "lightMyRequest"; } this.headers.host = this.headers.host || options.authority || hostHeaderFromURL(parsedURL); if (options.cookies) { const { cookies } = options; const cookieValues = Object.keys(cookies).map((key) => cookie.serialize(key, cookies[key])); if (this.headers.cookie) { cookieValues.unshift(this.headers.cookie); } this.headers.cookie = cookieValues.join("; "); } this.socket = new MockSocket(options.remoteAddress || "127.0.0.1"); Object.defineProperty(this, "connection", { get() { FST_LIGHTMYREQUEST_DEP01(); return this.socket; }, configurable: true }); let payload = options.payload || options.body || null; let payloadResume = payload && typeof payload.resume === "function"; if (isFormDataLike(payload)) { const stream = formDataToStream(payload); payload = stream.stream; payloadResume = true; this.headers["content-type"] = stream.contentType; } if (payload && typeof payload !== "string" && !payloadResume && !Buffer.isBuffer(payload)) { payload = JSON.stringify(payload); if ("content-type" in this.headers === false) { this.headers["content-type"] = "application/json"; } } if (payload && !payloadResume && !Object.prototype.hasOwnProperty.call(this.headers, "content-length")) { this.headers["content-length"] = (Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(payload)).toString(); } for (const header of Object.keys(this.headers)) { this.rawHeaders.push(header, this.headers[header]); } this._lightMyRequest = { payload, isDone: false, simulate: options.simulate || {} }; const signal = options.signal; if (signal) { addAbortSignal(signal, this); } return this; } util.inherits(Request, Readable); util.inherits(CustomRequest, Request); Request.prototype.prepare = function(next) { const payload = this._lightMyRequest.payload; if (!payload || typeof payload.resume !== "function") { return next(); } const chunks = []; payload.on("data", (chunk) => chunks.push(Buffer.from(chunk))); payload.on("end", () => { const payload2 = Buffer.concat(chunks); this.headers["content-length"] = this.headers["content-length"] || "" + payload2.length; this._lightMyRequest.payload = payload2; return next(); }); payload.resume(); }; Request.prototype._read = function(size) { setImmediate(() => { if (this._lightMyRequest.isDone) { if (this._lightMyRequest.simulate.end !== false) { this.push(null); } return; } this._lightMyRequest.isDone = true; if (this._lightMyRequest.payload) { if (this._lightMyRequest.simulate.split) { this.push(this._lightMyRequest.payload.slice(0, 1)); this.push(this._lightMyRequest.payload.slice(1)); } else { this.push(this._lightMyRequest.payload); } } if (this._lightMyRequest.simulate.error) { this.emit("error", new Error("Simulated")); } if (this._lightMyRequest.simulate.close) { this.emit("close"); } if (this._lightMyRequest.simulate.end !== false) { this.push(null); } }); }; Request.prototype.destroy = function(error) { if (this.destroyed || this._lightMyRequest.isDone) return; this.destroyed = true; if (error) { this._error = true; process.nextTick(() => this.emit("error", error)); } process.nextTick(() => this.emit("close")); }; module2.exports = Request; module2.exports.Request = Request; module2.exports.CustomRequest = CustomRequest; } }); // node_modules/set-cookie-parser/lib/set-cookie.js var require_set_cookie = __commonJS({ "node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module2) { "use strict"; var defaultParseOptions = { decodeValues: true, map: false, silent: false }; function isNonEmptyString(str) { return typeof str === "string" && !!str.trim(); } function parseString(setCookieValue, options) { var parts = setCookieValue.split(";").filter(isNonEmptyString); var nameValuePairStr = parts.shift(); var parsed = parseNameValuePair(nameValuePairStr); var name = parsed.name; var value = parsed.value; options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; try { value = options.decodeValues ? decodeURIComponent(value) : value; } catch (e) { console.error( "set-cookie-parser encountered an error while decoding a cookie with value '" + value + "'. Set options.decodeValues to false to disable this feature.", e ); } var cookie = { name, value }; parts.forEach(function(part) { var sides = part.split("="); var key = sides.shift().trimLeft().toLowerCase(); var value2 = sides.join("="); if (key === "expires") { cookie.expires = new Date(value2); } else if (key === "max-age") { cookie.maxAge = parseInt(value2, 10); } else if (key === "secure") { cookie.secure = true; } else if (key === "httponly") { cookie.httpOnly = true; } else if (key === "samesite") { cookie.sameSite = value2; } else { cookie[key] = value2; } }); return cookie; } function parseNameValuePair(nameValuePairStr) { var name = ""; var value = ""; var nameValueArr = nameValuePairStr.split("="); if (nameValueArr.length > 1) { name = nameValueArr.shift(); value = nameValueArr.join("="); } else { value = nameValuePairStr; } return { name, value }; } function parse(input, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; if (!input) { if (!options.map) { return []; } else { return {}; } } if (input.headers) { if (typeof input.headers.getSetCookie === "function") { input = input.headers.getSetCookie(); } else if (input.headers["set-cookie"]) { input = input.headers["set-cookie"]; } else { var sch = input.headers[Object.keys(input.headers).find(function(key) { return key.toLowerCase() === "set-cookie"; })]; if (!sch && input.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } input = sch; } } if (!Array.isArray(input)) { input = [input]; } options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; if (!options.map) { return input.filter(isNonEmptyString).map(function(str) { return parseString(str, options); }); } else { var cookies = {}; return input.filter(isNonEmptyString).reduce(function(cookies2, str) { var cookie = parseString(str, options); cookies2[cookie.name] = cookie; return cookies2; }, cookies); } } function splitCookiesString(cookiesString) { if (Array.isArray(cookiesString)) { return cookiesString; } if (typeof cookiesString !== "string") { return []; } var cookiesStrings = []; var pos = 0; var start; var ch; var lastComma; var nextStart; var cookiesSeparatorFound; function skipWhitespace() { while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { pos += 1; } return pos < cookiesString.length; } function notSpecialChar() { ch = cookiesString.charAt(pos); return ch !== "=" && ch !== ";" && ch !== ","; } while (pos < cookiesString.length) { start = pos; cookiesSeparatorFound = false; while (skipWhitespace()) { ch = cookiesString.charAt(pos); if (ch === ",") { lastComma = pos; pos += 1; skipWhitespace(); nextStart = pos; while (pos < cookiesString.length && notSpecialChar()) { pos += 1; } if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { cookiesSeparatorFound = true; pos = nextStart; cookiesStrings.push(cookiesString.substring(start, lastComma)); start = pos; } else { pos = lastComma + 1; } } else { pos += 1; } } if (!cookiesSeparatorFound || pos >= cookiesString.length) { cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); } } return cookiesStrings; } module2.exports = parse; module2.exports.parse = parse; module2.exports.parseString = parseString; module2.exports.splitCookiesString = splitCookiesString; } }); // node_modules/light-my-request/lib/response.js var require_response = __commonJS({ "node_modules/light-my-request/lib/response.js"(exports, module2) { "use strict"; var http = require("http"); var { Writable, Readable } = require("stream"); var util = require("util"); var setCookie = require_set_cookie(); function Response(req, onEnd, reject) { http.ServerResponse.call(this, req); this._lightMyRequest = { headers: null, trailers: {}, payloadChunks: [] }; this.setHeader("foo", "bar"); this.removeHeader("foo"); this.assignSocket(getNullSocket()); this._promiseCallback = typeof reject === "function"; let called = false; const onEndSuccess = (payload) => { called = true; if (this._promiseCallback) { return process.nextTick(() => onEnd(payload)); } process.nextTick(() => onEnd(null, payload)); }; const onEndFailure = (err) => { if (called) return; called = true; if (this._promiseCallback) { return process.nextTick(() => reject(err)); } process.nextTick(() => onEnd(err, null)); }; this.once("finish", () => { const res = generatePayload(this); res.raw.req = req; onEndSuccess(res); }); this.connection.once("error", onEndFailure); this.once("error", onEndFailure); this.once("close", onEndFailure); } util.inherits(Response, http.ServerResponse); Response.prototype.setTimeout = function(msecs, callback) { this.timeoutHandle = setTimeout(() => { this.emit("timeout"); }, msecs); this.on("timeout", callback); return this; }; Response.prototype.writeHead = function() { const result = http.ServerResponse.prototype.writeHead.apply(this, arguments); copyHeaders(this); return result; }; Response.prototype.write = function(data, encoding, callback) { if (this.timeoutHandle) { clearTimeout(this.timeoutHandle); } http.ServerResponse.prototype.write.call(this, data, encoding, callback); this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding)); return true; }; Response.prototype.end = function(data, encoding, callback) { if (data) { this.write(data, encoding); } http.ServerResponse.prototype.end.call(this, callback); this.emit("finish"); this.destroy(); }; Response.prototype.destroy = function(error) { if (this.destroyed) return; this.destroyed = true; if (error) { process.nextTick(() => this.emit("error", error)); } process.nextTick(() => this.emit("close")); }; Response.prototype.addTrailers = function(trailers) { for (const key in trailers) { this._lightMyRequest.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim(); } }; function generatePayload(response) { if (response._lightMyRequest.headers === null) { copyHeaders(response); } serializeHeaders(response); const res = { raw: { res: response }, headers: response._lightMyRequest.headers, statusCode: response.statusCode, statusMessage: response.statusMessage, trailers: {}, get cookies() { return setCookie.parse(this); } }; const rawBuffer = Buffer.concat(response._lightMyRequest.payloadChunks); res.rawPayload = rawBuffer; res.payload = rawBuffer.toString(); res.body = res.payload; res.trailers = response._lightMyRequest.trailers; res.json = function parseJsonPayload() { return JSON.parse(res.payload); }; res.stream = function streamPayload() { return Readable.from(response._lightMyRequest.payloadChunks); }; return res; } function getNullSocket() { return new Writable({ write(chunk, encoding, callback) { setImmediate(callback); } }); } function serializeHeaders(response) { const headers = response._lightMyRequest.headers; for (const headerName of Object.keys(headers)) { const headerValue = headers[headerName]; if (Array.isArray(headerValue)) { headers[headerName] = headerValue.map((value) => "" + value); } else { headers[headerName] = "" + headerValue; } } } function copyHeaders(response) { response._lightMyRequest.headers = Object.assign({}, response.getHeaders()); ["Date", "Connection", "Transfer-Encoding"].forEach((name) => { const regex = new RegExp("\\r\\n" + name + ": ([^\\r]*)\\r\\n"); const field = response._header.match(regex); if (field) { response._lightMyRequest.headers[name.toLowerCase()] = field[1]; } }); } module2.exports = Response; } }); // node_modules/light-my-request/lib/config-validator.js var require_config_validator = __commonJS({ "node_modules/light-my-request/lib/config-validator.js"(exports, module2) { "use strict"; module2.exports = validate10; module2.exports.default = validate10; var schema11 = { "type": "object", "properties": { "url": { "oneOf": [{ "type": "string" }, { "type": "object", "properties": { "protocol": { "type": "string" }, "hostname": { "type": "string" }, "pathname": { "type": "string" } }, "additionalProperties": true, "required": ["pathname"] }] }, "path": { "oneOf": [{ "type": "string" }, { "type": "object", "properties": { "protocol": { "type": "string" }, "hostname": { "type": "string" }, "pathname": { "type": "string" } }, "additionalProperties": true, "required": ["pathname"] }] }, "cookies": { "type": "object", "additionalProperties": true }, "headers": { "type": "object", "additionalProperties": true }, "query": { "anyOf": [{ "type": "object", "additionalProperties": true }, { "type": "string" }] }, "simulate": { "type": "object", "properties": { "end": { "type": "boolean" }, "split": { "type": "boolean" }, "error": { "type": "boolean" }, "close": { "type": "boolean" } } }, "authority": { "type": "string" }, "remoteAddress": { "type": "string" }, "method": { "type": "string", "enum": ["ACL", "BIND", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LINK", "LOCK", "M-SEARCH", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKCOL", "MOVE", "NOTIFY", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PURGE", "PUT", "REBIND", "REPORT", "SEARCH", "SOURCE", "SUBSCRIBE", "TRACE", "UNBIND", "UNLINK", "UNLOCK", "UNSUBSCRIBE", "acl", "bind", "checkout", "connect", "copy", "delete", "get", "head", "link", "lock", "m-search", "merge", "mkactivity", "mkcalendar", "mkcol", "move", "notify", "options", "patch", "post", "propfind", "proppatch", "purge", "put", "rebind", "report", "search", "source", "subscribe", "trace", "unbind", "unlink", "unlock", "unsubscribe"] }, "validate": { "type": "boolean" } }, "additionalProperties": true, "oneOf": [{ "required": ["url"] }, { "required": ["path"] }] }; function validate10(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { let vErrors = null; let errors = 0; const _errs1 = errors; let valid0 = false; let passing0 = null; const _errs2 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.url === void 0 && (missing0 = "url")) { const err0 = { instancePath, schemaPath: "#/oneOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } } var _valid0 = _errs2 === errors; if (_valid0) { valid0 = true; passing0 = 0; } const _errs3 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.path === void 0 && (missing1 = "path")) { const err1 = { instancePath, schemaPath: "#/oneOf/1/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } var _valid0 = _errs3 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid0 = true; passing0 = 1; } } if (!valid0) { const err2 = { instancePath, schemaPath: "#/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err2]; } else { vErrors.push(err2); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs1; if (vErrors !== null) { if (_errs1) { vErrors.length = _errs1; } else { vErrors = null; } } } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.url !== void 0) { let data0 = data.url; const _errs5 = errors; const _errs6 = errors; let valid2 = false; let passing1 = null; const _errs7 = errors; if (typeof data0 !== "string") { let dataType0 = typeof data0; let coerced0 = void 0; if (!(coerced0 !== void 0)) { if (dataType0 == "number" || dataType0 == "boolean") { coerced0 = "" + data0; } else if (data0 === null) { coerced0 = ""; } else { const err3 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } } if (coerced0 !== void 0) { data0 = coerced0; if (data !== void 0) { data["url"] = coerced0; } } } var _valid1 = _errs7 === errors; if (_valid1) { valid2 = true; passing1 = 0; } const _errs9 = errors; if (errors === _errs9) { if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { let missing2; if (data0.pathname === void 0 && (missing2 = "pathname")) { const err4 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf/1/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } else { if (data0.protocol !== void 0) { let data1 = data0.protocol; const _errs12 = errors; if (typeof data1 !== "string") { let dataType1 = typeof data1; let coerced1 = void 0; if (!(coerced1 !== void 0)) { if (dataType1 == "number" || dataType1 == "boolean") { coerced1 = "" + data1; } else if (data1 === null) { coerced1 = ""; } else { const err5 = { instancePath: instancePath + "/url/protocol", schemaPath: "#/properties/url/oneOf/1/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } } if (coerced1 !== void 0) { data1 = coerced1; if (data0 !== void 0) { data0["protocol"] = coerced1; } } } var valid3 = _errs12 === errors; } else { var valid3 = true; } if (valid3) { if (data0.hostname !== void 0) { let data2 = data0.hostname; const _errs14 = errors; if (typeof data2 !== "string") { let dataType2 = typeof data2; let coerced2 = void 0; if (!(coerced2 !== void 0)) { if (dataType2 == "number" || dataType2 == "boolean") { coerced2 = "" + data2; } else if (data2 === null) { coerced2 = ""; } else { const err6 = { instancePath: instancePath + "/url/hostname", schemaPath: "#/properties/url/oneOf/1/properties/hostname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } } if (coerced2 !== void 0) { data2 = coerced2; if (data0 !== void 0) { data0["hostname"] = coerced2; } } } var valid3 = _errs14 === errors; } else { var valid3 = true; } if (valid3) { if (data0.pathname !== void 0) { let data3 = data0.pathname; const _errs16 = errors; if (typeof data3 !== "string") { let dataType3 = typeof data3; let coerced3 = void 0; if (!(coerced3 !== void 0)) { if (dataType3 == "number" || dataType3 == "boolean") { coerced3 = "" + data3; } else if (data3 === null) { coerced3 = ""; } else { const err7 = { instancePath: instancePath + "/url/pathname", schemaPath: "#/properties/url/oneOf/1/properties/pathname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } } if (coerced3 !== void 0) { data3 = coerced3; if (data0 !== void 0) { data0["pathname"] = coerced3; } } } var valid3 = _errs16 === errors; } else { var valid3 = true; } } } } } else { const err8 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf/1/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } } var _valid1 = _errs9 === errors; if (_valid1 && valid2) { valid2 = false; passing1 = [passing1, 1]; } else { if (_valid1) { valid2 = true; passing1 = 1; } } if (!valid2) { const err9 = { instancePath: instancePath + "/url", schemaPath: "#/properties/url/oneOf", keyword: "oneOf", params: { passingSchemas: passing1 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs6; if (vErrors !== null) { if (_errs6) { vErrors.length = _errs6; } else { vErrors = null; } } } var valid1 = _errs5 === errors; } else { var valid1 = true; } if (valid1) { if (data.path !== void 0) { let data4 = data.path; const _errs18 = errors; const _errs19 = errors; let valid4 = false; let passing2 = null; const _errs20 = errors; if (typeof data4 !== "string") { let dataType4 = typeof data4; let coerced4 = void 0; if (!(coerced4 !== void 0)) { if (dataType4 == "number" || dataType4 == "boolean") { coerced4 = "" + data4; } else if (data4 === null) { coerced4 = ""; } else { const err10 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } } if (coerced4 !== void 0) { data4 = coerced4; if (data !== void 0) { data["path"] = coerced4; } } } var _valid2 = _errs20 === errors; if (_valid2) { valid4 = true; passing2 = 0; } const _errs22 = errors; if (errors === _errs22) { if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { let missing3; if (data4.pathname === void 0 && (missing3 = "pathname")) { const err11 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf/1/required", keyword: "required", params: { missingProperty: missing3 }, message: "must have required property '" + missing3 + "'" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } else { if (data4.protocol !== void 0) { let data5 = data4.protocol; const _errs25 = errors; if (typeof data5 !== "string") { let dataType5 = typeof data5; let coerced5 = void 0; if (!(coerced5 !== void 0)) { if (dataType5 == "number" || dataType5 == "boolean") { coerced5 = "" + data5; } else if (data5 === null) { coerced5 = ""; } else { const err12 = { instancePath: instancePath + "/path/protocol", schemaPath: "#/properties/path/oneOf/1/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } } if (coerced5 !== void 0) { data5 = coerced5; if (data4 !== void 0) { data4["protocol"] = coerced5; } } } var valid5 = _errs25 === errors; } else { var valid5 = true; } if (valid5) { if (data4.hostname !== void 0) { let data6 = data4.hostname; const _errs27 = errors; if (typeof data6 !== "string") { let dataType6 = typeof data6; let coerced6 = void 0; if (!(coerced6 !== void 0)) { if (dataType6 == "number" || dataType6 == "boolean") { coerced6 = "" + data6; } else if (data6 === null) { coerced6 = ""; } else { const err13 = { instancePath: instancePath + "/path/hostname", schemaPath: "#/properties/path/oneOf/1/properties/hostname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } } if (coerced6 !== void 0) { data6 = coerced6; if (data4 !== void 0) { data4["hostname"] = coerced6; } } } var valid5 = _errs27 === errors; } else { var valid5 = true; } if (valid5) { if (data4.pathname !== void 0) { let data7 = data4.pathname; const _errs29 = errors; if (typeof data7 !== "string") { let dataType7 = typeof data7; let coerced7 = void 0; if (!(coerced7 !== void 0)) { if (dataType7 == "number" || dataType7 == "boolean") { coerced7 = "" + data7; } else if (data7 === null) { coerced7 = ""; } else { const err14 = { instancePath: instancePath + "/path/pathname", schemaPath: "#/properties/path/oneOf/1/properties/pathname/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } } if (coerced7 !== void 0) { data7 = coerced7; if (data4 !== void 0) { data4["pathname"] = coerced7; } } } var valid5 = _errs29 === errors; } else { var valid5 = true; } } } } } else { const err15 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf/1/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } } var _valid2 = _errs22 === errors; if (_valid2 && valid4) { valid4 = false; passing2 = [passing2, 1]; } else { if (_valid2) { valid4 = true; passing2 = 1; } } if (!valid4) { const err16 = { instancePath: instancePath + "/path", schemaPath: "#/properties/path/oneOf", keyword: "oneOf", params: { passingSchemas: passing2 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs19; if (vErrors !== null) { if (_errs19) { vErrors.length = _errs19; } else { vErrors = null; } } } var valid1 = _errs18 === errors; } else { var valid1 = true; } if (valid1) { if (data.cookies !== void 0) { let data8 = data.cookies; const _errs31 = errors; if (errors === _errs31) { if (!(data8 && typeof data8 == "object" && !Array.isArray(data8))) { validate10.errors = [{ instancePath: instancePath + "/cookies", schemaPath: "#/properties/cookies/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs31 === errors; } else { var valid1 = true; } if (valid1) { if (data.headers !== void 0) { let data9 = data.headers; const _errs34 = errors; if (errors === _errs34) { if (!(data9 && typeof data9 == "object" && !Array.isArray(data9))) { validate10.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs34 === errors; } else { var valid1 = true; } if (valid1) { if (data.query !== void 0) { let data10 = data.query; const _errs37 = errors; const _errs38 = errors; let valid6 = false; const _errs39 = errors; if (errors === _errs39) { if (!(data10 && typeof data10 == "object" && !Array.isArray(data10))) { const err17 = { instancePath: instancePath + "/query", schemaPath: "#/properties/query/anyOf/0/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } } var _valid3 = _errs39 === errors; valid6 = valid6 || _valid3; if (!valid6) { const _errs42 = errors; if (typeof data10 !== "string") { let dataType8 = typeof data10; let coerced8 = void 0; if (!(coerced8 !== void 0)) { if (dataType8 == "number" || dataType8 == "boolean") { coerced8 = "" + data10; } else if (data10 === null) { coerced8 = ""; } else { const err18 = { instancePath: instancePath + "/query", schemaPath: "#/properties/query/anyOf/1/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } } if (coerced8 !== void 0) { data10 = coerced8; if (data !== void 0) { data["query"] = coerced8; } } } var _valid3 = _errs42 === errors; valid6 = valid6 || _valid3; } if (!valid6) { const err19 = { instancePath: instancePath + "/query", schemaPath: "#/properties/query/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; validate10.errors = vErrors; return false; } else { errors = _errs38; if (vErrors !== null) { if (_errs38) { vErrors.length = _errs38; } else { vErrors = null; } } } var valid1 = _errs37 === errors; } else { var valid1 = true; } if (valid1) { if (data.simulate !== void 0) { let data11 = data.simulate; const _errs44 = errors; if (errors === _errs44) { if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { if (data11.end !== void 0) { let data12 = data11.end; const _errs46 = errors; if (typeof data12 !== "boolean") { let coerced9 = void 0; if (!(coerced9 !== void 0)) { if (data12 === "false" || data12 === 0 || data12 === null) { coerced9 = false; } else if (data12 === "true" || data12 === 1) { coerced9 = true; } else { validate10.errors = [{ instancePath: instancePath + "/simulate/end", schemaPath: "#/properties/simulate/properties/end/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced9 !== void 0) { data12 = coerced9; if (data11 !== void 0) { data11["end"] = coerced9; } } } var valid7 = _errs46 === errors; } else { var valid7 = true; } if (valid7) { if (data11.split !== void 0) { let data13 = data11.split; const _errs48 = errors; if (typeof data13 !== "boolean") { let coerced10 = void 0; if (!(coerced10 !== void 0)) { if (data13 === "false" || data13 === 0 || data13 === null) { coerced10 = false; } else if (data13 === "true" || data13 === 1) { coerced10 = true; } else { validate10.errors = [{ instancePath: instancePath + "/simulate/split", schemaPath: "#/properties/simulate/properties/split/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced10 !== void 0) { data13 = coerced10; if (data11 !== void 0) { data11["split"] = coerced10; } } } var valid7 = _errs48 === errors; } else { var valid7 = true; } if (valid7) { if (data11.error !== void 0) { let data14 = data11.error; const _errs50 = errors; if (typeof data14 !== "boolean") { let coerced11 = void 0; if (!(coerced11 !== void 0)) { if (data14 === "false" || data14 === 0 || data14 === null) { coerced11 = false; } else if (data14 === "true" || data14 === 1) { coerced11 = true; } else { validate10.errors = [{ instancePath: instancePath + "/simulate/error", schemaPath: "#/properties/simulate/properties/error/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced11 !== void 0) { data14 = coerced11; if (data11 !== void 0) { data11["error"] = coerced11; } } } var valid7 = _errs50 === errors; } else { var valid7 = true; } if (valid7) { if (data11.close !== void 0) { let data15 = data11.close; const _errs52 = errors; if (typeof data15 !== "boolean") { let coerced12 = void 0; if (!(coerced12 !== void 0)) { if (data15 === "false" || data15 === 0 || data15 === null) { coerced12 = false; } else if (data15 === "true" || data15 === 1) { coerced12 = true; } else { validate10.errors = [{ instancePath: instancePath + "/simulate/close", schemaPath: "#/properties/simulate/properties/close/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced12 !== void 0) { data15 = coerced12; if (data11 !== void 0) { data11["close"] = coerced12; } } } var valid7 = _errs52 === errors; } else { var valid7 = true; } } } } } else { validate10.errors = [{ instancePath: instancePath + "/simulate", schemaPath: "#/properties/simulate/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs44 === errors; } else { var valid1 = true; } if (valid1) { if (data.authority !== void 0) { let data16 = data.authority; const _errs54 = errors; if (typeof data16 !== "string") { let dataType13 = typeof data16; let coerced13 = void 0; if (!(coerced13 !== void 0)) { if (dataType13 == "number" || dataType13 == "boolean") { coerced13 = "" + data16; } else if (data16 === null) { coerced13 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/authority", schemaPath: "#/properties/authority/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced13 !== void 0) { data16 = coerced13; if (data !== void 0) { data["authority"] = coerced13; } } } var valid1 = _errs54 === errors; } else { var valid1 = true; } if (valid1) { if (data.remoteAddress !== void 0) { let data17 = data.remoteAddress; const _errs56 = errors; if (typeof data17 !== "string") { let dataType14 = typeof data17; let coerced14 = void 0; if (!(coerced14 !== void 0)) { if (dataType14 == "number" || dataType14 == "boolean") { coerced14 = "" + data17; } else if (data17 === null) { coerced14 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/remoteAddress", schemaPath: "#/properties/remoteAddress/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced14 !== void 0) { data17 = coerced14; if (data !== void 0) { data["remoteAddress"] = coerced14; } } } var valid1 = _errs56 === errors; } else { var valid1 = true; } if (valid1) { if (data.method !== void 0) { let data18 = data.method; const _errs58 = errors; if (typeof data18 !== "string") { let dataType15 = typeof data18; let coerced15 = void 0; if (!(coerced15 !== void 0)) { if (dataType15 == "number" || dataType15 == "boolean") { coerced15 = "" + data18; } else if (data18 === null) { coerced15 = ""; } else { validate10.errors = [{ instancePath: instancePath + "/method", schemaPath: "#/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } if (coerced15 !== void 0) { data18 = coerced15; if (data !== void 0) { data["method"] = coerced15; } } } if (!(data18 === "ACL" || data18 === "BIND" || data18 === "CHECKOUT" || data18 === "CONNECT" || data18 === "COPY" || data18 === "DELETE" || data18 === "GET" || data18 === "HEAD" || data18 === "LINK" || data18 === "LOCK" || data18 === "M-SEARCH" || data18 === "MERGE" || data18 === "MKACTIVITY" || data18 === "MKCALENDAR" || data18 === "MKCOL" || data18 === "MOVE" || data18 === "NOTIFY" || data18 === "OPTIONS" || data18 === "PATCH" || data18 === "POST" || data18 === "PROPFIND" || data18 === "PROPPATCH" || data18 === "PURGE" || data18 === "PUT" || data18 === "REBIND" || data18 === "REPORT" || data18 === "SEARCH" || data18 === "SOURCE" || data18 === "SUBSCRIBE" || data18 === "TRACE" || data18 === "UNBIND" || data18 === "UNLINK" || data18 === "UNLOCK" || data18 === "UNSUBSCRIBE" || data18 === "acl" || data18 === "bind" || data18 === "checkout" || data18 === "connect" || data18 === "copy" || data18 === "delete" || data18 === "get" || data18 === "head" || data18 === "link" || data18 === "lock" || data18 === "m-search" || data18 === "merge" || data18 === "mkactivity" || data18 === "mkcalendar" || data18 === "mkcol" || data18 === "move" || data18 === "notify" || data18 === "options" || data18 === "patch" || data18 === "post" || data18 === "propfind" || data18 === "proppatch" || data18 === "purge" || data18 === "put" || data18 === "rebind" || data18 === "report" || data18 === "search" || data18 === "source" || data18 === "subscribe" || data18 === "trace" || data18 === "unbind" || data18 === "unlink" || data18 === "unlock" || data18 === "unsubscribe")) { validate10.errors = [{ instancePath: instancePath + "/method", schemaPath: "#/properties/method/enum", keyword: "enum", params: { allowedValues: schema11.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs58 === errors; } else { var valid1 = true; } if (valid1) { if (data.validate !== void 0) { let data19 = data.validate; const _errs60 = errors; if (typeof data19 !== "boolean") { let coerced16 = void 0; if (!(coerced16 !== void 0)) { if (data19 === "false" || data19 === 0 || data19 === null) { coerced16 = false; } else if (data19 === "true" || data19 === 1) { coerced16 = true; } else { validate10.errors = [{ instancePath: instancePath + "/validate", schemaPath: "#/properties/validate/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } } if (coerced16 !== void 0) { data19 = coerced16; if (data !== void 0) { data["validate"] = coerced16; } } } var valid1 = _errs60 === errors; } else { var valid1 = true; } } } } } } } } } } } else { validate10.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate10.errors = vErrors; return errors === 0; } } }); // node_modules/light-my-request/index.js var require_light_my_request = __commonJS({ "node_modules/light-my-request/index.js"(exports, module2) { "use strict"; var assert = require("assert"); var Request = require_request2(); var Response = require_response(); var errorMessage = "The dispatch function has already been invoked"; var optsValidator = require_config_validator(); function inject(dispatchFunc, options, callback) { if (callback === void 0) { return new Chain(dispatchFunc, options); } else { return doInject(dispatchFunc, options, callback); } } function makeRequest(dispatchFunc, server2, req, res) { req.once("error", function(err) { if (this.destroyed) res.destroy(err); }); req.once("close", function() { if (this.destroyed && !this._error) res.destroy(); }); return req.prepare(() => dispatchFunc.call(server2, req, res)); } function doInject(dispatchFunc, options, callback) { options = typeof options === "string" ? { url: options } : options; if (options.validate !== false) { assert(typeof dispatchFunc === "function", "dispatchFunc should be a function"); const isOptionValid = optsValidator(options); if (!isOptionValid) { throw new Error(optsValidator.errors.map((e) => e.message)); } } const server2 = options.server || {}; const RequestConstructor = options.Request ? Request.CustomRequest : Request; if (dispatchFunc.request && dispatchFunc.request.app === dispatchFunc) { Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.request), RequestConstructor.prototype); Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.response), Response.prototype); } if (typeof callback === "function") { const req = new RequestConstructor(options); const res = new Response(req, callback); return makeRequest(dispatchFunc, server2, req, res); } else { return new Promise((resolve, reject) => { const req = new RequestConstructor(options); const res = new Response(req, resolve, reject); makeRequest(dispatchFunc, server2, req, res); }); } } function Chain(dispatch, option) { if (typeof option === "string") { this.option = { url: option }; } else { this.option = Object.assign({}, option); } this.dispatch = dispatch; this._hasInvoked = false; this._promise = null; if (this.option.autoStart !== false) { process.nextTick(() => { if (!this._hasInvoked) { this.end(); } }); } } var httpMethods = [ "delete", "get", "head", "options", "patch", "post", "put", "trace" ]; httpMethods.forEach((method) => { Chain.prototype[method] = function(url) { if (this._hasInvoked === true || this._promise) { throw new Error(errorMessage); } this.option.url = url; this.option.method = method.toUpperCase(); return this; }; }); var chainMethods = [ "body", "cookies", "headers", "payload", "query" ]; chainMethods.forEach((method) => { Chain.prototype[method] = function(value) { if (this._hasInvoked === true || this._promise) { throw new Error(errorMessage); } this.option[method] = value; return this; }; }); Chain.prototype.end = function(callback) { if (this._hasInvoked === true || this._promise) { throw new Error(errorMessage); } this._hasInvoked = true; if (typeof callback === "function") { doInject(this.dispatch, this.option, callback); } else { this._promise = doInject(this.dispatch, this.option); return this._promise; } }; Object.getOwnPropertyNames(Promise.prototype).forEach((method) => { if (method === "constructor") return; Chain.prototype[method] = function(...args) { if (!this._promise) { if (this._hasInvoked === true) { throw new Error(errorMessage); } this._hasInvoked = true; this._promise = doInject(this.dispatch, this.option); } return this._promise[method](...args); }; }); function isInjection(obj) { return obj instanceof Request || obj instanceof Response || obj && obj.constructor && obj.constructor.name === "_CustomLMRRequest"; } module2.exports = inject; module2.exports.default = inject; module2.exports.inject = inject; module2.exports.isInjection = isInjection; } }); // node_modules/fastify/fastify.js var require_fastify = __commonJS({ "node_modules/fastify/fastify.js"(exports, module2) { "use strict"; var VERSION = "4.28.0"; var Avvio = require_boot(); var http = require("http"); var lightMyRequest; var { kAvvioBoot, kChildren, kServerBindings, kBodyLimit, kRoutePrefix, kLogLevel, kLogSerializers, kHooks, kSchemaController, kRequestAcceptVersion, kReplySerializerDefault, kContentTypeParser, kReply, kRequest, kFourOhFour, kState, kOptions, kPluginNameChain, kSchemaErrorFormatter, kErrorHandler, kKeepAliveConnections, kChildLoggerFactory, kGenReqId } = require_symbols2(); var { createServer, compileValidateHTTPVersion } = require_server(); var Reply = require_reply(); var Request = require_request(); var Context = require_context(); var { supportedMethods } = require_httpMethods(); var decorator = require_decorate(); var ContentTypeParser = require_contentTypeParser(); var SchemaController = require_schema_controller(); var { Hooks, hookRunnerApplication, supportedHooks } = require_hooks(); var { createLogger, createChildLogger, defaultChildLoggerFactory } = require_logger(); var pluginUtils = require_pluginUtils(); var { getGenReqId, reqIdGenFactory } = require_reqIdGenFactory(); var { buildRouting, validateBodyLimitOption } = require_route(); var build404 = require_fourOhFour(); var getSecuredInitialConfig = require_initialConfigValidation(); var override = require_pluginOverride(); var { FSTDEP009 } = require_warnings(); var noopSet = require_noop_set(); var { appendStackTrace, AVVIO_ERRORS_MAP, ...errorCodes } = require_errors2(); var { defaultInitOptions } = getSecuredInitialConfig; var { FST_ERR_ASYNC_CONSTRAINT, FST_ERR_BAD_URL, FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE, FST_ERR_OPTIONS_NOT_OBJ, FST_ERR_QSP_NOT_FN, FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN, FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ, FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR, FST_ERR_VERSION_CONSTRAINT_NOT_STR, FST_ERR_INSTANCE_ALREADY_LISTENING, FST_ERR_REOPENED_CLOSE_SERVER, FST_ERR_ROUTE_REWRITE_NOT_STR, FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN, FST_ERR_ERROR_HANDLER_NOT_FN } = errorCodes; var { buildErrorHandler } = require_error_handler(); function defaultBuildPrettyMeta(route) { const cleanKeys = {}; const allowedProps = ["errorHandler", "logLevel", "logSerializers"]; allowedProps.concat(supportedHooks).forEach((k) => { cleanKeys[k] = route.store[k]; }); return Object.assign({}, cleanKeys); } function fastify2(options) { var _a; options = options || {}; if (typeof options !== "object") { throw new FST_ERR_OPTIONS_NOT_OBJ(); } if (options.querystringParser && typeof options.querystringParser !== "function") { throw new FST_ERR_QSP_NOT_FN(typeof options.querystringParser); } if (options.schemaController && options.schemaController.bucket && typeof options.schemaController.bucket !== "function") { throw new FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN(typeof options.schemaController.bucket); } validateBodyLimitOption(options.bodyLimit); const requestIdHeader = options.requestIdHeader === false ? false : (options.requestIdHeader || defaultInitOptions.requestIdHeader).toLowerCase(); const genReqId = reqIdGenFactory(requestIdHeader, options.genReqId); const requestIdLogLabel = options.requestIdLogLabel || "reqId"; const bodyLimit = options.bodyLimit || defaultInitOptions.bodyLimit; const disableRequestLogging = options.disableRequestLogging || false; const ajvOptions = Object.assign({ customOptions: {}, plugins: [] }, options.ajv); const frameworkErrors = options.frameworkErrors; if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== "[object Object]") { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ(typeof ajvOptions.customOptions); } if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) { throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins); } const { logger, hasLogger } = createLogger(options); options.connectionTimeout = options.connectionTimeout || defaultInitOptions.connectionTimeout; options.keepAliveTimeout = options.keepAliveTimeout || defaultInitOptions.keepAliveTimeout; options.maxRequestsPerSocket = options.maxRequestsPerSocket || defaultInitOptions.maxRequestsPerSocket; options.requestTimeout = options.requestTimeout || defaultInitOptions.requestTimeout; options.logger = logger; options.requestIdHeader = requestIdHeader; options.requestIdLogLabel = requestIdLogLabel; options.disableRequestLogging = disableRequestLogging; options.ajv = ajvOptions; options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler; const initialConfig = getSecuredInitialConfig(options); options.exposeHeadRoutes = initialConfig.exposeHeadRoutes; let constraints = options.constraints; if (options.versioning) { FSTDEP009(); constraints = { ...constraints, version: { name: "version", mustMatchWhenDerived: true, storage: options.versioning.storage, deriveConstraint: options.versioning.deriveVersion, validate(value) { if (typeof value !== "string") { throw new FST_ERR_VERSION_CONSTRAINT_NOT_STR(); } } } }; } const router = buildRouting({ config: { defaultRoute, onBadUrl, constraints, ignoreTrailingSlash: options.ignoreTrailingSlash || defaultInitOptions.ignoreTrailingSlash, ignoreDuplicateSlashes: options.ignoreDuplicateSlashes || defaultInitOptions.ignoreDuplicateSlashes, maxParamLength: options.maxParamLength || defaultInitOptions.maxParamLength, caseSensitive: options.caseSensitive, allowUnsafeRegex: options.allowUnsafeRegex || defaultInitOptions.allowUnsafeRegex, buildPrettyMeta: defaultBuildPrettyMeta, querystringParser: options.querystringParser, useSemicolonDelimiter: (_a = options.useSemicolonDelimiter) != null ? _a : defaultInitOptions.useSemicolonDelimiter } }); const fourOhFour = build404(options); const httpHandler = wrapRouting(router, options); options.http2SessionTimeout = initialConfig.http2SessionTimeout; const { server: server2, listen } = createServer(options, httpHandler); const serverHasCloseAllConnections = typeof server2.closeAllConnections === "function"; const serverHasCloseIdleConnections = typeof server2.closeIdleConnections === "function"; let forceCloseConnections = options.forceCloseConnections; if (forceCloseConnections === "idle" && !serverHasCloseIdleConnections) { throw new FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE(); } else if (typeof forceCloseConnections !== "boolean") { forceCloseConnections = serverHasCloseIdleConnections ? "idle" : false; } const keepAliveConnections = !serverHasCloseAllConnections && forceCloseConnections === true ? /* @__PURE__ */ new Set() : noopSet(); const setupResponseListeners = Reply.setupResponseListeners; const schemaController = SchemaController.buildSchemaController(null, options.schemaController); const fastify3 = { // Fastify internals [kState]: { listening: false, closing: false, started: false, ready: false, booting: false, readyPromise: null }, [kKeepAliveConnections]: keepAliveConnections, [kOptions]: options, [kChildren]: [], [kServerBindings]: [], [kBodyLimit]: bodyLimit, [kRoutePrefix]: "", [kLogLevel]: "", [kLogSerializers]: null, [kHooks]: new Hooks(), [kSchemaController]: schemaController, [kSchemaErrorFormatter]: null, [kErrorHandler]: buildErrorHandler(), [kChildLoggerFactory]: defaultChildLoggerFactory, [kReplySerializerDefault]: null, [kContentTypeParser]: new ContentTypeParser( bodyLimit, options.onProtoPoisoning || defaultInitOptions.onProtoPoisoning, options.onConstructorPoisoning || defaultInitOptions.onConstructorPoisoning ), [kReply]: Reply.buildReply(Reply), [kRequest]: Request.buildRequest(Request, options.trustProxy), [kFourOhFour]: fourOhFour, [pluginUtils.kRegisteredPlugins]: [], [kPluginNameChain]: ["fastify"], [kAvvioBoot]: null, [kGenReqId]: genReqId, // routing method routing: httpHandler, getDefaultRoute: router.getDefaultRoute.bind(router), setDefaultRoute: router.setDefaultRoute.bind(router), // routes shorthand methods delete: function _delete(url, options2, handler) { return router.prepareRoute.call(this, { method: "DELETE", url, options: options2, handler }); }, get: function _get(url, options2, handler) { return router.prepareRoute.call(this, { method: "GET", url, options: options2, handler }); }, head: function _head(url, options2, handler) { return router.prepareRoute.call(this, { method: "HEAD", url, options: options2, handler }); }, patch: function _patch(url, options2, handler) { return router.prepareRoute.call(this, { method: "PATCH", url, options: options2, handler }); }, post: function _post(url, options2, handler) { return router.prepareRoute.call(this, { method: "POST", url, options: options2, handler }); }, put: function _put(url, options2, handler) { return router.prepareRoute.call(this, { method: "PUT", url, options: options2, handler }); }, options: function _options(url, options2, handler) { return router.prepareRoute.call(this, { method: "OPTIONS", url, options: options2, handler }); }, all: function _all(url, options2, handler) { return router.prepareRoute.call(this, { method: supportedMethods, url, options: options2, handler }); }, // extended route route: function _route(options2) { return router.route.call(this, { options: options2 }); }, hasRoute: function _route(options2) { return router.hasRoute.call(this, { options: options2 }); }, findRoute: function _findRoute(options2) { return router.findRoute(options2); }, // expose logger instance log: logger, // type provider withTypeProvider, // hooks addHook, // schemas addSchema, getSchema: schemaController.getSchema.bind(schemaController), getSchemas: schemaController.getSchemas.bind(schemaController), setValidatorCompiler, setSerializerCompiler, setSchemaController, setReplySerializer, setSchemaErrorFormatter, // set generated request id setGenReqId, // custom parsers addContentTypeParser: ContentTypeParser.helpers.addContentTypeParser, hasContentTypeParser: ContentTypeParser.helpers.hasContentTypeParser, getDefaultJsonParser: ContentTypeParser.defaultParsers.getDefaultJsonParser, defaultTextParser: ContentTypeParser.defaultParsers.defaultTextParser, removeContentTypeParser: ContentTypeParser.helpers.removeContentTypeParser, removeAllContentTypeParsers: ContentTypeParser.helpers.removeAllContentTypeParsers, // Fastify architecture methods (initialized by Avvio) register: null, after: null, ready: null, onClose: null, close: null, printPlugins: null, hasPlugin: function(name) { return this[pluginUtils.kRegisteredPlugins].includes(name) || this[kPluginNameChain].includes(name); }, // http server listen, server: server2, addresses: function() { const binded = this[kServerBindings].map((b) => b.address()); binded.push(this.server.address()); return binded.filter((adr) => adr); }, // extend fastify objects decorate: decorator.add, hasDecorator: decorator.exist, decorateReply: decorator.decorateReply, decorateRequest: decorator.decorateRequest, hasRequestDecorator: decorator.existRequest, hasReplyDecorator: decorator.existReply, // fake http injection inject, // pretty print of the registered routes printRoutes, // custom error handling setNotFoundHandler, setErrorHandler, // child logger setChildLoggerFactory, // Set fastify initial configuration options read-only object initialConfig, // constraint strategies addConstraintStrategy: router.addConstraintStrategy.bind(router), hasConstraintStrategy: router.hasConstraintStrategy.bind(router) }; Object.defineProperties(fastify3, { listeningOrigin: { get() { const address = this.addresses().slice(-1).pop(); if (typeof address === "string") { return address; } const host = address.family === "IPv6" ? `[${address.address}]` : address.address; return `${this[kOptions].https ? "https" : "http"}://${host}:${address.port}`; } }, pluginName: { configurable: true, get() { if (this[kPluginNameChain].length > 1) { return this[kPluginNameChain].join(" -> "); } return this[kPluginNameChain][0]; } }, prefix: { configurable: true, get() { return this[kRoutePrefix]; } }, validatorCompiler: { configurable: true, get() { return this[kSchemaController].getValidatorCompiler(); } }, serializerCompiler: { configurable: true, get() { return this[kSchemaController].getSerializerCompiler(); } }, childLoggerFactory: { configurable: true, get() { return this[kChildLoggerFactory]; } }, version: { configurable: true, get() { return VERSION; } }, errorHandler: { configurable: true, get() { return this[kErrorHandler].func; } }, genReqId: { configurable: true, get() { return this[kGenReqId]; } } }); if (options.schemaErrorFormatter) { validateSchemaErrorFormatter(options.schemaErrorFormatter); fastify3[kSchemaErrorFormatter] = options.schemaErrorFormatter.bind(fastify3); } const avvioPluginTimeout = Number(options.pluginTimeout); const avvio = Avvio(fastify3, { autostart: false, timeout: isNaN(avvioPluginTimeout) === false ? avvioPluginTimeout : defaultInitOptions.pluginTimeout, expose: { use: "register" } }); avvio.override = override; avvio.on("start", () => fastify3[kState].started = true); fastify3[kAvvioBoot] = fastify3.ready; fastify3.ready = ready; fastify3.printPlugins = avvio.prettyPrint.bind(avvio); avvio.once("preReady", () => { fastify3.onClose((instance, done) => { fastify3[kState].closing = true; router.closeRoutes(); hookRunnerApplication("preClose", fastify3[kAvvioBoot], fastify3, function() { if (fastify3[kState].listening) { if (forceCloseConnections === "idle") { instance.server.closeIdleConnections(); } else if (serverHasCloseAllConnections && forceCloseConnections) { instance.server.closeAllConnections(); } else if (forceCloseConnections === true) { for (const conn of fastify3[kKeepAliveConnections]) { conn.destroy(); fastify3[kKeepAliveConnections].delete(conn); } } } if (!options.serverFactory || fastify3[kState].listening) { instance.server.close(function(err) { if (err && err.code !== "ERR_SERVER_NOT_RUNNING") { done(null); } else { done(); } }); } else { process.nextTick(done, null); } }); }); }); const onBadUrlContext = new Context({ server: fastify3, config: {} }); fastify3.setNotFoundHandler(); fourOhFour.arrange404(fastify3); router.setup(options, { avvio, fourOhFour, logger, hasLogger, setupResponseListeners, throwIfAlreadyStarted, validateHTTPVersion: compileValidateHTTPVersion(options), keepAliveConnections }); server2.on("clientError", options.clientErrorHandler.bind(fastify3)); try { const dc = require("diagnostics_channel"); const initChannel = dc.channel("fastify.initialization"); if (initChannel.hasSubscribers) { initChannel.publish({ fastify: fastify3 }); } } catch (e) { } if ("asyncDispose" in Symbol) { fastify3[Symbol.asyncDispose] = function dispose() { return fastify3.close(); }; } return fastify3; function throwIfAlreadyStarted(msg) { if (fastify3[kState].started) throw new FST_ERR_INSTANCE_ALREADY_LISTENING(msg); } function inject(opts, cb) { if (lightMyRequest === void 0) { lightMyRequest = require_light_my_request(); } if (fastify3[kState].started) { if (fastify3[kState].closing) { const error = new FST_ERR_REOPENED_CLOSE_SERVER(); if (cb) { cb(error); return; } else { return Promise.reject(error); } } return lightMyRequest(httpHandler, opts, cb); } if (cb) { this.ready((err) => { if (err) cb(err, null); else lightMyRequest(httpHandler, opts, cb); }); } else { return lightMyRequest((req, res) => { this.ready(function(err) { if (err) { res.emit("error", err); return; } httpHandler(req, res); }); }, opts); } } function ready(cb) { if (this[kState].readyPromise !== null) { if (cb != null) { this[kState].readyPromise.then(() => cb(null, fastify3), cb); return; } return this[kState].readyPromise; } let resolveReady; let rejectReady; process.nextTick(runHooks); this[kState].readyPromise = new Promise(function(resolve, reject) { resolveReady = resolve; rejectReady = reject; }); if (!cb) { return this[kState].readyPromise; } else { this[kState].readyPromise.then(() => cb(null, fastify3), cb); } function runHooks() { fastify3[kAvvioBoot]((err, done) => { if (err || fastify3[kState].started || fastify3[kState].ready || fastify3[kState].booting) { manageErr(err); } else { fastify3[kState].booting = true; hookRunnerApplication("onReady", fastify3[kAvvioBoot], fastify3, manageErr); } done(); }); } function manageErr(err) { err = err != null && AVVIO_ERRORS_MAP[err.code] != null ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message)) : err; if (err) { return rejectReady(err); } resolveReady(fastify3); fastify3[kState].booting = false; fastify3[kState].ready = true; fastify3[kState].promise = null; } } function withTypeProvider() { return this; } function addHook(name, fn) { throwIfAlreadyStarted('Cannot call "addHook"!'); if (fn == null) { throw new errorCodes.FST_ERR_HOOK_INVALID_HANDLER(name, fn); } if (name === "onSend" || name === "preSerialization" || name === "onError" || name === "preParsing") { if (fn.constructor.name === "AsyncFunction" && fn.length === 4) { throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } else if (name === "onReady" || name === "onListen") { if (fn.constructor.name === "AsyncFunction" && fn.length !== 0) { throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } else if (name === "onRequestAbort") { if (fn.constructor.name === "AsyncFunction" && fn.length !== 1) { throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } else { if (fn.constructor.name === "AsyncFunction" && fn.length === 3) { throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER(); } } if (name === "onClose") { this.onClose(fn); } else if (name === "onReady" || name === "onListen" || name === "onRoute") { this[kHooks].add(name, fn); } else { this.after((err, done) => { _addHook.call(this, name, fn); done(err); }); } return this; function _addHook(name2, fn2) { this[kHooks].add(name2, fn2); this[kChildren].forEach((child) => _addHook.call(child, name2, fn2)); } } function addSchema(schema) { throwIfAlreadyStarted('Cannot call "addSchema"!'); this[kSchemaController].add(schema); this[kChildren].forEach((child) => child.addSchema(schema)); return this; } function defaultClientErrorHandler(err, socket) { if (err.code === "ECONNRESET" || socket.destroyed) { return; } let body, errorCode, errorStatus, errorLabel; if (err.code === "ERR_HTTP_REQUEST_TIMEOUT") { errorCode = "408"; errorStatus = http.STATUS_CODES[errorCode]; body = `{"error":"${errorStatus}","message":"Client Timeout","statusCode":408}`; errorLabel = "timeout"; } else if (err.code === "HPE_HEADER_OVERFLOW") { errorCode = "431"; errorStatus = http.STATUS_CODES[errorCode]; body = `{"error":"${errorStatus}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`; errorLabel = "header_overflow"; } else { errorCode = "400"; errorStatus = http.STATUS_CODES[errorCode]; body = `{"error":"${errorStatus}","message":"Client Error","statusCode":400}`; errorLabel = "error"; } this.log.trace({ err }, `client ${errorLabel}`); if (socket.writable) { socket.write(`HTTP/1.1 ${errorCode} ${errorStatus}\r Content-Length: ${body.length}\r Content-Type: application/json\r \r ${body}`); } socket.destroy(err); } function defaultRoute(req, res) { if (req.headers["accept-version"] !== void 0) { req.headers[kRequestAcceptVersion] = req.headers["accept-version"]; req.headers["accept-version"] = void 0; } fourOhFour.router.lookup(req, res); } function onBadUrl(path, req, res) { if (frameworkErrors) { const id = getGenReqId(onBadUrlContext.server, req); const childLogger = createChildLogger(onBadUrlContext, logger, req, id); const request = new Request(id, null, req, null, childLogger, onBadUrlContext); const reply = new Reply(res, request, childLogger); if (disableRequestLogging === false) { childLogger.info({ req: request }, "incoming request"); } return frameworkErrors(new FST_ERR_BAD_URL(path), request, reply); } const body = `{"error":"Bad Request","code":"FST_ERR_BAD_URL","message":"'${path}' is not a valid url component","statusCode":400}`; res.writeHead(400, { "Content-Type": "application/json", "Content-Length": body.length }); res.end(body); } function buildAsyncConstraintCallback(isAsync, req, res) { if (isAsync === false) return void 0; return function onAsyncConstraintError(err) { if (err) { if (frameworkErrors) { const id = getGenReqId(onBadUrlContext.server, req); const childLogger = createChildLogger(onBadUrlContext, logger, req, id); const request = new Request(id, null, req, null, childLogger, onBadUrlContext); const reply = new Reply(res, request, childLogger); if (disableRequestLogging === false) { childLogger.info({ req: request }, "incoming request"); } return frameworkErrors(new FST_ERR_ASYNC_CONSTRAINT(), request, reply); } const body = '{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}'; res.writeHead(500, { "Content-Type": "application/json", "Content-Length": body.length }); res.end(body); } }; } function setNotFoundHandler(opts, handler) { throwIfAlreadyStarted('Cannot call "setNotFoundHandler"!'); fourOhFour.setNotFoundHandler.call(this, opts, handler, avvio, router.routeHandler); return this; } function setValidatorCompiler(validatorCompiler) { throwIfAlreadyStarted('Cannot call "setValidatorCompiler"!'); this[kSchemaController].setValidatorCompiler(validatorCompiler); return this; } function setSchemaErrorFormatter(errorFormatter) { throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter"!'); validateSchemaErrorFormatter(errorFormatter); this[kSchemaErrorFormatter] = errorFormatter.bind(this); return this; } function setSerializerCompiler(serializerCompiler) { throwIfAlreadyStarted('Cannot call "setSerializerCompiler"!'); this[kSchemaController].setSerializerCompiler(serializerCompiler); return this; } function setSchemaController(schemaControllerOpts) { throwIfAlreadyStarted('Cannot call "setSchemaController"!'); const old = this[kSchemaController]; const schemaController2 = SchemaController.buildSchemaController(old, Object.assign({}, old.opts, schemaControllerOpts)); this[kSchemaController] = schemaController2; this.getSchema = schemaController2.getSchema.bind(schemaController2); this.getSchemas = schemaController2.getSchemas.bind(schemaController2); return this; } function setReplySerializer(replySerializer) { throwIfAlreadyStarted('Cannot call "setReplySerializer"!'); this[kReplySerializerDefault] = replySerializer; return this; } function setErrorHandler(func) { throwIfAlreadyStarted('Cannot call "setErrorHandler"!'); if (typeof func !== "function") { throw new FST_ERR_ERROR_HANDLER_NOT_FN(); } this[kErrorHandler] = buildErrorHandler(this[kErrorHandler], func.bind(this)); return this; } function setChildLoggerFactory(factory) { throwIfAlreadyStarted('Cannot call "setChildLoggerFactory"!'); this[kChildLoggerFactory] = factory; return this; } function printRoutes(opts = {}) { opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta; return router.printRoutes(opts); } function wrapRouting(router2, { rewriteUrl, logger: logger2 }) { let isAsync; return function preRouting(req, res) { if (isAsync === void 0) isAsync = router2.isAsyncConstraint(); if (rewriteUrl) { req.originalUrl = req.url; const url = rewriteUrl.call(fastify3, req); if (typeof url === "string") { req.url = url; } else { const err = new FST_ERR_ROUTE_REWRITE_NOT_STR(req.url, typeof url); req.destroy(err); } } router2.routing(req, res, buildAsyncConstraintCallback(isAsync, req, res)); }; } function setGenReqId(func) { throwIfAlreadyStarted('Cannot call "setGenReqId"!'); this[kGenReqId] = reqIdGenFactory(this[kOptions].requestIdHeader, func); return this; } } function validateSchemaErrorFormatter(schemaErrorFormatter) { if (typeof schemaErrorFormatter !== "function") { throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN(typeof schemaErrorFormatter); } else if (schemaErrorFormatter.constructor.name === "AsyncFunction") { throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN("AsyncFunction"); } } module2.exports = fastify2; module2.exports.errorCodes = errorCodes; module2.exports.fastify = fastify2; module2.exports.default = fastify2; } }); // main.ts var main_exports = {}; __export(main_exports, { default: () => ClipperMasterPlugin }); module.exports = __toCommonJS(main_exports); // common.ts var import_obsidian = require("obsidian"); var folderName = "ClipperMaster"; var upsertFile = async (app, fileName, content) => { const folder = await app.vault.getFolderByPath(folderName); if (!folder) { await app.vault.createFolder(folderName); } const filePath = `${folderName}/${fileName}.md`; const file = await app.vault.getFileByPath(filePath); if (file) { await app.vault.modify(file, content); } else { await app.vault.create(filePath, content); } }; var language = (0, import_obsidian.getLanguage)(); var isZh = language.startsWith("zh"); var getTexts = () => { if (isZh) { return { listeningPort: "\u76D1\u542C\u7AEF\u53E3\u53F7", desc: "HTTP\u8BF7\u6C42\u7684\u7AEF\u53E3\u53F7", enterPort: "\u8F93\u5165\u7AEF\u53E3\u53F7", error: "\u5FC5\u987B\u662F\u4E00\u4E2A\u6709\u6548\u7684\u7AEF\u53E3\u53F7 (1 - 65535)", welcome: "\u6B22\u8FCE\u4F7F\u7528 ClipperMaster for Obsidian", fileSaved: "\u{1F389} \u5DF2\u4FDD\u5B58\u5230\uFF1A", guidanceButton: "\u4F7F\u7528\u8BF4\u660E", guidanceDesc: "\u70B9\u51FB\u6253\u5F00\u4F7F\u7528\u8BF4\u660E\u9875\u9762", openGuidance: "\u6253\u5F00\u8BF4\u660E" }; } return { listeningPort: "Listening Port", desc: "Port to listen for HTTP requests", enterPort: "Enter Port Number", error: "Must be a valid port number (1 - 65535)", welcome: "Welcome to ClipperMaster for Obsidian", fileSaved: "\u{1F389} File saved to:", guidanceButton: "Guidance", guidanceDesc: "Click to open guidance page", openGuidance: "Open Guidance" }; }; var texts = getTexts(); var Welcome = isZh ? `# ClipperMaster for Obsidian [ClipperMaster](https://clippermaster.com) \u662F\u4E00\u6B3E\u5F3A\u5927\u7684 Chrome \u6D4F\u89C8\u5668\u6269\u5C55\uFF0C\u80FD\u8BA9\u4F60\u8F7B\u677E\u4ECE\u7F51\u9875\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316\u6570\u636E\uFF0C\u6784\u5EFA\u4F60\u7684\u4E13\u5C5E\u4FE1\u606F\u6570\u636E\u5E93\u3002 ![](https://clippermaster.com/clippermaster-intro.png) # ClipperMaster Obsidian \u63D2\u4EF6\u4F7F\u7528\u6307\u5357 **\u8BA9\u7F51\u9875\u5185\u5BB9\u4E00\u952E\u6210\u4E3A\u4F60\u7684\u77E5\u8BC6\u8D44\u4EA7** ClipperMaster Obsidian \u63D2\u4EF6\u662F **ClipperMaster Chrome \u63D2\u4EF6** \u7684\u5B8C\u7F8E\u642D\u6863\uFF0C\u5E2E\u52A9\u4F60\u5C06\u4ECE\u7F51\u9875\u4E2D\u63D0\u53D6\u7684\u7ED3\u6784\u5316\u4FE1\u606F\u65E0\u7F1D\u53D1\u9001\u5E76\u5B58\u50A8\u5230 Obsidian\uFF0C\u6253\u9020\u81EA\u52A8\u5316\u77E5\u8BC6\u7BA1\u7406\u6D41\u6C34\u7EBF\u3002 --- ## **\u63D2\u4EF6\u4F5C\u7528** - **\u4E00\u952E\u5B58\u50A8**\uFF1A\u5C06\u4ECE\u7F51\u9875\u63D0\u53D6\u7684\u6587\u672C\u3001\u56FE\u7247\u7B49\u5185\u5BB9\uFF0C\u8F6C\u6362\u4E3A Markdown \u683C\u5F0F\u5E76\u4FDD\u5B58\u5230 Obsidian\u3002 - **\u7ED3\u6784\u5316\u5B58\u50A8**\uFF1A\u652F\u6301\u6A21\u677F\u5316\u5B58\u50A8\u3001\u8BA9\u5185\u5BB9\u4E95\u4E95\u6709\u6761\u3002 --- ## **\u5B89\u88C5\u6B65\u9AA4** ### **1. \u5B89\u88C5 ClipperMaster Chrome \u63D2\u4EF6** \u5982\u679C\u4F60\u8FD8\u6CA1\u6709\u5B89\u88C5 Chrome \u63D2\u4EF6\uFF0C\u8BF7\u5148\u524D\u5F80 [Chrome \u5546\u5E97](https://chromewebstore.google.com/detail/clippermaster/bdilooeboaoifijdnpomfoinefbokjlj) \u5B89\u88C5\u3002 ### **2. \u5B89\u88C5 ClipperMaster Obsidian \u63D2\u4EF6** 1. \u6253\u5F00 Obsidian\uFF0C\u8FDB\u5165 **\u8BBE\u7F6E** \u2192 **\u793E\u533A\u63D2\u4EF6**\u3002 2. \u70B9\u51FB **\u6D4F\u89C8**\uFF0C\u641C\u7D22 **ClipperMaster**\u3002 3. \u627E\u5230\u63D2\u4EF6\u540E\uFF0C\u70B9\u51FB **\u5B89\u88C5**\uFF0C\u7136\u540E **\u542F\u7528**\u3002 4. \u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\uFF0C\u83B7\u53D6\u6216\u8005\u4FEE\u6539 **Port**\u3002 ### **3. \u914D\u7F6E Chrome \u63D2\u4EF6** 1. \u6253\u5F00 ClipperMaster Chrome \u63D2\u4EF6\uFF0C\u8FDB\u5165 **Options** \u2192 **\u81EA\u52A8\u5316** \u2192 **\u6DFB\u52A0\u81EA\u52A8\u5316** \u2192 \u53D1\u9001\u5230**Obsidian** \u3002 2. \u8F93\u5165 Obsidian \u7AEF\u8BBE\u7F6E\u7684 **Port**\u3002 --- ## **\u5E38\u89C1\u95EE\u9898** ### **1. \u63D2\u4EF6\u652F\u6301\u54EA\u4E9B\u7F51\u9875\u5185\u5BB9\uFF1F** - \u6587\u672C\u3001\u94FE\u63A5\u3001\u56FE\u7247\u7B49\u5747\u53EF\u63D0\u53D6\u5E76\u5B58\u50A8\u3002 ### **2. \u662F\u5426\u9700\u8981\u4ED8\u8D39\uFF1F** - **\u53D1\u9001\u5230Obsidian**\u8FD9\u9879\u529F\u80FD\u5B8C\u5168\u514D\u8D39 ### **3. \u5982\u4F55\u83B7\u53D6\u6280\u672F\u652F\u6301\uFF1F** - \u8BBF\u95EE [ClipperMaster \u5B98\u7F51](https://clippermaster.com) \u6216\u8005 [\u7ED9\u6211\u4EEC\u53D1\u9001\u90AE\u4EF6](mailto:tony@clippermaster.com)\u3002 --- ## **\u7ACB\u5373\u4F53\u9A8C** \u70B9\u51FB\u4E0B\u65B9\u94FE\u63A5\uFF0C\u5F00\u59CB\u4F60\u7684\u77E5\u8BC6\u7BA1\u7406\u9769\u547D\uFF1A - [\u5B89\u88C5 ClipperMaster Chrome \u63D2\u4EF6](https://chromewebstore.google.com/detail/clippermaster/bdilooeboaoifijdnpomfoinefbokjlj) - \u5B89\u88C5 ClipperMaster Obsidian \u63D2\u4EF6 --- ` : `# ClipperMaster for Obsidian [ClipperMaster](https://clippermaster.com) is a powerful Chrome extension that empowers you to effortlessly extract structured data from web pages, building your personalized information database. ![](https://clippermaster.com/clippermaster-intro.png) # ClipperMaster Obsidian Plugin User Guide **Turn Web Content into Your Knowledge Assets with One Click** The ClipperMaster Obsidian plugin is the perfect companion to the **ClipperMaster Chrome plugin**, helping you seamlessly send and store structured information extracted from web pages to Obsidian, creating an automated knowledge management pipeline. --- ## **Plugin Functionality** - **One-Click Storage**: Convert text, images, and other content extracted from web pages into Markdown format and save them to Obsidian. - **Structured Storage**: Supports templated storage, keeping your content organized. --- ## **Installation Steps** ### **1. Install the ClipperMaster Chrome Plugin** If not already installed, get the Chrome plugin from the [Chrome Web Store](https://chromewebstore.google.com/detail/clippermaster/bdilooeboaoifijdnpomfoinefbokjlj). ### **2. Install the ClipperMaster Obsidian Plugin** 1. Open Obsidian, go to **Settings** \u2192 **Community plugins**. 2. Click **Browse**, search for **ClipperMaster**. 3. After finding the plugin, click **Install**, then **Enable**. 4. In the plugin settings, get or modify the **Port**. ### **3. Configure the Chrome Plugin** 1. Open the ClipperMaster Chrome plugin, go to **Options** \u2192 **Automations** \u2192 **Add Automation** \u2192 Send to **Obsidian**. 2. Enter the **Port** set in Obsidian. --- ## **Frequently Asked Questions** ### **1. What web content does the plugin support?** - Text, links, images, etc., can be extracted and stored. ### **2. Is there a fee?** - The **Send to Obsidian** feature is completely free. ### **3. How do I get technical support?** - Visit the [ClipperMaster Official Website](https://clippermaster.com) or [send us an email](mailto:tony@clippermaster.com). --- ## **Experience It Now** Click the links below to start your knowledge management revolution: - [Install ClipperMaster Chrome Plugin](https://chromewebstore.google.com/detail/clippermaster/bdilooeboaoifijdnpomfoinefbokjlj) - Install ClipperMaster Obsidian Plugin ---`; // main.ts var import_obsidian3 = require("obsidian"); // server/index.ts var import_fastify = __toESM(require_fastify()); // server/service.ts var import_obsidian2 = require("obsidian"); var PRESET_DOC_PREFIX = "$"; var PresetAttributeID = ((PresetAttributeID2) => { PresetAttributeID2[PresetAttributeID2["LargestedImage"] = `${PRESET_DOC_PREFIX}largest_size_image`] = "LargestedImage"; PresetAttributeID2[PresetAttributeID2["Favicon"] = `${PRESET_DOC_PREFIX}favicon`] = "Favicon"; PresetAttributeID2[PresetAttributeID2["Title"] = `${PRESET_DOC_PREFIX}title`] = "Title"; PresetAttributeID2[PresetAttributeID2["H1"] = `${PRESET_DOC_PREFIX}h1`] = "H1"; PresetAttributeID2[PresetAttributeID2["Tags"] = `${PRESET_DOC_PREFIX}tags`] = "Tags"; PresetAttributeID2[PresetAttributeID2["Rate"] = `${PRESET_DOC_PREFIX}rate`] = "Rate"; PresetAttributeID2[PresetAttributeID2["Description"] = `${PRESET_DOC_PREFIX}description`] = "Description"; PresetAttributeID2[PresetAttributeID2["comment"] = `${PRESET_DOC_PREFIX}comment`] = "comment"; return PresetAttributeID2; })(PresetAttributeID || {}); function getMdContent(clip) { switch (clip.valueSource) { case "snapshot" /* snapshot */: case "img" /* imageUrl */: return `![](${clip.value})`; case "link" /* link */: return `[${clip.value}](${clip.value})`; case "v" /* videoUrl */: return ""; default: return clip.value; } } function generateMDContent(clipper) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; const tagsStr = ((_b = (_a = clipper.attributes) == null ? void 0 : _a.find((item) => item._id === PresetAttributeID.Tags)) == null ? void 0 : _b.value).map((item) => `#${item}`).join(" "); const comment = (_d = (_c = clipper.attributes) == null ? void 0 : _c.find((item) => item._id === PresetAttributeID.comment)) == null ? void 0 : _d.value; const rate = (_f = (_e = clipper.attributes) == null ? void 0 : _e.find((item) => item._id === PresetAttributeID.Rate)) == null ? void 0 : _f.value; const userSttributes = ((_h = (_g = clipper.attributes) == null ? void 0 : _g.filter((item) => !item._id.startsWith(PRESET_DOC_PREFIX)).map((item) => `##### \`${item.key}\` ${getMdContent(item)}`)) == null ? void 0 : _h.join("\n")) || ""; const clips = (((_i = clipper.clips) != null ? _i : []).length > 0 ? (_j = clipper.clips) == null ? void 0 : _j.map((item, index) => `##### \`clip_${index + 1}\` ${getMdContent(item)}`).join("\n") : "") || ""; return `${(tagsStr.length > 0 ? tagsStr + "\n" : "") + ((comment == null ? void 0 : comment.length) > 0 ? `## note > ${comment}` : "")} ## Url ${clipper.url} ${rate > 0 ? `## Rate ${rate}` : ""} ${(userSttributes == null ? void 0 : userSttributes.length) > 0 ? `## Attributes ${userSttributes}` : ""} ${(clips == null ? void 0 : clips.length) > 0 ? `## Clips ${clips}` : ""}`; } var Service = class { constructor(app) { this.app = app; } async upsert(clipper) { var _a, _b; this.app.vault.getFolderByPath; let title = (_b = (_a = clipper.attributes) == null ? void 0 : _a.find((item) => item._id === PresetAttributeID.Title)) == null ? void 0 : _b.value; title = title ? title.replace(/[\\/:]/g, "_") : title; const fileName = `${title || `Untitled_${clipper._id}`}`; try { await upsertFile(this.app, fileName, generateMDContent(clipper)); new import_obsidian2.Notice(`${texts.fileSaved} ${folderName}/${fileName}.md`, 5e3); } catch (error) { new import_obsidian2.Notice("ops, save file failed", 5e3); } } }; // server/index.ts var fastify = (0, import_fastify.default)({ logger: true, bodyLimit: 50 * 1024 * 1024 // 50MB }); var Server = class { constructor() { this.port = 8282; } async start(app) { this.app = app; this.service = new Service(app); fastify.post("/hook", async (request, reply) => { const clipper = request.body; await this.service.upsert(clipper); return { data: { vaultName: this.app.vault.getName() } }; }); try { await fastify.listen({ port: this.port }); } catch (error) { } } close() { return fastify.close(); } get isRunning() { return fastify.server.listening; } async switchPort(port) { this.port = port; await this.close(); return fastify.listen({ port }); } }; var server = new Server(); // main.ts var DEFAULT_SETTINGS = { port: 8282 }; var ClipperMasterPlugin = class extends import_obsidian3.Plugin { async onload() { (0, import_obsidian3.addIcon)( "clippermaster", ` ` ); await this.loadSettings(); this.addSettingTab(new ClipperMasterSettingTab(this.app, this)); server.start(this.app); } onUserEnable() { upsertFile(this.app, texts.welcome, Welcome); } onunload() { server.close(); } async loadSettings() { this.settings = Object.assign( {}, DEFAULT_SETTINGS, await this.loadData() ); } async saveSettings() { await this.saveData(this.settings); } }; var ClipperMasterSettingTab = class extends import_obsidian3.PluginSettingTab { constructor(app, plugin) { super(app, plugin); this.plugin = plugin; } display() { const { containerEl } = this; containerEl.empty(); const portSetting = new import_obsidian3.Setting(containerEl).setName(texts.listeningPort).setDesc(texts.desc); const invalidPortElement = portSetting.infoEl.createDiv(); invalidPortElement.hide(); invalidPortElement.createSpan("settings-error-element").setText(texts.error); portSetting.addText((text) => { text.setPlaceholder(texts.enterPort); text.setValue(String(this.plugin.settings.port)); text.onChange(async (value) => { const numValue = Number(value); if (isNaN(numValue) || numValue < 1 || numValue > 65535) { invalidPortElement.show(); return; } invalidPortElement.hide(); this.plugin.settings.port = numValue; await this.saveAndReload(); }); }); new import_obsidian3.Setting(containerEl).setName(texts.guidanceButton).setDesc(texts.guidanceDesc).addButton((btn) => { btn.setButtonText(texts.openGuidance).onClick(() => { window.open("https://docs.clippermaster.com/docs/integrations/obsidian", "_blank"); }); }); } async saveAndReload() { await this.plugin.saveSettings(); await server.close(); server.start(this.plugin.app); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = {}); /*! Bundled license information: forwarded/index.js: (*! * forwarded * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed *) proxy-addr/index.js: (*! * proxy-addr * Copyright(c) 2014-2016 Douglas Christopher Wilson * MIT Licensed *) toad-cache/dist/toad-cache.cjs: (** * toad-cache * * @copyright 2024 Igor Savin * @license MIT * @version 3.7.0 *) uri-js/dist/es5/uri.all.js: (** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *) cookie/index.js: (*! * cookie * Copyright(c) 2012-2014 Roman Shtylman * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed *) light-my-request/lib/form-data.js: (*! formdata-polyfill. MIT License. Jimmy Wärting *) */ /* nosourcemap */