UNPKG

@ai-sdk/provider-utils

Version:
1,592 lines (1,563 loc) 517 kB
"use strict"; 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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __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"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; // src/test/index.ts var test_exports = {}; __export(test_exports, { TestResponseController: () => TestResponseController, convertArrayToAsyncIterable: () => convertArrayToAsyncIterable, convertArrayToReadableStream: () => convertArrayToReadableStream, convertAsyncIterableToArray: () => convertAsyncIterableToArray, convertReadableStreamToArray: () => convertReadableStreamToArray, convertResponseStreamToArray: () => convertResponseStreamToArray, createTestServer: () => createTestServer, isNodeVersion: () => isNodeVersion, mockId: () => mockId }); module.exports = __toCommonJS(test_exports); // src/test/convert-array-to-async-iterable.ts function convertArrayToAsyncIterable(values) { return { async *[Symbol.asyncIterator]() { for (const value of values) { yield value; } } }; } // src/test/convert-array-to-readable-stream.ts function convertArrayToReadableStream(values) { return new ReadableStream({ start(controller) { try { for (const value of values) { controller.enqueue(value); } } finally { controller.close(); } } }); } // src/test/convert-async-iterable-to-array.ts async function convertAsyncIterableToArray(iterable) { const result = []; for await (const item of iterable) { result.push(item); } return result; } // src/test/convert-readable-stream-to-array.ts async function convertReadableStreamToArray(stream) { const reader = stream.getReader(); const result = []; while (true) { const { done, value } = await reader.read(); if (done) break; result.push(value); } return result; } // src/test/convert-response-stream-to-array.ts async function convertResponseStreamToArray(response) { return convertReadableStreamToArray( response.body.pipeThrough(new TextDecoderStream()) ); } // src/test/is-node-version.ts function isNodeVersion(version) { const nodeMajorVersion = parseInt(process.version.slice(1).split(".")[0], 10); return nodeMajorVersion === version; } // src/test/mock-id.ts function mockId({ prefix = "id" } = {}) { let counter = 0; return () => `${prefix}-${counter++}`; } // ../../node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/lib/index.mjs 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; } }; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/devUtils.mjs 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 }; var InternalError = class extends Error { constructor(message3) { super(message3); this.name = "InternalError"; } }; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/checkGlobals.mjs 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".` ) ); } // ../../node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs 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; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/pipeEvents.mjs function pipeEvents(source, destination) { const rawEmit = source.emit; if (rawEmit._isPiped) { return; } const sourceEmit = function sourceEmit2(event, ...data) { destination.emit(event, ...data); return rawEmit.call(this, event, ...data); }; sourceEmit._isPiped = true; source.emit = sourceEmit; } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/toReadonlyArray.mjs function toReadonlyArray(source) { const clone = [...source]; Object.freeze(clone); return clone; } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/Disposable.mjs var Disposable = class { constructor() { __publicField(this, "subscriptions", []); } dispose() { let subscription; while (subscription = this.subscriptions.shift()) { subscription(); } } }; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/SetupApi.mjs var InMemoryHandlersController = class { constructor(initialHandlers) { __publicField(this, "handlers"); this.initialHandlers = initialHandlers; this.handlers = [...initialHandlers]; } prepend(runtimeHandles) { this.handlers.unshift(...runtimeHandles); } reset(nextHandlers) { this.handlers = nextHandlers.length > 0 ? [...nextHandlers] : [...this.initialHandlers]; } currentHandlers() { return this.handlers; } }; var SetupApi = class extends Disposable { constructor(...initialHandlers) { super(); __publicField(this, "handlersController"); __publicField(this, "emitter"); __publicField(this, "publicEmitter"); __publicField(this, "events"); invariant( this.validateHandlers(initialHandlers), devUtils.formatMessage( `Failed to apply given request handlers: invalid input. Did you forget to spread the request handlers Array?` ) ); this.handlersController = new InMemoryHandlersController(initialHandlers); this.emitter = new Emitter(); this.publicEmitter = new Emitter(); pipeEvents(this.emitter, this.publicEmitter); this.events = this.createLifeCycleEvents(); this.subscriptions.push(() => { this.emitter.removeAllListeners(); this.publicEmitter.removeAllListeners(); }); } validateHandlers(handlers) { return handlers.every((handler) => !Array.isArray(handler)); } use(...runtimeHandlers) { invariant( this.validateHandlers(runtimeHandlers), devUtils.formatMessage( `Failed to call "use()" with the given request handlers: invalid input. Did you forget to spread the array of request handlers?` ) ); this.handlersController.prepend(runtimeHandlers); } restoreHandlers() { this.handlersController.currentHandlers().forEach((handler) => { if ("isUsed" in handler) { handler.isUsed = false; } }); } resetHandlers(...nextHandlers) { this.handlersController.reset(nextHandlers); } listHandlers() { return toReadonlyArray(this.handlersController.currentHandlers()); } createLifeCycleEvents() { return { on: (...args) => { return this.publicEmitter.on(...args); }, removeListener: (...args) => { return this.publicEmitter.removeListener(...args); }, removeAllListeners: (...args) => { return this.publicEmitter.removeAllListeners(...args); } }; } }; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/getCallFrame.mjs 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; } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/isIterable.mjs function isIterable(fn) { if (!fn) { return false; } return Reflect.has(fn, Symbol.iterator) || Reflect.has(fn, Symbol.asyncIterator); } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/handlers/RequestHandler.mjs var _RequestHandler = class _RequestHandler { constructor(args) { __publicField(this, "__kind"); __publicField(this, "info"); /** * Indicates whether this request handler has been used * (its resolver has successfully executed). */ __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 = _RequestHandler.cache.get(request); if (typeof existingClone !== "undefined") { return existingClone; } const clonedRequest = request.clone(); _RequestHandler.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 RequestHandler = _RequestHandler; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/internal/isStringEqual.mjs function isStringEqual(actual, expected) { return actual.toLowerCase() === expected.toLowerCase(); } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/logging/getStatusCodeColor.mjs function getStatusCodeColor(status) { if (status < 300) { return "#69AB32"; } if (status < 400) { return "#F0BB4B"; } return "#E95F5D"; } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/logging/getTimestamp.mjs function getTimestamp(options) { const now = /* @__PURE__ */ new Date(); const timestamp = `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`; if (options == null ? void 0 : options.milliseconds) { return `${timestamp}.${now.getMilliseconds().toString().padStart(3, "0")}`; } return timestamp; } // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/logging/serializeRequest.mjs async function serializeRequest(request) { const requestClone = request.clone(); const requestText = await requestClone.text(); return { url: new URL(request.url), method: request.method, headers: Object.fromEntries(request.headers.entries()), body: requestText }; } // ../../node_modules/.pnpm/@bundled-es-modules+statuses@1.0.1/node_modules/@bundled-es-modules/statuses/index-esm.js var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require2() { 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) __defProp2(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. isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, mod )); var require_codes = __commonJS({ "node_modules/statuses/codes.json"(exports2, module2) { module2.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"(exports2, module2) { "use strict"; var codes = require_codes(); module2.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); } } }); var import_statuses = __toESM2(require_statuses(), 1); var source_default = import_statuses.default; // ../../node_modules/.pnpm/msw@2.7.0_@types+node@20.17.24_typescript@5.8.3/node_modules/msw/lib/core/utils/logging/serializeResponse.mjs var { message } = source_default; async function serializeResponse(response) { const responseClone = response.clone(); const responseText = await responseClone.text(); const responseStatus = responseClone.status || 200; const responseStatusText = responseClone.statusText || message[responseStatus] || "OK"; return { status: responseStatus, statusText: responseStatusText, headers: Object.fromEntries(responseClone.headers.entries()), body: responseText }; } // ../../node_modules/.pnpm/path-to-regexp@6.3.0/node_modules/path-to-regexp/dist.es2015/index.js function lexer(str) { var tokens = []; var i = 0; while (i < str.length) { var char = str[i]; if (char === "*" || char === "+" || char === "?") { tokens.push({ type: "MODIFIER", index: i, value: str[i++] }); continue; } if (char === "\\") { tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] }); continue; } if (char === "{") { tokens.push({ type: "OPEN", index: i, value: str[i++] }); continue; } if (char === "}") { tokens.push({ type: "CLOSE", index: i, value: str[i++] }); continue; } if (char === ":") { var name = ""; var j = i + 1; while (j < str.length) { var code = str.charCodeAt(j); if ( // `0-9` code >= 48 && code <= 57 || // `A-Z` code >= 65 && code <= 90 || // `a-z` code >= 97 && code <= 122 || // `_` code === 95 ) { name += str[j++]; continue; } break; } if (!name) throw new TypeError("Missing parameter name at ".concat(i)); tokens.push({ type: "NAME", index: i, value: name }); i = j; continue; } if (char === "(") { var count = 1; var pattern = ""; var j = i + 1; if (str[j] === "?") { throw new TypeError('Pattern cannot start with "?" at '.concat(j)); } while (j < str.length) { if (str[j] === "\\") { pattern += str[j++] + str[j++]; continue; } if (str[j] === ")") { count--; if (count === 0) { j++; break; } } else if (str[j] === "(") { count++; if (str[j + 1] !== "?") { throw new TypeError("Capturing groups are not allowed at ".concat(j)); } } pattern += str[j++]; } if (count) throw new TypeError("Unbalanced pattern at ".concat(i)); if (!pattern) throw new TypeError("Missing pattern at ".concat(i)); tokens.push({ type: "PATTERN", index: i, value: pattern }); i = j; continue; } tokens.push({ type: "CHAR", index: i, value: str[i++] }); } tokens.push({ type: "END", index: i, value: "" }); return tokens; } function parse(str, options) { if (options === void 0) { options = {}; } var tokens = lexer(str); var _a4 = options.prefixes, prefixes = _a4 === void 0 ? "./" : _a4, _b2 = options.delimiter, delimiter = _b2 === void 0 ? "/#?" : _b2; var result = []; var key = 0; var i = 0; var path = ""; var tryConsume = function(type) { if (i < tokens.length && tokens[i].type === type) return tokens[i++].value; }; var mustConsume = function(type) { var value2 = tryConsume(type); if (value2 !== void 0) return value2; var _a5 = tokens[i], nextType = _a5.type, index = _a5.index; throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type)); }; var consumeText = function() { var result2 = ""; var value2; while (value2 = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR")) { result2 += value2; } return result2; }; var isSafe = function(value2) { for (var _i = 0, delimiter_1 = delimiter; _i < delimiter_1.length; _i++) { var char2 = delimiter_1[_i]; if (value2.indexOf(char2) > -1) return true; } return false; }; var safePattern = function(prefix2) { var prev = result[result.length - 1]; var prevText = prefix2 || (prev && typeof prev === "string" ? prev : ""); if (prev && !prevText) { throw new TypeError('Must have text between two parameters, missing text after "'.concat(prev.name, '"')); } if (!prevText || isSafe(prevText)) return "[^".concat(escapeString(delimiter), "]+?"); return "(?:(?!".concat(escapeString(prevText), ")[^").concat(escapeString(delimiter), "])+?"); }; while (i < tokens.length) { var char = tryConsume("CHAR"); var name = tryConsume("NAME"); var pattern = tryConsume("PATTERN"); if (name || pattern) { var prefix = char || ""; if (prefixes.indexOf(prefix) === -1) { path += prefix; prefix = ""; } if (path) { result.push(path); path = ""; } result.push({ name: name || key++, prefix, suffix: "", pattern: pattern || safePattern(prefix), modifier: tryConsume("MODIFIER") || "" }); continue; } var value = char || tryConsume("ESCAPED_CHAR"); if (value) { path += value; continue; } if (path) { result.push(path); path = ""; } var open = tryConsume("OPEN"); if (open) { var prefix = consumeText(); var name_1 = tryConsume("NAME") || ""; var pattern_1 = tryConsume("PATTERN") || ""; var suffix = consumeText(); mustConsume("CLOSE"); result.push({ name: name_1 || (pattern_1 ? key++ : ""), pattern: name_1 && !pattern_1 ? safePattern(prefix) : pattern_1, prefix, suffix, modifier: tryConsume("MODIFIER") || "" }); continue; } mustConsume("END"); } return result; } function match(str, options) { var keys = []; var re = pathToRegexp(str, keys, options); return regexpToFunction(re, keys, options); } function regexpToFunction(re, keys, options) { if (options === void 0) { options = {}; } var _a4 = options.decode, decode = _a4 === void 0 ? function(x) { return x; } : _a4; return function(pathname) { var m = re.exec(pathname); if (!m) return false; var path = m[0], index = m.index; var params = /* @__PURE__ */ Object.create(null); var _loop_1 = function(i2) { if (m[i2] === void 0) return "continue"; var key = keys[i2 - 1]; if (key.modifier === "*" || key.modifier === "+") { params[key.name] = m[i2].split(key.prefix + key.suffix).map(function(value) { return decode(value, key); }); } else { params[key.name] = decode(m[i2], key); } }; for (var i = 1; i < m.length; i++) { _loop_1(i); } return { path, index, params }; }; } function escapeString(str) { return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1"); } function flags(options) { return options && options.sensitive ? "" : "i"; } function regexpToRegexp(path, keys) { if (!keys) return path; var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g; var index = 0; var execResult = groupsRegex.exec(path.source); while (execResult) { keys.push({ // Use parenthesized substring match if available, index otherwise name: execResult[1] || index++, prefix: "", suffix: "", modifier: "", pattern: "" }); execResult = groupsRegex.exec(path.source); } return path; } function arrayToRegexp(paths, keys, options) { var parts = paths.map(function(path) { return pathToRegexp(path, keys, options).source; }); return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options)); } function stringToRegexp(path, keys, options) { return tokensToRegexp(parse(path, options), keys, options); } function tokensToRegexp(tokens, keys, options) { if (options === void 0) { options = {}; } var _a4 = options.strict, strict = _a4 === void 0 ? false : _a4, _b2 = options.start, start = _b2 === void 0 ? true : _b2, _c2 = options.end, end = _c2 === void 0 ? true : _c2, _d = options.encode, encode = _d === void 0 ? function(x) { return x; } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f; var endsWithRe = "[".concat(escapeString(endsWith), "]|$"); var delimiterRe = "[".concat(escapeString(delimiter), "]"); var route = start ? "^" : ""; for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) { var token = tokens_1[_i]; if (typeof token === "string") { route += escapeString(encode(token)); } else { var prefix = escapeString(encode(token.prefix)); var suffix = escapeString(encode(token.suffix)); if (token.pattern) { if (keys) keys.push(token); if (prefix || suffix) { if (token.modifier === "+" || token.modifier === "*") { var mod = token.modifier === "*" ? "?" : ""; route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod); } else { route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier); } } else { if (token.modifier === "+" || token.modifier === "*") { throw new TypeError('Can not repeat "'.concat(token.name, '" without a prefix and suffix')); } route += "(".concat(token.pattern, ")").concat(token.modifier); } } else { route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier); } } } if (end) { if (!strict) route += "".concat(delimiterRe, "?"); route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")"); } else { var endToken = tokens[tokens.length - 1]; var isEndDelimited = typeof endToken === "string" ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1 : endToken === void 0; if (!strict) { route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?"); } if (!isEndDelimited) { route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")"); } } return new RegExp(route, flags(options)); } function pathToRegexp(path, keys, options) { if (path instanceof RegExp) return regexpToRegexp(path, keys); if (Array.isArray(path)) return arrayToRegexp(path, keys, options); return stringToRegexp(path, keys, options); } // ../../node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs 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; } // ../../node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs var __defProp3 = Object.defineProperty; var __export2 = (target, all) => { for (var name in all) __defProp3(target, name, { get: all[name], enumerable: true }); }; var colors_exports = {}; __export2(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(); } // ../../node_modules/.pnpm/@mswjs+interceptors@0.37.5/node_modules/@mswjs/interceptors/lib/node/chunk-I7HQIBT7.mjs var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; function getGlobalSymbol(symbol) { return ( // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 globalThis[symbol] || void 0 ); } function setGlobalSymbol(symbol, value) { globalThis[symbol] = value; } function deleteGlobalSymbol(symbol) { delete globalThis[symbol]; } var InterceptorReadyState = /* @__PURE__ */ ((InterceptorReadyState2) => { InterceptorReadyState2["INACTIVE"] = "INACTIVE"; InterceptorReadyState2["APPLYING"] = "APPLYING"; InterceptorReadyState2["APPLIED"] = "APPLIED"; InterceptorReadyState2["DISPOSING"] = "DISPOSING"; InterceptorReadyState2["DISPOSED"] = "DISPOSED"; return InterceptorReadyState2; })(InterceptorReadyState || {}); var Interceptor = class { constructor(symbol) { this.symbol = symbol; this.readyState = "INACTIVE"; this.emitter = new Emitter(); this.subscriptions = []; this.logger = new Logger(symbol.description); this.emitter.setMaxListeners(0); this.logger.info("constructing the interceptor..."); } /** * Determine if this interceptor can be applied * in the current environment. */ checkEnvironment() { return true; } /** * Apply this interceptor to the current process. * Returns an already running interceptor instance if it's present. */ apply() { const logger4 = this.logger.extend("apply"); logger4.info("applying the interceptor..."); if (this.readyState === "APPLIED") { logger4.info("intercepted already applied!"); return; } const shouldApply = this.checkEnvironment(); if (!shouldApply) { logger4.info("the interc