UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

1,593 lines (1,591 loc) • 378 kB
'use strict'; var chunk57ZE2S4F_cjs = require('../chunk-57ZE2S4F.cjs'); var chunkY3T2Q2HR_cjs = require('../chunk-Y3T2Q2HR.cjs'); var async_hooks = require('async_hooks'); var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __require2 = /* @__PURE__ */ ((x) => typeof chunkY3T2Q2HR_cjs.__require !== "undefined" ? chunkY3T2Q2HR_cjs.__require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof chunkY3T2Q2HR_cjs.__require !== "undefined" ? chunkY3T2Q2HR_cjs.__require : a)[b] }) : x)(function(x) { if (typeof chunkY3T2Q2HR_cjs.__require !== "undefined") return chunkY3T2Q2HR_cjs.__require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; 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"); member.set(obj, value); return value; }; var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; var POSITIONALS_EXP = /(%?)(%([sdijo]))/g; function serializePositional(positional, flag) { switch (flag) { case "s": return positional; case "d": case "i": return Number(positional); case "j": return JSON.stringify(positional); case "o": { if (typeof positional === "string") { return positional; } const json = JSON.stringify(positional); if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) { return positional; } return json; } } } function format(message3, ...positionals) { if (positionals.length === 0) { return message3; } let positionalIndex = 0; let formattedMessage = message3.replace( POSITIONALS_EXP, (match2, isEscaped, _, flag) => { const positional = positionals[positionalIndex]; const value = serializePositional(positional, flag); if (!isEscaped) { positionalIndex++; return value; } return match2; } ); if (positionalIndex < positionals.length) { formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`; } formattedMessage = formattedMessage.replace(/%{2,2}/g, "%"); return formattedMessage; } var STACK_FRAMES_TO_IGNORE = 2; function cleanErrorStack(error3) { if (!error3.stack) { return; } const nextStack = error3.stack.split("\n"); nextStack.splice(1, STACK_FRAMES_TO_IGNORE); error3.stack = nextStack.join("\n"); } var InvariantError = class extends Error { constructor(message3, ...positionals) { super(message3); this.message = message3; this.name = "Invariant Violation"; this.message = format(message3, ...positionals); cleanErrorStack(this); } }; var invariant = (predicate, message3, ...positionals) => { if (!predicate) { throw new InvariantError(message3, ...positionals); } }; invariant.as = (ErrorConstructor, predicate, message3, ...positionals) => { if (!predicate) { const formatMessage2 = positionals.length === 0 ? message3 : format(message3, ...positionals); let error3; try { error3 = Reflect.construct(ErrorConstructor, [ formatMessage2 ]); } catch (err) { error3 = ErrorConstructor(formatMessage2); } throw error3; } }; var LIBRARY_PREFIX = "[MSW]"; function formatMessage(message3, ...positionals) { const interpolatedMessage = format(message3, ...positionals); return `${LIBRARY_PREFIX} ${interpolatedMessage}`; } function warn(message3, ...positionals) { console.warn(formatMessage(message3, ...positionals)); } function error(message3, ...positionals) { console.error(formatMessage(message3, ...positionals)); } var devUtils = { formatMessage, warn, error }; function checkGlobals() { invariant( typeof URL !== "undefined", devUtils.formatMessage( `Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".` ) ); } var MemoryLeakError = class extends Error { constructor(emitter, type, count) { super( `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` ); this.emitter = emitter; this.type = type; this.count = count; this.name = "MaxListenersExceededWarning"; } }; var _Emitter = class { static listenerCount(emitter, eventName) { return emitter.listenerCount(eventName); } constructor() { this.events = /* @__PURE__ */ new Map(); this.maxListeners = _Emitter.defaultMaxListeners; this.hasWarnedAboutPotentialMemoryLeak = false; } _emitInternalEvent(internalEventName, eventName, listener) { this.emit( internalEventName, ...[eventName, listener] ); } _getListeners(eventName) { return Array.prototype.concat.apply([], this.events.get(eventName)) || []; } _removeListener(listeners, listener) { const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } return []; } _wrapOnceListener(eventName, listener) { const onceListener = (...data) => { this.removeListener(eventName, onceListener); return listener.apply(this, data); }; Object.defineProperty(onceListener, "name", { value: listener.name }); return onceListener; } setMaxListeners(maxListeners) { this.maxListeners = maxListeners; return this; } /** * Returns the current max listener value for the `Emitter` which is * either set by `emitter.setMaxListeners(n)` or defaults to * `Emitter.defaultMaxListeners`. */ getMaxListeners() { return this.maxListeners; } /** * Returns an array listing the events for which the emitter has registered listeners. * The values in the array will be strings or Symbols. */ eventNames() { return Array.from(this.events.keys()); } /** * Synchronously calls each of the listeners registered for the event named `eventName`, * in the order they were registered, passing the supplied arguments to each. * Returns `true` if the event has listeners, `false` otherwise. * * @example * const emitter = new Emitter<{ hello: [string] }>() * emitter.emit('hello', 'John') */ emit(eventName, ...data) { const listeners = this._getListeners(eventName); listeners.forEach((listener) => { listener.apply(this, data); }); return listeners.length > 0; } addListener(eventName, listener) { this._emitInternalEvent("newListener", eventName, listener); const nextListeners = this._getListeners(eventName).concat(listener); this.events.set(eventName, nextListeners); if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { this.hasWarnedAboutPotentialMemoryLeak = true; const memoryLeakWarning = new MemoryLeakError( this, eventName, this.listenerCount(eventName) ); console.warn(memoryLeakWarning); } return this; } on(eventName, listener) { return this.addListener(eventName, listener); } once(eventName, listener) { return this.addListener( eventName, this._wrapOnceListener(eventName, listener) ); } prependListener(eventName, listener) { const listeners = this._getListeners(eventName); if (listeners.length > 0) { const nextListeners = [listener].concat(listeners); this.events.set(eventName, nextListeners); } else { this.events.set(eventName, listeners.concat(listener)); } return this; } prependOnceListener(eventName, listener) { return this.prependListener( eventName, this._wrapOnceListener(eventName, listener) ); } removeListener(eventName, listener) { const listeners = this._getListeners(eventName); if (listeners.length > 0) { this._removeListener(listeners, listener); this.events.set(eventName, listeners); this._emitInternalEvent("removeListener", eventName, listener); } return this; } /** * Alias for `emitter.removeListener()`. * * @example * emitter.off('hello', listener) */ off(eventName, listener) { return this.removeListener(eventName, listener); } removeAllListeners(eventName) { if (eventName) { this.events.delete(eventName); } else { this.events.clear(); } return this; } /** * Returns a copy of the array of listeners for the event named `eventName`. */ listeners(eventName) { return Array.from(this._getListeners(eventName)); } /** * Returns the number of listeners listening to the event named `eventName`. */ listenerCount(eventName) { return this._getListeners(eventName).length; } rawListeners(eventName) { return this.listeners(eventName); } }; var Emitter = _Emitter; Emitter.defaultMaxListeners = 10; var SOURCE_FRAME = /[\/\\]msw[\/\\]src[\/\\](.+)/; var BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](core|browser|node|native|iife)[\/\\]|^[^\/\\]*$/; function getCallFrame(error3) { const stack = error3.stack; if (!stack) { return; } const frames = stack.split("\n").slice(1); const declarationFrame = frames.find((frame) => { return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame)); }); if (!declarationFrame) { return; } const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, ""); return declarationPath; } function isIterable(fn) { if (!fn) { return false; } return Reflect.has(fn, Symbol.iterator) || Reflect.has(fn, Symbol.asyncIterator); } var _RequestHandler = class _RequestHandler2 { constructor(args) { __publicField(this, "__kind"); __publicField(this, "info"); __publicField(this, "isUsed"); __publicField(this, "resolver"); __publicField(this, "resolverIterator"); __publicField(this, "resolverIteratorResult"); __publicField(this, "options"); this.resolver = args.resolver; this.options = args.options; const callFrame = getCallFrame(new Error()); this.info = { ...args.info, callFrame }; this.isUsed = false; this.__kind = "RequestHandler"; } /** * Parse the intercepted request to extract additional information from it. * Parsed result is then exposed to other methods of this request handler. */ async parse(_args) { return {}; } /** * Test if this handler matches the given request. * * This method is not used internally but is exposed * as a convenience method for consumers writing custom * handlers. */ async test(args) { const parsedResult = await this.parse({ request: args.request, resolutionContext: args.resolutionContext }); return this.predicate({ request: args.request, parsedResult, resolutionContext: args.resolutionContext }); } extendResolverArgs(_args) { return {}; } // Clone the request instance before it's passed to the handler phases // and the response resolver so we can always read it for logging. // We only clone it once per request to avoid unnecessary overhead. cloneRequestOrGetFromCache(request) { const existingClone = _RequestHandler2.cache.get(request); if (typeof existingClone !== "undefined") { return existingClone; } const clonedRequest = request.clone(); _RequestHandler2.cache.set(request, clonedRequest); return clonedRequest; } /** * Execute this request handler and produce a mocked response * using the given resolver function. */ async run(args) { var _a4, _b2; if (this.isUsed && ((_a4 = this.options) == null ? void 0 : _a4.once)) { return null; } const requestClone = this.cloneRequestOrGetFromCache(args.request); const parsedResult = await this.parse({ request: args.request, resolutionContext: args.resolutionContext }); const shouldInterceptRequest = this.predicate({ request: args.request, parsedResult, resolutionContext: args.resolutionContext }); if (!shouldInterceptRequest) { return null; } if (this.isUsed && ((_b2 = this.options) == null ? void 0 : _b2.once)) { return null; } this.isUsed = true; const executeResolver = this.wrapResolver(this.resolver); const resolverExtras = this.extendResolverArgs({ request: args.request, parsedResult }); const mockedResponsePromise = executeResolver({ ...resolverExtras, requestId: args.requestId, request: args.request }).catch((errorOrResponse) => { if (errorOrResponse instanceof Response) { return errorOrResponse; } throw errorOrResponse; }); const mockedResponse = await mockedResponsePromise; const executionResult = this.createExecutionResult({ // Pass the cloned request to the result so that logging // and other consumers could read its body once more. request: requestClone, requestId: args.requestId, response: mockedResponse, parsedResult }); return executionResult; } wrapResolver(resolver) { return async (info) => { var _a4; if (!this.resolverIterator) { const result = await resolver(info); if (!isIterable(result)) { return result; } this.resolverIterator = Symbol.iterator in result ? result[Symbol.iterator]() : result[Symbol.asyncIterator](); } this.isUsed = false; const { done, value } = await this.resolverIterator.next(); const nextResponse = await value; if (nextResponse) { this.resolverIteratorResult = nextResponse.clone(); } if (done) { this.isUsed = true; return (_a4 = this.resolverIteratorResult) == null ? void 0 : _a4.clone(); } return nextResponse; }; } createExecutionResult(args) { return { handler: this, request: args.request, requestId: args.requestId, response: args.response, parsedResult: args.parsedResult }; } }; __publicField(_RequestHandler, "cache", /* @__PURE__ */ new WeakMap()); var __create = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require3() { 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) __defProp2(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. __defProp2(target, "default", { value: mod, enumerable: true }), mod )); var require_codes = __commonJS({ "node_modules/statuses/codes.json"(exports, module) { module.exports = { "100": "Continue", "101": "Switching Protocols", "102": "Processing", "103": "Early Hints", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-Authoritative Information", "204": "No Content", "205": "Reset Content", "206": "Partial Content", "207": "Multi-Status", "208": "Already Reported", "226": "IM Used", "300": "Multiple Choices", "301": "Moved Permanently", "302": "Found", "303": "See Other", "304": "Not Modified", "305": "Use Proxy", "307": "Temporary Redirect", "308": "Permanent Redirect", "400": "Bad Request", "401": "Unauthorized", "402": "Payment Required", "403": "Forbidden", "404": "Not Found", "405": "Method Not Allowed", "406": "Not Acceptable", "407": "Proxy Authentication Required", "408": "Request Timeout", "409": "Conflict", "410": "Gone", "411": "Length Required", "412": "Precondition Failed", "413": "Payload Too Large", "414": "URI Too Long", "415": "Unsupported Media Type", "416": "Range Not Satisfiable", "417": "Expectation Failed", "418": "I'm a Teapot", "421": "Misdirected Request", "422": "Unprocessable Entity", "423": "Locked", "424": "Failed Dependency", "425": "Too Early", "426": "Upgrade Required", "428": "Precondition Required", "429": "Too Many Requests", "431": "Request Header Fields Too Large", "451": "Unavailable For Legal Reasons", "500": "Internal Server Error", "501": "Not Implemented", "502": "Bad Gateway", "503": "Service Unavailable", "504": "Gateway Timeout", "505": "HTTP Version Not Supported", "506": "Variant Also Negotiates", "507": "Insufficient Storage", "508": "Loop Detected", "509": "Bandwidth Limit Exceeded", "510": "Not Extended", "511": "Network Authentication Required" }; } }); var require_statuses = __commonJS({ "node_modules/statuses/index.js"(exports, module) { var codes = require_codes(); module.exports = status2; status2.message = codes; status2.code = createMessageToStatusCodeMap(codes); status2.codes = createStatusCodeList(codes); status2.redirect = { 300: true, 301: true, 302: true, 303: true, 305: true, 307: true, 308: true }; status2.empty = { 204: true, 205: true, 304: true }; status2.retry = { 502: true, 503: true, 504: true }; function createMessageToStatusCodeMap(codes2) { var map = {}; Object.keys(codes2).forEach(function forEachCode(code) { var message3 = codes2[code]; var status3 = Number(code); map[message3.toLowerCase()] = status3; }); return map; } function createStatusCodeList(codes2) { return Object.keys(codes2).map(function mapCode(code) { return Number(code); }); } function getStatusCode(message3) { var msg = message3.toLowerCase(); if (!Object.prototype.hasOwnProperty.call(status2.code, msg)) { throw new Error('invalid status message: "' + message3 + '"'); } return status2.code[msg]; } function getStatusMessage(code) { if (!Object.prototype.hasOwnProperty.call(status2.message, code)) { throw new Error("invalid status code: " + code); } return status2.message[code]; } function status2(code) { if (typeof code === "number") { return getStatusMessage(code); } if (typeof code !== "string") { throw new TypeError("code must be a number or string"); } var n = parseInt(code, 10); if (!isNaN(n)) { return getStatusMessage(n); } return getStatusCode(code); } } }); __toESM(require_statuses()); function isNodeProcess() { if (typeof navigator !== "undefined" && navigator.product === "ReactNative") { return true; } if (typeof process !== "undefined") { const type = process.type; if (type === "renderer" || type === "worker") { return false; } return !!(process.versions && process.versions.node); } return false; } var __defProp22 = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp22(target, name, { get: all[name], enumerable: true }); }; var colors_exports = {}; __export(colors_exports, { blue: () => blue, gray: () => gray, green: () => green, red: () => red, yellow: () => yellow }); function yellow(text) { return `\x1B[33m${text}\x1B[0m`; } function blue(text) { return `\x1B[34m${text}\x1B[0m`; } function gray(text) { return `\x1B[90m${text}\x1B[0m`; } function red(text) { return `\x1B[31m${text}\x1B[0m`; } function green(text) { return `\x1B[32m${text}\x1B[0m`; } var IS_NODE = isNodeProcess(); var Logger = class { constructor(name) { __publicField(this, "prefix"); this.name = name; this.prefix = `[${this.name}]`; const LOGGER_NAME = getVariable("DEBUG"); const LOGGER_LEVEL = getVariable("LOG_LEVEL"); const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME); if (isLoggingEnabled) { this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug; this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info; this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success; this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning; this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error; } else { this.info = noop; this.success = noop; this.warning = noop; this.error = noop; this.only = noop; } } extend(domain) { return new Logger(`${this.name}:${domain}`); } /** * Print a debug message. * @example * logger.debug('no duplicates found, creating a document...') */ debug(message3, ...positionals) { this.logEntry({ level: "debug", message: gray(message3), positionals, prefix: this.prefix, colors: { prefix: "gray" } }); } /** * Print an info message. * @example * logger.info('start parsing...') */ info(message3, ...positionals) { this.logEntry({ level: "info", message: message3, positionals, prefix: this.prefix, colors: { prefix: "blue" } }); const performance2 = new PerformanceEntry(); return (message22, ...positionals2) => { performance2.measure(); this.logEntry({ level: "info", message: `${message22} ${gray(`${performance2.deltaTime}ms`)}`, positionals: positionals2, prefix: this.prefix, colors: { prefix: "blue" } }); }; } /** * Print a success message. * @example * logger.success('successfully created document') */ success(message3, ...positionals) { this.logEntry({ level: "info", message: message3, positionals, prefix: `\u2714 ${this.prefix}`, colors: { timestamp: "green", prefix: "green" } }); } /** * Print a warning. * @example * logger.warning('found legacy document format') */ warning(message3, ...positionals) { this.logEntry({ level: "warning", message: message3, positionals, prefix: `\u26A0 ${this.prefix}`, colors: { timestamp: "yellow", prefix: "yellow" } }); } /** * Print an error message. * @example * logger.error('something went wrong') */ error(message3, ...positionals) { this.logEntry({ level: "error", message: message3, positionals, prefix: `\u2716 ${this.prefix}`, colors: { timestamp: "red", prefix: "red" } }); } /** * Execute the given callback only when the logging is enabled. * This is skipped in its entirety and has no runtime cost otherwise. * This executes regardless of the log level. * @example * logger.only(() => { * logger.info('additional info') * }) */ only(callback) { callback(); } createEntry(level, message3) { return { timestamp: /* @__PURE__ */ new Date(), level, message: message3 }; } logEntry(args) { const { level, message: message3, prefix, colors: customColors, positionals = [] } = args; const entry = this.createEntry(level, message3); const timestampColor = (customColors == null ? void 0 : customColors.timestamp) || "gray"; const prefixColor = (customColors == null ? void 0 : customColors.prefix) || "gray"; const colorize = { timestamp: colors_exports[timestampColor], prefix: colors_exports[prefixColor] }; const write = this.getWriter(level); write( [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message3)).join(" "), ...positionals.map(serializeInput) ); } formatTimestamp(timestamp) { return `${timestamp.toLocaleTimeString( "en-GB" )}:${timestamp.getMilliseconds()}`; } getWriter(level) { switch (level) { case "debug": case "success": case "info": { return log; } case "warning": { return warn2; } case "error": { return error2; } } } }; var PerformanceEntry = class { constructor() { __publicField(this, "startTime"); __publicField(this, "endTime"); __publicField(this, "deltaTime"); this.startTime = performance.now(); } measure() { this.endTime = performance.now(); const deltaTime = this.endTime - this.startTime; this.deltaTime = deltaTime.toFixed(2); } }; var noop = () => void 0; function log(message3, ...positionals) { if (IS_NODE) { process.stdout.write(format(message3, ...positionals) + "\n"); return; } console.log(message3, ...positionals); } function warn2(message3, ...positionals) { if (IS_NODE) { process.stderr.write(format(message3, ...positionals) + "\n"); return; } console.warn(message3, ...positionals); } function error2(message3, ...positionals) { if (IS_NODE) { process.stderr.write(format(message3, ...positionals) + "\n"); return; } console.error(message3, ...positionals); } function getVariable(variableName) { var _a4; if (IS_NODE) { return process.env[variableName]; } return (_a4 = globalThis[variableName]) == null ? void 0 : _a4.toString(); } function isDefinedAndNotEquals(value, expected) { return value !== void 0 && value !== expected; } function serializeInput(message3) { if (typeof message3 === "undefined") { return "undefined"; } if (message3 === null) { return "null"; } if (typeof message3 === "string") { return message3; } if (typeof message3 === "object") { return JSON.stringify(message3); } return message3.toString(); } var _FetchResponse = class extends Response { static isConfigurableStatusCode(status) { return status >= 200 && status <= 599; } static isRedirectResponse(status) { return _FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status); } /** * Returns a boolean indicating whether the given response status * code represents a response that can have a body. */ static isResponseWithBody(status) { return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status); } static setUrl(url, response) { if (!url) { return; } if (response.url != "") { return; } Object.defineProperty(response, "url", { value: url, enumerable: true, configurable: true, writable: false }); } /** * Parses the given raw HTTP headers into a Fetch API `Headers` instance. */ static parseRawHeaders(rawHeaders) { const headers = new Headers(); for (let line = 0; line < rawHeaders.length; line += 2) { headers.append(rawHeaders[line], rawHeaders[line + 1]); } return headers; } constructor(body, init = {}) { var _a4; const status = (_a4 = init.status) != null ? _a4 : 200; const safeStatus = _FetchResponse.isConfigurableStatusCode(status) ? status : 200; const finalBody = _FetchResponse.isResponseWithBody(status) ? body : null; super(finalBody, { ...init, status: safeStatus }); if (status !== safeStatus) { const stateSymbol = Object.getOwnPropertySymbols(this).find( (symbol) => symbol.description === "state" ); if (stateSymbol) { const state = Reflect.get(this, stateSymbol); Reflect.set(state, "status", status); } else { Object.defineProperty(this, "status", { value: status, enumerable: true, configurable: true, writable: false }); } } _FetchResponse.setUrl(init.url, this); } }; var FetchResponse = _FetchResponse; FetchResponse.STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]; FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]; new TextEncoder(); var __create2 = Object.create; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __commonJS2 = (cb, mod) => function __require3() { return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( // 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. __defProp3(target, "default", { value: mod, enumerable: true }), mod )); var require_cookie = __commonJS2({ "node_modules/cookie/index.js"(exports) { exports.parse = parse2; exports.serialize = serialize; var __toString = Object.prototype.toString; var __hasOwnProperty = Object.prototype.hasOwnProperty; var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i; var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/; function parse2(str, opt) { if (typeof str !== "string") { throw new TypeError("argument str must be a string"); } var obj = {}; var len = str.length; if (len < 2) return obj; var dec = opt && opt.decode || decode; var index = 0; var eqIdx = 0; var endIdx = 0; do { eqIdx = str.indexOf("=", index); if (eqIdx === -1) break; endIdx = str.indexOf(";", index); if (endIdx === -1) { endIdx = len; } else if (eqIdx > endIdx) { index = str.lastIndexOf(";", eqIdx - 1) + 1; continue; } var keyStartIdx = startIndex(str, index, eqIdx); var keyEndIdx = endIndex(str, eqIdx, keyStartIdx); var key = str.slice(keyStartIdx, keyEndIdx); if (!__hasOwnProperty.call(obj, key)) { var valStartIdx = startIndex(str, eqIdx + 1, endIdx); var valEndIdx = endIndex(str, endIdx, valStartIdx); if (str.charCodeAt(valStartIdx) === 34 && str.charCodeAt(valEndIdx - 1) === 34) { valStartIdx++; valEndIdx--; } var val = str.slice(valStartIdx, valEndIdx); obj[key] = tryDecode(val, dec); } index = endIdx + 1; } while (index < len); return obj; } function startIndex(str, index, max) { do { var code = str.charCodeAt(index); if (code !== 32 && code !== 9) return index; } while (++index < max); return max; } function endIndex(str, index, min) { while (index > min) { var code = str.charCodeAt(--index); if (code !== 32 && code !== 9) return index + 1; } return min; } function serialize(name, val, opt) { var enc = opt && opt.encode || encodeURIComponent; if (typeof enc !== "function") { throw new TypeError("option encode is invalid"); } if (!cookieNameRegExp.test(name)) { throw new TypeError("argument name is invalid"); } var value = enc(val); if (!cookieValueRegExp.test(value)) { throw new TypeError("argument val is invalid"); } var str = name + "=" + value; if (!opt) return str; if (null != opt.maxAge) { var maxAge = Math.floor(opt.maxAge); if (!isFinite(maxAge)) { throw new TypeError("option maxAge is invalid"); } str += "; Max-Age=" + maxAge; } if (opt.domain) { if (!domainValueRegExp.test(opt.domain)) { throw new TypeError("option domain is invalid"); } str += "; Domain=" + opt.domain; } if (opt.path) { if (!pathValueRegExp.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 isDate(val) { return __toString.call(val) === "[object Date]"; } function tryDecode(str, decode2) { try { return decode2(str); } catch (e) { return str; } } } }); __toESM2(require_cookie()); var __create3 = Object.create; var __defProp4 = Object.defineProperty; var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; var __getOwnPropNames3 = Object.getOwnPropertyNames; var __getProtoOf3 = Object.getPrototypeOf; var __hasOwnProp3 = Object.prototype.hasOwnProperty; var __require22 = /* @__PURE__ */ ((x) => typeof __require2 !== "undefined" ? __require2 : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof __require2 !== "undefined" ? __require2 : a)[b] }) : x)(function(x) { if (typeof __require2 !== "undefined") return __require2.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); var __commonJS3 = (cb, mod) => function __require222() { return mod || (0, cb[__getOwnPropNames3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps3 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames3(from)) if (!__hasOwnProp3.call(to, key) && key !== except) __defProp4(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable }); } return to; }; var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3( // 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. __defProp4(target, "default", { value: mod, enumerable: true }), mod )); var require_punycode = __commonJS3({ "node_modules/punycode/punycode.js"(exports, module) { 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-\x7F]/; 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 error3(type) { throw new RangeError(errors[type]); } function map(array, callback) { const result = []; let length = array.length; while (length--) { result[length] = callback(array[length]); } return result; } function mapDomain(domain, callback) { const parts = domain.split("@"); let result = ""; if (parts.length > 1) { result = parts[0] + "@"; domain = parts[1]; } domain = domain.replace(regexSeparators, "."); const labels = domain.split("."); const encoded = map(labels, callback).join("."); return result + encoded; } function ucs2decode(string) { const output = []; let counter = 0; const length = string.length; while (counter < length) { const value = string.charCodeAt(counter++); if (value >= 55296 && value <= 56319 && counter < length) { const 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 = (codePoints) => String.fromCodePoint(...codePoints); var basicToDigit = function(codePoint) { if (codePoint >= 48 && codePoint < 58) { return 26 + (codePoint - 48); } if (codePoint >= 65 && codePoint < 91) { return codePoint - 65; } if (codePoint >= 97 && codePoint < 123) { return codePoint - 97; } return base; }; var digitToBasic = function(digit, flag) { return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; var adapt = function(delta, numPoints, firstTime) { let k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; var decode = function(input) { const output = []; const inputLength = input.length; let i = 0; let n = initialN; let bias = initialBias; let basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (let j = 0; j < basic; ++j) { if (input.charCodeAt(j) >= 128) { error3("not-basic"); } output.push(input.charCodeAt(j)); } for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) { const oldi = i; for (let w = 1, k = base; ; k += base) { if (index >= inputLength) { error3("invalid-input"); } const digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base) { error3("invalid-input"); } if (digit > floor((maxInt - i) / w)) { error3("overflow"); } i += digit * w; const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } const baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error3("overflow"); } w *= baseMinusT; } const out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); if (floor(i / out) > maxInt - n) { error3("overflow"); } n += floor(i / out); i %= out; output.splice(i++, 0, n); } return String.fromCodePoint(...output); }; var encode = function(input) { const output = []; input = ucs2decode(input); const inputLength = input.length; let n = initialN; let delta = 0; let bias = initialBias; for (const currentValue of input) { if (currentValue < 128) { output.push(stringFromCharCode(currentValue)); } } const basicLength = output.length; let handledCPCount = basicLength; if (basicLength) { output.push(delimiter); } while (handledCPCount < inputLength) { let m = maxInt; for (const currentValue of input) { if (currentValue >= n && currentValue < m) { m = currentValue; } } const handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error3("overflow"); } delta += (m - n) * handledCPCountPlusOne; n = m; for (const currentValue of input) { if (currentValue < n && ++delta > maxInt) { error3("overflow"); } if (currentValue === n) { let q = delta; for (let k = base; ; k += base) { const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } const qMinusT = q - t; const 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; } } ++delta; ++n; } return output.join(""); }; var toUnicode = function(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }; var toASCII = function(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.3.1", /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ "ucs2": { "decode": ucs2decode, "encode": ucs2encode }, "decode": decode, "encode": encode, "toASCII": toASCII, "toUnicode": toUnicode }; module.exports = punycode; } }); var require_requires_port = __commonJS3({ "node_modules/requires-port/index.js"(exports, module) { module.exports = function required(port, protocol) { protocol = protocol.split(":")[0]; port = +port; if (!port) return false; switch (protocol) { case "http": case "ws": return port !== 80; case "https": case "wss": return port !== 443; case "ftp": return port !== 21; case "gopher": return port !== 70; case "file": return false; } return port !== 0; }; } }); var require_querystringify = __commonJS3({ "node_modules/querystringify/index.js"(exports) { var has = Object.prototype.hasOwnProperty; var undef; function decode(input) { try { return decodeURIComponent(input.replace(/\+/g, " ")); } catch (e) { return null; } } function encode(input) { try { return encodeURIComponent(input); } catch (e) { return null; } } function querystring(query) { var parser = /([^=?#&]+)=?([^&]*)/g, result = {}, part; while (part = parser.exec(query)) { var key = decode(part[1]), value = decode(part[2]); if (key === null || value === null || key in result) continue; result[key] = value; } return result; } function querystringify(obj, prefix) { prefix = prefix || ""; var pairs = [], value, key; if ("string" !== typeof prefix) prefix = "?"; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; if (!value && (value === null || value === undef || isNaN(value))) { value = ""; } key = encode(key); value = encode(value); if (key === null || value === null) continue; pairs.push(key + "=" + value); } } return pairs.length ? prefix + pairs.join("&") : ""; } exports.stringify = querystringify; exports.parse = querystring; } }); var require_url_parse = __commonJS3({ "node_modules/url-parse/index.js"(exports, module) { var required = require_requires_port(); var qs = require_querystringify(); var controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/; var CRHTLF = /[\n\r\t]/g; var slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//; var port = /:\d+$/; var protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i; var windowsDriveLetter = /^[a-zA-Z]:/; function trimLeft(str) { return (str ? str : "").toString().replace(controlOrWhitespace, ""); } var rules = [ ["#", "hash"], // Extract from the back. ["?", "query"], // Extract from the back. function sanitize(address, url) { return isSpecial(url.protocol) ? address.replace(/\\/g, "/") : address; }, ["/", "pathname"], // Extract from the back. ["@", "auth", 1], // Extract from the front. [NaN, "host", void 0, 1, 1], // Set left over value. [/:(\d*)$/, "port", void 0, 1], // RegExp the back. [NaN, "hostname", void 0, 1, 1] // Set left over. ]; var ignore = { hash: 1, query: 1 }; function lolcation(loc) { var globalVar; if (typeof window !== "undefined") globalVar = window; else if (typeof global !== "undefined") globalVar = global; else if (typeof self !== "undefined") globalVar = self; else globalVar = {}; var location2 = globalVar.location || {}; loc = loc || location2; var finaldestination = {}, type = typeof loc, key; if ("blob:" === loc.protocol) { finaldestination = new Url(unescape(loc.pathname), {}); } else if ("string" === type) { finaldestination = new Url(loc, {}); for (key in ignore) delete finaldestination[key]; } else if ("object" === type) { for (key in loc) { if (key in ignore) continue; finaldestination[key] = loc[key]; } if (finaldestination.