UNPKG

@interopio/gateway-server

Version:

## `@glue42/gateway-ent` compatibility

1,441 lines (1,434 loc) 1.03 MB
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; 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 )); // node_modules/undici/lib/core/symbols.js var require_symbols = __commonJS({ "node_modules/undici/lib/core/symbols.js"(exports, module) { module.exports = { kClose: Symbol("close"), kDestroy: Symbol("destroy"), kDispatch: Symbol("dispatch"), kUrl: Symbol("url"), kWriting: Symbol("writing"), kResuming: Symbol("resuming"), kQueue: Symbol("queue"), kConnect: Symbol("connect"), kConnecting: Symbol("connecting"), kKeepAliveDefaultTimeout: Symbol("default keep alive timeout"), kKeepAliveMaxTimeout: Symbol("max keep alive timeout"), kKeepAliveTimeoutThreshold: Symbol("keep alive timeout threshold"), kKeepAliveTimeoutValue: Symbol("keep alive timeout"), kKeepAlive: Symbol("keep alive"), kHeadersTimeout: Symbol("headers timeout"), kBodyTimeout: Symbol("body timeout"), kServerName: Symbol("server name"), kLocalAddress: Symbol("local address"), kHost: Symbol("host"), kNoRef: Symbol("no ref"), kBodyUsed: Symbol("used"), kBody: Symbol("abstracted request body"), kRunning: Symbol("running"), kBlocking: Symbol("blocking"), kPending: Symbol("pending"), kSize: Symbol("size"), kBusy: Symbol("busy"), kQueued: Symbol("queued"), kFree: Symbol("free"), kConnected: Symbol("connected"), kClosed: Symbol("closed"), kNeedDrain: Symbol("need drain"), kReset: Symbol("reset"), kDestroyed: Symbol.for("nodejs.stream.destroyed"), kResume: Symbol("resume"), kOnError: Symbol("on error"), kMaxHeadersSize: Symbol("max headers size"), kRunningIdx: Symbol("running index"), kPendingIdx: Symbol("pending index"), kError: Symbol("error"), kClients: Symbol("clients"), kClient: Symbol("client"), kParser: Symbol("parser"), kOnDestroyed: Symbol("destroy callbacks"), kPipelining: Symbol("pipelining"), kSocket: Symbol("socket"), kHostHeader: Symbol("host header"), kConnector: Symbol("connector"), kStrictContentLength: Symbol("strict content length"), kMaxRedirections: Symbol("maxRedirections"), kMaxRequests: Symbol("maxRequestsPerClient"), kProxy: Symbol("proxy agent options"), kCounter: Symbol("socket request counter"), kInterceptors: Symbol("dispatch interceptors"), kMaxResponseSize: Symbol("max response size"), kHTTP2Session: Symbol("http2Session"), kHTTP2SessionState: Symbol("http2Session state"), kRetryHandlerDefaultRetry: Symbol("retry agent default retry"), kConstruct: Symbol("constructable"), kListeners: Symbol("listeners"), kHTTPContext: Symbol("http context"), kMaxConcurrentStreams: Symbol("max concurrent streams"), kNoProxyAgent: Symbol("no proxy agent"), kHttpProxyAgent: Symbol("http proxy agent"), kHttpsProxyAgent: Symbol("https proxy agent") }; } }); // node_modules/undici/lib/core/errors.js var require_errors = __commonJS({ "node_modules/undici/lib/core/errors.js"(exports, module) { "use strict"; var UndiciError = class extends Error { constructor(message) { super(message); this.name = "UndiciError"; this.code = "UND_ERR"; } }; var ConnectTimeoutError = class extends UndiciError { constructor(message) { super(message); this.name = "ConnectTimeoutError"; this.message = message || "Connect Timeout Error"; this.code = "UND_ERR_CONNECT_TIMEOUT"; } }; var HeadersTimeoutError = class extends UndiciError { constructor(message) { super(message); this.name = "HeadersTimeoutError"; this.message = message || "Headers Timeout Error"; this.code = "UND_ERR_HEADERS_TIMEOUT"; } }; var HeadersOverflowError = class extends UndiciError { constructor(message) { super(message); this.name = "HeadersOverflowError"; this.message = message || "Headers Overflow Error"; this.code = "UND_ERR_HEADERS_OVERFLOW"; } }; var BodyTimeoutError = class extends UndiciError { constructor(message) { super(message); this.name = "BodyTimeoutError"; this.message = message || "Body Timeout Error"; this.code = "UND_ERR_BODY_TIMEOUT"; } }; var ResponseStatusCodeError = class extends UndiciError { constructor(message, statusCode, headers, body) { super(message); this.name = "ResponseStatusCodeError"; this.message = message || "Response Status Code Error"; this.code = "UND_ERR_RESPONSE_STATUS_CODE"; this.body = body; this.status = statusCode; this.statusCode = statusCode; this.headers = headers; } }; var InvalidArgumentError = class extends UndiciError { constructor(message) { super(message); this.name = "InvalidArgumentError"; this.message = message || "Invalid Argument Error"; this.code = "UND_ERR_INVALID_ARG"; } }; var InvalidReturnValueError = class extends UndiciError { constructor(message) { super(message); this.name = "InvalidReturnValueError"; this.message = message || "Invalid Return Value Error"; this.code = "UND_ERR_INVALID_RETURN_VALUE"; } }; var AbortError = class extends UndiciError { constructor(message) { super(message); this.name = "AbortError"; this.message = message || "The operation was aborted"; } }; var RequestAbortedError = class extends AbortError { constructor(message) { super(message); this.name = "AbortError"; this.message = message || "Request aborted"; this.code = "UND_ERR_ABORTED"; } }; var InformationalError = class extends UndiciError { constructor(message) { super(message); this.name = "InformationalError"; this.message = message || "Request information"; this.code = "UND_ERR_INFO"; } }; var RequestContentLengthMismatchError = class extends UndiciError { constructor(message) { super(message); this.name = "RequestContentLengthMismatchError"; this.message = message || "Request body length does not match content-length header"; this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH"; } }; var ResponseContentLengthMismatchError = class extends UndiciError { constructor(message) { super(message); this.name = "ResponseContentLengthMismatchError"; this.message = message || "Response body length does not match content-length header"; this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH"; } }; var ClientDestroyedError = class extends UndiciError { constructor(message) { super(message); this.name = "ClientDestroyedError"; this.message = message || "The client is destroyed"; this.code = "UND_ERR_DESTROYED"; } }; var ClientClosedError = class extends UndiciError { constructor(message) { super(message); this.name = "ClientClosedError"; this.message = message || "The client is closed"; this.code = "UND_ERR_CLOSED"; } }; var SocketError = class extends UndiciError { constructor(message, socket) { super(message); this.name = "SocketError"; this.message = message || "Socket error"; this.code = "UND_ERR_SOCKET"; this.socket = socket; } }; var NotSupportedError = class extends UndiciError { constructor(message) { super(message); this.name = "NotSupportedError"; this.message = message || "Not supported error"; this.code = "UND_ERR_NOT_SUPPORTED"; } }; var BalancedPoolMissingUpstreamError = class extends UndiciError { constructor(message) { super(message); this.name = "MissingUpstreamError"; this.message = message || "No upstream has been added to the BalancedPool"; this.code = "UND_ERR_BPL_MISSING_UPSTREAM"; } }; var HTTPParserError = class extends Error { constructor(message, code, data) { super(message); this.name = "HTTPParserError"; this.code = code ? `HPE_${code}` : void 0; this.data = data ? data.toString() : void 0; } }; var ResponseExceededMaxSizeError = class extends UndiciError { constructor(message) { super(message); this.name = "ResponseExceededMaxSizeError"; this.message = message || "Response content exceeded max size"; this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE"; } }; var RequestRetryError = class extends UndiciError { constructor(message, code, { headers, data }) { super(message); this.name = "RequestRetryError"; this.message = message || "Request retry error"; this.code = "UND_ERR_REQ_RETRY"; this.statusCode = code; this.data = data; this.headers = headers; } }; var ResponseError = class extends UndiciError { constructor(message, code, { headers, data }) { super(message); this.name = "ResponseError"; this.message = message || "Response error"; this.code = "UND_ERR_RESPONSE"; this.statusCode = code; this.data = data; this.headers = headers; } }; var SecureProxyConnectionError = class extends UndiciError { constructor(cause, message, options) { super(message, { cause, ...options ?? {} }); this.name = "SecureProxyConnectionError"; this.message = message || "Secure Proxy Connection failed"; this.code = "UND_ERR_PRX_TLS"; this.cause = cause; } }; module.exports = { AbortError, HTTPParserError, UndiciError, HeadersTimeoutError, HeadersOverflowError, BodyTimeoutError, RequestContentLengthMismatchError, ConnectTimeoutError, ResponseStatusCodeError, InvalidArgumentError, InvalidReturnValueError, RequestAbortedError, ClientDestroyedError, ClientClosedError, InformationalError, SocketError, NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, ResponseExceededMaxSizeError, RequestRetryError, ResponseError, SecureProxyConnectionError }; } }); // node_modules/undici/lib/core/constants.js var require_constants = __commonJS({ "node_modules/undici/lib/core/constants.js"(exports, module) { "use strict"; var headerNameLowerCasedRecord = {}; var wellknownHeaderNames = [ "Accept", "Accept-Encoding", "Accept-Language", "Accept-Ranges", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age", "Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Alt-Svc", "Alt-Used", "Authorization", "Cache-Control", "Clear-Site-Data", "Connection", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-Range", "Content-Security-Policy", "Content-Security-Policy-Report-Only", "Content-Type", "Cookie", "Cross-Origin-Embedder-Policy", "Cross-Origin-Opener-Policy", "Cross-Origin-Resource-Policy", "Date", "Device-Memory", "Downlink", "ECT", "ETag", "Expect", "Expect-CT", "Expires", "Forwarded", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Keep-Alive", "Last-Modified", "Link", "Location", "Max-Forwards", "Origin", "Permissions-Policy", "Pragma", "Proxy-Authenticate", "Proxy-Authorization", "RTT", "Range", "Referer", "Referrer-Policy", "Refresh", "Retry-After", "Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol", "Sec-WebSocket-Version", "Server", "Server-Timing", "Service-Worker-Allowed", "Service-Worker-Navigation-Preload", "Set-Cookie", "SourceMap", "Strict-Transport-Security", "Supports-Loading-Mode", "TE", "Timing-Allow-Origin", "Trailer", "Transfer-Encoding", "Upgrade", "Upgrade-Insecure-Requests", "User-Agent", "Vary", "Via", "WWW-Authenticate", "X-Content-Type-Options", "X-DNS-Prefetch-Control", "X-Frame-Options", "X-Permitted-Cross-Domain-Policies", "X-Powered-By", "X-Requested-With", "X-XSS-Protection" ]; for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = wellknownHeaderNames[i]; const lowerCasedKey = key.toLowerCase(); headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey; } Object.setPrototypeOf(headerNameLowerCasedRecord, null); module.exports = { wellknownHeaderNames, headerNameLowerCasedRecord }; } }); // node_modules/undici/lib/core/tree.js var require_tree = __commonJS({ "node_modules/undici/lib/core/tree.js"(exports, module) { "use strict"; var { wellknownHeaderNames, headerNameLowerCasedRecord } = require_constants(); var TstNode = class _TstNode { /** @type {any} */ value = null; /** @type {null | TstNode} */ left = null; /** @type {null | TstNode} */ middle = null; /** @type {null | TstNode} */ right = null; /** @type {number} */ code; /** * @param {string} key * @param {any} value * @param {number} index */ constructor(key, value, index) { if (index === void 0 || index >= key.length) { throw new TypeError("Unreachable"); } const code = this.code = key.charCodeAt(index); if (code > 127) { throw new TypeError("key must be ascii string"); } if (key.length !== ++index) { this.middle = new _TstNode(key, value, index); } else { this.value = value; } } /** * @param {string} key * @param {any} value */ add(key, value) { const length = key.length; if (length === 0) { throw new TypeError("Unreachable"); } let index = 0; let node = this; while (true) { const code = key.charCodeAt(index); if (code > 127) { throw new TypeError("key must be ascii string"); } if (node.code === code) { if (length === ++index) { node.value = value; break; } else if (node.middle !== null) { node = node.middle; } else { node.middle = new _TstNode(key, value, index); break; } } else if (node.code < code) { if (node.left !== null) { node = node.left; } else { node.left = new _TstNode(key, value, index); break; } } else if (node.right !== null) { node = node.right; } else { node.right = new _TstNode(key, value, index); break; } } } /** * @param {Uint8Array} key * @return {TstNode | null} */ search(key) { const keylength = key.length; let index = 0; let node = this; while (node !== null && index < keylength) { let code = key[index]; if (code <= 90 && code >= 65) { code |= 32; } while (node !== null) { if (code === node.code) { if (keylength === ++index) { return node; } node = node.middle; break; } node = node.code < code ? node.left : node.right; } } return null; } }; var TernarySearchTree = class { /** @type {TstNode | null} */ node = null; /** * @param {string} key * @param {any} value * */ insert(key, value) { if (this.node === null) { this.node = new TstNode(key, value, 0); } else { this.node.add(key, value); } } /** * @param {Uint8Array} key * @return {any} */ lookup(key) { return this.node?.search(key)?.value ?? null; } }; var tree = new TernarySearchTree(); for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]; tree.insert(key, key); } module.exports = { TernarySearchTree, tree }; } }); // node_modules/undici/lib/core/util.js var require_util = __commonJS({ "node_modules/undici/lib/core/util.js"(exports, module) { "use strict"; var assert = __require("node:assert"); var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols(); var { IncomingMessage } = __require("node:http"); var stream = __require("node:stream"); var net = __require("node:net"); var { Blob: Blob2 } = __require("node:buffer"); var nodeUtil = __require("node:util"); var { stringify } = __require("node:querystring"); var { EventEmitter: EE } = __require("node:events"); var { InvalidArgumentError } = require_errors(); var { headerNameLowerCasedRecord } = require_constants(); var { tree } = require_tree(); var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v) => Number(v)); var BodyAsyncIterable = class { constructor(body) { this[kBody] = body; this[kBodyUsed] = false; } async *[Symbol.asyncIterator]() { assert(!this[kBodyUsed], "disturbed"); this[kBodyUsed] = true; yield* this[kBody]; } }; function wrapRequestBody(body) { if (isStream(body)) { if (bodyLength(body) === 0) { body.on("data", function() { assert(false); }); } if (typeof body.readableDidRead !== "boolean") { body[kBodyUsed] = false; EE.prototype.on.call(body, "data", function() { this[kBodyUsed] = true; }); } return body; } else if (body && typeof body.pipeTo === "function") { return new BodyAsyncIterable(body); } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) { return new BodyAsyncIterable(body); } else { return body; } } function nop() { } function isStream(obj) { return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function"; } function isBlobLike(object) { if (object === null) { return false; } else if (object instanceof Blob2) { return true; } else if (typeof object !== "object") { return false; } else { const sTag = object[Symbol.toStringTag]; return (sTag === "Blob" || sTag === "File") && ("stream" in object && typeof object.stream === "function" || "arrayBuffer" in object && typeof object.arrayBuffer === "function"); } } function buildURL(url, queryParams) { if (url.includes("?") || url.includes("#")) { throw new Error('Query params cannot be passed when url already contains "?" or "#".'); } const stringified = stringify(queryParams); if (stringified) { url += "?" + stringified; } return url; } function isValidPort(port) { const value = parseInt(port, 10); return value === Number(port) && value >= 0 && value <= 65535; } function isHttpOrHttpsPrefixed(value) { return value != null && value[0] === "h" && value[1] === "t" && value[2] === "t" && value[3] === "p" && (value[4] === ":" || value[4] === "s" && value[5] === ":"); } function parseURL(url) { if (typeof url === "string") { url = new URL(url); if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); } return url; } if (!url || typeof url !== "object") { throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object."); } if (!(url instanceof URL)) { if (url.port != null && url.port !== "" && isValidPort(url.port) === false) { throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer."); } if (url.path != null && typeof url.path !== "string") { throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined."); } if (url.pathname != null && typeof url.pathname !== "string") { throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined."); } if (url.hostname != null && typeof url.hostname !== "string") { throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined."); } if (url.origin != null && typeof url.origin !== "string") { throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined."); } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); } const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80; let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`; let path = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`; if (origin[origin.length - 1] === "/") { origin = origin.slice(0, origin.length - 1); } if (path && path[0] !== "/") { path = `/${path}`; } return new URL(`${origin}${path}`); } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); } return url; } function parseOrigin(url) { url = parseURL(url); if (url.pathname !== "/" || url.search || url.hash) { throw new InvalidArgumentError("invalid url"); } return url; } function getHostname(host) { if (host[0] === "[") { const idx2 = host.indexOf("]"); assert(idx2 !== -1); return host.substring(1, idx2); } const idx = host.indexOf(":"); if (idx === -1) return host; return host.substring(0, idx); } function getServerName(host) { if (!host) { return null; } assert(typeof host === "string"); const servername = getHostname(host); if (net.isIP(servername)) { return ""; } return servername; } function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } function isAsyncIterable(obj) { return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function"); } function isIterable(obj) { return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function")); } function bodyLength(body) { if (body == null) { return 0; } else if (isStream(body)) { const state = body._readableState; return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null; } else if (isBlobLike(body)) { return body.size != null ? body.size : null; } else if (isBuffer(body)) { return body.byteLength; } return null; } function isDestroyed(body) { return body && !!(body.destroyed || body[kDestroyed] || stream.isDestroyed?.(body)); } function destroy(stream2, err) { if (stream2 == null || !isStream(stream2) || isDestroyed(stream2)) { return; } if (typeof stream2.destroy === "function") { if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) { stream2.socket = null; } stream2.destroy(err); } else if (err) { queueMicrotask(() => { stream2.emit("error", err); }); } if (stream2.destroyed !== true) { stream2[kDestroyed] = true; } } var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/; function parseKeepAliveTimeout(val) { const m2 = val.toString().match(KEEPALIVE_TIMEOUT_EXPR); return m2 ? parseInt(m2[1], 10) * 1e3 : null; } function headerNameToString(value) { return typeof value === "string" ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase(); } function bufferToLowerCasedHeaderName(value) { return tree.lookup(value) ?? value.toString("latin1").toLowerCase(); } function parseHeaders(headers, obj) { if (obj === void 0) obj = {}; for (let i = 0; i < headers.length; i += 2) { const key = headerNameToString(headers[i]); let val = obj[key]; if (val) { if (typeof val === "string") { val = [val]; obj[key] = val; } val.push(headers[i + 1].toString("utf8")); } else { const headersValue = headers[i + 1]; if (typeof headersValue === "string") { obj[key] = headersValue; } else { obj[key] = Array.isArray(headersValue) ? headersValue.map((x) => x.toString("utf8")) : headersValue.toString("utf8"); } } } if ("content-length" in obj && "content-disposition" in obj) { obj["content-disposition"] = Buffer.from(obj["content-disposition"]).toString("latin1"); } return obj; } function parseRawHeaders(headers) { const len = headers.length; const ret = new Array(len); let hasContentLength = false; let contentDispositionIdx = -1; let key; let val; let kLen = 0; for (let n = 0; n < headers.length; n += 2) { key = headers[n]; val = headers[n + 1]; typeof key !== "string" && (key = key.toString()); typeof val !== "string" && (val = val.toString("utf8")); kLen = key.length; if (kLen === 14 && key[7] === "-" && (key === "content-length" || key.toLowerCase() === "content-length")) { hasContentLength = true; } else if (kLen === 19 && key[7] === "-" && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) { contentDispositionIdx = n + 1; } ret[n] = key; ret[n + 1] = val; } if (hasContentLength && contentDispositionIdx !== -1) { ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1"); } return ret; } function isBuffer(buffer) { return buffer instanceof Uint8Array || Buffer.isBuffer(buffer); } function validateHandler(handler, method, upgrade) { if (!handler || typeof handler !== "object") { throw new InvalidArgumentError("handler must be an object"); } if (typeof handler.onConnect !== "function") { throw new InvalidArgumentError("invalid onConnect method"); } if (typeof handler.onError !== "function") { throw new InvalidArgumentError("invalid onError method"); } if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) { throw new InvalidArgumentError("invalid onBodySent method"); } if (upgrade || method === "CONNECT") { if (typeof handler.onUpgrade !== "function") { throw new InvalidArgumentError("invalid onUpgrade method"); } } else { if (typeof handler.onHeaders !== "function") { throw new InvalidArgumentError("invalid onHeaders method"); } if (typeof handler.onData !== "function") { throw new InvalidArgumentError("invalid onData method"); } if (typeof handler.onComplete !== "function") { throw new InvalidArgumentError("invalid onComplete method"); } } } function isDisturbed(body) { return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])); } function isErrored(body) { return !!(body && stream.isErrored(body)); } function isReadable(body) { return !!(body && stream.isReadable(body)); } function getSocketInfo(socket) { return { localAddress: socket.localAddress, localPort: socket.localPort, remoteAddress: socket.remoteAddress, remotePort: socket.remotePort, remoteFamily: socket.remoteFamily, timeout: socket.timeout, bytesWritten: socket.bytesWritten, bytesRead: socket.bytesRead }; } function ReadableStreamFrom(iterable) { let iterator; return new ReadableStream( { async start() { iterator = iterable[Symbol.asyncIterator](); }, async pull(controller) { const { done, value } = await iterator.next(); if (done) { queueMicrotask(() => { controller.close(); controller.byobRequest?.respond(0); }); } else { const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); if (buf.byteLength) { controller.enqueue(new Uint8Array(buf)); } } return controller.desiredSize > 0; }, async cancel(reason) { await iterator.return(); }, type: "bytes" } ); } function isFormDataLike(object) { return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData"; } function addAbortListener(signal, listener) { if ("addEventListener" in signal) { signal.addEventListener("abort", listener, { once: true }); return () => signal.removeEventListener("abort", listener); } signal.addListener("abort", listener); return () => signal.removeListener("abort", listener); } var hasToWellFormed = typeof String.prototype.toWellFormed === "function"; var hasIsWellFormed = typeof String.prototype.isWellFormed === "function"; function toUSVString(val) { return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val); } function isUSVString(val) { return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`; } function isTokenCharCode(c2) { switch (c2) { case 34: case 40: case 41: case 44: case 47: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 91: case 92: case 93: case 123: case 125: return false; default: return c2 >= 33 && c2 <= 126; } } function isValidHTTPToken(characters) { if (characters.length === 0) { return false; } for (let i = 0; i < characters.length; ++i) { if (!isTokenCharCode(characters.charCodeAt(i))) { return false; } } return true; } var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/; function isValidHeaderValue(characters) { return !headerCharRegex.test(characters); } function parseRangeHeader(range) { if (range == null || range === "") return { start: 0, end: null, size: null }; const m2 = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null; return m2 ? { start: parseInt(m2[1]), end: m2[2] ? parseInt(m2[2]) : null, size: m2[3] ? parseInt(m2[3]) : null } : null; } function addListener(obj, name2, listener) { const listeners = obj[kListeners] ??= []; listeners.push([name2, listener]); obj.on(name2, listener); return obj; } function removeAllListeners(obj) { for (const [name2, listener] of obj[kListeners] ?? []) { obj.removeListener(name2, listener); } obj[kListeners] = null; } function errorRequest(client, request, err) { try { request.onError(err); assert(request.aborted); } catch (err2) { client.emit("error", err2); } } var kEnumerableProperty = /* @__PURE__ */ Object.create(null); kEnumerableProperty.enumerable = true; var normalizedMethodRecordsBase = { delete: "DELETE", DELETE: "DELETE", get: "GET", GET: "GET", head: "HEAD", HEAD: "HEAD", options: "OPTIONS", OPTIONS: "OPTIONS", post: "POST", POST: "POST", put: "PUT", PUT: "PUT" }; var normalizedMethodRecords = { ...normalizedMethodRecordsBase, patch: "patch", PATCH: "PATCH" }; Object.setPrototypeOf(normalizedMethodRecordsBase, null); Object.setPrototypeOf(normalizedMethodRecords, null); module.exports = { kEnumerableProperty, nop, isDisturbed, isErrored, isReadable, toUSVString, isUSVString, isBlobLike, parseOrigin, parseURL, getServerName, isStream, isIterable, isAsyncIterable, isDestroyed, headerNameToString, bufferToLowerCasedHeaderName, addListener, removeAllListeners, errorRequest, parseRawHeaders, parseHeaders, parseKeepAliveTimeout, destroy, bodyLength, deepClone, ReadableStreamFrom, isBuffer, validateHandler, getSocketInfo, isFormDataLike, buildURL, addAbortListener, isValidHTTPToken, isValidHeaderValue, isTokenCharCode, parseRangeHeader, normalizedMethodRecordsBase, normalizedMethodRecords, isValidPort, isHttpOrHttpsPrefixed, nodeMajor, nodeMinor, safeHTTPMethods: ["GET", "HEAD", "OPTIONS", "TRACE"], wrapRequestBody }; } }); // node_modules/undici/lib/core/diagnostics.js var require_diagnostics = __commonJS({ "node_modules/undici/lib/core/diagnostics.js"(exports, module) { "use strict"; var diagnosticsChannel = __require("node:diagnostics_channel"); var util = __require("node:util"); var undiciDebugLog = util.debuglog("undici"); var fetchDebuglog = util.debuglog("fetch"); var websocketDebuglog = util.debuglog("websocket"); var isClientSet = false; var channels = { // Client beforeConnect: diagnosticsChannel.channel("undici:client:beforeConnect"), connected: diagnosticsChannel.channel("undici:client:connected"), connectError: diagnosticsChannel.channel("undici:client:connectError"), sendHeaders: diagnosticsChannel.channel("undici:client:sendHeaders"), // Request create: diagnosticsChannel.channel("undici:request:create"), bodySent: diagnosticsChannel.channel("undici:request:bodySent"), headers: diagnosticsChannel.channel("undici:request:headers"), trailers: diagnosticsChannel.channel("undici:request:trailers"), error: diagnosticsChannel.channel("undici:request:error"), // WebSocket open: diagnosticsChannel.channel("undici:websocket:open"), close: diagnosticsChannel.channel("undici:websocket:close"), socketError: diagnosticsChannel.channel("undici:websocket:socket_error"), ping: diagnosticsChannel.channel("undici:websocket:ping"), pong: diagnosticsChannel.channel("undici:websocket:pong") }; if (undiciDebugLog.enabled || fetchDebuglog.enabled) { const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog; diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => { const { connectParams: { version, protocol, port, host } } = evt; debuglog( "connecting to %s using %s%s", `${host}${port ? `:${port}` : ""}`, protocol, version ); }); diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => { const { connectParams: { version, protocol, port, host } } = evt; debuglog( "connected to %s using %s%s", `${host}${port ? `:${port}` : ""}`, protocol, version ); }); diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => { const { connectParams: { version, protocol, port, host }, error } = evt; debuglog( "connection to %s using %s%s errored - %s", `${host}${port ? `:${port}` : ""}`, protocol, version, error.message ); }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { const { request: { method, path, origin } } = evt; debuglog("sending request to %s %s/%s", method, origin, path); }); diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => { const { request: { method, path, origin }, response: { statusCode } } = evt; debuglog( "received response to %s %s/%s - HTTP %d", method, origin, path, statusCode ); }); diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => { const { request: { method, path, origin } } = evt; debuglog("trailers received from %s %s/%s", method, origin, path); }); diagnosticsChannel.channel("undici:request:error").subscribe((evt) => { const { request: { method, path, origin }, error } = evt; debuglog( "request to %s %s/%s errored - %s", method, origin, path, error.message ); }); isClientSet = true; } if (websocketDebuglog.enabled) { if (!isClientSet) { const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog; diagnosticsChannel.channel("undici:client:beforeConnect").subscribe((evt) => { const { connectParams: { version, protocol, port, host } } = evt; debuglog( "connecting to %s%s using %s%s", host, port ? `:${port}` : "", protocol, version ); }); diagnosticsChannel.channel("undici:client:connected").subscribe((evt) => { const { connectParams: { version, protocol, port, host } } = evt; debuglog( "connected to %s%s using %s%s", host, port ? `:${port}` : "", protocol, version ); }); diagnosticsChannel.channel("undici:client:connectError").subscribe((evt) => { const { connectParams: { version, protocol, port, host }, error } = evt; debuglog( "connection to %s%s using %s%s errored - %s", host, port ? `:${port}` : "", protocol, version, error.message ); }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { const { request: { method, path, origin } } = evt; debuglog("sending request to %s %s/%s", method, origin, path); }); } diagnosticsChannel.channel("undici:websocket:open").subscribe((evt) => { const { address: { address, port } } = evt; websocketDebuglog("connection opened %s%s", address, port ? `:${port}` : ""); }); diagnosticsChannel.channel("undici:websocket:close").subscribe((evt) => { const { websocket, code, reason } = evt; websocketDebuglog( "closed connection to %s - %s %s", websocket.url, code, reason ); }); diagnosticsChannel.channel("undici:websocket:socket_error").subscribe((err) => { websocketDebuglog("connection errored - %s", err.message); }); diagnosticsChannel.channel("undici:websocket:ping").subscribe((evt) => { websocketDebuglog("ping received"); }); diagnosticsChannel.channel("undici:websocket:pong").subscribe((evt) => { websocketDebuglog("pong received"); }); } module.exports = { channels }; } }); // node_modules/undici/lib/core/request.js var require_request = __commonJS({ "node_modules/undici/lib/core/request.js"(exports, module) { "use strict"; var { InvalidArgumentError, NotSupportedError } = require_errors(); var assert = __require("node:assert"); var { isValidHTTPToken, isValidHeaderValue, isStream, destroy, isBuffer, isFormDataLike, isIterable, isBlobLike, buildURL, validateHandler, getServerName, normalizedMethodRecords } = require_util(); var { channels } = require_diagnostics(); var { headerNameLowerCasedRecord } = require_constants(); var invalidPathRegex = /[^\u0021-\u00ff]/; var kHandler = Symbol("handler"); var Request = class { constructor(origin, { path, method, body, headers, query, idempotent, blocking, upgrade, headersTimeout, bodyTimeout, reset, throwOnError, expectContinue, servername }, handler) { if (typeof path !== "string") { throw new InvalidArgumentError("path must be a string"); } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") { throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); } else if (invalidPathRegex.test(path)) { throw new InvalidArgumentError("invalid request path"); } if (typeof method !== "string") { throw new InvalidArgumentError("method must be a string"); } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) { throw new InvalidArgumentError("invalid request method"); } if (upgrade && typeof upgrade !== "string") { throw new InvalidArgumentError("upgrade must be a string"); } if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError("invalid headersTimeout"); } if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError("invalid bodyTimeout"); } if (reset != null && typeof reset !== "boolean") { throw new InvalidArgumentError("invalid reset"); } if (expectContinue != null && typeof expectContinue !== "boolean") { throw new InvalidArgumentError("invalid expectContinue"); } this.headersTimeout = headersTimeout; this.bodyTimeout = bodyTimeout; this.throwOnError = throwOnError === true; this.method = method; this.abort = null; if (body == null) { this.body = null; } else if (isStream(body)) { this.body = body; const rState = this.body._readableState; if (!rState || !rState.autoDestroy) { this.endHandler = function autoDestroy() { destroy(this); }; this.body.on("end", this.endHandler); } this.errorHandler = (err) => { if (this.abort) { this.abort(err); } else { this.error = err; } }; this.body.on("error", this.errorHandler); } else if (isBuffer(body)) { this.body = body.byteLength ? body : null; } else if (ArrayBuffer.isView(body)) { this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null; } else if (body instanceof ArrayBuffer) { this.body = body.byteLength ? Buffer.from(body) : null; } else if (typeof body === "string") { this.body = body.length ? Buffer.from(body) : null; } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { this.body = body; } else { throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable"); } this.completed = false; this.aborted = false; this.upgrade = upgrade || null; this.path = query ? buildURL(path, query) : path; this.origin = origin; this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent; this.blocking = blocking == null ? false : blocking; this.reset = reset == null ? null : reset; this.host = null; this.contentLength = null; this.contentType = null; this.headers = []; this.expectContinue = expectContinue != null ? expectContinue : false; if (Array.isArray(headers)) { if (headers.length % 2 !== 0) { throw new InvalidArgumentError("headers array must be even"); } for (let i = 0; i < headers.length; i += 2) { processHeader(this, headers[i], headers[i + 1]); } } else if (headers && typeof headers === "object") { if (headers[Symbol.iterator]) { for (const header of headers) { if (!Array.isArray(header) || header.length !== 2) { throw new InvalidArgumentError("headers must be in key-value pair format"); } processHeader(this, header[0], header[1]); } } else { const keys = Object.keys(headers); for (let i = 0; i < keys.length; ++i) { processHeader(this, keys[i], headers[keys[i]]); } } } else if (headers != null) { throw new InvalidArgumentError("headers must be an object or an array"); } validateHandler(handler, method, upgrade); this.servername = servername || getServerName(this.host); this[kHandler] = handler; if (channels.create.hasSubscribers) { channels.create.publish({ request: this }); } } onBodySent(chunk) { if (this[kHandler].onBodySent) { try { return this[kHandler].onBodySent(chunk); } catch (err) { this.abort(err); } } } onRequestSent() { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: