UNPKG

opentrader

Version:

OpenTrader is a powerful open-source crypto trading bot designated to automate your trading strategies on various cryptocurrency exchanges.

1,533 lines (1,513 loc) 2.63 MB
import { createRequire } from 'module'; import { __commonJS, __require, __export, __toESM, XOrderType, MarketEventType, StrategyAction, __reExport, ExchangeCode, isValidSymbolId, BarSize, cancelSmartTrade, useIndicators, extractIndicators, evaluateConditions, useDca, requiredHistory, decomposeSymbol, useExchange, computeGridLevelsFromCurrentAssetPrice, useSmartTrade, calcGridLines, useRSI, sell, buy, useMarket, useCandle, XOrderStatus, XEntityType, decomposeSymbolId, XSmartTradeType, OrderType, getExponentAbs, composeSymbolIdFromPair, createStrategyRunner, XTakeProfitType, XOrderSide, XEntryType, Watcher, isValidSymbol, barSizeToDuration } from './chunk-SWPT4CTA.mjs'; import { pino } from 'pino'; import path, { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify'; import { initTRPC, TRPCError } from '@trpc/server'; import superjson from 'superjson'; import * as client_star from '@prisma/client'; import { Prisma, PrismaClient } from '@prisma/client'; import { z, ZodFirstPartyTypeKind, ZodOptional } from 'zod'; import { pro, NetworkError, RequestTimeout, ExchangeClosedByUser, AuthenticationError, InvalidNonce, OrderNotFound, InsufficientFunds, ExchangeError } from 'ccxt'; import { readdir } from 'node:fs/promises'; import { EventEmitter } from 'node:events'; createRequire(import.meta.url); if (typeof globalThis.__dirname === "undefined") { globalThis.__dirname = new URL('.', import.meta.url).pathname; } if (typeof globalThis.__filename === "undefined") { globalThis.__filename = new URL(import.meta.url).pathname; } // ../../node_modules/.pnpm/reusify@1.0.4/node_modules/reusify/reusify.js var require_reusify = __commonJS({ "../../node_modules/.pnpm/reusify@1.0.4/node_modules/reusify/reusify.js"(exports, module) { 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 }; } module.exports = reusify; } }); // ../../node_modules/.pnpm/fastq@1.17.1/node_modules/fastq/queue.js var require_queue = __commonJS({ "../../node_modules/.pnpm/fastq@1.17.1/node_modules/fastq/queue.js"(exports, module) { 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 cache2 = reusify(Task); var queueHead = null; var queueTail = null; var _running = 0; var errorHandler = null; var self2 = { 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 (self2.paused) return; for (; queueHead && _running < _concurrency; ) { _running++; release(); } }, running, resume, idle, length, getQueue, unshift, empty: noop, kill, killAndDrain, error }; return self2; function running() { return _running; } function pause() { self2.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 (!self2.paused) return; self2.paused = false; if (queueHead === null) { _running++; release(); return; } for (; queueHead && _running < _concurrency; ) { _running++; release(); } } function idle() { return _running === 0 && self2.length() === 0; } function push(value, done) { var current = cache2.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop; current.errorHandler = errorHandler; if (_running >= _concurrency || self2.paused) { if (queueTail) { queueTail.next = current; queueTail = current; } else { queueHead = current; queueTail = current; self2.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function unshift(value, done) { var current = cache2.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop; current.errorHandler = errorHandler; if (_running >= _concurrency || self2.paused) { if (queueHead) { current.next = queueHead; queueHead = current; } else { queueHead = current; queueTail = current; self2.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function release(holder) { if (holder) { cache2.release(holder); } var next = queueHead; if (next && _running <= _concurrency) { if (!self2.paused) { if (queueTail === queueHead) { queueTail = null; } queueHead = next.next; next.next = null; worker.call(context, next.value, next.worked); if (queueTail === null) { self2.empty(); } } else { _running--; } } else if (--_running === 0) { self2.drain(); } } function kill() { queueHead = null; queueTail = null; self2.drain = noop; } function killAndDrain() { queueHead = null; queueTail = null; self2.drain(); self2.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 self2 = this; this.worked = function worked(err, result) { var callback = self2.callback; var errorHandler = self2.errorHandler; var val = self2.value; self2.value = null; self2.callback = noop; if (self2.errorHandler) { errorHandler(err, val); } callback.call(self2.context, err, result); self2.release(self2); }; } 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, reject2) { pushCb(value, function(err, result) { if (err) { reject2(err); return; } resolve(result); }); }); p.catch(noop); return p; } function unshift(value) { var p = new Promise(function(resolve, reject2) { unshiftCb(value, function(err, result) { if (err) { reject2(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; } } module.exports = fastqueue; module.exports.promise = queueAsPromised; } }); // ../../node_modules/.pnpm/@fastify+error@4.0.0/node_modules/@fastify/error/index.js var require_error = __commonJS({ "../../node_modules/.pnpm/@fastify+error@4.0.0/node_modules/@fastify/error/index.js"(exports, module) { var { format } = __require("node: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; } module.exports = createError; module.exports.default = createError; module.exports.createError = createError; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/errors.js var require_errors = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/errors.js"(exports, module) { var { createError } = require_error(); module.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/.pnpm/avvio@9.1.0/node_modules/avvio/lib/symbols.js var require_symbols = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/symbols.js"(exports, module) { 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"); module.exports = { kAvvio, kIsOnCloseHandler, kThenifyDoNotWrap, kUntrackNode, kTrackNode, kGetParent, kGetNode, kAddNode, kPluginMeta }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/time-tree.js var require_time_tree = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/time-tree.js"(exports, module) { 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; } module.exports = { TimeTree }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/debug.js var require_debug = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/debug.js"(exports, module) { var { debuglog } = __require("node:util"); var debug2 = debuglog("avvio"); module.exports = { debug: debug2 }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/create-promise.js var require_create_promise = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/create-promise.js"(exports, module) { function createPromise() { const obj = { resolve: null, reject: null, promise: null }; obj.promise = new Promise((resolve, reject2) => { obj.resolve = resolve; obj.reject = reject2; }); return obj; } module.exports = { createPromise }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/get-plugin-name.js var require_get_plugin_name = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/get-plugin-name.js"(exports, module) { 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(" -- "); } } module.exports = { getPluginName }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/is-promise-like.js var require_is_promise_like = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/is-promise-like.js"(exports, module) { function isPromiseLike(maybePromiseLike) { return maybePromiseLike !== null && typeof maybePromiseLike === "object" && typeof maybePromiseLike.then === "function"; } module.exports = { isPromiseLike }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/plugin.js var require_plugin = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/plugin.js"(exports, module) { var { EventEmitter: EventEmitter18 } = __require("node:events"); var { inherits } = __require("node:util"); var { debug: debug2 } = 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 Plugin(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(Plugin, EventEmitter18); Plugin.prototype.exec = function(server, callback) { debug2("exec", this.name); this.server = server; 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) { debug2("loading complete", name); return; } this._error = execErr; if (execErr) { debug2("exec errored", name); } else { debug2("exec completed", name); } completed = true; if (timer) { clearTimeout(timer); } callback(execErr); }; if (this.timeout > 0) { debug2("setting up timeout", name, this.timeout); timer = setTimeout(function() { debug2("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)) { debug2("exec: resolving promise", name); maybePromiseLike.then( () => process.nextTick(done), (e) => process.nextTick(done, e) ); } else if (func.length < 3) { done(); } }; Plugin.prototype.loadedSoFar = function() { debug2("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) { debug2("rejecting promise", this.name, afterErr); this._promise.reject(afterErr); } else { debug2("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; }; Plugin.prototype.enqueue = function(plugin, callback) { debug2("enqueue", this.name, plugin.name); this.emit("enqueue", this.server ? this.server.name : null, this.name, Date.now()); this.queue.push(plugin, callback); }; Plugin.prototype.finish = function(err, callback) { debug2("finish", this.name, err); const done = () => { if (this.loaded) { return; } debug2("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 = () => { debug2("check", this.name, this.queue.length(), this.queue.running(), this._promise); if (this.queue.length() === 0 && this.queue.running() === 0) { if (this._promise) { const wrap2 = () => { debug2("wrap"); queueMicrotask(check); }; this._promise.resolve(); this._promise.promise.then(wrap2, wrap2); this._promise = null; } else { done(); } } else { debug2("delayed", this.name); this.queue.drain = () => { debug2("drain", this.name); this.queue.drain = noop; queueMicrotask(check); }; } }; queueMicrotask(check); this.queue.resume(); }; function noop() { } module.exports = { Plugin }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/validate-plugin.js var require_validate_plugin = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/validate-plugin.js"(exports, module) { 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); } } } module.exports = { validatePlugin }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js var require_is_bundled_or_typescript_plugin = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js"(exports, module) { function isBundledOrTypescriptPlugin(maybeBundledOrTypescriptPlugin) { return maybeBundledOrTypescriptPlugin !== null && typeof maybeBundledOrTypescriptPlugin === "object" && typeof maybeBundledOrTypescriptPlugin.default === "function"; } module.exports = { isBundledOrTypescriptPlugin }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/thenify.js var require_thenify = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/thenify.js"(exports, module) { var { debug: debug2 } = require_debug(); var { kThenifyDoNotWrap } = require_symbols(); function thenify() { if (this.booted) { debug2("thenify returning undefined because we are already booted"); return; } if (this[kThenifyDoNotWrap]) { this[kThenifyDoNotWrap] = false; return; } debug2("thenify"); return (resolve, reject2) => { const p = this._loadRegistered(); return p.then(() => { this[kThenifyDoNotWrap] = true; return resolve(this._server); }, reject2); }; } module.exports = { thenify }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/execute-with-thenable.js var require_execute_with_thenable = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/lib/execute-with-thenable.js"(exports, module) { 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); } } module.exports = { executeWithThenable }; } }); // ../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/boot.js var require_boot = __commonJS({ "../../node_modules/.pnpm/avvio@9.1.0/node_modules/avvio/boot.js"(exports, module) { var fastq = require_queue(); var EE = __require("node:events").EventEmitter; var inherits = __require("node: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 } = require_plugin(); var { debug: debug2 } = 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(server, opts, done) { if (typeof server === "function" && arguments.length === 1) { done = server; opts = {}; server = 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(server, opts, done); } this._server = server || this; this._opts = opts; if (server) { 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 Plugin(fastq(this, this._loadPluginNextTick, 1), function root(server2, opts2, done2) { instance._doStart = done2; opts2.autostart && instance.start(); }, opts, false, 0); this._trackPluginLoading(this._root); this._loadPlugin(this._root, (err) => { debug2("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(server, func, opts) { return server; }; 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 Plugin(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 server = instance._server; const { use: useKey = "use", after: afterKey = "after", ready: readyKey = "ready", onClose: onCloseKey = "onClose", close: closeKey = "close" } = this._opts.expose; if (server[useKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(useKey, "use"); } server[useKey] = function(fn, opts) { instance.use(fn, opts); return this; }; if (server[afterKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(afterKey, "after"); } server[afterKey] = function(func) { if (typeof func !== "function") { return instance._loadRegistered(); } instance.after(encapsulateThreeParam(func, this)); return this; }; if (server[readyKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(readyKey, "ready"); } server[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 (server[onCloseKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(onCloseKey, "onClose"); } server[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 (server[closeKey]) { throw new AVV_ERR_EXPOSE_ALREADY_DEFINED(closeKey, "close"); } server[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 (server.then) { throw new AVV_ERR_ATTRIBUTE_ALREADY_DEFINED("then"); } Object.defineProperty(server, "then", { get: thenify.bind(instance) }); server[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, reject2) { func = function(err) { if (err) { return reject2(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, reject2) => { this._readyQ.push(readyPromiseCB); this.start(); const relativeContext = this._current[0].server; function readyPromiseCB(err, context, done) { if (err) { reject2(err); } else { resolve(relativeContext); } process.nextTick(done); } }); }; Boot.prototype._trackPluginLoading = function(plugin) { const parentName = this._current[0]?.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) { debug2("skipping loading of plugin as instance errored and it is not an after", plugin.name); process.nextTick(execCallback); return; } let server = last && last.server || instance._server; if (!plugin.isAfter) { try { server = instance.override(server, plugin.func, plugin.options); } catch (overrideErr) { debug2("override errored", plugin.name); return execCallback(overrideErr); } } plugin.exec(server, 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.unwrappedName ?? func.name; debug2("setting up ready timeout", name, this._opts.timeout); let timer = setTimeout(() => { debug2("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); } } } 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") { debug2("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) { const wrapped = _encapsulateThreeParam.bind(that); wrapped.unwrappedName = func.name; return wrapped; 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); } } } module.exports = Boot; } }); // ../../node_modules/.pnpm/fastify@5.2.0/node_modules/fastify/lib/symbols.js var require_symbols2 = __commonJS({ "../../node_modules/.pnpm/fastify@5.2.0/node_modules/fastify/lib/symbols.js"(exports, module) { var keys = { kAvvioBoot: Symbol("fastify.avvioBoot"), kChildren: Symbol("fastify.children"), kServerBindings: Symbol("fastify.serverBindings"), kBodyLimit: Symbol("fastify.bodyLimit"), kSupportedHTTPMethods: Symbol("fastify.acceptedHTTPMethods"), 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"), 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") }; module.exports = keys; } }); // ../../node_modules/.pnpm/fastify@5.2.0/node_modules/fastify/lib/errors.js var require_errors2 = __commonJS({ "../../node_modules/.pnpm/fastify@5.2.0/node_modules/fastify/lib/errors.js"(exports, module) { 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_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