msw 2.11.5 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/lib/browser/index.js +365 -308
  2. package/lib/browser/index.js.map +1 -1
  3. package/lib/browser/index.mjs +365 -308
  4. package/lib/browser/index.mjs.map +1 -1
  5. package/lib/core/index.d.mts +1 -0
  6. package/lib/core/index.d.ts +1 -0
  7. package/lib/core/index.js +2 -0
  8. package/lib/core/index.js.map +1 -1
  9. package/lib/core/index.mjs +4 -0
  10. package/lib/core/index.mjs.map +1 -1
  11. package/lib/core/sse.d.mts +116 -0
  12. package/lib/core/sse.d.ts +116 -0
  13. package/lib/core/sse.js +599 -0
  14. package/lib/core/sse.js.map +1 -0
  15. package/lib/core/sse.mjs +581 -0
  16. package/lib/core/sse.mjs.map +1 -0
  17. package/lib/core/utils/internal/isObject.d.mts +1 -1
  18. package/lib/core/utils/internal/isObject.d.ts +1 -1
  19. package/lib/core/utils/internal/isObject.js.map +1 -1
  20. package/lib/core/utils/internal/isObject.mjs.map +1 -1
  21. package/lib/core/ws/utils/attachWebSocketLogger.d.mts +7 -1
  22. package/lib/core/ws/utils/attachWebSocketLogger.d.ts +7 -1
  23. package/lib/core/ws/utils/attachWebSocketLogger.js +1 -0
  24. package/lib/core/ws/utils/attachWebSocketLogger.js.map +1 -1
  25. package/lib/core/ws/utils/attachWebSocketLogger.mjs +1 -0
  26. package/lib/core/ws/utils/attachWebSocketLogger.mjs.map +1 -1
  27. package/lib/core/ws/utils/getMessageLength.js +2 -1
  28. package/lib/core/ws/utils/getMessageLength.js.map +1 -1
  29. package/lib/core/ws/utils/getMessageLength.mjs +2 -1
  30. package/lib/core/ws/utils/getMessageLength.mjs.map +1 -1
  31. package/lib/core/ws/utils/getPublicData.js +2 -1
  32. package/lib/core/ws/utils/getPublicData.js.map +1 -1
  33. package/lib/core/ws/utils/getPublicData.mjs +2 -1
  34. package/lib/core/ws/utils/getPublicData.mjs.map +1 -1
  35. package/lib/iife/index.js +1367 -746
  36. package/lib/iife/index.js.map +1 -1
  37. package/lib/mockServiceWorker.js +1 -1
  38. package/package.json +6 -4
  39. package/src/browser/tsconfig.browser.json +1 -1
  40. package/src/core/index.ts +9 -0
  41. package/src/core/sse.ts +897 -0
  42. package/src/core/utils/internal/isObject.ts +1 -1
  43. package/src/core/ws/utils/attachWebSocketLogger.ts +1 -1
  44. package/src/core/ws/utils/getMessageLength.ts +2 -1
  45. package/src/core/ws/utils/getPublicData.ts +3 -2
package/lib/iife/index.js CHANGED
@@ -13447,6 +13447,7 @@ ${operationTypes.join("\n")}
13447
13447
  onUnhandledRequest: () => onUnhandledRequest,
13448
13448
  passthrough: () => passthrough,
13449
13449
  setupWorker: () => setupWorker,
13450
+ sse: () => sse,
13450
13451
  ws: () => ws
13451
13452
  });
13452
13453
 
@@ -14395,7 +14396,7 @@ ${operationTypes.join("\n")}
14395
14396
  return stringToRegexp(path, keys, options);
14396
14397
  }
14397
14398
 
14398
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs
14399
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs
14399
14400
  var encoder = new TextEncoder();
14400
14401
  function encodeBuffer(text) {
14401
14402
  return encoder.encode(text);
@@ -14411,100 +14412,6 @@ ${operationTypes.join("\n")}
14411
14412
  );
14412
14413
  }
14413
14414
 
14414
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-3RXCRGL2.mjs
14415
- var IS_PATCHED_MODULE = Symbol("isPatchedModule");
14416
- function canParseUrl(url) {
14417
- try {
14418
- new URL(url);
14419
- return true;
14420
- } catch (_error) {
14421
- return false;
14422
- }
14423
- }
14424
- function getValueBySymbol(symbolName, source) {
14425
- const ownSymbols = Object.getOwnPropertySymbols(source);
14426
- const symbol = ownSymbols.find((symbol2) => {
14427
- return symbol2.description === symbolName;
14428
- });
14429
- if (symbol) {
14430
- return Reflect.get(source, symbol);
14431
- }
14432
- return;
14433
- }
14434
- var _FetchResponse = class extends Response {
14435
- static isConfigurableStatusCode(status) {
14436
- return status >= 200 && status <= 599;
14437
- }
14438
- static isRedirectResponse(status) {
14439
- return _FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status);
14440
- }
14441
- /**
14442
- * Returns a boolean indicating whether the given response status
14443
- * code represents a response that can have a body.
14444
- */
14445
- static isResponseWithBody(status) {
14446
- return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
14447
- }
14448
- static setUrl(url, response) {
14449
- if (!url || url === "about:" || !canParseUrl(url)) {
14450
- return;
14451
- }
14452
- const state = getValueBySymbol("state", response);
14453
- if (state) {
14454
- state.urlList.push(new URL(url));
14455
- } else {
14456
- Object.defineProperty(response, "url", {
14457
- value: url,
14458
- enumerable: true,
14459
- configurable: true,
14460
- writable: false
14461
- });
14462
- }
14463
- }
14464
- /**
14465
- * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
14466
- */
14467
- static parseRawHeaders(rawHeaders) {
14468
- const headers = new Headers();
14469
- for (let line = 0; line < rawHeaders.length; line += 2) {
14470
- headers.append(rawHeaders[line], rawHeaders[line + 1]);
14471
- }
14472
- return headers;
14473
- }
14474
- constructor(body, init = {}) {
14475
- var _a2;
14476
- const status = (_a2 = init.status) != null ? _a2 : 200;
14477
- const safeStatus = _FetchResponse.isConfigurableStatusCode(status) ? status : 200;
14478
- const finalBody = _FetchResponse.isResponseWithBody(status) ? body : null;
14479
- super(finalBody, {
14480
- status: safeStatus,
14481
- statusText: init.statusText,
14482
- headers: init.headers
14483
- });
14484
- if (status !== safeStatus) {
14485
- const state = getValueBySymbol("state", this);
14486
- if (state) {
14487
- state.status = status;
14488
- } else {
14489
- Object.defineProperty(this, "status", {
14490
- value: status,
14491
- enumerable: true,
14492
- configurable: true,
14493
- writable: false
14494
- });
14495
- }
14496
- }
14497
- _FetchResponse.setUrl(init.url, this);
14498
- }
14499
- };
14500
- var FetchResponse = _FetchResponse;
14501
- FetchResponse.STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304];
14502
- FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308];
14503
- var kRawRequest = Symbol("kRawRequest");
14504
- function setRawRequest(request, rawRequest) {
14505
- Reflect.set(request, kRawRequest, rawRequest);
14506
- }
14507
-
14508
14415
  // node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs
14509
14416
  function isNodeProcess() {
14510
14417
  if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
@@ -14792,7 +14699,20 @@ ${operationTypes.join("\n")}
14792
14699
  return message4.toString();
14793
14700
  }
14794
14701
 
14795
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs
14702
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-Z5TSB3T6.mjs
14703
+ var __accessCheck = (obj, member, msg) => {
14704
+ if (!member.has(obj))
14705
+ throw TypeError("Cannot " + msg);
14706
+ };
14707
+ var __privateGet = (obj, member, getter) => {
14708
+ __accessCheck(obj, member, "read from private field");
14709
+ return getter ? getter.call(obj) : member.get(obj);
14710
+ };
14711
+ var __privateAdd = (obj, member, value) => {
14712
+ if (member.has(obj))
14713
+ throw TypeError("Cannot add the same private member more than once");
14714
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
14715
+ };
14796
14716
  var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id";
