- Vue 3 + TypeScript + Element Plus 前端界面 - Pinia 状态管理 - Vue Router 4 路由管理 - Axios HTTP 客户端 - MSW (Mock Service Worker) 开发环境模拟 - 账户管理界面 (列表、详情、三科目余额展示) - 交易管理界面 (列表、详情) - 对账管理界面 (三账校验) - 完善的 API 客户端封装 - Docker 容器化配置 - Nginx 配置用于生产环境
2675 lines
83 KiB
JavaScript
2675 lines
83 KiB
JavaScript
import {
|
||
parse
|
||
} from "./chunk-ZMZWMYZI.js";
|
||
import {
|
||
DeferredPromise,
|
||
Emitter,
|
||
RequestHandler,
|
||
SetupApi,
|
||
__privateAdd as __privateAdd2,
|
||
__privateGet as __privateGet2,
|
||
colors,
|
||
cookieStore,
|
||
createRequestId,
|
||
decorateResponse,
|
||
devUtils,
|
||
executeHandlers,
|
||
getCallFrame,
|
||
getTimestamp,
|
||
handleRequest,
|
||
invariant,
|
||
isCommonAssetRequest,
|
||
isNodeProcess,
|
||
jsonParse,
|
||
normalizeResponseInit,
|
||
onUnhandledRequest,
|
||
statuses_default,
|
||
stringToHeaders,
|
||
toPublicUrl
|
||
} from "./chunk-JLOFLLAE.js";
|
||
import {
|
||
__privateAdd,
|
||
__privateGet,
|
||
__privateMethod,
|
||
__privateSet,
|
||
__publicField
|
||
} from "./chunk-DWA4UIM3.js";
|
||
|
||
// 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/msw/lib/core/utils/internal/isStringEqual.mjs
|
||
function isStringEqual(actual, expected) {
|
||
return actual.toLowerCase() === expected.toLowerCase();
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/logging/getStatusCodeColor.mjs
|
||
var StatusCodeColor = ((StatusCodeColor2) => {
|
||
StatusCodeColor2["Success"] = "#69AB32";
|
||
StatusCodeColor2["Warning"] = "#F0BB4B";
|
||
StatusCodeColor2["Danger"] = "#E95F5D";
|
||
return StatusCodeColor2;
|
||
})(StatusCodeColor || {});
|
||
function getStatusCodeColor(status) {
|
||
if (status < 300) {
|
||
return "#69AB32";
|
||
}
|
||
if (status < 400) {
|
||
return "#F0BB4B";
|
||
}
|
||
return "#E95F5D";
|
||
}
|
||
|
||
// 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/msw/lib/core/utils/logging/serializeResponse.mjs
|
||
var { message } = statuses_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/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 parse2(str, options) {
|
||
if (options === void 0) {
|
||
options = {};
|
||
}
|
||
var tokens = lexer(str);
|
||
var _a4 = options.prefixes, prefixes = _a4 === void 0 ? "./" : _a4, _b3 = options.delimiter, delimiter = _b3 === void 0 ? "/#?" : _b3;
|
||
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 _i2 = 0, delimiter_1 = delimiter; _i2 < delimiter_1.length; _i2++) {
|
||
var char2 = delimiter_1[_i2];
|
||
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(parse2(path, options), keys, options);
|
||
}
|
||
function tokensToRegexp(tokens, keys, options) {
|
||
if (options === void 0) {
|
||
options = {};
|
||
}
|
||
var _a4 = options.strict, strict = _a4 === void 0 ? false : _a4, _b3 = options.start, start = _b3 === void 0 ? true : _b3, _c2 = options.end, end = _c2 === void 0 ? true : _c2, _d2 = options.encode, encode = _d2 === void 0 ? function(x) {
|
||
return x;
|
||
} : _d2, _e2 = options.delimiter, delimiter = _e2 === void 0 ? "/#?" : _e2, _f2 = options.endsWith, endsWith = _f2 === void 0 ? "" : _f2;
|
||
var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
|
||
var delimiterRe = "[".concat(escapeString(delimiter), "]");
|
||
var route = start ? "^" : "";
|
||
for (var _i2 = 0, tokens_1 = tokens; _i2 < tokens_1.length; _i2++) {
|
||
var token = tokens_1[_i2];
|
||
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/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs
|
||
var encoder = new TextEncoder();
|
||
|
||
// node_modules/@mswjs/interceptors/lib/browser/chunk-LIKZF2VU.mjs
|
||
var IS_PATCHED_MODULE = Symbol("isPatchedModule");
|
||
var InterceptorError = class extends Error {
|
||
constructor(message2) {
|
||
super(message2);
|
||
this.name = "InterceptorError";
|
||
Object.setPrototypeOf(this, InterceptorError.prototype);
|
||
}
|
||
};
|
||
var _handled;
|
||
var handled_get;
|
||
var _RequestController = class {
|
||
constructor(request, source) {
|
||
this.request = request;
|
||
this.source = source;
|
||
__privateAdd2(this, _handled);
|
||
this.readyState = _RequestController.PENDING;
|
||
this.handled = new DeferredPromise();
|
||
}
|
||
/**
|
||
* Perform this request as-is.
|
||
*/
|
||
async passthrough() {
|
||
invariant.as(
|
||
InterceptorError,
|
||
this.readyState === _RequestController.PENDING,
|
||
'Failed to passthrough the "%s %s" request: the request has already been handled',
|
||
this.request.method,
|
||
this.request.url
|
||
);
|
||
this.readyState = _RequestController.PASSTHROUGH;
|
||
await this.source.passthrough();
|
||
__privateGet2(this, _handled, handled_get).resolve();
|
||
}
|
||
/**
|
||
* Respond to this request with the given `Response` instance.
|
||
*
|
||
* @example
|
||
* controller.respondWith(new Response())
|
||
* controller.respondWith(Response.json({ id }))
|
||
* controller.respondWith(Response.error())
|
||
*/
|
||
respondWith(response) {
|
||
invariant.as(
|
||
InterceptorError,
|
||
this.readyState === _RequestController.PENDING,
|
||
'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)',
|
||
this.request.method,
|
||
this.request.url,
|
||
response.status,
|
||
response.statusText || "OK",
|
||
this.readyState
|
||
);
|
||
this.readyState = _RequestController.RESPONSE;
|
||
__privateGet2(this, _handled, handled_get).resolve();
|
||
this.source.respondWith(response);
|
||
}
|
||
/**
|
||
* Error this request with the given reason.
|
||
*
|
||
* @example
|
||
* controller.errorWith()
|
||
* controller.errorWith(new Error('Oops!'))
|
||
* controller.errorWith({ message: 'Oops!'})
|
||
*/
|
||
errorWith(reason) {
|
||
invariant.as(
|
||
InterceptorError,
|
||
this.readyState === _RequestController.PENDING,
|
||
'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)',
|
||
this.request.method,
|
||
this.request.url,
|
||
reason == null ? void 0 : reason.toString(),
|
||
this.readyState
|
||
);
|
||
this.readyState = _RequestController.ERROR;
|
||
this.source.errorWith(reason);
|
||
__privateGet2(this, _handled, handled_get).resolve();
|
||
}
|
||
};
|
||
var RequestController = _RequestController;
|
||
_handled = /* @__PURE__ */ new WeakSet();
|
||
handled_get = function() {
|
||
return this.handled;
|
||
};
|
||
RequestController.PENDING = 0;
|
||
RequestController.PASSTHROUGH = 1;
|
||
RequestController.RESPONSE = 2;
|
||
RequestController.ERROR = 3;
|
||
function canParseUrl(url) {
|
||
try {
|
||
new URL(url);
|
||
return true;
|
||
} catch (_error) {
|
||
return false;
|
||
}
|
||
}
|
||
function getValueBySymbol(symbolName, source) {
|
||
const ownSymbols = Object.getOwnPropertySymbols(source);
|
||
const symbol = ownSymbols.find((symbol2) => {
|
||
return symbol2.description === symbolName;
|
||
});
|
||
if (symbol) {
|
||
return Reflect.get(source, symbol);
|
||
}
|
||
return;
|
||
}
|
||
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 || url === "about:" || !canParseUrl(url)) {
|
||
return;
|
||
}
|
||
const state = getValueBySymbol("state", response);
|
||
if (state) {
|
||
state.urlList.push(new URL(url));
|
||
} else {
|
||
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, {
|
||
status: safeStatus,
|
||
statusText: init.statusText,
|
||
headers: init.headers
|
||
});
|
||
if (status !== safeStatus) {
|
||
const state = getValueBySymbol("state", this);
|
||
if (state) {
|
||
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];
|
||
var kRawRequest = Symbol("kRawRequest");
|
||
|
||
// node_modules/@mswjs/interceptors/lib/browser/index.mjs
|
||
function getCleanUrl(url, isAbsolute = true) {
|
||
return [isAbsolute && url.origin, url.pathname].filter(Boolean).join("");
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/url/cleanUrl.mjs
|
||
var REDUNDANT_CHARACTERS_EXP = /[?|#].*$/g;
|
||
function cleanUrl(path) {
|
||
if (path.endsWith("?")) {
|
||
return path;
|
||
}
|
||
return path.replace(REDUNDANT_CHARACTERS_EXP, "");
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/url/isAbsoluteUrl.mjs
|
||
function isAbsoluteUrl(url) {
|
||
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/url/getAbsoluteUrl.mjs
|
||
function getAbsoluteUrl(path, baseUrl) {
|
||
if (isAbsoluteUrl(path)) {
|
||
return path;
|
||
}
|
||
if (path.startsWith("*")) {
|
||
return path;
|
||
}
|
||
const origin = baseUrl || typeof location !== "undefined" && location.href;
|
||
return origin ? (
|
||
// Encode and decode the path to preserve escaped characters.
|
||
decodeURI(new URL(encodeURI(path), origin).href)
|
||
) : path;
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/matching/normalizePath.mjs
|
||
function normalizePath(path, baseUrl) {
|
||
if (path instanceof RegExp) {
|
||
return path;
|
||
}
|
||
const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
|
||
return cleanUrl(maybeAbsoluteUrl);
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/matching/matchRequestUrl.mjs
|
||
function coercePath(path) {
|
||
return path.replace(
|
||
/([:a-zA-Z_-]*)(\*{1,2})+/g,
|
||
(_, parameterName, wildcard) => {
|
||
const expression = "(.*)";
|
||
if (!parameterName) {
|
||
return expression;
|
||
}
|
||
return parameterName.startsWith(":") ? `${parameterName}${wildcard}` : `${parameterName}${expression}`;
|
||
}
|
||
).replace(/([^/])(:)(?=\d+)/, "$1\\$2").replace(/^([^/]+)(:)(?=\/\/)/, "$1\\$2");
|
||
}
|
||
function matchRequestUrl(url, path, baseUrl) {
|
||
const normalizedPath = normalizePath(path, baseUrl);
|
||
const cleanPath = typeof normalizedPath === "string" ? coercePath(normalizedPath) : normalizedPath;
|
||
const cleanUrl2 = getCleanUrl(url);
|
||
const result = match(cleanPath, { decode: decodeURIComponent })(cleanUrl2);
|
||
const params = result && result.params || {};
|
||
return {
|
||
matches: result !== false,
|
||
params
|
||
};
|
||
}
|
||
function isPath(value) {
|
||
return typeof value === "string" || value instanceof RegExp;
|
||
}
|
||
|
||
// node_modules/msw/lib/shims/cookie.mjs
|
||
var __create = Object.create;
|
||
var __defProp = Object.defineProperty;
|
||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||
var __getProtoOf = Object.getPrototypeOf;
|
||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||
var __commonJS = (cb, mod) => function __require() {
|
||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
||
};
|
||
var __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 require_dist = __commonJS({
|
||
"node_modules/.pnpm/cookie@1.0.2/node_modules/cookie/dist/index.js"(exports) {
|
||
"use strict";
|
||
Object.defineProperty(exports, "__esModule", { value: true });
|
||
exports.parse = parse22;
|
||
exports.serialize = serialize2;
|
||
var cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
|
||
var cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
|
||
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]*$/;
|
||
var __toString = Object.prototype.toString;
|
||
var NullObject = (() => {
|
||
const C = function() {
|
||
};
|
||
C.prototype = /* @__PURE__ */ Object.create(null);
|
||
return C;
|
||
})();
|
||
function parse22(str, options) {
|
||
const obj = new NullObject();
|
||
const len = str.length;
|
||
if (len < 2)
|
||
return obj;
|
||
const dec = (options == null ? void 0 : options.decode) || decode;
|
||
let index = 0;
|
||
do {
|
||
const eqIdx = str.indexOf("=", index);
|
||
if (eqIdx === -1)
|
||
break;
|
||
const colonIdx = str.indexOf(";", index);
|
||
const endIdx = colonIdx === -1 ? len : colonIdx;
|
||
if (eqIdx > endIdx) {
|
||
index = str.lastIndexOf(";", eqIdx - 1) + 1;
|
||
continue;
|
||
}
|
||
const keyStartIdx = startIndex(str, index, eqIdx);
|
||
const keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
|
||
const key = str.slice(keyStartIdx, keyEndIdx);
|
||
if (obj[key] === void 0) {
|
||
let valStartIdx = startIndex(str, eqIdx + 1, endIdx);
|
||
let valEndIdx = endIndex(str, endIdx, valStartIdx);
|
||
const value = dec(str.slice(valStartIdx, valEndIdx));
|
||
obj[key] = value;
|
||
}
|
||
index = endIdx + 1;
|
||
} while (index < len);
|
||
return obj;
|
||
}
|
||
function startIndex(str, index, max) {
|
||
do {
|
||
const code = str.charCodeAt(index);
|
||
if (code !== 32 && code !== 9)
|
||
return index;
|
||
} while (++index < max);
|
||
return max;
|
||
}
|
||
function endIndex(str, index, min) {
|
||
while (index > min) {
|
||
const code = str.charCodeAt(--index);
|
||
if (code !== 32 && code !== 9)
|
||
return index + 1;
|
||
}
|
||
return min;
|
||
}
|
||
function serialize2(name, val, options) {
|
||
const enc = (options == null ? void 0 : options.encode) || encodeURIComponent;
|
||
if (!cookieNameRegExp.test(name)) {
|
||
throw new TypeError(`argument name is invalid: ${name}`);
|
||
}
|
||
const value = enc(val);
|
||
if (!cookieValueRegExp.test(value)) {
|
||
throw new TypeError(`argument val is invalid: ${val}`);
|
||
}
|
||
let str = name + "=" + value;
|
||
if (!options)
|
||
return str;
|
||
if (options.maxAge !== void 0) {
|
||
if (!Number.isInteger(options.maxAge)) {
|
||
throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);
|
||
}
|
||
str += "; Max-Age=" + options.maxAge;
|
||
}
|
||
if (options.domain) {
|
||
if (!domainValueRegExp.test(options.domain)) {
|
||
throw new TypeError(`option domain is invalid: ${options.domain}`);
|
||
}
|
||
str += "; Domain=" + options.domain;
|
||
}
|
||
if (options.path) {
|
||
if (!pathValueRegExp.test(options.path)) {
|
||
throw new TypeError(`option path is invalid: ${options.path}`);
|
||
}
|
||
str += "; Path=" + options.path;
|
||
}
|
||
if (options.expires) {
|
||
if (!isDate(options.expires) || !Number.isFinite(options.expires.valueOf())) {
|
||
throw new TypeError(`option expires is invalid: ${options.expires}`);
|
||
}
|
||
str += "; Expires=" + options.expires.toUTCString();
|
||
}
|
||
if (options.httpOnly) {
|
||
str += "; HttpOnly";
|
||
}
|
||
if (options.secure) {
|
||
str += "; Secure";
|
||
}
|
||
if (options.partitioned) {
|
||
str += "; Partitioned";
|
||
}
|
||
if (options.priority) {
|
||
const priority = typeof options.priority === "string" ? options.priority.toLowerCase() : void 0;
|
||
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: ${options.priority}`);
|
||
}
|
||
}
|
||
if (options.sameSite) {
|
||
const sameSite = typeof options.sameSite === "string" ? options.sameSite.toLowerCase() : options.sameSite;
|
||
switch (sameSite) {
|
||
case true:
|
||
case "strict":
|
||
str += "; SameSite=Strict";
|
||
break;
|
||
case "lax":
|
||
str += "; SameSite=Lax";
|
||
break;
|
||
case "none":
|
||
str += "; SameSite=None";
|
||
break;
|
||
default:
|
||
throw new TypeError(`option sameSite is invalid: ${options.sameSite}`);
|
||
}
|
||
}
|
||
return str;
|
||
}
|
||
function decode(str) {
|
||
if (str.indexOf("%") === -1)
|
||
return str;
|
||
try {
|
||
return decodeURIComponent(str);
|
||
} catch (e) {
|
||
return str;
|
||
}
|
||
}
|
||
function isDate(val) {
|
||
return __toString.call(val) === "[object Date]";
|
||
}
|
||
}
|
||
});
|
||
var allCookie = __toESM(require_dist(), 1);
|
||
var cookie = allCookie.default || allCookie;
|
||
var parse3 = cookie.parse;
|
||
var serialize = cookie.serialize;
|
||
|
||
// node_modules/msw/lib/core/utils/request/getRequestCookies.mjs
|
||
function parseCookies(input) {
|
||
const parsedCookies = parse3(input);
|
||
const cookies = {};
|
||
for (const cookieName in parsedCookies) {
|
||
if (typeof parsedCookies[cookieName] !== "undefined") {
|
||
cookies[cookieName] = parsedCookies[cookieName];
|
||
}
|
||
}
|
||
return cookies;
|
||
}
|
||
function getAllDocumentCookies() {
|
||
return parseCookies(document.cookie);
|
||
}
|
||
function getDocumentCookies(request) {
|
||
if (typeof document === "undefined" || typeof location === "undefined") {
|
||
return {};
|
||
}
|
||
switch (request.credentials) {
|
||
case "same-origin": {
|
||
const requestUrl = new URL(request.url);
|
||
return location.origin === requestUrl.origin ? getAllDocumentCookies() : {};
|
||
}
|
||
case "include": {
|
||
return getAllDocumentCookies();
|
||
}
|
||
default: {
|
||
return {};
|
||
}
|
||
}
|
||
}
|
||
function getAllRequestCookies(request) {
|
||
const requestCookieHeader = request.headers.get("cookie");
|
||
const cookiesFromHeaders = requestCookieHeader ? parseCookies(requestCookieHeader) : {};
|
||
const cookiesFromDocument = getDocumentCookies(request);
|
||
for (const name in cookiesFromDocument) {
|
||
request.headers.append(
|
||
"cookie",
|
||
serialize(name, cookiesFromDocument[name])
|
||
);
|
||
}
|
||
const cookiesFromStore = cookieStore.getCookies(request.url);
|
||
const storedCookiesObject = Object.fromEntries(
|
||
cookiesFromStore.map((cookie2) => [cookie2.key, cookie2.value])
|
||
);
|
||
for (const cookie2 of cookiesFromStore) {
|
||
request.headers.append("cookie", cookie2.toString());
|
||
}
|
||
return {
|
||
...cookiesFromDocument,
|
||
...storedCookiesObject,
|
||
...cookiesFromHeaders
|
||
};
|
||
}
|
||
|
||
// node_modules/msw/lib/core/handlers/HttpHandler.mjs
|
||
var HttpMethods = ((HttpMethods2) => {
|
||
HttpMethods2["HEAD"] = "HEAD";
|
||
HttpMethods2["GET"] = "GET";
|
||
HttpMethods2["POST"] = "POST";
|
||
HttpMethods2["PUT"] = "PUT";
|
||
HttpMethods2["PATCH"] = "PATCH";
|
||
HttpMethods2["OPTIONS"] = "OPTIONS";
|
||
HttpMethods2["DELETE"] = "DELETE";
|
||
return HttpMethods2;
|
||
})(HttpMethods || {});
|
||
var HttpHandler = class extends RequestHandler {
|
||
constructor(method, predicate, resolver, options) {
|
||
const displayPath = typeof predicate === "function" ? "[custom predicate]" : predicate;
|
||
super({
|
||
info: {
|
||
header: `${method}${displayPath ? ` ${displayPath}` : ""}`,
|
||
path: predicate,
|
||
method
|
||
},
|
||
resolver,
|
||
options
|
||
});
|
||
this.checkRedundantQueryParameters();
|
||
}
|
||
checkRedundantQueryParameters() {
|
||
const { method, path } = this.info;
|
||
if (!path || path instanceof RegExp || typeof path === "function") {
|
||
return;
|
||
}
|
||
const url = cleanUrl(path);
|
||
if (url === path) {
|
||
return;
|
||
}
|
||
devUtils.warn(
|
||
`Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters using "new URL(request.url).searchParams" instead. Learn more: https://mswjs.io/docs/http/intercepting-requests#querysearch-parameters`
|
||
);
|
||
}
|
||
async parse(args) {
|
||
var _a4;
|
||
const url = new URL(args.request.url);
|
||
const cookies = getAllRequestCookies(args.request);
|
||
if (typeof this.info.path === "function") {
|
||
const customPredicateResult = await this.info.path({
|
||
request: args.request,
|
||
cookies
|
||
});
|
||
const match22 = typeof customPredicateResult === "boolean" ? {
|
||
matches: customPredicateResult,
|
||
params: {}
|
||
} : customPredicateResult;
|
||
return {
|
||
match: match22,
|
||
cookies
|
||
};
|
||
}
|
||
const match2 = this.info.path ? matchRequestUrl(url, this.info.path, (_a4 = args.resolutionContext) == null ? void 0 : _a4.baseUrl) : { matches: false, params: {} };
|
||
return {
|
||
match: match2,
|
||
cookies
|
||
};
|
||
}
|
||
async predicate(args) {
|
||
const hasMatchingMethod = this.matchMethod(args.request.method);
|
||
const hasMatchingUrl = args.parsedResult.match.matches;
|
||
return hasMatchingMethod && hasMatchingUrl;
|
||
}
|
||
matchMethod(actualMethod) {
|
||
return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : isStringEqual(this.info.method, actualMethod);
|
||
}
|
||
extendResolverArgs(args) {
|
||
var _a4;
|
||
return {
|
||
params: ((_a4 = args.parsedResult.match) == null ? void 0 : _a4.params) || {},
|
||
cookies: args.parsedResult.cookies
|
||
};
|
||
}
|
||
async log(args) {
|
||
const publicUrl = toPublicUrl(args.request.url);
|
||
const loggedRequest = await serializeRequest(args.request);
|
||
const loggedResponse = await serializeResponse(args.response);
|
||
const statusColor = getStatusCodeColor(loggedResponse.status);
|
||
console.groupCollapsed(
|
||
devUtils.formatMessage(
|
||
`${getTimestamp()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
|
||
),
|
||
`color:${statusColor}`,
|
||
"color:inherit"
|
||
);
|
||
console.log("Request", loggedRequest);
|
||
console.log("Handler:", this);
|
||
console.log("Response", loggedResponse);
|
||
console.groupEnd();
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/http.mjs
|
||
function createHttpHandler(method) {
|
||
return (predicate, resolver, options = {}) => {
|
||
return new HttpHandler(method, predicate, resolver, options);
|
||
};
|
||
}
|
||
var http = {
|
||
all: createHttpHandler(/.+/),
|
||
head: createHttpHandler(HttpMethods.HEAD),
|
||
get: createHttpHandler(HttpMethods.GET),
|
||
post: createHttpHandler(HttpMethods.POST),
|
||
put: createHttpHandler(HttpMethods.PUT),
|
||
delete: createHttpHandler(HttpMethods.DELETE),
|
||
patch: createHttpHandler(HttpMethods.PATCH),
|
||
options: createHttpHandler(HttpMethods.OPTIONS)
|
||
};
|
||
|
||
// node_modules/msw/lib/core/utils/internal/parseMultipartData.mjs
|
||
function parseContentHeaders(headersString) {
|
||
var _a4, _b3;
|
||
const headers = stringToHeaders(headersString);
|
||
const contentType = headers.get("content-type") || "text/plain";
|
||
const disposition = headers.get("content-disposition");
|
||
if (!disposition) {
|
||
throw new Error('"Content-Disposition" header is required.');
|
||
}
|
||
const directives = disposition.split(";").reduce((acc, chunk) => {
|
||
const [name2, ...rest] = chunk.trim().split("=");
|
||
acc[name2] = rest.join("=");
|
||
return acc;
|
||
}, {});
|
||
const name = (_a4 = directives.name) == null ? void 0 : _a4.slice(1, -1);
|
||
const filename = (_b3 = directives.filename) == null ? void 0 : _b3.slice(1, -1);
|
||
return {
|
||
name,
|
||
filename,
|
||
contentType
|
||
};
|
||
}
|
||
function parseMultipartData(data, headers) {
|
||
const contentType = headers == null ? void 0 : headers.get("content-type");
|
||
if (!contentType) {
|
||
return void 0;
|
||
}
|
||
const [, ...directives] = contentType.split(/; */);
|
||
const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
|
||
if (!boundary) {
|
||
return void 0;
|
||
}
|
||
const boundaryRegExp = new RegExp(`--+${boundary}`);
|
||
const fields = data.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
|
||
if (!fields.length) {
|
||
return void 0;
|
||
}
|
||
const parsedBody = {};
|
||
try {
|
||
for (const field of fields) {
|
||
const [contentHeaders, ...rest] = field.split("\r\n\r\n");
|
||
const contentBody = rest.join("\r\n\r\n");
|
||
const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
|
||
const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
|
||
const parsedValue = parsedBody[name];
|
||
if (parsedValue === void 0) {
|
||
parsedBody[name] = value;
|
||
} else if (Array.isArray(parsedValue)) {
|
||
parsedBody[name] = [...parsedValue, value];
|
||
} else {
|
||
parsedBody[name] = [parsedValue, value];
|
||
}
|
||
}
|
||
return parsedBody;
|
||
} catch {
|
||
return void 0;
|
||
}
|
||
}
|
||
|
||
// node_modules/msw/lib/core/utils/internal/parseGraphQLRequest.mjs
|
||
function parseDocumentNode(node) {
|
||
var _a4;
|
||
const operationDef = node.definitions.find((definition) => {
|
||
return definition.kind === "OperationDefinition";
|
||
});
|
||
return {
|
||
operationType: operationDef == null ? void 0 : operationDef.operation,
|
||
operationName: (_a4 = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a4.value
|
||
};
|
||
}
|
||
async function parseQuery(query) {
|
||
const { parse: parse4 } = await import("./graphql-55Y3X5ZY.js").catch((error) => {
|
||
console.error('[MSW] Failed to parse a GraphQL query: cannot import the "graphql" module. Please make sure you install it if you wish to intercept GraphQL requests. See the original import error below.');
|
||
throw error;
|
||
});
|
||
try {
|
||
const ast = parse4(query);
|
||
return parseDocumentNode(ast);
|
||
} catch (error) {
|
||
return error;
|
||
}
|
||
}
|
||
function extractMultipartVariables(variables, map, files) {
|
||
const operations = { variables };
|
||
for (const [key, pathArray] of Object.entries(map)) {
|
||
if (!(key in files)) {
|
||
throw new Error(`Given files do not have a key '${key}' .`);
|
||
}
|
||
for (const dotPath of pathArray) {
|
||
const [lastPath, ...reversedPaths] = dotPath.split(".").reverse();
|
||
const paths = reversedPaths.reverse();
|
||
let target = operations;
|
||
for (const path of paths) {
|
||
if (!(path in target)) {
|
||
throw new Error(`Property '${paths}' is not in operations.`);
|
||
}
|
||
target = target[path];
|
||
}
|
||
target[lastPath] = files[key];
|
||
}
|
||
}
|
||
return operations.variables;
|
||
}
|
||
async function getGraphQLInput(request) {
|
||
var _a4;
|
||
switch (request.method) {
|
||
case "GET": {
|
||
const url = new URL(request.url);
|
||
const query = url.searchParams.get("query");
|
||
const variables = url.searchParams.get("variables") || "";
|
||
return {
|
||
query,
|
||
variables: jsonParse(variables)
|
||
};
|
||
}
|
||
case "POST": {
|
||
const requestClone = request.clone();
|
||
if ((_a4 = request.headers.get("content-type")) == null ? void 0 : _a4.includes("multipart/form-data")) {
|
||
const responseJson = parseMultipartData(
|
||
await requestClone.text(),
|
||
request.headers
|
||
);
|
||
if (!responseJson) {
|
||
return null;
|
||
}
|
||
const { operations, map, ...files } = responseJson;
|
||
const parsedOperations = jsonParse(
|
||
operations
|
||
) || {};
|
||
if (!parsedOperations.query) {
|
||
return null;
|
||
}
|
||
const parsedMap = jsonParse(map || "") || {};
|
||
const variables = parsedOperations.variables ? extractMultipartVariables(
|
||
parsedOperations.variables,
|
||
parsedMap,
|
||
files
|
||
) : {};
|
||
return {
|
||
query: parsedOperations.query,
|
||
variables
|
||
};
|
||
}
|
||
const requestJson = await requestClone.json().catch(() => null);
|
||
if (requestJson == null ? void 0 : requestJson.query) {
|
||
const { query, variables } = requestJson;
|
||
return {
|
||
query,
|
||
variables
|
||
};
|
||
}
|
||
return null;
|
||
}
|
||
default:
|
||
return null;
|
||
}
|
||
}
|
||
async function parseGraphQLRequest(request) {
|
||
const input = await getGraphQLInput(request);
|
||
if (!input || !input.query) {
|
||
return;
|
||
}
|
||
const { query, variables } = input;
|
||
const parsedResult = await parseQuery(query);
|
||
if (parsedResult instanceof Error) {
|
||
const requestPublicUrl = toPublicUrl(request.url);
|
||
throw new Error(
|
||
devUtils.formatMessage(
|
||
'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
|
||
request.method,
|
||
requestPublicUrl,
|
||
parsedResult.message
|
||
)
|
||
);
|
||
}
|
||
return {
|
||
query: input.query,
|
||
operationType: parsedResult.operationType,
|
||
operationName: parsedResult.operationName,
|
||
variables
|
||
};
|
||
}
|
||
|
||
// node_modules/msw/lib/core/handlers/GraphQLHandler.mjs
|
||
function isDocumentNode(value) {
|
||
if (value == null) {
|
||
return false;
|
||
}
|
||
return typeof value === "object" && "kind" in value && "definitions" in value;
|
||
}
|
||
function isDocumentTypeDecoration(value) {
|
||
return value instanceof String;
|
||
}
|
||
var _GraphQLHandler_static, parseOperationName_fn;
|
||
var _GraphQLHandler = class _GraphQLHandler extends RequestHandler {
|
||
constructor(operationType, predicate, endpoint, resolver, options) {
|
||
var _a4, _b3;
|
||
const operationName = __privateMethod(_a4 = _GraphQLHandler, _GraphQLHandler_static, parseOperationName_fn).call(_a4, predicate, operationType);
|
||
const displayOperationName = typeof operationName === "function" ? "[custom predicate]" : operationName;
|
||
const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ""} (origin: ${endpoint.toString()})`;
|
||
super({
|
||
info: {
|
||
header,
|
||
operationType,
|
||
operationName: __privateMethod(_b3 = _GraphQLHandler, _GraphQLHandler_static, parseOperationName_fn).call(_b3, predicate, operationType)
|
||
},
|
||
resolver,
|
||
options
|
||
});
|
||
__publicField(this, "endpoint");
|
||
this.endpoint = endpoint;
|
||
}
|
||
/**
|
||
* Parses the request body, once per request, cached across all
|
||
* GraphQL handlers. This is done to avoid multiple parsing of the
|
||
* request body, which each requires a clone of the request.
|
||
*/
|
||
async parseGraphQLRequestOrGetFromCache(request) {
|
||
if (!_GraphQLHandler.parsedRequestCache.has(request)) {
|
||
_GraphQLHandler.parsedRequestCache.set(
|
||
request,
|
||
await parseGraphQLRequest(request).catch((error) => {
|
||
console.error(error);
|
||
return void 0;
|
||
})
|
||
);
|
||
}
|
||
return _GraphQLHandler.parsedRequestCache.get(request);
|
||
}
|
||
async parse(args) {
|
||
const match2 = matchRequestUrl(new URL(args.request.url), this.endpoint);
|
||
const cookies = getAllRequestCookies(args.request);
|
||
if (!match2.matches) {
|
||
return {
|
||
match: match2,
|
||
cookies
|
||
};
|
||
}
|
||
const parsedResult = await this.parseGraphQLRequestOrGetFromCache(
|
||
args.request
|
||
);
|
||
if (typeof parsedResult === "undefined") {
|
||
return {
|
||
match: match2,
|
||
cookies
|
||
};
|
||
}
|
||
return {
|
||
match: match2,
|
||
cookies,
|
||
query: parsedResult.query,
|
||
operationType: parsedResult.operationType,
|
||
operationName: parsedResult.operationName,
|
||
variables: parsedResult.variables
|
||
};
|
||
}
|
||
async predicate(args) {
|
||
if (args.parsedResult.operationType === void 0) {
|
||
return false;
|
||
}
|
||
if (!args.parsedResult.operationName && this.info.operationType !== "all") {
|
||
const publicUrl = toPublicUrl(args.request.url);
|
||
devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
|
||
|
||
Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`);
|
||
return false;
|
||
}
|
||
const hasMatchingOperationType = this.info.operationType === "all" || args.parsedResult.operationType === this.info.operationType;
|
||
const hasMatchingOperationName = await this.matchOperationName({
|
||
request: args.request,
|
||
parsedResult: args.parsedResult
|
||
});
|
||
return args.parsedResult.match.matches && hasMatchingOperationType && hasMatchingOperationName;
|
||
}
|
||
async matchOperationName(args) {
|
||
if (typeof this.info.operationName === "function") {
|
||
const customPredicateResult = await this.info.operationName({
|
||
request: args.request,
|
||
...this.extendResolverArgs({
|
||
request: args.request,
|
||
parsedResult: args.parsedResult
|
||
})
|
||
});
|
||
return typeof customPredicateResult === "boolean" ? customPredicateResult : customPredicateResult.matches;
|
||
}
|
||
if (this.info.operationName instanceof RegExp) {
|
||
return this.info.operationName.test(args.parsedResult.operationName || "");
|
||
}
|
||
return args.parsedResult.operationName === this.info.operationName;
|
||
}
|
||
extendResolverArgs(args) {
|
||
return {
|
||
query: args.parsedResult.query || "",
|
||
operationType: args.parsedResult.operationType,
|
||
operationName: args.parsedResult.operationName || "",
|
||
variables: args.parsedResult.variables || {},
|
||
cookies: args.parsedResult.cookies
|
||
};
|
||
}
|
||
async log(args) {
|
||
const loggedRequest = await serializeRequest(args.request);
|
||
const loggedResponse = await serializeResponse(args.response);
|
||
const statusColor = getStatusCodeColor(loggedResponse.status);
|
||
const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`;
|
||
console.groupCollapsed(
|
||
devUtils.formatMessage(
|
||
`${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
|
||
),
|
||
`color:${statusColor}`,
|
||
"color:inherit"
|
||
);
|
||
console.log("Request:", loggedRequest);
|
||
console.log("Handler:", this);
|
||
console.log("Response:", loggedResponse);
|
||
console.groupEnd();
|
||
}
|
||
};
|
||
_GraphQLHandler_static = new WeakSet();
|
||
parseOperationName_fn = function(predicate, operationType) {
|
||
const getOperationName = (node) => {
|
||
invariant(
|
||
node.operationType === operationType,
|
||
'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "%s" but got "%s").',
|
||
operationType,
|
||
node.operationType
|
||
);
|
||
invariant(
|
||
node.operationName,
|
||
"Failed to create a GraphQL handler: provided a DocumentNode without operation name"
|
||
);
|
||
return node.operationName;
|
||
};
|
||
if (isDocumentNode(predicate)) {
|
||
return getOperationName(parseDocumentNode(predicate));
|
||
}
|
||
if (isDocumentTypeDecoration(predicate)) {
|
||
const documentNode = parse(predicate.toString());
|
||
invariant(
|
||
isDocumentNode(documentNode),
|
||
"Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode",
|
||
predicate
|
||
);
|
||
return getOperationName(parseDocumentNode(documentNode));
|
||
}
|
||
return predicate;
|
||
};
|
||
__privateAdd(_GraphQLHandler, _GraphQLHandler_static);
|
||
__publicField(_GraphQLHandler, "parsedRequestCache", /* @__PURE__ */ new WeakMap());
|
||
var GraphQLHandler = _GraphQLHandler;
|
||
|
||
// node_modules/msw/lib/core/graphql.mjs
|
||
function createScopedGraphQLHandler(operationType, url) {
|
||
return (predicate, resolver, options = {}) => {
|
||
return new GraphQLHandler(operationType, predicate, url, resolver, options);
|
||
};
|
||
}
|
||
function createGraphQLOperationHandler(url) {
|
||
return (resolver, options) => {
|
||
return new GraphQLHandler("all", new RegExp(".*"), url, resolver, options);
|
||
};
|
||
}
|
||
var graphql = {
|
||
/**
|
||
* Intercepts a GraphQL query by a given name.
|
||
*
|
||
* @example
|
||
* graphql.query('GetUser', () => {
|
||
* return HttpResponse.json({ data: { user: { name: 'John' } } })
|
||
* })
|
||
*
|
||
* @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}
|
||
*/
|
||
query: createScopedGraphQLHandler("query", "*"),
|
||
/**
|
||
* Intercepts a GraphQL mutation by its name.
|
||
*
|
||
* @example
|
||
* graphql.mutation('SavePost', () => {
|
||
* return HttpResponse.json({ data: { post: { id: 'abc-123 } } })
|
||
* })
|
||
*
|
||
* @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}
|
||
*
|
||
*/
|
||
mutation: createScopedGraphQLHandler("mutation", "*"),
|
||
/**
|
||
* Intercepts any GraphQL operation, regardless of its type or name.
|
||
*
|
||
* @example
|
||
* graphql.operation(() => {
|
||
* return HttpResponse.json({ data: { name: 'John' } })
|
||
* })
|
||
*
|
||
* @see {@link https://mswjs.io/docs/api/graphql#graphqloperationresolver `graphql.operation()` API reference}
|
||
*/
|
||
operation: createGraphQLOperationHandler("*"),
|
||
/**
|
||
* Intercepts GraphQL operations scoped by the given URL.
|
||
*
|
||
* @example
|
||
* const github = graphql.link('https://api.github.com/graphql')
|
||
* github.query('GetRepo', resolver)
|
||
*
|
||
* @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}
|
||
*/
|
||
link(url) {
|
||
return {
|
||
operation: createGraphQLOperationHandler(url),
|
||
query: createScopedGraphQLHandler("query", url),
|
||
mutation: createScopedGraphQLHandler(
|
||
"mutation",
|
||
url
|
||
)
|
||
};
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/handlers/WebSocketHandler.mjs
|
||
var kEmitter = Symbol("kEmitter");
|
||
var kSender = Symbol("kSender");
|
||
var kStopPropagationPatched = Symbol("kStopPropagationPatched");
|
||
var KOnStopPropagation = Symbol("KOnStopPropagation");
|
||
var _a;
|
||
_a = kEmitter;
|
||
var WebSocketHandler = class {
|
||
constructor(url) {
|
||
__publicField(this, "__kind");
|
||
__publicField(this, "id");
|
||
__publicField(this, "callFrame");
|
||
__publicField(this, _a);
|
||
this.url = url;
|
||
this.id = createRequestId();
|
||
this[kEmitter] = new Emitter();
|
||
this.callFrame = getCallFrame(new Error());
|
||
this.__kind = "EventHandler";
|
||
}
|
||
parse(args) {
|
||
var _a4;
|
||
const clientUrl = new URL(args.url);
|
||
clientUrl.pathname = clientUrl.pathname.replace(/^\/socket.io\//, "/");
|
||
const match2 = matchRequestUrl(
|
||
clientUrl,
|
||
this.url,
|
||
(_a4 = args.resolutionContext) == null ? void 0 : _a4.baseUrl
|
||
);
|
||
return {
|
||
match: match2
|
||
};
|
||
}
|
||
predicate(args) {
|
||
return args.parsedResult.match.matches;
|
||
}
|
||
async run(connection, resolutionContext) {
|
||
const parsedResult = this.parse({
|
||
url: connection.client.url,
|
||
resolutionContext
|
||
});
|
||
if (!this.predicate({ url: connection.client.url, parsedResult })) {
|
||
return false;
|
||
}
|
||
const resolvedConnection = {
|
||
...connection,
|
||
params: parsedResult.match.params || {}
|
||
};
|
||
return this.connect(resolvedConnection);
|
||
}
|
||
connect(connection) {
|
||
connection.client.addEventListener(
|
||
"message",
|
||
createStopPropagationListener(this)
|
||
);
|
||
connection.client.addEventListener(
|
||
"close",
|
||
createStopPropagationListener(this)
|
||
);
|
||
connection.server.addEventListener(
|
||
"open",
|
||
createStopPropagationListener(this)
|
||
);
|
||
connection.server.addEventListener(
|
||
"message",
|
||
createStopPropagationListener(this)
|
||
);
|
||
connection.server.addEventListener(
|
||
"error",
|
||
createStopPropagationListener(this)
|
||
);
|
||
connection.server.addEventListener(
|
||
"close",
|
||
createStopPropagationListener(this)
|
||
);
|
||
return this[kEmitter].emit("connection", connection);
|
||
}
|
||
};
|
||
function createStopPropagationListener(handler) {
|
||
return function stopPropagationListener(event) {
|
||
const propagationStoppedAt = Reflect.get(event, "kPropagationStoppedAt");
|
||
if (propagationStoppedAt && handler.id !== propagationStoppedAt) {
|
||
event.stopImmediatePropagation();
|
||
return;
|
||
}
|
||
Object.defineProperty(event, KOnStopPropagation, {
|
||
value() {
|
||
Object.defineProperty(event, "kPropagationStoppedAt", {
|
||
value: handler.id
|
||
});
|
||
},
|
||
configurable: true
|
||
});
|
||
if (!Reflect.get(event, kStopPropagationPatched)) {
|
||
event.stopPropagation = new Proxy(event.stopPropagation, {
|
||
apply: (target, thisArg, args) => {
|
||
var _a4;
|
||
(_a4 = Reflect.get(event, KOnStopPropagation)) == null ? void 0 : _a4.call(handler);
|
||
return Reflect.apply(target, thisArg, args);
|
||
}
|
||
});
|
||
Object.defineProperty(event, kStopPropagationPatched, {
|
||
value: true,
|
||
// If something else attempts to redefine this, throw.
|
||
configurable: false
|
||
});
|
||
}
|
||
};
|
||
}
|
||
|
||
// node_modules/msw/lib/core/ws/WebSocketMemoryClientStore.mjs
|
||
var WebSocketMemoryClientStore = class {
|
||
constructor() {
|
||
__publicField(this, "store");
|
||
this.store = /* @__PURE__ */ new Map();
|
||
}
|
||
async add(client) {
|
||
this.store.set(client.id, { id: client.id, url: client.url.href });
|
||
}
|
||
getAll() {
|
||
return Promise.resolve(Array.from(this.store.values()));
|
||
}
|
||
async deleteMany(clientIds) {
|
||
for (const clientId of clientIds) {
|
||
this.store.delete(clientId);
|
||
}
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/ws/WebSocketIndexedDBClientStore.mjs
|
||
var DB_NAME = "msw-websocket-clients";
|
||
var DB_STORE_NAME = "clients";
|
||
var WebSocketIndexedDBClientStore = class {
|
||
constructor() {
|
||
__publicField(this, "db");
|
||
this.db = this.createDatabase();
|
||
}
|
||
async add(client) {
|
||
const promise = new DeferredPromise();
|
||
const store = await this.getStore();
|
||
const request = store.put({
|
||
id: client.id,
|
||
url: client.url.href
|
||
});
|
||
request.onsuccess = () => {
|
||
promise.resolve();
|
||
};
|
||
request.onerror = () => {
|
||
console.error(request.error);
|
||
promise.reject(
|
||
new Error(
|
||
`Failed to add WebSocket client "${client.id}". There is likely an additional output above.`
|
||
)
|
||
);
|
||
};
|
||
return promise;
|
||
}
|
||
async getAll() {
|
||
const promise = new DeferredPromise();
|
||
const store = await this.getStore();
|
||
const request = store.getAll();
|
||
request.onsuccess = () => {
|
||
promise.resolve(request.result);
|
||
};
|
||
request.onerror = () => {
|
||
console.log(request.error);
|
||
promise.reject(
|
||
new Error(
|
||
`Failed to get all WebSocket clients. There is likely an additional output above.`
|
||
)
|
||
);
|
||
};
|
||
return promise;
|
||
}
|
||
async deleteMany(clientIds) {
|
||
const promise = new DeferredPromise();
|
||
const store = await this.getStore();
|
||
for (const clientId of clientIds) {
|
||
store.delete(clientId);
|
||
}
|
||
store.transaction.oncomplete = () => {
|
||
promise.resolve();
|
||
};
|
||
store.transaction.onerror = () => {
|
||
console.error(store.transaction.error);
|
||
promise.reject(
|
||
new Error(
|
||
`Failed to delete WebSocket clients [${clientIds.join(", ")}]. There is likely an additional output above.`
|
||
)
|
||
);
|
||
};
|
||
return promise;
|
||
}
|
||
async createDatabase() {
|
||
const promise = new DeferredPromise();
|
||
const request = indexedDB.open(DB_NAME, 1);
|
||
request.onsuccess = ({ currentTarget }) => {
|
||
const db = Reflect.get(currentTarget, "result");
|
||
if (db.objectStoreNames.contains(DB_STORE_NAME)) {
|
||
return promise.resolve(db);
|
||
}
|
||
};
|
||
request.onupgradeneeded = async ({ currentTarget }) => {
|
||
const db = Reflect.get(currentTarget, "result");
|
||
if (db.objectStoreNames.contains(DB_STORE_NAME)) {
|
||
return;
|
||
}
|
||
const store = db.createObjectStore(DB_STORE_NAME, { keyPath: "id" });
|
||
store.transaction.oncomplete = () => {
|
||
promise.resolve(db);
|
||
};
|
||
store.transaction.onerror = () => {
|
||
console.error(store.transaction.error);
|
||
promise.reject(
|
||
new Error(
|
||
"Failed to create WebSocket client store. There is likely an additional output above."
|
||
)
|
||
);
|
||
};
|
||
};
|
||
request.onerror = () => {
|
||
console.error(request.error);
|
||
promise.reject(
|
||
new Error(
|
||
"Failed to open an IndexedDB database. There is likely an additional output above."
|
||
)
|
||
);
|
||
};
|
||
return promise;
|
||
}
|
||
async getStore() {
|
||
const db = await this.db;
|
||
return db.transaction(DB_STORE_NAME, "readwrite").objectStore(DB_STORE_NAME);
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/ws/WebSocketClientManager.mjs
|
||
var WebSocketClientManager = class {
|
||
constructor(channel) {
|
||
__publicField(this, "store");
|
||
__publicField(this, "runtimeClients");
|
||
__publicField(this, "allClients");
|
||
this.channel = channel;
|
||
this.store = typeof indexedDB !== "undefined" ? new WebSocketIndexedDBClientStore() : new WebSocketMemoryClientStore();
|
||
this.runtimeClients = /* @__PURE__ */ new Map();
|
||
this.allClients = /* @__PURE__ */ new Set();
|
||
this.channel.addEventListener("message", (message2) => {
|
||
var _a4;
|
||
if (((_a4 = message2.data) == null ? void 0 : _a4.type) === "db:update") {
|
||
this.flushDatabaseToMemory();
|
||
}
|
||
});
|
||
if (typeof window !== "undefined") {
|
||
window.addEventListener("message", async (message2) => {
|
||
var _a4;
|
||
if (((_a4 = message2.data) == null ? void 0 : _a4.type) === "msw/worker:stop") {
|
||
await this.removeRuntimeClients();
|
||
}
|
||
});
|
||
}
|
||
}
|
||
async flushDatabaseToMemory() {
|
||
const storedClients = await this.store.getAll();
|
||
this.allClients = new Set(
|
||
storedClients.map((client) => {
|
||
const runtimeClient = this.runtimeClients.get(client.id);
|
||
if (runtimeClient) {
|
||
return runtimeClient;
|
||
}
|
||
return new WebSocketRemoteClientConnection(
|
||
client.id,
|
||
new URL(client.url),
|
||
this.channel
|
||
);
|
||
})
|
||
);
|
||
}
|
||
async removeRuntimeClients() {
|
||
await this.store.deleteMany(Array.from(this.runtimeClients.keys()));
|
||
this.runtimeClients.clear();
|
||
await this.flushDatabaseToMemory();
|
||
this.notifyOthersAboutDatabaseUpdate();
|
||
}
|
||
/**
|
||
* All active WebSocket client connections.
|
||
*/
|
||
get clients() {
|
||
return this.allClients;
|
||
}
|
||
/**
|
||
* Notify other runtimes about the database update
|
||
* using the shared `BroadcastChannel` instance.
|
||
*/
|
||
notifyOthersAboutDatabaseUpdate() {
|
||
this.channel.postMessage({ type: "db:update" });
|
||
}
|
||
async addClient(client) {
|
||
await this.store.add(client);
|
||
await this.flushDatabaseToMemory();
|
||
this.notifyOthersAboutDatabaseUpdate();
|
||
}
|
||
/**
|
||
* Adds the given `WebSocket` client connection to the set
|
||
* of all connections. The given connection is always the complete
|
||
* connection object because `addConnection()` is called only
|
||
* for the opened connections in the same runtime.
|
||
*/
|
||
async addConnection(client) {
|
||
this.runtimeClients.set(client.id, client);
|
||
await this.addClient(client);
|
||
const handleExtraneousMessage = (message2) => {
|
||
const { type, payload } = message2.data;
|
||
if (typeof payload === "object" && "clientId" in payload && payload.clientId !== client.id) {
|
||
return;
|
||
}
|
||
switch (type) {
|
||
case "extraneous:send": {
|
||
client.send(payload.data);
|
||
break;
|
||
}
|
||
case "extraneous:close": {
|
||
client.close(payload.code, payload.reason);
|
||
break;
|
||
}
|
||
}
|
||
};
|
||
const abortController = new AbortController();
|
||
this.channel.addEventListener("message", handleExtraneousMessage, {
|
||
signal: abortController.signal
|
||
});
|
||
client.addEventListener("close", () => abortController.abort(), {
|
||
once: true
|
||
});
|
||
}
|
||
};
|
||
var WebSocketRemoteClientConnection = class {
|
||
constructor(id, url, channel) {
|
||
this.id = id;
|
||
this.url = url;
|
||
this.channel = channel;
|
||
}
|
||
send(data) {
|
||
this.channel.postMessage({
|
||
type: "extraneous:send",
|
||
payload: {
|
||
clientId: this.id,
|
||
data
|
||
}
|
||
});
|
||
}
|
||
close(code, reason) {
|
||
this.channel.postMessage({
|
||
type: "extraneous:close",
|
||
payload: {
|
||
clientId: this.id,
|
||
code,
|
||
reason
|
||
}
|
||
});
|
||
}
|
||
addEventListener(_type, _listener, _options) {
|
||
throw new Error(
|
||
"WebSocketRemoteClientConnection.addEventListener is not supported"
|
||
);
|
||
}
|
||
removeEventListener(_event, _listener, _options) {
|
||
throw new Error(
|
||
"WebSocketRemoteClientConnection.removeEventListener is not supported"
|
||
);
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/ws.mjs
|
||
function isBroadcastChannelWithUnref(channel) {
|
||
return typeof Reflect.get(channel, "unref") !== "undefined";
|
||
}
|
||
var webSocketChannel = new BroadcastChannel("msw:websocket-client-manager");
|
||
if (isBroadcastChannelWithUnref(webSocketChannel)) {
|
||
webSocketChannel.unref();
|
||
}
|
||
function createWebSocketLinkHandler(url) {
|
||
invariant(url, "Expected a WebSocket server URL but got undefined");
|
||
invariant(
|
||
isPath(url),
|
||
"Expected a WebSocket server URL to be a valid path but got %s",
|
||
typeof url
|
||
);
|
||
const clientManager = new WebSocketClientManager(webSocketChannel);
|
||
return {
|
||
get clients() {
|
||
return clientManager.clients;
|
||
},
|
||
addEventListener(event, listener) {
|
||
const handler = new WebSocketHandler(url);
|
||
handler[kEmitter].on("connection", async ({ client }) => {
|
||
await clientManager.addConnection(client);
|
||
});
|
||
handler[kEmitter].on(event, listener);
|
||
return handler;
|
||
},
|
||
broadcast(data) {
|
||
this.broadcastExcept([], data);
|
||
},
|
||
broadcastExcept(clients, data) {
|
||
const ignoreClients = Array.prototype.concat(clients).map((client) => client.id);
|
||
clientManager.clients.forEach((otherClient) => {
|
||
if (!ignoreClients.includes(otherClient.id)) {
|
||
otherClient.send(data);
|
||
}
|
||
});
|
||
}
|
||
};
|
||
}
|
||
var ws = {
|
||
link: createWebSocketLinkHandler
|
||
};
|
||
|
||
// node_modules/msw/lib/core/delay.mjs
|
||
var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
|
||
var MIN_SERVER_RESPONSE_TIME = 100;
|
||
var MAX_SERVER_RESPONSE_TIME = 400;
|
||
var NODE_SERVER_RESPONSE_TIME = 5;
|
||
function getRealisticResponseTime() {
|
||
if (isNodeProcess()) {
|
||
return NODE_SERVER_RESPONSE_TIME;
|
||
}
|
||
return Math.floor(
|
||
Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
|
||
);
|
||
}
|
||
async function delay(durationOrMode) {
|
||
let delayTime;
|
||
if (typeof durationOrMode === "string") {
|
||
switch (durationOrMode) {
|
||
case "infinite": {
|
||
delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
|
||
break;
|
||
}
|
||
case "real": {
|
||
delayTime = getRealisticResponseTime();
|
||
break;
|
||
}
|
||
default: {
|
||
throw new Error(
|
||
`Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
|
||
);
|
||
}
|
||
}
|
||
} else if (typeof durationOrMode === "undefined") {
|
||
delayTime = getRealisticResponseTime();
|
||
} else {
|
||
if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
|
||
throw new Error(
|
||
`Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
|
||
);
|
||
}
|
||
delayTime = durationOrMode;
|
||
}
|
||
return new Promise((resolve) => setTimeout(resolve, delayTime));
|
||
}
|
||
|
||
// node_modules/msw/lib/core/sse.mjs
|
||
var sse = (path, resolver) => {
|
||
return new ServerSentEventHandler(path, resolver);
|
||
};
|
||
var SSE_RESPONSE_INIT = {
|
||
headers: {
|
||
"content-type": "text/event-stream",
|
||
"cache-control": "no-cache",
|
||
connection: "keep-alive"
|
||
}
|
||
};
|
||
var _emitter, _ServerSentEventHandler_instances, attachClientLogger_fn;
|
||
var ServerSentEventHandler = class extends HttpHandler {
|
||
constructor(path, resolver) {
|
||
invariant(
|
||
typeof EventSource !== "undefined",
|
||
'Failed to construct a Server-Sent Event handler for path "%s": the EventSource API is not supported in this environment',
|
||
path
|
||
);
|
||
super("GET", path, async (info) => {
|
||
const stream = new ReadableStream({
|
||
start: async (controller) => {
|
||
const client = new ServerSentEventClient({
|
||
controller,
|
||
emitter: __privateGet(this, _emitter)
|
||
});
|
||
const server = new ServerSentEventServer({
|
||
request: info.request,
|
||
client
|
||
});
|
||
await resolver({
|
||
...info,
|
||
client,
|
||
server
|
||
});
|
||
}
|
||
});
|
||
return new Response(stream, SSE_RESPONSE_INIT);
|
||
});
|
||
__privateAdd(this, _ServerSentEventHandler_instances);
|
||
__privateAdd(this, _emitter);
|
||
__privateSet(this, _emitter, new Emitter());
|
||
}
|
||
async predicate(args) {
|
||
var _a4;
|
||
if (args.request.headers.get("accept") !== "text/event-stream") {
|
||
return false;
|
||
}
|
||
const matches = await super.predicate(args);
|
||
if (matches && !((_a4 = args.resolutionContext) == null ? void 0 : _a4.quiet)) {
|
||
await super.log({
|
||
request: args.request,
|
||
/**
|
||
* @note Construct a placeholder response since SSE response
|
||
* is being streamed and cannot be cloned/consumed for logging.
|
||
*/
|
||
response: new Response("[streaming]", SSE_RESPONSE_INIT)
|
||
});
|
||
__privateMethod(this, _ServerSentEventHandler_instances, attachClientLogger_fn).call(this, args.request, __privateGet(this, _emitter));
|
||
}
|
||
return matches;
|
||
}
|
||
async log(_args) {
|
||
return;
|
||
}
|
||
};
|
||
_emitter = new WeakMap();
|
||
_ServerSentEventHandler_instances = new WeakSet();
|
||
attachClientLogger_fn = function(request, emitter) {
|
||
const publicUrl = toPublicUrl(request.url);
|
||
emitter.on("message", (payload) => {
|
||
console.groupCollapsed(
|
||
devUtils.formatMessage(
|
||
`${getTimestamp()} SSE %s %c⇣%c ${payload.event}`
|
||
),
|
||
publicUrl,
|
||
`color:${colors.mocked}`,
|
||
"color:inherit"
|
||
);
|
||
console.log(payload.frames);
|
||
console.groupEnd();
|
||
});
|
||
emitter.on("error", () => {
|
||
console.groupCollapsed(
|
||
devUtils.formatMessage(`${getTimestamp()} SSE %s %c×%c error`),
|
||
publicUrl,
|
||
`color: ${colors.system}`,
|
||
"color:inherit"
|
||
);
|
||
console.log("Handler:", this);
|
||
console.groupEnd();
|
||
});
|
||
emitter.on("close", () => {
|
||
console.groupCollapsed(
|
||
devUtils.formatMessage(`${getTimestamp()} SSE %s %c■%c close`),
|
||
publicUrl,
|
||
`colors:${colors.system}`,
|
||
"color:inherit"
|
||
);
|
||
console.log("Handler:", this);
|
||
console.groupEnd();
|
||
});
|
||
};
|
||
var _encoder, _controller, _emitter2, _ServerSentEventClient_instances, sendRetry_fn, sendMessage_fn;
|
||
var ServerSentEventClient = class {
|
||
constructor(args) {
|
||
__privateAdd(this, _ServerSentEventClient_instances);
|
||
__privateAdd(this, _encoder);
|
||
__privateAdd(this, _controller);
|
||
__privateAdd(this, _emitter2);
|
||
__privateSet(this, _encoder, new TextEncoder());
|
||
__privateSet(this, _controller, args.controller);
|
||
__privateSet(this, _emitter2, args.emitter);
|
||
}
|
||
/**
|
||
* Sends the given payload to the intercepted `EventSource`.
|
||
*/
|
||
send(payload) {
|
||
if ("retry" in payload && payload.retry != null) {
|
||
__privateMethod(this, _ServerSentEventClient_instances, sendRetry_fn).call(this, payload.retry);
|
||
return;
|
||
}
|
||
__privateMethod(this, _ServerSentEventClient_instances, sendMessage_fn).call(this, {
|
||
id: payload.id,
|
||
event: payload.event,
|
||
data: typeof payload.data === "object" ? JSON.stringify(payload.data) : payload.data
|
||
});
|
||
}
|
||
/**
|
||
* Dispatches the given event on the intercepted `EventSource`.
|
||
*/
|
||
dispatchEvent(event) {
|
||
if (event instanceof MessageEvent) {
|
||
__privateMethod(this, _ServerSentEventClient_instances, sendMessage_fn).call(this, {
|
||
id: event.lastEventId || void 0,
|
||
event: event.type === "message" ? void 0 : event.type,
|
||
data: event.data
|
||
});
|
||
return;
|
||
}
|
||
if (event.type === "error") {
|
||
this.error();
|
||
return;
|
||
}
|
||
if (event.type === "close") {
|
||
this.close();
|
||
return;
|
||
}
|
||
}
|
||
/**
|
||
* Errors the underlying `EventSource`, closing the connection with an error.
|
||
* This is equivalent to aborting the connection and will produce a `TypeError: Failed to fetch`
|
||
* error.
|
||
*/
|
||
error() {
|
||
__privateGet(this, _controller).error();
|
||
__privateGet(this, _emitter2).emit("error");
|
||
}
|
||
/**
|
||
* Closes the underlying `EventSource`, closing the connection.
|
||
*/
|
||
close() {
|
||
__privateGet(this, _controller).close();
|
||
__privateGet(this, _emitter2).emit("close");
|
||
}
|
||
};
|
||
_encoder = new WeakMap();
|
||
_controller = new WeakMap();
|
||
_emitter2 = new WeakMap();
|
||
_ServerSentEventClient_instances = new WeakSet();
|
||
sendRetry_fn = function(retry) {
|
||
if (typeof retry === "number") {
|
||
__privateGet(this, _controller).enqueue(__privateGet(this, _encoder).encode(`retry:${retry}
|
||
|
||
`));
|
||
}
|
||
};
|
||
sendMessage_fn = function(message2) {
|
||
var _a4, _b3;
|
||
const frames = [];
|
||
if (message2.id) {
|
||
frames.push(`id:${message2.id}`);
|
||
}
|
||
if (message2.event) {
|
||
frames.push(`event:${(_a4 = message2.event) == null ? void 0 : _a4.toString()}`);
|
||
}
|
||
if (message2.data != null) {
|
||
for (const line of message2.data.toString().split(/\r\n|\r|\n/)) {
|
||
frames.push(`data:${line}`);
|
||
}
|
||
}
|
||
frames.push("", "");
|
||
__privateGet(this, _controller).enqueue(__privateGet(this, _encoder).encode(frames.join("\n")));
|
||
__privateGet(this, _emitter2).emit("message", {
|
||
id: message2.id,
|
||
event: ((_b3 = message2.event) == null ? void 0 : _b3.toString()) || "message",
|
||
data: message2.data,
|
||
frames
|
||
});
|
||
};
|
||
var _request, _client;
|
||
var ServerSentEventServer = class {
|
||
constructor(args) {
|
||
__privateAdd(this, _request);
|
||
__privateAdd(this, _client);
|
||
__privateSet(this, _request, args.request);
|
||
__privateSet(this, _client, args.client);
|
||
}
|
||
/**
|
||
* Establishes the actual connection for this SSE request
|
||
* and returns the `EventSource` instance.
|
||
*/
|
||
connect() {
|
||
const source = new ObservableEventSource(__privateGet(this, _request).url, {
|
||
withCredentials: __privateGet(this, _request).credentials === "include",
|
||
headers: {
|
||
/**
|
||
* @note Mark this request as passthrough so it doesn't trigger
|
||
* an infinite loop matching against the existing request handler.
|
||
*/
|
||
accept: "msw/passthrough"
|
||
}
|
||
});
|
||
source[kOnAnyMessage] = (event) => {
|
||
Object.defineProperties(event, {
|
||
target: {
|
||
value: this,
|
||
enumerable: true,
|
||
writable: true,
|
||
configurable: true
|
||
}
|
||
});
|
||
queueMicrotask(() => {
|
||
if (!event.defaultPrevented) {
|
||
__privateGet(this, _client).dispatchEvent(event);
|
||
}
|
||
});
|
||
};
|
||
source.addEventListener("error", (event) => {
|
||
Object.defineProperties(event, {
|
||
target: {
|
||
value: this,
|
||
enumerable: true,
|
||
writable: true,
|
||
configurable: true
|
||
}
|
||
});
|
||
queueMicrotask(() => {
|
||
if (!event.defaultPrevented) {
|
||
__privateGet(this, _client).dispatchEvent(event);
|
||
}
|
||
});
|
||
});
|
||
return source;
|
||
}
|
||
};
|
||
_request = new WeakMap();
|
||
_client = new WeakMap();
|
||
var kRequest = Symbol("kRequest");
|
||
var kReconnectionTime = Symbol("kReconnectionTime");
|
||
var kLastEventId = Symbol("kLastEventId");
|
||
var kAbortController = Symbol("kAbortController");
|
||
var kOnOpen = Symbol("kOnOpen");
|
||
var kOnMessage = Symbol("kOnMessage");
|
||
var kOnAnyMessage = Symbol("kOnAnyMessage");
|
||
var kOnError = Symbol("kOnError");
|
||
var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
|
||
var _ObservableEventSource = class _ObservableEventSource extends (_i = EventTarget, _h = kRequest, _g = kReconnectionTime, _f = kLastEventId, _e = kAbortController, _d = kOnOpen, _c = kOnMessage, _b = kOnAnyMessage, _a2 = kOnError, _i) {
|
||
constructor(url, init) {
|
||
super();
|
||
__publicField(this, "CONNECTING", _ObservableEventSource.CONNECTING);
|
||
__publicField(this, "OPEN", _ObservableEventSource.OPEN);
|
||
__publicField(this, "CLOSED", _ObservableEventSource.CLOSED);
|
||
__publicField(this, "readyState");
|
||
__publicField(this, "url");
|
||
__publicField(this, "withCredentials");
|
||
__publicField(this, _h);
|
||
__publicField(this, _g);
|
||
__publicField(this, _f);
|
||
__publicField(this, _e);
|
||
__publicField(this, _d, null);
|
||
__publicField(this, _c, null);
|
||
__publicField(this, _b, null);
|
||
__publicField(this, _a2, null);
|
||
this.url = new URL(url).href;
|
||
this.withCredentials = (init == null ? void 0 : init.withCredentials) ?? false;
|
||
this.readyState = this.CONNECTING;
|
||
const headers = new Headers((init == null ? void 0 : init.headers) || {});
|
||
headers.append("accept", "text/event-stream");
|
||
this[kAbortController] = new AbortController();
|
||
this[kReconnectionTime] = 2e3;
|
||
this[kLastEventId] = "";
|
||
this[kRequest] = new Request(this.url, {
|
||
method: "GET",
|
||
headers,
|
||
credentials: this.withCredentials ? "include" : "omit",
|
||
signal: this[kAbortController].signal
|
||
});
|
||
this.connect();
|
||
}
|
||
get onopen() {
|
||
return this[kOnOpen];
|
||
}
|
||
set onopen(handler) {
|
||
if (this[kOnOpen]) {
|
||
this.removeEventListener("open", this[kOnOpen]);
|
||
}
|
||
this[kOnOpen] = handler.bind(this);
|
||
this.addEventListener("open", this[kOnOpen]);
|
||
}
|
||
get onmessage() {
|
||
return this[kOnMessage];
|
||
}
|
||
set onmessage(handler) {
|
||
if (this[kOnMessage]) {
|
||
this.removeEventListener("message", { handleEvent: this[kOnMessage] });
|
||
}
|
||
this[kOnMessage] = handler.bind(this);
|
||
this.addEventListener("message", { handleEvent: this[kOnMessage] });
|
||
}
|
||
get onerror() {
|
||
return this[kOnError];
|
||
}
|
||
set oneerror(handler) {
|
||
if (this[kOnError]) {
|
||
this.removeEventListener("error", { handleEvent: this[kOnError] });
|
||
}
|
||
this[kOnError] = handler.bind(this);
|
||
this.addEventListener("error", { handleEvent: this[kOnError] });
|
||
}
|
||
addEventListener(type, listener, options) {
|
||
super.addEventListener(
|
||
type,
|
||
listener,
|
||
options
|
||
);
|
||
}
|
||
removeEventListener(type, listener, options) {
|
||
super.removeEventListener(
|
||
type,
|
||
listener,
|
||
options
|
||
);
|
||
}
|
||
dispatchEvent(event) {
|
||
return super.dispatchEvent(event);
|
||
}
|
||
close() {
|
||
this[kAbortController].abort();
|
||
this.readyState = this.CLOSED;
|
||
}
|
||
async connect() {
|
||
await fetch(this[kRequest]).then((response) => {
|
||
this.processResponse(response);
|
||
}).catch(() => {
|
||
this.failConnection();
|
||
});
|
||
}
|
||
processResponse(response) {
|
||
if (!response.body) {
|
||
this.failConnection();
|
||
return;
|
||
}
|
||
if (isNetworkError(response)) {
|
||
this.reestablishConnection();
|
||
return;
|
||
}
|
||
if (response.status !== 200 || response.headers.get("content-type") !== "text/event-stream") {
|
||
this.failConnection();
|
||
return;
|
||
}
|
||
this.announceConnection();
|
||
this.interpretResponseBody(response);
|
||
}
|
||
announceConnection() {
|
||
queueMicrotask(() => {
|
||
if (this.readyState !== this.CLOSED) {
|
||
this.readyState = this.OPEN;
|
||
this.dispatchEvent(new Event("open"));
|
||
}
|
||
});
|
||
}
|
||
interpretResponseBody(response) {
|
||
const parsingStream = new EventSourceParsingStream({
|
||
message: (message2) => {
|
||
var _a4;
|
||
if (message2.id) {
|
||
this[kLastEventId] = message2.id;
|
||
}
|
||
if (message2.retry) {
|
||
this[kReconnectionTime] = message2.retry;
|
||
}
|
||
const messageEvent = new MessageEvent(
|
||
message2.event ? message2.event : "message",
|
||
{
|
||
data: message2.data,
|
||
origin: this[kRequest].url,
|
||
lastEventId: this[kLastEventId],
|
||
cancelable: true
|
||
}
|
||
);
|
||
(_a4 = this[kOnAnyMessage]) == null ? void 0 : _a4.call(this, messageEvent);
|
||
this.dispatchEvent(messageEvent);
|
||
},
|
||
abort: () => {
|
||
throw new Error("Stream abort is not implemented");
|
||
},
|
||
close: () => {
|
||
this.failConnection();
|
||
}
|
||
});
|
||
response.body.pipeTo(parsingStream).then(() => {
|
||
this.processResponseEndOfBody(response);
|
||
}).catch(() => {
|
||
this.failConnection();
|
||
});
|
||
}
|
||
processResponseEndOfBody(response) {
|
||
if (!isNetworkError(response)) {
|
||
this.reestablishConnection();
|
||
}
|
||
}
|
||
async reestablishConnection() {
|
||
queueMicrotask(() => {
|
||
if (this.readyState === this.CLOSED) {
|
||
return;
|
||
}
|
||
this.readyState = this.CONNECTING;
|
||
this.dispatchEvent(new Event("error"));
|
||
});
|
||
await delay(this[kReconnectionTime]);
|
||
queueMicrotask(async () => {
|
||
if (this.readyState !== this.CONNECTING) {
|
||
return;
|
||
}
|
||
if (this[kLastEventId] !== "") {
|
||
this[kRequest].headers.set("last-event-id", this[kLastEventId]);
|
||
}
|
||
await this.connect();
|
||
});
|
||
}
|
||
failConnection() {
|
||
queueMicrotask(() => {
|
||
if (this.readyState !== this.CLOSED) {
|
||
this.readyState = this.CLOSED;
|
||
this.dispatchEvent(new Event("error"));
|
||
}
|
||
});
|
||
}
|
||
};
|
||
__publicField(_ObservableEventSource, "CONNECTING", 0);
|
||
__publicField(_ObservableEventSource, "OPEN", 1);
|
||
__publicField(_ObservableEventSource, "CLOSED", 2);
|
||
var ObservableEventSource = _ObservableEventSource;
|
||
function isNetworkError(response) {
|
||
return response.type === "error" && response.status === 0 && response.statusText === "" && Array.from(response.headers.entries()).length === 0 && response.body === null;
|
||
}
|
||
var ControlCharacters = ((ControlCharacters2) => {
|
||
ControlCharacters2[ControlCharacters2["NewLine"] = 10] = "NewLine";
|
||
ControlCharacters2[ControlCharacters2["CarriageReturn"] = 13] = "CarriageReturn";
|
||
ControlCharacters2[ControlCharacters2["Space"] = 32] = "Space";
|
||
ControlCharacters2[ControlCharacters2["Colon"] = 58] = "Colon";
|
||
return ControlCharacters2;
|
||
})(ControlCharacters || {});
|
||
var EventSourceParsingStream = class extends WritableStream {
|
||
constructor(underlyingSink) {
|
||
super({
|
||
write: (chunk) => {
|
||
this.processResponseBodyChunk(chunk);
|
||
},
|
||
abort: (reason) => {
|
||
var _a4, _b3;
|
||
(_b3 = (_a4 = this.underlyingSink).abort) == null ? void 0 : _b3.call(_a4, reason);
|
||
},
|
||
close: () => {
|
||
var _a4, _b3;
|
||
(_b3 = (_a4 = this.underlyingSink).close) == null ? void 0 : _b3.call(_a4);
|
||
}
|
||
});
|
||
__publicField(this, "decoder");
|
||
__publicField(this, "buffer");
|
||
__publicField(this, "position");
|
||
__publicField(this, "fieldLength");
|
||
__publicField(this, "discardTrailingNewline", false);
|
||
__publicField(this, "message", {
|
||
id: void 0,
|
||
event: void 0,
|
||
data: void 0,
|
||
retry: void 0
|
||
});
|
||
this.underlyingSink = underlyingSink;
|
||
this.decoder = new TextDecoder();
|
||
this.position = 0;
|
||
}
|
||
resetMessage() {
|
||
this.message = {
|
||
id: void 0,
|
||
event: void 0,
|
||
data: void 0,
|
||
retry: void 0
|
||
};
|
||
}
|
||
processResponseBodyChunk(chunk) {
|
||
if (this.buffer == null) {
|
||
this.buffer = chunk;
|
||
this.position = 0;
|
||
this.fieldLength = -1;
|
||
} else {
|
||
const nextBuffer = new Uint8Array(this.buffer.length + chunk.length);
|
||
nextBuffer.set(this.buffer);
|
||
nextBuffer.set(chunk, this.buffer.length);
|
||
this.buffer = nextBuffer;
|
||
}
|
||
const bufferLength = this.buffer.length;
|
||
let lineStart = 0;
|
||
while (this.position < bufferLength) {
|
||
if (this.discardTrailingNewline) {
|
||
if (this.buffer[this.position] === 10) {
|
||
lineStart = ++this.position;
|
||
}
|
||
this.discardTrailingNewline = false;
|
||
}
|
||
let lineEnd = -1;
|
||
for (; this.position < bufferLength && lineEnd === -1; ++this.position) {
|
||
switch (this.buffer[this.position]) {
|
||
case 58: {
|
||
if (this.fieldLength === -1) {
|
||
this.fieldLength = this.position - lineStart;
|
||
}
|
||
break;
|
||
}
|
||
case 13: {
|
||
this.discardTrailingNewline = true;
|
||
break;
|
||
}
|
||
case 10: {
|
||
lineEnd = this.position;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if (lineEnd === -1) {
|
||
break;
|
||
}
|
||
this.processLine(
|
||
this.buffer.subarray(lineStart, lineEnd),
|
||
this.fieldLength
|
||
);
|
||
lineStart = this.position;
|
||
this.fieldLength = -1;
|
||
}
|
||
if (lineStart === bufferLength) {
|
||
this.buffer = void 0;
|
||
} else if (lineStart !== 0) {
|
||
this.buffer = this.buffer.subarray(lineStart);
|
||
this.position -= lineStart;
|
||
}
|
||
}
|
||
processLine(line, fieldLength) {
|
||
if (line.length === 0) {
|
||
if (this.message.data === void 0) {
|
||
this.message.event = void 0;
|
||
return;
|
||
}
|
||
this.underlyingSink.message(this.message);
|
||
this.resetMessage();
|
||
return;
|
||
}
|
||
if (fieldLength > 0) {
|
||
const field = this.decoder.decode(line.subarray(0, fieldLength));
|
||
const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
|
||
const value = this.decoder.decode(line.subarray(valueOffset));
|
||
switch (field) {
|
||
case "data": {
|
||
this.message.data = this.message.data ? this.message.data + "\n" + value : value;
|
||
break;
|
||
}
|
||
case "event": {
|
||
this.message.event = value;
|
||
break;
|
||
}
|
||
case "id": {
|
||
this.message.id = value;
|
||
break;
|
||
}
|
||
case "retry": {
|
||
const retry = parseInt(value, 10);
|
||
if (!isNaN(retry)) {
|
||
this.message.retry = retry;
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/getResponse.mjs
|
||
var getResponse = async (handlers, request, resolutionContext) => {
|
||
const result = await executeHandlers({
|
||
request,
|
||
requestId: createRequestId(),
|
||
handlers,
|
||
resolutionContext
|
||
});
|
||
return result == null ? void 0 : result.response;
|
||
};
|
||
|
||
// node_modules/msw/lib/core/HttpResponse.mjs
|
||
var bodyType = Symbol("bodyType");
|
||
var _a3, _b2;
|
||
var HttpResponse = class _HttpResponse extends (_b2 = FetchResponse, _a3 = bodyType, _b2) {
|
||
constructor(body, init) {
|
||
const responseInit = normalizeResponseInit(init);
|
||
super(body, responseInit);
|
||
__publicField(this, _a3, null);
|
||
decorateResponse(this, responseInit);
|
||
}
|
||
static error() {
|
||
return super.error();
|
||
}
|
||
/**
|
||
* Create a `Response` with a `Content-Type: "text/plain"` body.
|
||
* @example
|
||
* HttpResponse.text('hello world')
|
||
* HttpResponse.text('Error', { status: 500 })
|
||
*/
|
||
static text(body, init) {
|
||
const responseInit = normalizeResponseInit(init);
|
||
if (!responseInit.headers.has("Content-Type")) {
|
||
responseInit.headers.set("Content-Type", "text/plain");
|
||
}
|
||
if (!responseInit.headers.has("Content-Length")) {
|
||
responseInit.headers.set(
|
||
"Content-Length",
|
||
body ? new Blob([body]).size.toString() : "0"
|
||
);
|
||
}
|
||
return new _HttpResponse(body, responseInit);
|
||
}
|
||
/**
|
||
* Create a `Response` with a `Content-Type: "application/json"` body.
|
||
* @example
|
||
* HttpResponse.json({ firstName: 'John' })
|
||
* HttpResponse.json({ error: 'Not Authorized' }, { status: 401 })
|
||
*/
|
||
static json(body, init) {
|
||
const responseInit = normalizeResponseInit(init);
|
||
if (!responseInit.headers.has("Content-Type")) {
|
||
responseInit.headers.set("Content-Type", "application/json");
|
||
}
|
||
const responseText = JSON.stringify(body);
|
||
if (!responseInit.headers.has("Content-Length")) {
|
||
responseInit.headers.set(
|
||
"Content-Length",
|
||
responseText ? new Blob([responseText]).size.toString() : "0"
|
||
);
|
||
}
|
||
return new _HttpResponse(responseText, responseInit);
|
||
}
|
||
/**
|
||
* Create a `Response` with a `Content-Type: "application/xml"` body.
|
||
* @example
|
||
* HttpResponse.xml(`<user name="John" />`)
|
||
* HttpResponse.xml(`<article id="abc-123" />`, { status: 201 })
|
||
*/
|
||
static xml(body, init) {
|
||
const responseInit = normalizeResponseInit(init);
|
||
if (!responseInit.headers.has("Content-Type")) {
|
||
responseInit.headers.set("Content-Type", "text/xml");
|
||
}
|
||
return new _HttpResponse(body, responseInit);
|
||
}
|
||
/**
|
||
* Create a `Response` with a `Content-Type: "text/html"` body.
|
||
* @example
|
||
* HttpResponse.html(`<p class="author">Jane Doe</p>`)
|
||
* HttpResponse.html(`<main id="abc-123">Main text</main>`, { status: 201 })
|
||
*/
|
||
static html(body, init) {
|
||
const responseInit = normalizeResponseInit(init);
|
||
if (!responseInit.headers.has("Content-Type")) {
|
||
responseInit.headers.set("Content-Type", "text/html");
|
||
}
|
||
return new _HttpResponse(body, responseInit);
|
||
}
|
||
/**
|
||
* Create a `Response` with an `ArrayBuffer` body.
|
||
* @example
|
||
* const buffer = new ArrayBuffer(3)
|
||
* const view = new Uint8Array(buffer)
|
||
* view.set([1, 2, 3])
|
||
*
|
||
* HttpResponse.arrayBuffer(buffer)
|
||
*/
|
||
static arrayBuffer(body, init) {
|
||
const responseInit = normalizeResponseInit(init);
|
||
if (!responseInit.headers.has("Content-Type")) {
|
||
responseInit.headers.set("Content-Type", "application/octet-stream");
|
||
}
|
||
if (body && !responseInit.headers.has("Content-Length")) {
|
||
responseInit.headers.set("Content-Length", body.byteLength.toString());
|
||
}
|
||
return new _HttpResponse(body, responseInit);
|
||
}
|
||
/**
|
||
* Create a `Response` with a `FormData` body.
|
||
* @example
|
||
* const data = new FormData()
|
||
* data.set('name', 'Alice')
|
||
*
|
||
* HttpResponse.formData(data)
|
||
*/
|
||
static formData(body, init) {
|
||
return new _HttpResponse(body, normalizeResponseInit(init));
|
||
}
|
||
};
|
||
|
||
// node_modules/msw/lib/core/bypass.mjs
|
||
function bypass(input, init) {
|
||
const request = new Request(
|
||
// If given a Request instance, clone it not to exhaust
|
||
// the original request's body.
|
||
input instanceof Request ? input.clone() : input,
|
||
init
|
||
);
|
||
invariant(
|
||
!request.bodyUsed,
|
||
'Failed to create a bypassed request to "%s %s": given request instance already has its body read. Make sure to clone the intercepted request if you wish to read its body before bypassing it.',
|
||
request.method,
|
||
request.url
|
||
);
|
||
const requestClone = request.clone();
|
||
requestClone.headers.append("accept", "msw/passthrough");
|
||
return requestClone;
|
||
}
|
||
|
||
// node_modules/msw/lib/core/passthrough.mjs
|
||
function passthrough() {
|
||
return new Response(null, {
|
||
status: 302,
|
||
statusText: "Passthrough",
|
||
headers: {
|
||
"x-msw-intention": "passthrough"
|
||
}
|
||
});
|
||
}
|
||
|
||
// node_modules/msw/lib/core/index.mjs
|
||
checkGlobals();
|
||
export {
|
||
GraphQLHandler,
|
||
HttpHandler,
|
||
HttpMethods,
|
||
HttpResponse,
|
||
MAX_SERVER_RESPONSE_TIME,
|
||
MIN_SERVER_RESPONSE_TIME,
|
||
NODE_SERVER_RESPONSE_TIME,
|
||
RequestHandler,
|
||
SET_TIMEOUT_MAX_ALLOWED_INT,
|
||
SetupApi,
|
||
WebSocketHandler,
|
||
bodyType,
|
||
bypass,
|
||
cleanUrl,
|
||
delay,
|
||
getResponse,
|
||
graphql,
|
||
handleRequest,
|
||
http,
|
||
isCommonAssetRequest,
|
||
matchRequestUrl,
|
||
onUnhandledRequest,
|
||
passthrough,
|
||
sse,
|
||
ws
|
||
};
|
||
//# sourceMappingURL=msw.js.map
|