14797
14717
  function getGlobalSymbol(symbol) {
14798
14718
  return (
@@ -14940,92 +14860,339 @@ ${operationTypes.join("\n")}
14940
14860
  return Math.random().toString(16).slice(2);
14941
14861
  }
14942
14862
 
14943
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/index.mjs
14944
- var BatchInterceptor = class extends Interceptor {
14945
- constructor(options) {
14946
- BatchInterceptor.symbol = Symbol(options.name);
14947
- super(BatchInterceptor.symbol);
14948
- this.interceptors = options.interceptors;
14863
+ // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
14864
+ function createDeferredExecutor() {
14865
+ const executor = (resolve, reject) => {
14866
+ executor.state = "pending";
14867
+ executor.resolve = (data) => {
14868
+ if (executor.state !== "pending") {
14869
+ return;
14870
+ }
14871
+ executor.result = data;
14872
+ const onFulfilled = (value) => {
14873
+ executor.state = "fulfilled";
14874
+ return value;
14875
+ };
14876
+ return resolve(
14877
+ data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
14878
+ );
14879
+ };
14880
+ executor.reject = (reason) => {
14881
+ if (executor.state !== "pending") {
14882
+ return;
14883
+ }
14884
+ queueMicrotask(() => {
14885
+ executor.state = "rejected";
14886
+ });
14887
+ return reject(executor.rejectionReason = reason);
14888
+ };
14889
+ };
14890
+ return executor;
14891
+ }
14892
+ var DeferredPromise = class extends Promise {
14893
+ #executor;
14894
+ resolve;
14895
+ reject;
14896
+ constructor(executor = null) {
14897
+ const deferredExecutor = createDeferredExecutor();
14898
+ super((originalResolve, originalReject) => {
14899
+ deferredExecutor(originalResolve, originalReject);
14900
+ executor?.(deferredExecutor.resolve, deferredExecutor.reject);
14901
+ });
14902
+ this.#executor = deferredExecutor;
14903
+ this.resolve = this.#executor.resolve;
14904
+ this.reject = this.#executor.reject;
14949
14905
  }
14950
- setup() {
14951
- const logger = this.logger.extend("setup");
14952
- logger.info("applying all %d interceptors...", this.interceptors.length);
14953
- for (const interceptor of this.interceptors) {
14954
- logger.info('applying "%s" interceptor...', interceptor.constructor.name);
14955
- interceptor.apply();
14956
- logger.info("adding interceptor dispose subscription");
14957
- this.subscriptions.push(() => interceptor.dispose());
14958
- }
14906
+ get state() {
14907
+ return this.#executor.state;
14959
14908
  }
14960
- on(event, listener) {
14961
- for (const interceptor of this.interceptors) {
14962
- interceptor.on(event, listener);
14963
- }
14964
- return this;
14909
+ get rejectionReason() {
14910
+ return this.#executor.rejectionReason;
14965
14911
  }
14966
- once(event, listener) {
14967
- for (const interceptor of this.interceptors) {
14968
- interceptor.once(event, listener);
14969
- }
14970
- return this;
14912
+ then(onFulfilled, onRejected) {
14913
+ return this.#decorate(super.then(onFulfilled, onRejected));
14971
14914
  }
14972
- off(event, listener) {
14973
- for (const interceptor of this.interceptors) {
14974
- interceptor.off(event, listener);
14975
- }
14976
- return this;
14915
+ catch(onRejected) {
14916
+ return this.#decorate(super.catch(onRejected));
14977
14917
  }
14978
- removeAllListeners(event) {
14979
- for (const interceptors of this.interceptors) {
14980
- interceptors.removeAllListeners(event);
14981
- }
14982
- return this;
14918
+ finally(onfinally) {
14919
+ return this.#decorate(super.finally(onfinally));
14920
+ }
14921
+ #decorate(promise) {
14922
+ return Object.defineProperties(promise, {
14923
+ resolve: { configurable: true, value: this.resolve },
14924
+ reject: { configurable: true, value: this.reject }
14925
+ });
14983
14926
  }
14984
14927
  };
14985
- function getCleanUrl(url, isAbsolute = true) {
14986
- return [isAbsolute && url.origin, url.pathname].filter(Boolean).join("");
14987
- }
14988
14928
 
14989
- // src/core/utils/url/cleanUrl.ts
14990
- var REDUNDANT_CHARACTERS_EXP = /[?|#].*$/g;
14991
- function cleanUrl(path) {
14992
- if (path.endsWith("?")) {
14993
- return path;
14929
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-LIKZF2VU.mjs
14930
+ var IS_PATCHED_MODULE = Symbol("isPatchedModule");
14931
+ var InterceptorError = class extends Error {
14932
+ constructor(message4) {
14933
+ super(message4);
14934
+ this.name = "InterceptorError";
14935
+ Object.setPrototypeOf(this, InterceptorError.prototype);
14994
14936
  }
14995
- return path.replace(REDUNDANT_CHARACTERS_EXP, "");
14996
- }
14997
-
14998
- // src/core/utils/url/isAbsoluteUrl.ts
14999
- function isAbsoluteUrl(url) {
15000
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
15001
- }
15002
-
15003
- // src/core/utils/url/getAbsoluteUrl.ts
15004
- function getAbsoluteUrl(path, baseUrl) {
15005
- if (isAbsoluteUrl(path)) {
15006
- return path;
14937
+ };
14938
+ var _handled;
14939
+ var handled_get;
14940
+ var _RequestController = class {
14941
+ constructor(request, source) {
14942
+ this.request = request;
14943
+ this.source = source;
14944
+ __privateAdd(this, _handled);
14945
+ this.readyState = _RequestController.PENDING;
14946
+ this.handled = new DeferredPromise();
15007
14947
  }
15008
- if (path.startsWith("*")) {
15009
- return path;
14948
+ /**
14949
+ * Perform this request as-is.
14950
+ */
14951
+ async passthrough() {
14952
+ invariant.as(
14953
+ InterceptorError,
14954
+ this.readyState === _RequestController.PENDING,
14955
+ 'Failed to passthrough the "%s %s" request: the request has already been handled',
14956
+ this.request.method,
14957
+ this.request.url
14958
+ );
14959
+ this.readyState = _RequestController.PASSTHROUGH;
14960
+ await this.source.passthrough();
14961
+ __privateGet(this, _handled, handled_get).resolve();
15010
14962
  }
15011
- const origin = baseUrl || typeof location !== "undefined" && location.href;
15012
- return origin ? (
15013
- // Encode and decode the path to preserve escaped characters.
15014
- decodeURI(new URL(encodeURI(path), origin).href)
15015
- ) : path;
15016
- }
15017
-
15018
- // src/core/utils/matching/normalizePath.ts
15019
- function normalizePath(path, baseUrl) {
15020
- if (path instanceof RegExp) {
15021
- return path;
14963
+ /**
14964
+ * Respond to this request with the given `Response` instance.
14965
+ *
14966
+ * @example
14967
+ * controller.respondWith(new Response())
14968
+ * controller.respondWith(Response.json({ id }))
14969
+ * controller.respondWith(Response.error())
14970
+ */
14971
+ respondWith(response) {
14972
+ invariant.as(
14973
+ InterceptorError,
14974
+ this.readyState === _RequestController.PENDING,
14975
+ 'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)',
14976
+ this.request.method,
14977
+ this.request.url,
14978
+ response.status,
14979
+ response.statusText || "OK",
14980
+ this.readyState
14981
+ );
14982
+ this.readyState = _RequestController.RESPONSE;
14983
+ __privateGet(this, _handled, handled_get).resolve();
14984
+ this.source.respondWith(response);
15022
14985
  }
15023
- const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
15024
- return cleanUrl(maybeAbsoluteUrl);
15025
- }
15026
-
15027
- // src/core/utils/matching/matchRequestUrl.ts
15028
- function coercePath(path) {
14986
+ /**
14987
+ * Error this request with the given reason.
14988
+ *
14989
+ * @example
14990
+ * controller.errorWith()
14991
+ * controller.errorWith(new Error('Oops!'))
14992
+ * controller.errorWith({ message: 'Oops!'})
14993
+ */
14994
+ errorWith(reason) {
14995
+ invariant.as(
14996
+ InterceptorError,
14997
+ this.readyState === _RequestController.PENDING,
14998
+ 'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)',
14999
+ this.request.method,
15000
+ this.request.url,
15001
+ reason == null ? void 0 : reason.toString(),
15002
+ this.readyState
15003
+ );
15004
+ this.readyState = _RequestController.ERROR;
15005
+ this.source.errorWith(reason);
15006
+ __privateGet(this, _handled, handled_get).resolve();
15007
+ }
15008
+ };
15009
+ var RequestController = _RequestController;
15010
+ _handled = /* @__PURE__ */ new WeakSet();
15011
+ handled_get = function() {
15012
+ return this.handled;
15013
+ };
15014
+ RequestController.PENDING = 0;
15015
+ RequestController.PASSTHROUGH = 1;
15016
+ RequestController.RESPONSE = 2;
15017
+ RequestController.ERROR = 3;
15018
+ function canParseUrl(url) {
15019
+ try {
15020
+ new URL(url);
15021
+ return true;
15022
+ } catch (_error) {
15023
+ return false;
15024
+ }
15025
+ }
15026
+ function getValueBySymbol(symbolName, source) {
15027
+ const ownSymbols = Object.getOwnPropertySymbols(source);
15028
+ const symbol = ownSymbols.find((symbol2) => {
15029
+ return symbol2.description === symbolName;
15030
+ });
15031
+ if (symbol) {
15032
+ return Reflect.get(source, symbol);
15033
+ }
15034
+ return;
15035
+ }
15036
+ var _FetchResponse = class extends Response {
15037
+ static isConfigurableStatusCode(status) {
15038
+ return status >= 200 && status <= 599;
15039
+ }
15040
+ static isRedirectResponse(status) {
15041
+ return _FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status);
15042
+ }
15043
+ /**
15044
+ * Returns a boolean indicating whether the given response status
15045
+ * code represents a response that can have a body.
15046
+ */
15047
+ static isResponseWithBody(status) {
15048
+ return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
15049
+ }
15050
+ static setUrl(url, response) {
15051
+ if (!url || url === "about:" || !canParseUrl(url)) {
15052
+ return;
15053
+ }
15054
+ const state = getValueBySymbol("state", response);
15055
+ if (state) {
15056
+ state.urlList.push(new URL(url));
15057
+ } else {
15058
+ Object.defineProperty(response, "url", {
15059
+ value: url,
15060
+ enumerable: true,
15061
+ configurable: true,
15062
+ writable: false
15063
+ });
15064
+ }
15065
+ }
15066
+ /**
15067
+ * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
15068
+ */
15069
+ static parseRawHeaders(rawHeaders) {
15070
+ const headers = new Headers();
15071
+ for (let line = 0; line < rawHeaders.length; line += 2) {
15072
+ headers.append(rawHeaders[line], rawHeaders[line + 1]);
15073
+ }
15074
+ return headers;
15075
+ }
15076
+ constructor(body, init = {}) {
15077
+ var _a2;
15078
+ const status = (_a2 = init.status) != null ? _a2 : 200;
15079
+ const safeStatus = _FetchResponse.isConfigurableStatusCode(status) ? status : 200;
15080
+ const finalBody = _FetchResponse.isResponseWithBody(status) ? body : null;
15081
+ super(finalBody, {
15082
+ status: safeStatus,
15083
+ statusText: init.statusText,
15084
+ headers: init.headers
15085
+ });
15086
+ if (status !== safeStatus) {
15087
+ const state = getValueBySymbol("state", this);
15088
+ if (state) {
15089
+ state.status = status;
15090
+ } else {
15091
+ Object.defineProperty(this, "status", {
15092
+ value: status,
15093
+ enumerable: true,
15094
+ configurable: true,
15095
+ writable: false
15096
+ });
15097
+ }
15098
+ }
15099
+ _FetchResponse.setUrl(init.url, this);
15100
+ }
15101
+ };
15102
+ var FetchResponse = _FetchResponse;
15103
+ FetchResponse.STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304];
15104
+ FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308];
15105
+ var kRawRequest = Symbol("kRawRequest");
15106
+ function setRawRequest(request, rawRequest) {
15107
+ Reflect.set(request, kRawRequest, rawRequest);
15108
+ }
15109
+
15110
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/index.mjs
15111
+ var BatchInterceptor = class extends Interceptor {
15112
+ constructor(options) {
15113
+ BatchInterceptor.symbol = Symbol(options.name);
15114
+ super(BatchInterceptor.symbol);
15115
+ this.interceptors = options.interceptors;
15116
+ }
15117
+ setup() {
15118
+ const logger = this.logger.extend("setup");
15119
+ logger.info("applying all %d interceptors...", this.interceptors.length);
15120
+ for (const interceptor of this.interceptors) {
15121
+ logger.info('applying "%s" interceptor...', interceptor.constructor.name);
15122
+ interceptor.apply();
15123
+ logger.info("adding interceptor dispose subscription");
15124
+ this.subscriptions.push(() => interceptor.dispose());
15125
+ }
15126
+ }
15127
+ on(event, listener) {
15128
+ for (const interceptor of this.interceptors) {
15129
+ interceptor.on(event, listener);
15130
+ }
15131
+ return this;
15132
+ }
15133
+ once(event, listener) {
15134
+ for (const interceptor of this.interceptors) {
15135
+ interceptor.once(event, listener);
15136
+ }
15137
+ return this;
15138
+ }
15139
+ off(event, listener) {
15140
+ for (const interceptor of this.interceptors) {
15141
+ interceptor.off(event, listener);
15142
+ }
15143
+ return this;
15144
+ }
15145
+ removeAllListeners(event) {
15146
+ for (const interceptors of this.interceptors) {
15147
+ interceptors.removeAllListeners(event);
15148
+ }
15149
+ return this;
15150
+ }
15151
+ };
15152
+ function getCleanUrl(url, isAbsolute = true) {
15153
+ return [isAbsolute && url.origin, url.pathname].filter(Boolean).join("");
15154
+ }
15155
+
15156
+ // src/core/utils/url/cleanUrl.ts
15157
+ var REDUNDANT_CHARACTERS_EXP = /[?|#].*$/g;
15158
+ function cleanUrl(path) {
15159
+ if (path.endsWith("?")) {
15160
+ return path;
15161
+ }
15162
+ return path.replace(REDUNDANT_CHARACTERS_EXP, "");
15163
+ }
15164
+
15165
+ // src/core/utils/url/isAbsoluteUrl.ts
15166
+ function isAbsoluteUrl(url) {
15167
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
15168
+ }
15169
+
15170
+ // src/core/utils/url/getAbsoluteUrl.ts
15171
+ function getAbsoluteUrl(path, baseUrl) {
15172
+ if (isAbsoluteUrl(path)) {
15173
+ return path;
15174
+ }
15175
+ if (path.startsWith("*")) {
15176
+ return path;
15177
+ }
15178
+ const origin = baseUrl || typeof location !== "undefined" && location.href;
15179
+ return origin ? (
15180
+ // Encode and decode the path to preserve escaped characters.
15181
+ decodeURI(new URL(encodeURI(path), origin).href)
15182
+ ) : path;
15183
+ }
15184
+
15185
+ // src/core/utils/matching/normalizePath.ts
15186
+ function normalizePath(path, baseUrl) {
15187
+ if (path instanceof RegExp) {
15188
+ return path;
15189
+ }
15190
+ const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
15191
+ return cleanUrl(maybeAbsoluteUrl);
15192
+ }
15193
+
15194
+ // src/core/utils/matching/matchRequestUrl.ts
15195
+ function coercePath(path) {
15029
15196
  return path.replace(
15030
15197
  /([:a-zA-Z_-]*)(\*{1,2})+/g,
15031
15198
  (_, parameterName, wildcard) => {
@@ -18836,106 +19003,40 @@ Consider naming this operation or using "graphql.operation()" request handler to
18836
19003
  }
18837
19004
  };
18838
19005
 
18839
- // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
18840
- function createDeferredExecutor() {
18841
- const executor = (resolve, reject) => {
18842
- executor.state = "pending";
18843
- executor.resolve = (data) => {
18844
- if (executor.state !== "pending") {
18845
- return;
18846
- }
18847
- executor.result = data;
18848
- const onFulfilled = (value) => {
18849
- executor.state = "fulfilled";
18850
- return value;
18851
- };
18852
- return resolve(
18853
- data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
19006
+ // src/core/ws/WebSocketIndexedDBClientStore.ts
19007
+ var DB_NAME = "msw-websocket-clients";
19008
+ var DB_STORE_NAME = "clients";
19009
+ var WebSocketIndexedDBClientStore = class {
19010
+ db;
19011
+ constructor() {
19012
+ this.db = this.createDatabase();
19013
+ }
19014
+ async add(client) {
19015
+ const promise = new DeferredPromise();
19016
+ const store = await this.getStore();
19017
+ const request = store.put({
19018
+ id: client.id,
19019
+ url: client.url.href
19020
+ });
19021
+ request.onsuccess = () => {
19022
+ promise.resolve();
19023
+ };
19024
+ request.onerror = () => {
19025
+ console.error(request.error);
19026
+ promise.reject(
19027
+ new Error(
19028
+ `Failed to add WebSocket client "${client.id}". There is likely an additional output above.`
19029
+ )
18854
19030
  );
18855
19031
  };
18856
- executor.reject = (reason) => {
18857
- if (executor.state !== "pending") {
18858
- return;
18859
- }
18860
- queueMicrotask(() => {
18861
- executor.state = "rejected";
18862
- });
18863
- return reject(executor.rejectionReason = reason);
18864
- };
18865
- };
18866
- return executor;
18867
- }
18868
- var DeferredPromise = class extends Promise {
18869
- #executor;
18870
- resolve;
18871
- reject;
18872
- constructor(executor = null) {
18873
- const deferredExecutor = createDeferredExecutor();
18874
- super((originalResolve, originalReject) => {
18875
- deferredExecutor(originalResolve, originalReject);
18876
- executor?.(deferredExecutor.resolve, deferredExecutor.reject);
18877
- });
18878
- this.#executor = deferredExecutor;
18879
- this.resolve = this.#executor.resolve;
18880
- this.reject = this.#executor.reject;
18881
- }
18882
- get state() {
18883
- return this.#executor.state;
18884
- }
18885
- get rejectionReason() {
18886
- return this.#executor.rejectionReason;
18887
- }
18888
- then(onFulfilled, onRejected) {
18889
- return this.#decorate(super.then(onFulfilled, onRejected));
18890
- }
18891
- catch(onRejected) {
18892
- return this.#decorate(super.catch(onRejected));
18893
- }
18894
- finally(onfinally) {
18895
- return this.#decorate(super.finally(onfinally));
18896
- }
18897
- #decorate(promise) {
18898
- return Object.defineProperties(promise, {
18899
- resolve: { configurable: true, value: this.resolve },
18900
- reject: { configurable: true, value: this.reject }
18901
- });
18902
- }
18903
- };
18904
-
18905
- // src/core/ws/WebSocketIndexedDBClientStore.ts
18906
- var DB_NAME = "msw-websocket-clients";
18907
- var DB_STORE_NAME = "clients";
18908
- var WebSocketIndexedDBClientStore = class {
18909
- db;
18910
- constructor() {
18911
- this.db = this.createDatabase();
18912
- }
18913
- async add(client) {
18914
- const promise = new DeferredPromise();
18915
- const store = await this.getStore();
18916
- const request = store.put({
18917
- id: client.id,
18918
- url: client.url.href
18919
- });
18920
- request.onsuccess = () => {
18921
- promise.resolve();
18922
- };
18923
- request.onerror = () => {
18924
- console.error(request.error);
18925
- promise.reject(
18926
- new Error(
18927
- `Failed to add WebSocket client "${client.id}". There is likely an additional output above.`
18928
- )
18929
- );
18930
- };
18931
- return promise;
18932
- }
18933
- async getAll() {
18934
- const promise = new DeferredPromise();
18935
- const store = await this.getStore();
18936
- const request = store.getAll();
18937
- request.onsuccess = () => {
18938
- promise.resolve(request.result);
19032
+ return promise;
19033
+ }
19034
+ async getAll() {
19035
+ const promise = new DeferredPromise();
19036
+ const store = await this.getStore();
19037
+ const request = store.getAll();
19038
+ request.onsuccess = () => {
19039
+ promise.resolve(request.result);
18939
19040
  };
18940
19041
  request.onerror = () => {
18941
19042
  console.log(request.error);
@@ -19180,12 +19281,826 @@ Consider naming this operation or using "graphql.operation()" request handler to
19180
19281
  if (!ignoreClients.includes(otherClient.id)) {
19181
19282
  otherClient.send(data);
19182
19283
  }
19183
- });
19284
+ });
19285
+ }
19286
+ };
19287
+ }
19288
+ var ws = {
19289
+ link: createWebSocketLinkHandler
19290
+ };
19291
+
19292
+ // src/core/delay.ts
19293
+ var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
19294
+ var MIN_SERVER_RESPONSE_TIME = 100;
19295
+ var MAX_SERVER_RESPONSE_TIME = 400;
19296
+ var NODE_SERVER_RESPONSE_TIME = 5;
19297
+ function getRealisticResponseTime() {
19298
+ if (isNodeProcess()) {
19299
+ return NODE_SERVER_RESPONSE_TIME;
19300
+ }
19301
+ return Math.floor(
19302
+ Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
19303
+ );
19304
+ }
19305
+ async function delay(durationOrMode) {
19306
+ let delayTime;
19307
+ if (typeof durationOrMode === "string") {
19308
+ switch (durationOrMode) {
19309
+ case "infinite": {
19310
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
19311
+ break;
19312
+ }
19313
+ case "real": {
19314
+ delayTime = getRealisticResponseTime();
19315
+ break;
19316
+ }
19317
+ default: {
19318
+ throw new Error(
19319
+ `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
19320
+ );
19321
+ }
19322
+ }
19323
+ } else if (typeof durationOrMode === "undefined") {
19324
+ delayTime = getRealisticResponseTime();
19325
+ } else {
19326
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
19327
+ throw new Error(
19328
+ `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.`
19329
+ );
19330
+ }
19331
+ delayTime = durationOrMode;
19332
+ }
19333
+ return new Promise((resolve) => setTimeout(resolve, delayTime));
19334
+ }
19335
+
19336
+ // src/core/utils/internal/isObject.ts
19337
+ function isObject2(value) {
19338
+ return value != null && typeof value === "object" && !Array.isArray(value);
19339
+ }
19340
+
19341
+ // src/core/ws/utils/getMessageLength.ts
19342
+ function getMessageLength(data) {
19343
+ if (data instanceof Blob) {
19344
+ return data.size;
19345
+ }
19346
+ if (isObject2(data) && "byteLength" in data) {
19347
+ return data.byteLength;
19348
+ }
19349
+ return new Blob([data]).size;
19350
+ }
19351
+
19352
+ // src/core/ws/utils/truncateMessage.ts
19353
+ var MAX_LENGTH = 24;
19354
+ function truncateMessage(message4) {
19355
+ if (message4.length <= MAX_LENGTH) {
19356
+ return message4;
19357
+ }
19358
+ return `${message4.slice(0, MAX_LENGTH)}\u2026`;
19359
+ }
19360
+
19361
+ // src/core/ws/utils/getPublicData.ts
19362
+ async function getPublicData(data) {
19363
+ if (data instanceof Blob) {
19364
+ const text = await data.text();
19365
+ return `Blob(${truncateMessage(text)})`;
19366
+ }
19367
+ if (isObject2(data)) {
19368
+ const text = new TextDecoder().decode(data);
19369
+ return `ArrayBuffer(${truncateMessage(text)})`;
19370
+ }
19371
+ return truncateMessage(data);
19372
+ }
19373
+
19374
+ // src/core/ws/utils/attachWebSocketLogger.ts
19375
+ var colors = {
19376
+ system: "#3b82f6",
19377
+ outgoing: "#22c55e",
19378
+ incoming: "#ef4444",
19379
+ mocked: "#ff6a33"
19380
+ };
19381
+ function attachWebSocketLogger(connection) {
19382
+ const { client, server } = connection;
19383
+ logConnectionOpen(client);
19384
+ client.addEventListener("message", (event) => {
19385
+ logOutgoingClientMessage(event);
19386
+ });
19387
+ client.addEventListener("close", (event) => {
19388
+ logConnectionClose(event);
19389
+ });
19390
+ client.socket.addEventListener("error", (event) => {
19391
+ logClientError(event);
19392
+ });
19393
+ client.send = new Proxy(client.send, {
19394
+ apply(target, thisArg, args) {
19395
+ const [data] = args;
19396
+ const messageEvent = new MessageEvent("message", { data });
19397
+ Object.defineProperties(messageEvent, {
19398
+ currentTarget: {
19399
+ enumerable: true,
19400
+ writable: false,
19401
+ value: client.socket
19402
+ },
19403
+ target: {
19404
+ enumerable: true,
19405
+ writable: false,
19406
+ value: client.socket
19407
+ }
19408
+ });
19409
+ queueMicrotask(() => {
19410
+ logIncomingMockedClientMessage(messageEvent);
19411
+ });
19412
+ return Reflect.apply(target, thisArg, args);
19413
+ }
19414
+ });
19415
+ server.addEventListener(
19416
+ "open",
19417
+ () => {
19418
+ server.addEventListener("message", (event) => {
19419
+ logIncomingServerMessage(event);
19420
+ });
19421
+ },
19422
+ { once: true }
19423
+ );
19424
+ server.send = new Proxy(server.send, {
19425
+ apply(target, thisArg, args) {
19426
+ const [data] = args;
19427
+ const messageEvent = new MessageEvent("message", { data });
19428
+ Object.defineProperties(messageEvent, {
19429
+ currentTarget: {
19430
+ enumerable: true,
19431
+ writable: false,
19432
+ value: server.socket
19433
+ },
19434
+ target: {
19435
+ enumerable: true,
19436
+ writable: false,
19437
+ value: server.socket
19438
+ }
19439
+ });
19440
+ logOutgoingMockedClientMessage(messageEvent);
19441
+ return Reflect.apply(target, thisArg, args);
19442
+ }
19443
+ });
19444
+ }
19445
+ function logConnectionOpen(client) {
19446
+ const publicUrl = toPublicUrl(client.url);
19447
+ console.groupCollapsed(
19448
+ devUtils.formatMessage(`${getTimestamp()} %c\u25B6%c ${publicUrl}`),
19449
+ `color:${colors.system}`,
19450
+ "color:inherit"
19451
+ );
19452
+ console.log("Client:", client.socket);
19453
+ console.groupEnd();
19454
+ }
19455
+ function logConnectionClose(event) {
19456
+ const target = event.target;
19457
+ const publicUrl = toPublicUrl(target.url);
19458
+ console.groupCollapsed(
19459
+ devUtils.formatMessage(
19460
+ `${getTimestamp({ milliseconds: true })} %c\u25A0%c ${publicUrl}`
19461
+ ),
19462
+ `color:${colors.system}`,
19463
+ "color:inherit"
19464
+ );
19465
+ console.log(event);
19466
+ console.groupEnd();
19467
+ }
19468
+ function logClientError(event) {
19469
+ const socket = event.target;
19470
+ const publicUrl = toPublicUrl(socket.url);
19471
+ console.groupCollapsed(
19472
+ devUtils.formatMessage(
19473
+ `${getTimestamp({ milliseconds: true })} %c\xD7%c ${publicUrl}`
19474
+ ),
19475
+ `color:${colors.system}`,
19476
+ "color:inherit"
19477
+ );
19478
+ console.log(event);
19479
+ console.groupEnd();
19480
+ }
19481
+ async function logOutgoingClientMessage(event) {
19482
+ const byteLength = getMessageLength(event.data);
19483
+ const publicData = await getPublicData(event.data);
19484
+ const arrow = event.defaultPrevented ? "\u21E1" : "\u2B06";
19485
+ console.groupCollapsed(
19486
+ devUtils.formatMessage(
19487
+ `${getTimestamp({ milliseconds: true })} %c${arrow}%c ${publicData} %c${byteLength}%c`
19488
+ ),
19489
+ `color:${colors.outgoing}`,
19490
+ "color:inherit",
19491
+ "color:gray;font-weight:normal",
19492
+ "color:inherit;font-weight:inherit"
19493
+ );
19494
+ console.log(event);
19495
+ console.groupEnd();
19496
+ }
19497
+ async function logOutgoingMockedClientMessage(event) {
19498
+ const byteLength = getMessageLength(event.data);
19499
+ const publicData = await getPublicData(event.data);
19500
+ console.groupCollapsed(
19501
+ devUtils.formatMessage(
19502
+ `${getTimestamp({ milliseconds: true })} %c\u2B06%c ${publicData} %c${byteLength}%c`
19503
+ ),
19504
+ `color:${colors.mocked}`,
19505
+ "color:inherit",
19506
+ "color:gray;font-weight:normal",
19507
+ "color:inherit;font-weight:inherit"
19508
+ );
19509
+ console.log(event);
19510
+ console.groupEnd();
19511
+ }
19512
+ async function logIncomingMockedClientMessage(event) {
19513
+ const byteLength = getMessageLength(event.data);
19514
+ const publicData = await getPublicData(event.data);
19515
+ console.groupCollapsed(
19516
+ devUtils.formatMessage(
19517
+ `${getTimestamp({ milliseconds: true })} %c\u2B07%c ${publicData} %c${byteLength}%c`
19518
+ ),
19519
+ `color:${colors.mocked}`,
19520
+ "color:inherit",
19521
+ "color:gray;font-weight:normal",
19522
+ "color:inherit;font-weight:inherit"
19523
+ );
19524
+ console.log(event);
19525
+ console.groupEnd();
19526
+ }
19527
+ async function logIncomingServerMessage(event) {
19528
+ const byteLength = getMessageLength(event.data);
19529
+ const publicData = await getPublicData(event.data);
19530
+ const arrow = event.defaultPrevented ? "\u21E3" : "\u2B07";
19531
+ console.groupCollapsed(
19532
+ devUtils.formatMessage(
19533
+ `${getTimestamp({ milliseconds: true })} %c${arrow}%c ${publicData} %c${byteLength}%c`
19534
+ ),
19535
+ `color:${colors.incoming}`,
19536
+ "color:inherit",
19537
+ "color:gray;font-weight:normal",
19538
+ "color:inherit;font-weight:inherit"
19539
+ );
19540
+ console.log(event);
19541
+ console.groupEnd();
19542
+ }
19543
+
19544
+ // src/core/sse.ts
19545
+ var sse = (path, resolver) => {
19546
+ return new ServerSentEventHandler(path, resolver);
19547
+ };
19548
+ var ServerSentEventHandler = class extends HttpHandler {
19549
+ constructor(path, resolver) {
19550
+ invariant(
19551
+ typeof EventSource !== "undefined",
19552
+ 'Failed to construct a Server-Sent Event handler for path "%s": the EventSource API is not supported in this environment',
19553
+ path
19554
+ );
19555
+ const clientEmitter = new Emitter();
19556
+ super("GET", path, async (info) => {
19557
+ const responseInit = {
19558
+ headers: {
19559
+ "content-type": "text/event-stream",
19560
+ "cache-control": "no-cache",
19561
+ connection: "keep-alive"
19562
+ }
19563
+ };
19564
+ await super.log({
19565
+ request: info.request,
19566
+ /**
19567
+ * @note Construct a placeholder response since SSE response
19568
+ * is being streamed and cannot be cloned/consumed for logging.
19569
+ */
19570
+ response: new Response("[streaming]", responseInit)
19571
+ });
19572
+ this.#attachClientLogger(info.request, clientEmitter);
19573
+ const stream = new ReadableStream({
19574
+ async start(controller) {
19575
+ const client = new ServerSentEventClient({
19576
+ controller,
19577
+ emitter: clientEmitter
19578
+ });
19579
+ const server = new ServerSentEventServer({
19580
+ request: info.request,
19581
+ client
19582
+ });
19583
+ await resolver({
19584
+ ...info,
19585
+ client,
19586
+ server
19587
+ });
19588
+ }
19589
+ });
19590
+ return new Response(stream, responseInit);
19591
+ });
19592
+ }
19593
+ async predicate(args) {
19594
+ if (args.request.headers.get("accept") !== "text/event-stream") {
19595
+ return false;
19596
+ }
19597
+ return super.predicate(args);
19598
+ }
19599
+ async log(_args) {
19600
+ return;
19601
+ }
19602
+ #attachClientLogger(request, emitter) {
19603
+ const publicUrl = toPublicUrl(request.url);
19604
+ emitter.on("message", (payload) => {
19605
+ console.groupCollapsed(
19606
+ devUtils.formatMessage(
19607
+ `${getTimestamp()} SSE %s %c\u21E3%c ${payload.event}`
19608
+ ),
19609
+ publicUrl,
19610
+ `color:${colors.mocked}`,
19611
+ "color:inherit"
19612
+ );
19613
+ console.log(payload.frames);
19614
+ console.groupEnd();
19615
+ });
19616
+ emitter.on("error", () => {
19617
+ console.groupCollapsed(
19618
+ devUtils.formatMessage(`${getTimestamp()} SSE %s %c\xD7%c error`),
19619
+ publicUrl,
19620
+ `color: ${colors.system}`,
19621
+ "color:inherit"
19622
+ );
19623
+ console.log("Handler:", this);
19624
+ console.groupEnd();
19625
+ });
19626
+ emitter.on("close", () => {
19627
+ console.groupCollapsed(
19628
+ devUtils.formatMessage(`${getTimestamp()} SSE %s %c\u25A0%c close`),
19629
+ publicUrl,
19630
+ `colors:${colors.system}`,
19631
+ "color:inherit"
19632
+ );
19633
+ console.log("Handler:", this);
19634
+ console.groupEnd();
19635
+ });
19636
+ }
19637
+ };
19638
+ var ServerSentEventClient = class {
19639
+ #encoder;
19640
+ #controller;
19641
+ #emitter;
19642
+ constructor(args) {
19643
+ this.#encoder = new TextEncoder();
19644
+ this.#controller = args.controller;
19645
+ this.#emitter = args.emitter;
19646
+ }
19647
+ /**
19648
+ * Sends the given payload to the intercepted `EventSource`.
19649
+ */
19650
+ send(payload) {
19651
+ if ("retry" in payload && payload.retry != null) {
19652
+ this.#sendRetry(payload.retry);
19653
+ return;
19654
+ }
19655
+ this.#sendMessage({
19656
+ id: payload.id,
19657
+ event: payload.event,
19658
+ data: typeof payload.data === "object" ? JSON.stringify(payload.data) : payload.data
19659
+ });
19660
+ }
19661
+ /**
19662
+ * Dispatches the given event on the intercepted `EventSource`.
19663
+ */
19664
+ dispatchEvent(event) {
19665
+ if (event instanceof MessageEvent) {
19666
+ this.#sendMessage({
19667
+ id: event.lastEventId || void 0,
19668
+ event: event.type === "message" ? void 0 : event.type,
19669
+ data: event.data
19670
+ });
19671
+ return;
19672
+ }
19673
+ if (event.type === "error") {
19674
+ this.error();
19675
+ return;
19676
+ }
19677
+ if (event.type === "close") {
19678
+ this.close();
19679
+ return;
19680
+ }
19681
+ }
19682
+ /**
19683
+ * Errors the underlying `EventSource`, closing the connection with an error.
19684
+ * This is equivalent to aborting the connection and will produce a `TypeError: Failed to fetch`
19685
+ * error.
19686
+ */
19687
+ error() {
19688
+ this.#controller.error();
19689
+ this.#emitter.emit("error");
19690
+ }
19691
+ /**
19692
+ * Closes the underlying `EventSource`, closing the connection.
19693
+ */
19694
+ close() {
19695
+ this.#controller.close();
19696
+ this.#emitter.emit("close");
19697
+ }
19698
+ #sendRetry(retry) {
19699
+ if (typeof retry === "number") {
19700
+ this.#controller.enqueue(this.#encoder.encode(`retry:${retry}
19701
+
19702
+ `));
19703
+ }
19704
+ }
19705
+ #sendMessage(message4) {
19706
+ const frames = [];
19707
+ if (message4.id) {
19708
+ frames.push(`id:${message4.id}`);
19709
+ }
19710
+ if (message4.event) {
19711
+ frames.push(`event:${message4.event?.toString()}`);
19712
+ }
19713
+ frames.push(`data:${message4.data}`);
19714
+ frames.push("", "");
19715
+ this.#controller.enqueue(this.#encoder.encode(frames.join("\n")));
19716
+ this.#emitter.emit("message", {
19717
+ id: message4.id,
19718
+ event: message4.event?.toString() || "message",
19719
+ data: message4.data,
19720
+ frames
19721
+ });
19722
+ }
19723
+ };
19724
+ var ServerSentEventServer = class {
19725
+ #request;
19726
+ #client;
19727
+ constructor(args) {
19728
+ this.#request = args.request;
19729
+ this.#client = args.client;
19730
+ }
19731
+ /**
19732
+ * Establishes the actual connection for this SSE request
19733
+ * and returns the `EventSource` instance.
19734
+ */
19735
+ connect() {
19736
+ const source = new ObservableEventSource(this.#request.url, {
19737
+ withCredentials: this.#request.credentials === "include",
19738
+ headers: {
19739
+ /**
19740
+ * @note Mark this request as passthrough so it doesn't trigger
19741
+ * an infinite loop matching against the existing request handler.
19742
+ */
19743
+ accept: "msw/passthrough"
19744
+ }
19745
+ });
19746
+ source[kOnAnyMessage] = (event) => {
19747
+ Object.defineProperties(event, {
19748
+ target: {
19749
+ value: this,
19750
+ enumerable: true,
19751
+ writable: true,
19752
+ configurable: true
19753
+ }
19754
+ });
19755
+ queueMicrotask(() => {
19756
+ if (!event.defaultPrevented) {
19757
+ this.#client.dispatchEvent(event);
19758
+ }
19759
+ });
19760
+ };
19761
+ source.addEventListener("error", (event) => {
19762
+ Object.defineProperties(event, {
19763
+ target: {
19764
+ value: this,
19765
+ enumerable: true,
19766
+ writable: true,
19767
+ configurable: true
19768
+ }
19769
+ });
19770
+ queueMicrotask(() => {
19771
+ if (!event.defaultPrevented) {
19772
+ this.#client.dispatchEvent(event);
19773
+ }
19774
+ });
19775
+ });
19776
+ return source;
19777
+ }
19778
+ };
19779
+ var kRequest = Symbol("kRequest");
19780
+ var kReconnectionTime = Symbol("kReconnectionTime");
19781
+ var kLastEventId = Symbol("kLastEventId");
19782
+ var kAbortController = Symbol("kAbortController");
19783
+ var kOnOpen = Symbol("kOnOpen");
19784
+ var kOnMessage = Symbol("kOnMessage");
19785
+ var kOnAnyMessage = Symbol("kOnAnyMessage");
19786
+ var kOnError = Symbol("kOnError");
19787
+ var ObservableEventSource = class _ObservableEventSource extends EventTarget {
19788
+ static CONNECTING = 0;
19789
+ static OPEN = 1;
19790
+ static CLOSED = 2;
19791
+ CONNECTING = _ObservableEventSource.CONNECTING;
19792
+ OPEN = _ObservableEventSource.OPEN;
19793
+ CLOSED = _ObservableEventSource.CLOSED;
19794
+ readyState;
19795
+ url;
19796
+ withCredentials;
19797
+ [kRequest];
19798
+ [kReconnectionTime];
19799
+ [kLastEventId];
19800
+ [kAbortController];
19801
+ [kOnOpen] = null;
19802
+ [kOnMessage] = null;
19803
+ [kOnAnyMessage] = null;
19804
+ [kOnError] = null;
19805
+ constructor(url, init) {
19806
+ super();
19807
+ this.url = new URL(url).href;
19808
+ this.withCredentials = init?.withCredentials ?? false;
19809
+ this.readyState = this.CONNECTING;
19810
+ const headers = new Headers(init?.headers || {});
19811
+ headers.append("accept", "text/event-stream");
19812
+ this[kAbortController] = new AbortController();
19813
+ this[kReconnectionTime] = 2e3;
19814
+ this[kLastEventId] = "";
19815
+ this[kRequest] = new Request(this.url, {
19816
+ method: "GET",
19817
+ headers,
19818
+ credentials: this.withCredentials ? "include" : "omit",
19819
+ signal: this[kAbortController].signal
19820
+ });
19821
+ this.connect();
19822
+ }
19823
+ get onopen() {
19824
+ return this[kOnOpen];
19825
+ }
19826
+ set onopen(handler) {
19827
+ if (this[kOnOpen]) {
19828
+ this.removeEventListener("open", this[kOnOpen]);
19829
+ }
19830
+ this[kOnOpen] = handler.bind(this);
19831
+ this.addEventListener("open", this[kOnOpen]);
19832
+ }
19833
+ get onmessage() {
19834
+ return this[kOnMessage];
19835
+ }
19836
+ set onmessage(handler) {
19837
+ if (this[kOnMessage]) {
19838
+ this.removeEventListener("message", { handleEvent: this[kOnMessage] });
19839
+ }
19840
+ this[kOnMessage] = handler.bind(this);
19841
+ this.addEventListener("message", { handleEvent: this[kOnMessage] });
19842
+ }
19843
+ get onerror() {
19844
+ return this[kOnError];
19845
+ }
19846
+ set oneerror(handler) {
19847
+ if (this[kOnError]) {
19848
+ this.removeEventListener("error", { handleEvent: this[kOnError] });
19849
+ }
19850
+ this[kOnError] = handler.bind(this);
19851
+ this.addEventListener("error", { handleEvent: this[kOnError] });
19852
+ }
19853
+ addEventListener(type, listener, options) {
19854
+ super.addEventListener(
19855
+ type,
19856
+ listener,
19857
+ options
19858
+ );
19859
+ }
19860
+ removeEventListener(type, listener, options) {
19861
+ super.removeEventListener(
19862
+ type,
19863
+ listener,
19864
+ options
19865
+ );
19866
+ }
19867
+ dispatchEvent(event) {
19868
+ return super.dispatchEvent(event);
19869
+ }
19870
+ close() {
19871
+ this[kAbortController].abort();
19872
+ this.readyState = this.CLOSED;
19873
+ }
19874
+ async connect() {
19875
+ await fetch(this[kRequest]).then((response) => {
19876
+ this.processResponse(response);
19877
+ }).catch(() => {
19878
+ this.failConnection();
19879
+ });
19880
+ }
19881
+ processResponse(response) {
19882
+ if (!response.body) {
19883
+ this.failConnection();
19884
+ return;
19885
+ }
19886
+ if (isNetworkError(response)) {
19887
+ this.reestablishConnection();
19888
+ return;
19889
+ }
19890
+ if (response.status !== 200 || response.headers.get("content-type") !== "text/event-stream") {
19891
+ this.failConnection();
19892
+ return;
19893
+ }
19894
+ this.announceConnection();
19895
+ this.interpretResponseBody(response);
19896
+ }
19897
+ announceConnection() {
19898
+ queueMicrotask(() => {
19899
+ if (this.readyState !== this.CLOSED) {
19900
+ this.readyState = this.OPEN;
19901
+ this.dispatchEvent(new Event("open"));
19902
+ }
19903
+ });
19904
+ }
19905
+ interpretResponseBody(response) {
19906
+ const parsingStream = new EventSourceParsingStream({
19907
+ message: (message4) => {
19908
+ if (message4.id) {
19909
+ this[kLastEventId] = message4.id;
19910
+ }
19911
+ if (message4.retry) {
19912
+ this[kReconnectionTime] = message4.retry;
19913
+ }
19914
+ const messageEvent = new MessageEvent(
19915
+ message4.event ? message4.event : "message",
19916
+ {
19917
+ data: message4.data,
19918
+ origin: this[kRequest].url,
19919
+ lastEventId: this[kLastEventId],
19920
+ cancelable: true
19921
+ }
19922
+ );
19923
+ this[kOnAnyMessage]?.(messageEvent);
19924
+ this.dispatchEvent(messageEvent);
19925
+ },
19926
+ abort: () => {
19927
+ throw new Error("Stream abort is not implemented");
19928
+ },
19929
+ close: () => {
19930
+ this.failConnection();
19931
+ }
19932
+ });
19933
+ response.body.pipeTo(parsingStream).then(() => {
19934
+ this.processResponseEndOfBody(response);
19935
+ }).catch(() => {
19936
+ this.failConnection();
19937
+ });
19938
+ }
19939
+ processResponseEndOfBody(response) {
19940
+ if (!isNetworkError(response)) {
19941
+ this.reestablishConnection();
19184
19942
  }
19185
- };
19943
+ }
19944
+ async reestablishConnection() {
19945
+ queueMicrotask(() => {
19946
+ if (this.readyState === this.CLOSED) {
19947
+ return;
19948
+ }
19949
+ this.readyState = this.CONNECTING;
19950
+ this.dispatchEvent(new Event("error"));
19951
+ });
19952
+ await delay(this[kReconnectionTime]);
19953
+ queueMicrotask(async () => {
19954
+ if (this.readyState !== this.CONNECTING) {
19955
+ return;
19956
+ }
19957
+ if (this[kLastEventId] !== "") {
19958
+ this[kRequest].headers.set("last-event-id", this[kLastEventId]);
19959
+ }
19960
+ await this.connect();
19961
+ });
19962
+ }
19963
+ failConnection() {
19964
+ queueMicrotask(() => {
19965
+ if (this.readyState !== this.CLOSED) {
19966
+ this.readyState = this.CLOSED;
19967
+ this.dispatchEvent(new Event("error"));
19968
+ }
19969
+ });
19970
+ }
19971
+ };
19972
+ function isNetworkError(response) {
19973
+ return response.type === "error" && response.status === 0 && response.statusText === "" && Array.from(response.headers.entries()).length === 0 && response.body === null;
19186
19974
  }
19187
- var ws = {
19188
- link: createWebSocketLinkHandler
19975
+ var EventSourceParsingStream = class extends WritableStream {
19976
+ constructor(underlyingSink) {
19977
+ super({
19978
+ write: (chunk) => {
19979
+ this.processResponseBodyChunk(chunk);
19980
+ },
19981
+ abort: (reason) => {
19982
+ this.underlyingSink.abort?.(reason);
19983
+ },
19984
+ close: () => {
19985
+ this.underlyingSink.close?.();
19986
+ }
19987
+ });
19988
+ this.underlyingSink = underlyingSink;
19989
+ this.decoder = new TextDecoder();
19990
+ this.position = 0;
19991
+ }
19992
+ decoder;
19993
+ buffer;
19994
+ position;
19995
+ fieldLength;
19996
+ discardTrailingNewline = false;
19997
+ message = {
19998
+ id: void 0,
19999
+ event: void 0,
20000
+ data: void 0,
20001
+ retry: void 0
20002
+ };
20003
+ resetMessage() {
20004
+ this.message = {
20005
+ id: void 0,
20006
+ event: void 0,
20007
+ data: void 0,
20008
+ retry: void 0
20009
+ };
20010
+ }
20011
+ processResponseBodyChunk(chunk) {
20012
+ if (this.buffer == null) {
20013
+ this.buffer = chunk;
20014
+ this.position = 0;
20015
+ this.fieldLength = -1;
20016
+ } else {
20017
+ const nextBuffer = new Uint8Array(this.buffer.length + chunk.length);
20018
+ nextBuffer.set(this.buffer);
20019
+ nextBuffer.set(chunk, this.buffer.length);
20020
+ this.buffer = nextBuffer;
20021
+ }
20022
+ const bufferLength = this.buffer.length;
20023
+ let lineStart = 0;
20024
+ while (this.position < bufferLength) {
20025
+ if (this.discardTrailingNewline) {
20026
+ if (this.buffer[this.position] === 10 /* NewLine */) {
20027
+ lineStart = ++this.position;
20028
+ }
20029
+ this.discardTrailingNewline = false;
20030
+ }
20031
+ let lineEnd = -1;
20032
+ for (; this.position < bufferLength && lineEnd === -1; ++this.position) {
20033
+ switch (this.buffer[this.position]) {
20034
+ case 58 /* Colon */: {
20035
+ if (this.fieldLength === -1) {
20036
+ this.fieldLength = this.position - lineStart;
20037
+ }
20038
+ break;
20039
+ }
20040
+ case 13 /* CarriageReturn */: {
20041
+ this.discardTrailingNewline = true;
20042
+ break;
20043
+ }
20044
+ case 10 /* NewLine */: {
20045
+ lineEnd = this.position;
20046
+ break;
20047
+ }
20048
+ }
20049
+ }
20050
+ if (lineEnd === -1) {
20051
+ break;
20052
+ }
20053
+ this.processLine(
20054
+ this.buffer.subarray(lineStart, lineEnd),
20055
+ this.fieldLength
20056
+ );
20057
+ lineStart = this.position;
20058
+ this.fieldLength = -1;
20059
+ }
20060
+ if (lineStart === bufferLength) {
20061
+ this.buffer = void 0;
20062
+ } else if (lineStart !== 0) {
20063
+ this.buffer = this.buffer.subarray(lineStart);
20064
+ this.position -= lineStart;
20065
+ }
20066
+ }
20067
+ processLine(line, fieldLength) {
20068
+ if (line.length === 0) {
20069
+ if (this.message.data === void 0) {
20070
+ this.message.event = void 0;
20071
+ return;
20072
+ }
20073
+ this.underlyingSink.message(this.message);
20074
+ this.resetMessage();
20075
+ return;
20076
+ }
20077
+ if (fieldLength > 0) {
20078
+ const field = this.decoder.decode(line.subarray(0, fieldLength));
20079
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
20080
+ const value = this.decoder.decode(line.subarray(valueOffset));
20081
+ switch (field) {
20082
+ case "data": {
20083
+ this.message.data = this.message.data ? this.message.data + "\n" + value : value;
20084
+ break;
20085
+ }
20086
+ case "event": {
20087
+ this.message.event = value;
20088
+ break;
20089
+ }
20090
+ case "id": {
20091
+ this.message.id = value;
20092
+ break;
20093
+ }
20094
+ case "retry": {
20095
+ const retry = parseInt(value, 10);
20096
+ if (!isNaN(retry)) {
20097
+ this.message.retry = retry;
20098
+ }
20099
+ break;
20100
+ }
20101
+ }
20102
+ }
20103
+ }
19189
20104
  };
19190
20105
 
19191
20106
  // node_modules/.pnpm/until-async@3.0.2/node_modules/until-async/lib/index.js
@@ -19517,50 +20432,6 @@ Read more: https://mswjs.io/docs/http/intercepting-requests`;
19517
20432
  }
19518
20433
  };
19519
20434
 
19520
- // src/core/delay.ts
19521
- var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
19522
- var MIN_SERVER_RESPONSE_TIME = 100;
19523
- var MAX_SERVER_RESPONSE_TIME = 400;
19524
- var NODE_SERVER_RESPONSE_TIME = 5;
19525
- function getRealisticResponseTime() {
19526
- if (isNodeProcess()) {
19527
- return NODE_SERVER_RESPONSE_TIME;
19528
- }
19529
- return Math.floor(
19530
- Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
19531
- );
19532
- }
19533
- async function delay(durationOrMode) {
19534
- let delayTime;
19535
- if (typeof durationOrMode === "string") {
19536
- switch (durationOrMode) {
19537
- case "infinite": {
19538
- delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
19539
- break;
19540
- }
19541
- case "real": {
19542
- delayTime = getRealisticResponseTime();
19543
- break;
19544
- }
19545
- default: {
19546
- throw new Error(
19547
- `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
19548
- );
19549
- }
19550
- }
19551
- } else if (typeof durationOrMode === "undefined") {
19552
- delayTime = getRealisticResponseTime();
19553
- } else {
19554
- if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
19555
- throw new Error(
19556
- `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.`
19557
- );
19558
- }
19559
- delayTime = durationOrMode;
19560
- }
19561
- return new Promise((resolve) => setTimeout(resolve, delayTime));
19562
- }
19563
-
19564
20435
  // src/core/bypass.ts
19565
20436
  function bypass(input, init) {
19566
20437
  const request = new Request(
@@ -19594,11 +20465,6 @@ Read more: https://mswjs.io/docs/http/intercepting-requests`;
19594
20465
  // src/core/index.ts
19595
20466
  checkGlobals();
19596
20467
 
19597
- // src/core/utils/internal/isObject.ts
19598
- function isObject2(value) {
19599
- return value != null && typeof value === "object" && !Array.isArray(value);
19600
- }
19601
-
19602
20468
  // src/core/utils/internal/mergeRight.ts
19603
20469
  function mergeRight(left, right) {
19604
20470
  return Object.entries(right).reduce(
@@ -20042,7 +20908,16 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
20042
20908
  };
20043
20909
  };
20044
20910
 
20045
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-TX5GBTFY.mjs
20911
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-VYSDLBSS.mjs
20912
+ async function emitAsync(emitter, eventName, ...data) {
20913
+ const listeners = emitter.listeners(eventName);
20914
+ if (listeners.length === 0) {
20915
+ return;
20916
+ }
20917
+ for (const listener of listeners) {
20918
+ await listener.apply(emitter, data);
20919
+ }
20920
+ }
20046
20921
  function hasConfigurableGlobal(propertyName) {
20047
20922
  const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName);
20048
20923
  if (typeof descriptor === "undefined") {
@@ -20063,7 +20938,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
20063
20938
  return true;
20064
20939
  }
20065
20940
 
20066
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs
20941
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs
20067
20942
  function bindEvent(target, event) {
20068
20943
  Object.defineProperties(event, {
20069
20944
  target: {
@@ -20685,14 +21560,15 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
20685
21560
  };
20686
21561
  const socket = new WebSocketOverride(url, protocols);
20687
21562
  const transport = new WebSocketClassTransport(socket);
20688
- queueMicrotask(() => {
21563
+ queueMicrotask(async () => {
20689
21564
  try {
20690
21565
  const server = new WebSocketServerConnection(
20691
21566
  socket,
20692
21567
  transport,
20693
21568
  createConnection
20694
21569
  );
20695
- const hasConnectionListeners = this.emitter.emit("connection", {
21570
+ const hasConnectionListeners = this.emitter.listenerCount("connection") > 0;
21571
+ await emitAsync(this.emitter, "connection", {
20696
21572
  client: new WebSocketClientConnection(socket, transport),
20697
21573
  server,
20698
21574
  info: {
@@ -20747,240 +21623,37 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
20747
21623
  function handleWebSocketEvent(options) {
20748
21624
  webSocketInterceptor.on("connection", async (connection) => {
20749
21625
  const handlers = options.getHandlers().filter(isHandlerKind("EventHandler"));
20750
- if (handlers.length > 0) {
20751
- options?.onMockedConnection(connection);
20752
- await Promise.all(
20753
- handlers.map((handler) => {
20754
- return handler.run(connection);
20755
- })
20756
- );
20757
- return;
20758
- }
20759
- const request = new Request(connection.client.url, {
20760
- headers: {
20761
- upgrade: "websocket",
20762
- connection: "upgrade"
20763
- }
20764
- });
20765
- await onUnhandledRequest(
20766
- request,
20767
- options.getUnhandledRequestStrategy()
20768
- ).catch((error3) => {
20769
- const errorEvent = new Event("error");
20770
- Object.defineProperty(errorEvent, "cause", {
20771
- enumerable: true,
20772
- configurable: false,
20773
- value: error3
20774
- });
20775
- connection.client.socket.dispatchEvent(errorEvent);
20776
- });
20777
- options?.onPassthroughConnection(connection);
20778
- connection.server.connect();
20779
- });
20780
- }
20781
-
20782
- // src/core/ws/utils/getMessageLength.ts
20783
- function getMessageLength(data) {
20784
- if (data instanceof Blob) {
20785
- return data.size;
20786
- }
20787
- if (data instanceof ArrayBuffer) {
20788
- return data.byteLength;
20789
- }
20790
- return new Blob([data]).size;
20791
- }
20792
-
20793
- // src/core/ws/utils/truncateMessage.ts
20794
- var MAX_LENGTH = 24;
20795
- function truncateMessage(message4) {
20796
- if (message4.length <= MAX_LENGTH) {
20797
- return message4;
20798
- }
20799
- return `${message4.slice(0, MAX_LENGTH)}\u2026`;
20800
- }
20801
-
20802
- // src/core/ws/utils/getPublicData.ts
20803
- async function getPublicData(data) {
20804
- if (data instanceof Blob) {
20805
- const text = await data.text();
20806
- return `Blob(${truncateMessage(text)})`;
20807
- }
20808
- if (typeof data === "object" && "byteLength" in data) {
20809
- const text = new TextDecoder().decode(data);
20810
- return `ArrayBuffer(${truncateMessage(text)})`;
20811
- }
20812
- return truncateMessage(data);
20813
- }
20814
-
20815
- // src/core/ws/utils/attachWebSocketLogger.ts
20816
- var colors = {
20817
- system: "#3b82f6",
20818
- outgoing: "#22c55e",
20819
- incoming: "#ef4444",
20820
- mocked: "#ff6a33"
20821
- };
20822
- function attachWebSocketLogger(connection) {
20823
- const { client, server } = connection;
20824
- logConnectionOpen(client);
20825
- client.addEventListener("message", (event) => {
20826
- logOutgoingClientMessage(event);
20827
- });
20828
- client.addEventListener("close", (event) => {
20829
- logConnectionClose(event);
20830
- });
20831
- client.socket.addEventListener("error", (event) => {
20832
- logClientError(event);
20833
- });
20834
- client.send = new Proxy(client.send, {
20835
- apply(target, thisArg, args) {
20836
- const [data] = args;
20837
- const messageEvent = new MessageEvent("message", { data });
20838
- Object.defineProperties(messageEvent, {
20839
- currentTarget: {
20840
- enumerable: true,
20841
- writable: false,
20842
- value: client.socket
20843
- },
20844
- target: {
20845
- enumerable: true,
20846
- writable: false,
20847
- value: client.socket
20848
- }
20849
- });
20850
- queueMicrotask(() => {
20851
- logIncomingMockedClientMessage(messageEvent);
20852
- });
20853
- return Reflect.apply(target, thisArg, args);
20854
- }
20855
- });
20856
- server.addEventListener(
20857
- "open",
20858
- () => {
20859
- server.addEventListener("message", (event) => {
20860
- logIncomingServerMessage(event);
20861
- });
20862
- },
20863
- { once: true }
20864
- );
20865
- server.send = new Proxy(server.send, {
20866
- apply(target, thisArg, args) {
20867
- const [data] = args;
20868
- const messageEvent = new MessageEvent("message", { data });
20869
- Object.defineProperties(messageEvent, {
20870
- currentTarget: {
20871
- enumerable: true,
20872
- writable: false,
20873
- value: server.socket
20874
- },
20875
- target: {
20876
- enumerable: true,
20877
- writable: false,
20878
- value: server.socket
20879
- }
20880
- });
20881
- logOutgoingMockedClientMessage(messageEvent);
20882
- return Reflect.apply(target, thisArg, args);
21626
+ if (handlers.length > 0) {
21627
+ options?.onMockedConnection(connection);
21628
+ await Promise.all(
21629
+ handlers.map((handler) => {
21630
+ return handler.run(connection);
21631
+ })
21632
+ );
21633
+ return;
20883
21634
  }
21635
+ const request = new Request(connection.client.url, {
21636
+ headers: {
21637
+ upgrade: "websocket",
21638
+ connection: "upgrade"
21639
+ }
21640
+ });
21641
+ await onUnhandledRequest(
21642
+ request,
21643
+ options.getUnhandledRequestStrategy()
21644
+ ).catch((error3) => {
21645
+ const errorEvent = new Event("error");
21646
+ Object.defineProperty(errorEvent, "cause", {
21647
+ enumerable: true,
21648
+ configurable: false,
21649
+ value: error3
21650
+ });
21651
+ connection.client.socket.dispatchEvent(errorEvent);
21652
+ });
21653
+ options?.onPassthroughConnection(connection);
21654
+ connection.server.connect();
20884
21655
  });
20885
21656
  }
20886
- function logConnectionOpen(client) {
20887
- const publicUrl = toPublicUrl(client.url);
20888
- console.groupCollapsed(
20889
- devUtils.formatMessage(`${getTimestamp()} %c\u25B6%c ${publicUrl}`),
20890
- `color:${colors.system}`,
20891
- "color:inherit"
20892
- );
20893
- console.log("Client:", client.socket);
20894
- console.groupEnd();
20895
- }
20896
- function logConnectionClose(event) {
20897
- const target = event.target;
20898
- const publicUrl = toPublicUrl(target.url);
20899
- console.groupCollapsed(
20900
- devUtils.formatMessage(
20901
- `${getTimestamp({ milliseconds: true })} %c\u25A0%c ${publicUrl}`
20902
- ),
20903
- `color:${colors.system}`,
20904
- "color:inherit"
20905
- );
20906
- console.log(event);
20907
- console.groupEnd();
20908
- }
20909
- function logClientError(event) {
20910
- const socket = event.target;
20911
- const publicUrl = toPublicUrl(socket.url);
20912
- console.groupCollapsed(
20913
- devUtils.formatMessage(
20914
- `${getTimestamp({ milliseconds: true })} %c\xD7%c ${publicUrl}`
20915
- ),
20916
- `color:${colors.system}`,
20917
- "color:inherit"
20918
- );
20919
- console.log(event);
20920
- console.groupEnd();
20921
- }
20922
- async function logOutgoingClientMessage(event) {
20923
- const byteLength = getMessageLength(event.data);
20924
- const publicData = await getPublicData(event.data);
20925
- const arrow = event.defaultPrevented ? "\u21E1" : "\u2B06";
20926
- console.groupCollapsed(
20927
- devUtils.formatMessage(
20928
- `${getTimestamp({ milliseconds: true })} %c${arrow}%c ${publicData} %c${byteLength}%c`
20929
- ),
20930
- `color:${colors.outgoing}`,
20931
- "color:inherit",
20932
- "color:gray;font-weight:normal",
20933
- "color:inherit;font-weight:inherit"
20934
- );
20935
- console.log(event);
20936
- console.groupEnd();
20937
- }
20938
- async function logOutgoingMockedClientMessage(event) {
20939
- const byteLength = getMessageLength(event.data);
20940
- const publicData = await getPublicData(event.data);
20941
- console.groupCollapsed(
20942
- devUtils.formatMessage(
20943
- `${getTimestamp({ milliseconds: true })} %c\u2B06%c ${publicData} %c${byteLength}%c`
20944
- ),
20945
- `color:${colors.mocked}`,
20946
- "color:inherit",
20947
- "color:gray;font-weight:normal",
20948
- "color:inherit;font-weight:inherit"
20949
- );
20950
- console.log(event);
20951
- console.groupEnd();
20952
- }
20953
- async function logIncomingMockedClientMessage(event) {
20954
- const byteLength = getMessageLength(event.data);
20955
- const publicData = await getPublicData(event.data);
20956
- console.groupCollapsed(
20957
- devUtils.formatMessage(
20958
- `${getTimestamp({ milliseconds: true })} %c\u2B07%c ${publicData} %c${byteLength}%c`
20959
- ),
20960
- `color:${colors.mocked}`,
20961
- "color:inherit",
20962
- "color:gray;font-weight:normal",
20963
- "color:inherit;font-weight:inherit"
20964
- );
20965
- console.log(event);
20966
- console.groupEnd();
20967
- }
20968
- async function logIncomingServerMessage(event) {
20969
- const byteLength = getMessageLength(event.data);
20970
- const publicData = await getPublicData(event.data);
20971
- const arrow = event.defaultPrevented ? "\u21E3" : "\u2B07";
20972
- console.groupCollapsed(
20973
- devUtils.formatMessage(
20974
- `${getTimestamp({ milliseconds: true })} %c${arrow}%c ${publicData} %c${byteLength}%c`
20975
- ),
20976
- `color:${colors.incoming}`,
20977
- "color:inherit",
20978
- "color:gray;font-weight:normal",
20979
- "color:inherit;font-weight:inherit"
20980
- );
20981
- console.log(event);
20982
- console.groupEnd();
20983
- }
20984
21657
 
20985
21658
  // node_modules/.pnpm/rettime@0.7.0/node_modules/rettime/build/index.js
20986
21659
  var kDefaultPrevented2 = Symbol("kDefaultPrevented");
@@ -21286,69 +21959,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21286
21959
  }
21287
21960
  };
21288
21961
 
21289
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-L37TY7LC.mjs
21290
- var InterceptorError = class extends Error {
21291
- constructor(message4) {
21292
- super(message4);
21293
- this.name = "InterceptorError";
21294
- Object.setPrototypeOf(this, InterceptorError.prototype);
21295
- }
21296
- };
21297
- var kRequestHandled = Symbol("kRequestHandled");
21298
- var kResponsePromise = Symbol("kResponsePromise");
21299
- var RequestController = class {
21300
- constructor(request) {
21301
- this.request = request;
21302
- this[kRequestHandled] = false;
21303
- this[kResponsePromise] = new DeferredPromise();
21304
- }
21305
- /**
21306
- * Respond to this request with the given `Response` instance.
21307
- * @example
21308
- * controller.respondWith(new Response())
21309
- * controller.respondWith(Response.json({ id }))
21310
- * controller.respondWith(Response.error())
21311
- */
21312
- respondWith(response) {
21313
- invariant.as(
21314
- InterceptorError,
21315
- !this[kRequestHandled],
21316
- 'Failed to respond to the "%s %s" request: the "request" event has already been handled.',
21317
- this.request.method,
21318
- this.request.url
21319
- );
21320
- this[kRequestHandled] = true;
21321
- this[kResponsePromise].resolve(response);
21322
- }
21323
- /**
21324
- * Error this request with the given reason.
21325
- *
21326
- * @example
21327
- * controller.errorWith()
21328
- * controller.errorWith(new Error('Oops!'))
21329
- * controller.errorWith({ message: 'Oops!'})
21330
- */
21331
- errorWith(reason) {
21332
- invariant.as(
21333
- InterceptorError,
21334
- !this[kRequestHandled],
21335
- 'Failed to error the "%s %s" request: the "request" event has already been handled.',
21336
- this.request.method,
21337
- this.request.url
21338
- );
21339
- this[kRequestHandled] = true;
21340
- this[kResponsePromise].resolve(reason);
21341
- }
21342
- };
21343
- async function emitAsync(emitter, eventName, ...data) {
21344
- const listners = emitter.listeners(eventName);
21345
- if (listners.length === 0) {
21346
- return;
21347
- }
21348
- for (const listener of listners) {
21349
- await listener.apply(emitter, data);
21350
- }
21351
- }
21962
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-VOUOVDAW.mjs
21352
21963
  function isObject3(value, loose = false) {
21353
21964
  return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]";
21354
21965
  }
@@ -21396,19 +22007,19 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21396
22007
  async function handleRequest2(options) {
21397
22008
  const handleResponse = async (response) => {
21398
22009
  if (response instanceof Error) {
21399
- options.onError(response);
22010
+ await options.controller.errorWith(response);
21400
22011
  return true;
21401
22012
  }
21402
22013
  if (isResponseError(response)) {
21403
- options.onRequestError(response);
22014
+ await options.controller.respondWith(response);
21404
22015
  return true;
21405
22016
  }
21406
22017
  if (isResponseLike(response)) {
21407
- await options.onResponse(response);
22018
+ await options.controller.respondWith(response);
21408
22019
  return true;
21409
22020
  }
21410
22021
  if (isObject3(response)) {
21411
- options.onError(response);
22022
+ await options.controller.errorWith(response);
21412
22023
  return true;
21413
22024
  }
21414
22025
  return false;
@@ -21418,7 +22029,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21418
22029
  throw result.error;
21419
22030
  }
21420
22031
  if (isNodeLikeError(error3)) {
21421
- options.onError(error3);
22032
+ await options.controller.errorWith(error3);
21422
22033
  return true;
21423
22034
  }
21424
22035
  if (error3 instanceof Response) {
@@ -21426,27 +22037,19 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21426
22037
  }
21427
22038
  return false;
21428
22039
  };
21429
- options.emitter.once("request", ({ requestId: pendingRequestId }) => {
21430
- if (pendingRequestId !== options.requestId) {
21431
- return;
21432
- }
21433
- if (options.controller[kResponsePromise].state === "pending") {
21434
- options.controller[kResponsePromise].resolve(void 0);
21435
- }
21436
- });
21437
22040
  const requestAbortPromise = new DeferredPromise();
21438
22041
  if (options.request.signal) {
21439
22042
  if (options.request.signal.aborted) {
21440
- requestAbortPromise.reject(options.request.signal.reason);
21441
- } else {
21442
- options.request.signal.addEventListener(
21443
- "abort",
21444
- () => {
21445
- requestAbortPromise.reject(options.request.signal.reason);
21446
- },
21447
- { once: true }
21448
- );
22043
+ await options.controller.errorWith(options.request.signal.reason);
22044
+ return;
21449
22045
  }
22046
+ options.request.signal.addEventListener(
22047
+ "abort",
22048
+ () => {
22049
+ requestAbortPromise.reject(options.request.signal.reason);
22050
+ },
22051
+ { once: true }
22052
+ );
21450
22053
  }
21451
22054
  const result = await until2(async () => {
21452
22055
  const requestListenersPromise = emitAsync(options.emitter, "request", {
@@ -21458,52 +22061,58 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21458
22061
  // Short-circuit the request handling promise if the request gets aborted.
21459
22062
  requestAbortPromise,
21460
22063
  requestListenersPromise,
21461
- options.controller[kResponsePromise]
22064
+ options.controller.handled
21462
22065
  ]);
21463
- return await options.controller[kResponsePromise];
21464
22066
  });
21465
22067
  if (requestAbortPromise.state === "rejected") {
21466
- options.onError(requestAbortPromise.rejectionReason);
21467
- return true;
22068
+ await options.controller.errorWith(requestAbortPromise.rejectionReason);
22069
+ return;
21468
22070
  }
21469
22071
  if (result.error) {
21470
22072
  if (await handleResponseError(result.error)) {
21471
- return true;
22073
+ return;
21472
22074
  }
21473
22075
  if (options.emitter.listenerCount("unhandledException") > 0) {
21474
22076
  const unhandledExceptionController = new RequestController(
21475
- options.request
22077
+ options.request,
22078
+ {
22079
+ /**
22080
+ * @note Intentionally empty passthrough handle.
22081
+ * This controller is created within another controller and we only need
22082
+ * to know if `unhandledException` listeners handled the request.
22083
+ */
22084
+ passthrough() {
22085
+ },
22086
+ async respondWith(response) {
22087
+ await handleResponse(response);
22088
+ },
22089
+ async errorWith(reason) {
22090
+ await options.controller.errorWith(reason);
22091
+ }
22092
+ }
21476
22093
  );
21477
22094
  await emitAsync(options.emitter, "unhandledException", {
21478
22095
  error: result.error,
21479
22096
  request: options.request,
21480
22097
  requestId: options.requestId,
21481
22098
  controller: unhandledExceptionController
21482
- }).then(() => {
21483
- if (unhandledExceptionController[kResponsePromise].state === "pending") {
21484
- unhandledExceptionController[kResponsePromise].resolve(void 0);
21485
- }
21486
22099
  });
21487
- const nextResult = await until2(
21488
- () => unhandledExceptionController[kResponsePromise]
21489
- );
21490
- if (nextResult.error) {
21491
- return handleResponseError(nextResult.error);
21492
- }
21493
- if (nextResult.data) {
21494
- return handleResponse(nextResult.data);
22100
+ if (unhandledExceptionController.readyState !== RequestController.PENDING) {
22101
+ return;
21495
22102
  }
21496
22103
  }
21497
- options.onResponse(createServerErrorResponse(result.error));
21498
- return true;
22104
+ await options.controller.respondWith(
22105
+ createServerErrorResponse(result.error)
22106
+ );
22107
+ return;
21499
22108
  }
21500
- if (result.data) {
21501
- return handleResponse(result.data);
22109
+ if (options.controller.readyState === RequestController.PENDING) {
22110
+ return await options.controller.passthrough();
21502
22111
  }
21503
- return false;
22112
+ return options.controller.handled;
21504
22113
  }
21505
22114
 
21506
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-ARPHZXGT.mjs
22115
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-WOWPV4GR.mjs
21507
22116
  function createNetworkError(cause) {
21508
22117
  return Object.assign(new TypeError("Failed to fetch"), {
21509
22118
  cause
@@ -21559,7 +22168,12 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21559
22168
  request.headers.delete("host");
21560
22169
  }
21561
22170
  requestInit.headers = request.headers;
21562
- return fetch(new Request(locationUrl, requestInit));
22171
+ const finalResponse = await fetch(new Request(locationUrl, requestInit));
22172
+ Object.defineProperty(finalResponse, "redirected", {
22173
+ value: true,
22174
+ configurable: true
22175
+ });
22176
+ return finalResponse;
21563
22177
  }
21564
22178
  function sameOrigin(left, right) {
21565
22179
  if (left.origin === right.origin && left.origin === "null") {
@@ -21657,19 +22271,35 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21657
22271
  setRawRequest(request, input);
21658
22272
  }
21659
22273
  const responsePromise = new DeferredPromise();
21660
- const controller = new RequestController(request);
21661
- this.logger.info("[%s] %s", request.method, request.url);
21662
- this.logger.info("awaiting for the mocked response...");
21663
- this.logger.info(
21664
- 'emitting the "request" event for %s listener(s)...',
21665
- this.emitter.listenerCount("request")
21666
- );
21667
- const isRequestHandled = await handleRequest2({
21668
- request,
21669
- requestId,
21670
- emitter: this.emitter,
21671
- controller,
21672
- onResponse: async (rawResponse) => {
22274
+ const controller = new RequestController(request, {
22275
+ passthrough: async () => {
22276
+ this.logger.info("request has not been handled, passthrough...");
22277
+ const requestCloneForResponseEvent = request.clone();
22278
+ const { error: responseError, data: originalResponse } = await until2(
22279
+ () => pureFetch(request)
22280
+ );
22281
+ if (responseError) {
22282
+ return responsePromise.reject(responseError);
22283
+ }
22284
+ this.logger.info("original fetch performed", originalResponse);
22285
+ if (this.emitter.listenerCount("response") > 0) {
22286
+ this.logger.info('emitting the "response" event...');
22287
+ const responseClone = originalResponse.clone();
22288
+ await emitAsync(this.emitter, "response", {
22289
+ response: responseClone,
22290
+ isMockedResponse: false,
22291
+ request: requestCloneForResponseEvent,
22292
+ requestId
22293
+ });
22294
+ }
22295
+ responsePromise.resolve(originalResponse);
22296
+ },
22297
+ respondWith: async (rawResponse) => {
22298
+ if (isResponseError(rawResponse)) {
22299
+ this.logger.info("request has errored!", { response: rawResponse });
22300
+ responsePromise.reject(createNetworkError(rawResponse));
22301
+ return;
22302
+ }
21673
22303
  this.logger.info("received mocked response!", {
21674
22304
  rawResponse
21675
22305
  });
@@ -21707,37 +22337,24 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21707
22337
  }
21708
22338
  responsePromise.resolve(response);
21709
22339
  },
21710
- onRequestError: (response) => {
21711
- this.logger.info("request has errored!", { response });
21712
- responsePromise.reject(createNetworkError(response));
21713
- },
21714
- onError: (error3) => {
21715
- this.logger.info("request has been aborted!", { error: error3 });
21716
- responsePromise.reject(error3);
22340
+ errorWith: (reason) => {
22341
+ this.logger.info("request has been aborted!", { reason });
22342
+ responsePromise.reject(reason);
21717
22343
  }
21718
22344
  });
21719
- if (isRequestHandled) {
21720
- this.logger.info("request has been handled, returning mock promise...");
21721
- return responsePromise;
21722
- }
22345
+ this.logger.info("[%s] %s", request.method, request.url);
22346
+ this.logger.info("awaiting for the mocked response...");
21723
22347
  this.logger.info(
21724
- "no mocked response received, performing request as-is..."
22348
+ 'emitting the "request" event for %s listener(s)...',
22349
+ this.emitter.listenerCount("request")
21725
22350
  );
21726
- const requestCloneForResponseEvent = request.clone();
21727
- return pureFetch(request).then(async (response) => {
21728
- this.logger.info("original fetch performed", response);
21729
- if (this.emitter.listenerCount("response") > 0) {
21730
- this.logger.info('emitting the "response" event...');
21731
- const responseClone = response.clone();
21732
- await emitAsync(this.emitter, "response", {
21733
- response: responseClone,
21734
- isMockedResponse: false,
21735
- request: requestCloneForResponseEvent,
21736
- requestId
21737
- });
21738
- }
21739
- return response;
22351
+ await handleRequest2({
22352
+ request,
22353
+ requestId,
22354
+ emitter: this.emitter,
22355
+ controller
21740
22356
  });
22357
+ return responsePromise;
21741
22358
  };
21742
22359
  Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
21743
22360
  enumerable: true,
@@ -21759,7 +22376,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21759
22376
  var FetchInterceptor = _FetchInterceptor;
21760
22377
  FetchInterceptor.symbol = Symbol("fetch");
21761
22378
 
21762
- // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-QKSBFQDK.mjs
22379
+ // node_modules/.pnpm/@mswjs+interceptors@0.40.0/node_modules/@mswjs/interceptors/lib/browser/chunk-WADP6VHN.mjs
21763
22380
  function concatArrayBuffer(left, right) {
21764
22381
  const result = new Uint8Array(left.byteLength + right.byteLength);
21765
22382
  result.set(left, 0);
@@ -21927,12 +22544,12 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21927
22544
  url: request.responseURL,
21928
22545
  status: request.status,
21929
22546
  statusText: request.statusText,
21930
- headers: createHeadersFromXMLHttpReqestHeaders(
22547
+ headers: createHeadersFromXMLHttpRequestHeaders(
21931
22548
  request.getAllResponseHeaders()
21932
22549
  )
21933
22550
  });
21934
22551
  }
21935
- function createHeadersFromXMLHttpReqestHeaders(headersString) {
22552
+ function createHeadersFromXMLHttpRequestHeaders(headersString) {
21936
22553
  const headers = new Headers();
21937
22554
  const lines = headersString.split(/[\r\n]+/);
21938
22555
  for (const line of lines) {
@@ -21984,7 +22601,6 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
21984
22601
  }
21985
22602
  },
21986
22603
  methodCall: ([methodName, args], invoke) => {
21987
- var _a2;
21988
22604
  switch (methodName) {
21989
22605
  case "open": {
21990
22606
  const [method, url] = args;
@@ -22035,24 +22651,27 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
22035
22651
  const requestBody = typeof body === "string" ? encodeBuffer(body) : body;
22036
22652
  const fetchRequest = this.toFetchApiRequest(requestBody);
22037
22653
  this[kFetchRequest] = fetchRequest.clone();
22038
- const onceRequestSettled = ((_a2 = this.onRequest) == null ? void 0 : _a2.call(this, {
22039
- request: fetchRequest,
22040
- requestId: this.requestId
22041
- })) || Promise.resolve();
22042
- onceRequestSettled.finally(() => {
22043
- if (!this[kIsRequestHandled]) {
22044
- this.logger.info(
22045
- "request callback settled but request has not been handled (readystate %d), performing as-is...",
22046
- this.request.readyState
22047
- );
22048
- if (IS_NODE2) {
22049
- this.request.setRequestHeader(
22050
- INTERNAL_REQUEST_ID_HEADER_NAME,
22051
- this.requestId
22654
+ queueMicrotask(() => {
22655
+ var _a2;
22656
+ const onceRequestSettled = ((_a2 = this.onRequest) == null ? void 0 : _a2.call(this, {
22657
+ request: fetchRequest,
22658
+ requestId: this.requestId
22659
+ })) || Promise.resolve();
22660
+ onceRequestSettled.finally(() => {
22661
+ if (!this[kIsRequestHandled]) {
22662
+ this.logger.info(
22663
+ "request callback settled but request has not been handled (readystate %d), performing as-is...",
22664
+ this.request.readyState
22052
22665
  );
22666
+ if (IS_NODE2) {
22667
+ this.request.setRequestHeader(
22668
+ INTERNAL_REQUEST_ID_HEADER_NAME,
22669
+ this.requestId
22670
+ );
22671
+ }
22672
+ return invoke();
22053
22673
  }
22054
- return invoke();
22055
- }
22674
+ });
22056
22675
  });
22057
22676
  break;
22058
22677
  }
@@ -22342,7 +22961,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
22342
22961
  define(this.request, "readyState", nextReadyState);
22343
22962
  this.logger.info("set readyState to: %d", nextReadyState);
22344
22963
  if (nextReadyState !== this.request.UNSENT) {
22345
- this.logger.info('triggerring "readystatechange" event...');
22964
+ this.logger.info('triggering "readystatechange" event...');
22346
22965
  this.trigger("readystatechange", this.request);
22347
22966
  }
22348
22967
  }
@@ -22451,35 +23070,37 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
22451
23070
  logger
22452
23071
  );
22453
23072
  xhrRequestController.onRequest = async function({ request, requestId }) {
22454
- const controller = new RequestController(request);
23073
+ const controller = new RequestController(request, {
23074
+ passthrough: () => {
23075
+ this.logger.info(
23076
+ "no mocked response received, performing request as-is..."
23077
+ );
23078
+ },
23079
+ respondWith: async (response) => {
23080
+ if (isResponseError(response)) {
23081
+ this.errorWith(new TypeError("Network error"));
23082
+ return;
23083
+ }
23084
+ await this.respondWith(response);
23085
+ },
23086
+ errorWith: (reason) => {
23087
+ this.logger.info("request errored!", { error: reason });
23088
+ if (reason instanceof Error) {
23089
+ this.errorWith(reason);
23090
+ }
23091
+ }
23092
+ });
22455
23093
  this.logger.info("awaiting mocked response...");
22456
23094
  this.logger.info(
22457
23095
  'emitting the "request" event for %s listener(s)...',
22458
23096
  emitter.listenerCount("request")
22459
23097
  );
22460
- const isRequestHandled = await handleRequest2({
23098
+ await handleRequest2({
22461
23099
  request,
22462
23100
  requestId,
22463
23101
  controller,
22464
- emitter,
22465
- onResponse: async (response) => {
22466
- await this.respondWith(response);
22467
- },
22468
- onRequestError: () => {
22469
- this.errorWith(new TypeError("Network error"));
22470
- },
22471
- onError: (error3) => {
22472
- this.logger.info("request errored!", { error: error3 });
22473
- if (error3 instanceof Error) {
22474
- this.errorWith(error3);
22475
- }
22476
- }
23102
+ emitter
22477
23103
  });
22478
- if (!isRequestHandled) {
22479
- this.logger.info(
22480
- "no mocked response received, performing request as-is..."
22481
- );
22482
- }
22483
23104
  };
22484
23105
  xhrRequestController.onResponse = async function({
22485
23106
  response,