msw 2.13.5 → 2.14.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 (111) hide show
  1. package/lib/core/{HttpResponse-BMMzfpjG.d.mts → HttpResponse-CxHR1nNN.d.mts} +5 -1
  2. package/lib/core/{HttpResponse-DPDqE4Pb.d.ts → HttpResponse-aGiIzO91.d.ts} +5 -1
  3. package/lib/core/HttpResponse.d.mts +1 -1
  4. package/lib/core/HttpResponse.d.ts +1 -1
  5. package/lib/core/experimental/compat.d.mts +1 -1
  6. package/lib/core/experimental/compat.d.ts +1 -1
  7. package/lib/core/experimental/define-network.d.mts +1 -1
  8. package/lib/core/experimental/define-network.d.ts +1 -1
  9. package/lib/core/experimental/frames/http-frame.d.mts +1 -1
  10. package/lib/core/experimental/frames/http-frame.d.ts +1 -1
  11. package/lib/core/experimental/frames/http-frame.js +3 -2
  12. package/lib/core/experimental/frames/http-frame.js.map +1 -1
  13. package/lib/core/experimental/frames/http-frame.mjs +3 -2
  14. package/lib/core/experimental/frames/http-frame.mjs.map +1 -1
  15. package/lib/core/experimental/frames/network-frame.d.mts +1 -1
  16. package/lib/core/experimental/frames/network-frame.d.ts +1 -1
  17. package/lib/core/experimental/frames/websocket-frame.d.mts +1 -1
  18. package/lib/core/experimental/frames/websocket-frame.d.ts +1 -1
  19. package/lib/core/experimental/handlers-controller.d.mts +1 -1
  20. package/lib/core/experimental/handlers-controller.d.ts +1 -1
  21. package/lib/core/experimental/handlers-controller.js +16 -5
  22. package/lib/core/experimental/handlers-controller.js.map +1 -1
  23. package/lib/core/experimental/handlers-controller.mjs +16 -5
  24. package/lib/core/experimental/handlers-controller.mjs.map +1 -1
  25. package/lib/core/experimental/index.d.mts +1 -1
  26. package/lib/core/experimental/index.d.ts +1 -1
  27. package/lib/core/experimental/on-unhandled-frame.d.mts +1 -1
  28. package/lib/core/experimental/on-unhandled-frame.d.ts +1 -1
  29. package/lib/core/experimental/setup-api.d.mts +1 -1
  30. package/lib/core/experimental/setup-api.d.ts +1 -1
  31. package/lib/core/experimental/sources/interceptor-source.d.mts +1 -1
  32. package/lib/core/experimental/sources/interceptor-source.d.ts +1 -1
  33. package/lib/core/experimental/sources/network-source.d.mts +1 -1
  34. package/lib/core/experimental/sources/network-source.d.ts +1 -1
  35. package/lib/core/getResponse.d.mts +1 -1
  36. package/lib/core/getResponse.d.ts +1 -1
  37. package/lib/core/graphql.d.mts +1 -1
  38. package/lib/core/graphql.d.ts +1 -1
  39. package/lib/core/handlers/GraphQLHandler.d.mts +1 -1
  40. package/lib/core/handlers/GraphQLHandler.d.ts +1 -1
  41. package/lib/core/handlers/HttpHandler.d.mts +1 -1
  42. package/lib/core/handlers/HttpHandler.d.ts +1 -1
  43. package/lib/core/handlers/RequestHandler.d.mts +1 -1
  44. package/lib/core/handlers/RequestHandler.d.ts +1 -1
  45. package/lib/core/handlers/RequestHandler.js +22 -1
  46. package/lib/core/handlers/RequestHandler.js.map +1 -1
  47. package/lib/core/handlers/RequestHandler.mjs +22 -1
  48. package/lib/core/handlers/RequestHandler.mjs.map +1 -1
  49. package/lib/core/handlers/WebSocketHandler.d.mts +5 -2
  50. package/lib/core/handlers/WebSocketHandler.d.ts +5 -2
  51. package/lib/core/handlers/WebSocketHandler.js +23 -6
  52. package/lib/core/handlers/WebSocketHandler.js.map +1 -1
  53. package/lib/core/handlers/WebSocketHandler.mjs +23 -6
  54. package/lib/core/handlers/WebSocketHandler.mjs.map +1 -1
  55. package/lib/core/http.d.mts +1 -1
  56. package/lib/core/http.d.ts +1 -1
  57. package/lib/core/index.d.mts +1 -1
  58. package/lib/core/index.d.ts +1 -1
  59. package/lib/core/passthrough.d.mts +1 -1
  60. package/lib/core/passthrough.d.ts +1 -1
  61. package/lib/core/sse.d.mts +1 -1
  62. package/lib/core/sse.d.ts +1 -1
  63. package/lib/core/utils/HttpResponse/decorators.d.mts +3 -3
  64. package/lib/core/utils/HttpResponse/decorators.d.ts +3 -3
  65. package/lib/core/utils/HttpResponse/decorators.js +4 -10
  66. package/lib/core/utils/HttpResponse/decorators.js.map +1 -1
  67. package/lib/core/utils/HttpResponse/decorators.mjs +4 -10
  68. package/lib/core/utils/HttpResponse/decorators.mjs.map +1 -1
  69. package/lib/core/utils/executeHandlers.d.mts +1 -1
  70. package/lib/core/utils/executeHandlers.d.ts +1 -1
  71. package/lib/core/utils/handleRequest.d.mts +1 -1
  72. package/lib/core/utils/handleRequest.d.ts +1 -1
  73. package/lib/core/utils/internal/attachSiblingHandlers.d.mts +15 -0
  74. package/lib/core/utils/internal/attachSiblingHandlers.d.ts +15 -0
  75. package/lib/core/utils/internal/attachSiblingHandlers.js +44 -0
  76. package/lib/core/utils/internal/attachSiblingHandlers.js.map +1 -0
  77. package/lib/core/utils/internal/attachSiblingHandlers.mjs +24 -0
  78. package/lib/core/utils/internal/attachSiblingHandlers.mjs.map +1 -0
  79. package/lib/core/utils/internal/isHandlerKind.d.mts +1 -1
  80. package/lib/core/utils/internal/isHandlerKind.d.ts +1 -1
  81. package/lib/core/utils/internal/parseGraphQLRequest.d.mts +1 -1
  82. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +1 -1
  83. package/lib/core/utils/internal/parseMultipartData.d.mts +1 -1
  84. package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
  85. package/lib/core/utils/request/storeResponseCookies.js +1 -1
  86. package/lib/core/utils/request/storeResponseCookies.js.map +1 -1
  87. package/lib/core/utils/request/storeResponseCookies.mjs +2 -2
  88. package/lib/core/utils/request/storeResponseCookies.mjs.map +1 -1
  89. package/lib/core/ws/handleWebSocketEvent.d.mts +1 -1
  90. package/lib/core/ws/handleWebSocketEvent.d.ts +1 -1
  91. package/lib/core/ws.d.mts +17 -4
  92. package/lib/core/ws.d.ts +17 -4
  93. package/lib/core/ws.js +30 -5
  94. package/lib/core/ws.js.map +1 -1
  95. package/lib/core/ws.mjs +34 -6
  96. package/lib/core/ws.mjs.map +1 -1
  97. package/lib/iife/index.js +1241 -1158
  98. package/lib/iife/index.js.map +1 -1
  99. package/lib/mockServiceWorker.js +1 -1
  100. package/package.json +2 -2
  101. package/src/core/experimental/frames/http-frame.test.ts +6 -1
  102. package/src/core/experimental/frames/http-frame.ts +6 -2
  103. package/src/core/experimental/handlers-controller.test.ts +139 -5
  104. package/src/core/experimental/handlers-controller.ts +24 -9
  105. package/src/core/handlers/RequestHandler.ts +36 -1
  106. package/src/core/handlers/WebSocketHandler.test.ts +58 -0
  107. package/src/core/handlers/WebSocketHandler.ts +37 -8
  108. package/src/core/utils/HttpResponse/decorators.ts +6 -21
  109. package/src/core/utils/internal/attachSiblingHandlers.ts +28 -0
  110. package/src/core/utils/request/storeResponseCookies.ts +2 -4
  111. package/src/core/ws.ts +65 -6
package/lib/iife/index.js CHANGED
@@ -14652,1282 +14652,1282 @@ ${operationTypes.join("\n")}
14652
14652
  }
14653
14653
  };
14654
14654
 
14655
- // src/core/utils/internal/getCallFrame.ts
14656
- var SOURCE_FRAME = /[/\\]msw[/\\]src[/\\](.+)/;
14657
- var BUILD_FRAME = /(node_modules)?[/\\]lib[/\\](core|browser|node|native|iife)[/\\]|^[^/\\]*$/;
14658
- function getCallFrame(error3) {
14659
- const stack = error3.stack;
14660
- if (!stack) {
14661
- return;
14662
- }
14663
- const frames = stack.split("\n").slice(1);
14664
- const declarationFrame = frames.find((frame) => {
14665
- return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame));
14666
- });
14667
- if (!declarationFrame) {
14668
- return;
14669
- }
14670
- const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, "");
14671
- return declarationPath;
14655
+ // node_modules/.pnpm/set-cookie-parser@3.1.0/node_modules/set-cookie-parser/lib/set-cookie.js
14656
+ var defaultParseOptions = {
14657
+ decodeValues: true,
14658
+ map: false,
14659
+ silent: false,
14660
+ split: "auto"
14661
+ // auto = split strings but not arrays
14662
+ };
14663
+ function isForbiddenKey(key) {
14664
+ return typeof key !== "string" || key in {};
14672
14665
  }
14673
-
14674
- // src/core/utils/internal/isIterable.ts
14675
- function isIterable(fn) {
14676
- if (!fn) {
14677
- return false;
14678
- }
14679
- return Reflect.has(fn, Symbol.iterator) || Reflect.has(fn, Symbol.asyncIterator);
14666
+ function createNullObj() {
14667
+ return /* @__PURE__ */ Object.create(null);
14680
14668
  }
14681
-
14682
- // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
14683
- function createDeferredExecutor() {
14684
- const executor = (resolve, reject) => {
14685
- executor.state = "pending";
14686
- executor.resolve = (data) => {
14687
- if (executor.state !== "pending") {
14688
- return;
14689
- }
14690
- executor.result = data;
14691
- const onFulfilled = (value) => {
14692
- executor.state = "fulfilled";
14693
- return value;
14694
- };
14695
- return resolve(
14696
- data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
14697
- );
14698
- };
14699
- executor.reject = (reason) => {
14700
- if (executor.state !== "pending") {
14701
- return;
14702
- }
14703
- queueMicrotask(() => {
14704
- executor.state = "rejected";
14705
- });
14706
- return reject(executor.rejectionReason = reason);
14707
- };
14708
- };
14709
- return executor;
14669
+ function isNonEmptyString(str) {
14670
+ return typeof str === "string" && !!str.trim();
14710
14671
  }
14711
- var DeferredPromise = class extends Promise {
14712
- #executor;
14713
- resolve;
14714
- reject;
14715
- constructor(executor = null) {
14716
- const deferredExecutor = createDeferredExecutor();
14717
- super((originalResolve, originalReject) => {
14718
- deferredExecutor(originalResolve, originalReject);
14719
- executor?.(deferredExecutor.resolve, deferredExecutor.reject);
14720
- });
14721
- this.#executor = deferredExecutor;
14722
- this.resolve = this.#executor.resolve;
14723
- this.reject = this.#executor.reject;
14724
- }
14725
- get state() {
14726
- return this.#executor.state;
14727
- }
14728
- get rejectionReason() {
14729
- return this.#executor.rejectionReason;
14672
+ function parseString(setCookieValue, options) {
14673
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
14674
+ var nameValuePairStr = parts.shift();
14675
+ var parsed = parseNameValuePair(nameValuePairStr);
14676
+ var name = parsed.name;
14677
+ var value = parsed.value;
14678
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
14679
+ if (isForbiddenKey(name)) {
14680
+ return null;
14730
14681
  }
14731
- then(onFulfilled, onRejected) {
14732
- return this.#decorate(super.then(onFulfilled, onRejected));
14682
+ try {
14683
+ value = options.decodeValues ? decodeURIComponent(value) : value;
14684
+ } catch (e) {
14685
+ console.error(
14686
+ "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",
14687
+ e
14688
+ );
14733
14689
  }
14734
- catch(onRejected) {
14735
- return this.#decorate(super.catch(onRejected));
14690
+ var cookie2 = createNullObj();
14691
+ cookie2.name = name;
14692
+ cookie2.value = value;
14693
+ parts.forEach(function(part) {
14694
+ var sides = part.split("=");
14695
+ var key = sides.shift().trimLeft().toLowerCase();
14696
+ if (isForbiddenKey(key)) {
14697
+ return;
14698
+ }
14699
+ var value2 = sides.join("=");
14700
+ if (key === "expires") {
14701
+ cookie2.expires = new Date(value2);
14702
+ } else if (key === "max-age") {
14703
+ var n = parseInt(value2, 10);
14704
+ if (!Number.isNaN(n)) cookie2.maxAge = n;
14705
+ } else if (key === "secure") {
14706
+ cookie2.secure = true;
14707
+ } else if (key === "httponly") {
14708
+ cookie2.httpOnly = true;
14709
+ } else if (key === "samesite") {
14710
+ cookie2.sameSite = value2;
14711
+ } else if (key === "partitioned") {
14712
+ cookie2.partitioned = true;
14713
+ } else if (key) {
14714
+ cookie2[key] = value2;
14715
+ }
14716
+ });
14717
+ return cookie2;
14718
+ }
14719
+ function parseNameValuePair(nameValuePairStr) {
14720
+ var name = "";
14721
+ var value = "";
14722
+ var nameValueArr = nameValuePairStr.split("=");
14723
+ if (nameValueArr.length > 1) {
14724
+ name = nameValueArr.shift();
14725
+ value = nameValueArr.join("=");
14726
+ } else {
14727
+ value = nameValuePairStr;
14736
14728
  }
14737
- finally(onfinally) {
14738
- return this.#decorate(super.finally(onfinally));
14729
+ return { name, value };
14730
+ }
14731
+ function parseSetCookie(input, options) {
14732
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
14733
+ if (!input) {
14734
+ if (!options.map) {
14735
+ return [];
14736
+ } else {
14737
+ return createNullObj();
14738
+ }
14739
14739
  }
14740
- #decorate(promise) {
14741
- return Object.defineProperties(promise, {
14742
- resolve: { configurable: true, value: this.resolve },
14743
- reject: { configurable: true, value: this.reject }
14744
- });
14740
+ if (input.headers) {
14741
+ if (typeof input.headers.getSetCookie === "function") {
14742
+ input = input.headers.getSetCookie();
14743
+ } else if (input.headers["set-cookie"]) {
14744
+ input = input.headers["set-cookie"];
14745
+ } else {
14746
+ var sch = input.headers[Object.keys(input.headers).find(function(key) {
14747
+ return key.toLowerCase() === "set-cookie";
14748
+ })];
14749
+ if (!sch && input.headers.cookie && !options.silent) {
14750
+ console.warn(
14751
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
14752
+ );
14753
+ }
14754
+ input = sch;
14755
+ }
14745
14756
  }
14746
- };
14747
-
14748
- // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-BTaNLFr0.mjs
14749
- var IS_PATCHED_MODULE = Symbol("isPatchedModule");
14750
- var InterceptorError = class InterceptorError2 extends Error {
14751
- constructor(message4) {
14752
- super(message4);
14753
- this.name = "InterceptorError";
14754
- Object.setPrototypeOf(this, InterceptorError2.prototype);
14757
+ var split = options.split;
14758
+ var isArray = Array.isArray(input);
14759
+ if (split === "auto") {
14760
+ split = !isArray;
14755
14761
  }
14756
- };
14757
- var RequestController = class RequestController2 {
14758
- static {
14759
- this.PENDING = 0;
14762
+ if (!isArray) {
14763
+ input = [input];
14760
14764
  }
14761
- static {
14762
- this.PASSTHROUGH = 1;
14765
+ input = input.filter(isNonEmptyString);
14766
+ if (split) {
14767
+ input = input.map(splitCookiesString).flat();
14763
14768
  }
14764
- static {
14765
- this.RESPONSE = 2;
14769
+ if (!options.map) {
14770
+ return input.map(function(str) {
14771
+ return parseString(str, options);
14772
+ }).filter(Boolean);
14773
+ } else {
14774
+ var cookies = createNullObj();
14775
+ return input.reduce(function(cookies2, str) {
14776
+ var cookie2 = parseString(str, options);
14777
+ if (cookie2 && !isForbiddenKey(cookie2.name)) {
14778
+ cookies2[cookie2.name] = cookie2;
14779
+ }
14780
+ return cookies2;
14781
+ }, cookies);
14766
14782
  }
14767
- static {
14768
- this.ERROR = 3;
14783
+ }
14784
+ function splitCookiesString(cookiesString) {
14785
+ if (Array.isArray(cookiesString)) {
14786
+ return cookiesString;
14769
14787
  }
14770
- constructor(request, source) {
14771
- this.request = request;
14772
- this.source = source;
14773
- this.readyState = RequestController2.PENDING;
14774
- this.handled = new DeferredPromise();
14788
+ if (typeof cookiesString !== "string") {
14789
+ return [];
14775
14790
  }
14776
- get #handled() {
14777
- return this.handled;
14791
+ var cookiesStrings = [];
14792
+ var pos = 0;
14793
+ var start;
14794
+ var ch;
14795
+ var lastComma;
14796
+ var nextStart;
14797
+ var cookiesSeparatorFound;
14798
+ function skipWhitespace() {
14799
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
14800
+ pos += 1;
14801
+ }
14802
+ return pos < cookiesString.length;
14778
14803
  }
14779
- /**
14780
- * Perform this request as-is.
14781
- */
14782
- async passthrough() {
14783
- invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to passthrough the "%s %s" request: the request has already been handled', this.request.method, this.request.url);
14784
- this.readyState = RequestController2.PASSTHROUGH;
14785
- await this.source.passthrough();
14786
- this.#handled.resolve();
14804
+ function notSpecialChar() {
14805
+ ch = cookiesString.charAt(pos);
14806
+ return ch !== "=" && ch !== ";" && ch !== ",";
14787
14807
  }
14788
- /**
14789
- * Respond to this request with the given `Response` instance.
14790
- *
14791
- * @example
14792
- * controller.respondWith(new Response())
14793
- * controller.respondWith(Response.json({ id }))
14794
- * controller.respondWith(Response.error())
14795
- */
14796
- respondWith(response) {
14797
- invariant.as(InterceptorError, this.readyState === RequestController2.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);
14798
- this.readyState = RequestController2.RESPONSE;
14799
- this.#handled.resolve();
14800
- this.source.respondWith(response);
14801
- }
14802
- /**
14803
- * Error this request with the given reason.
14804
- *
14805
- * @example
14806
- * controller.errorWith()
14807
- * controller.errorWith(new Error('Oops!'))
14808
- * controller.errorWith({ message: 'Oops!'})
14809
- */
14810
- errorWith(reason) {
14811
- invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)', this.request.method, this.request.url, reason?.toString(), this.readyState);
14812
- this.readyState = RequestController2.ERROR;
14813
- this.source.errorWith(reason);
14814
- this.#handled.resolve();
14808
+ while (pos < cookiesString.length) {
14809
+ start = pos;
14810
+ cookiesSeparatorFound = false;
14811
+ while (skipWhitespace()) {
14812
+ ch = cookiesString.charAt(pos);
14813
+ if (ch === ",") {
14814
+ lastComma = pos;
14815
+ pos += 1;
14816
+ skipWhitespace();
14817
+ nextStart = pos;
14818
+ while (pos < cookiesString.length && notSpecialChar()) {
14819
+ pos += 1;
14820
+ }
14821
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
14822
+ cookiesSeparatorFound = true;
14823
+ pos = nextStart;
14824
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
14825
+ start = pos;
14826
+ } else {
14827
+ pos = lastComma + 1;
14828
+ }
14829
+ } else {
14830
+ pos += 1;
14831
+ }
14832
+ }
14833
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
14834
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
14835
+ }
14815
14836
  }
14816
- };
14817
- function canParseUrl(url) {
14818
- try {
14819
- new URL(url);
14820
- return true;
14821
- } catch (_error) {
14822
- return false;
14837
+ return cookiesStrings;
14838
+ }
14839
+ parseSetCookie.parseSetCookie = parseSetCookie;
14840
+ parseSetCookie.parse = parseSetCookie;
14841
+ parseSetCookie.parseString = parseString;
14842
+ parseSetCookie.splitCookiesString = splitCookiesString;
14843
+
14844
+ // node_modules/.pnpm/headers-polyfill@5.0.1/node_modules/headers-polyfill/lib/index.mjs
14845
+ var HEADERS_INVALID_CHARACTERS = /[^a-z0-9\-#$%&'*+.^_`|~]/i;
14846
+ function normalizeHeaderName(name) {
14847
+ if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === "") throw new TypeError("Invalid character in header field name");
14848
+ return name.trim().toLowerCase();
14849
+ }
14850
+ var charCodesToRemove = [
14851
+ String.fromCharCode(10),
14852
+ String.fromCharCode(13),
14853
+ String.fromCharCode(9),
14854
+ String.fromCharCode(32)
14855
+ ];
14856
+ var HEADER_VALUE_REMOVE_REGEXP = new RegExp(`(^[${charCodesToRemove.join("")}]|$[${charCodesToRemove.join("")}])`, "g");
14857
+ function normalizeHeaderValue(value) {
14858
+ return value.replace(HEADER_VALUE_REMOVE_REGEXP, "");
14859
+ }
14860
+ function isValidHeaderName(value) {
14861
+ if (typeof value !== "string") return false;
14862
+ if (value.length === 0) return false;
14863
+ for (let i = 0; i < value.length; i++) {
14864
+ const character = value.charCodeAt(i);
14865
+ if (character > 127 || !isToken(character)) return false;
14823
14866
  }
14867
+ return true;
14824
14868
  }
14825
- function getValueBySymbol(symbolName, source) {
14826
- const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => {
14827
- return symbol$1.description === symbolName;
14828
- });
14829
- if (symbol) return Reflect.get(source, symbol);
14869
+ function isToken(value) {
14870
+ return ![
14871
+ 127,
14872
+ 32,
14873
+ "(",
14874
+ ")",
14875
+ "<",
14876
+ ">",
14877
+ "@",
14878
+ ",",
14879
+ ";",
14880
+ ":",
14881
+ "\\",
14882
+ '"',
14883
+ "/",
14884
+ "[",
14885
+ "]",
14886
+ "?",
14887
+ "=",
14888
+ "{",
14889
+ "}"
14890
+ ].includes(value);
14830
14891
  }
14831
- var FetchResponse = class FetchResponse2 extends Response {
14832
- static {
14833
- this.STATUS_CODES_WITHOUT_BODY = [
14834
- 101,
14835
- 103,
14836
- 204,
14837
- 205,
14838
- 304
14839
- ];
14892
+ function isValidHeaderValue(value) {
14893
+ if (typeof value !== "string") return false;
14894
+ if (value.trim() !== value) return false;
14895
+ for (let i = 0; i < value.length; i++) {
14896
+ const character = value.charCodeAt(i);
14897
+ if (character === 0 || character === 10 || character === 13) return false;
14840
14898
  }
14841
- static {
14842
- this.STATUS_CODES_WITH_REDIRECT = [
14843
- 301,
14844
- 302,
14845
- 303,
14846
- 307,
14847
- 308
14848
- ];
14899
+ return true;
14900
+ }
14901
+ var _Symbol$toStringTag;
14902
+ var NORMALIZED_HEADERS = Symbol("normalizedHeaders");
14903
+ var RAW_HEADER_NAMES = Symbol("rawHeaderNames");
14904
+ var HEADER_VALUE_DELIMITER = ", ";
14905
+ var Headers2 = class Headers3 {
14906
+ constructor(init) {
14907
+ this[NORMALIZED_HEADERS] = {};
14908
+ this[RAW_HEADER_NAMES] = /* @__PURE__ */ new Map();
14909
+ this[_Symbol$toStringTag] = "Headers";
14910
+ if (["Headers", "HeadersPolyfill"].includes(init?.constructor?.name) || init instanceof Headers3 || typeof globalThis.Headers !== "undefined" && init instanceof globalThis.Headers) init.forEach((value, name) => {
14911
+ this.append(name, value);
14912
+ }, this);
14913
+ else if (Array.isArray(init)) init.forEach(([name, value]) => {
14914
+ this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value);
14915
+ });
14916
+ else if (init) Object.getOwnPropertyNames(init).forEach((name) => {
14917
+ const value = init[name];
14918
+ this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value);
14919
+ });
14849
14920
  }
14850
- static isConfigurableStatusCode(status) {
14851
- return status >= 200 && status <= 599;
14921
+ [(_Symbol$toStringTag = Symbol.toStringTag, Symbol.iterator)]() {
14922
+ return this.entries();
14852
14923
  }
14853
- static isRedirectResponse(status) {
14854
- return FetchResponse2.STATUS_CODES_WITH_REDIRECT.includes(status);
14924
+ *keys() {
14925
+ for (const [name] of this.entries()) yield name;
14926
+ }
14927
+ *values() {
14928
+ for (const [, value] of this.entries()) yield value;
14929
+ }
14930
+ *entries() {
14931
+ let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) => a.localeCompare(b));
14932
+ for (const name of sortedKeys) if (name === "set-cookie") for (const value of this.getSetCookie()) yield [name, value];
14933
+ else yield [name, this.get(name)];
14855
14934
  }
14856
14935
  /**
14857
- * Returns a boolean indicating whether the given response status
14858
- * code represents a response that can have a body.
14936
+ * Returns a boolean stating whether a `Headers` object contains a certain header.
14859
14937
  */
14860
- static isResponseWithBody(status) {
14861
- return !FetchResponse2.STATUS_CODES_WITHOUT_BODY.includes(status);
14862
- }
14863
- static setUrl(url, response) {
14864
- if (!url || url === "about:" || !canParseUrl(url)) return;
14865
- const state = getValueBySymbol("state", response);
14866
- if (state) state.urlList.push(new URL(url));
14867
- else Object.defineProperty(response, "url", {
14868
- value: url,
14869
- enumerable: true,
14870
- configurable: true,
14871
- writable: false
14872
- });
14938
+ has(name) {
14939
+ if (!isValidHeaderName(name)) throw new TypeError(`Invalid header name "${name}"`);
14940
+ return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name));
14873
14941
  }
14874
14942
  /**
14875
- * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
14943
+ * Returns a `ByteString` sequence of all the values of a header with a given name.
14876
14944
  */
14877
- static parseRawHeaders(rawHeaders) {
14878
- const headers = new Headers();
14879
- for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]);
14880
- return headers;
14945
+ get(name) {
14946
+ if (!isValidHeaderName(name)) throw TypeError(`Invalid header name "${name}"`);
14947
+ return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null;
14881
14948
  }
14882
- constructor(body, init = {}) {
14883
- const status = init.status ?? 200;
14884
- const safeStatus = FetchResponse2.isConfigurableStatusCode(status) ? status : 200;
14885
- const finalBody = FetchResponse2.isResponseWithBody(status) ? body : null;
14886
- super(finalBody, {
14887
- status: safeStatus,
14888
- statusText: init.statusText,
14889
- headers: init.headers
14890
- });
14891
- if (status !== safeStatus) {
14892
- const state = getValueBySymbol("state", this);
14893
- if (state) state.status = status;
14894
- else Object.defineProperty(this, "status", {
14895
- value: status,
14896
- enumerable: true,
14897
- configurable: true,
14898
- writable: false
14899
- });
14900
- }
14901
- FetchResponse2.setUrl(init.url, this);
14949
+ /**
14950
+ * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.
14951
+ */
14952
+ set(name, value) {
14953
+ if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return;
14954
+ const normalizedName = normalizeHeaderName(name);
14955
+ const normalizedValue = normalizeHeaderValue(value);
14956
+ this[NORMALIZED_HEADERS][normalizedName] = normalizeHeaderValue(normalizedValue);
14957
+ this[RAW_HEADER_NAMES].set(normalizedName, name);
14902
14958
  }
14903
- };
14904
- var kRawRequest = Symbol("kRawRequest");
14905
- function setRawRequest(request, rawRequest) {
14906
- Reflect.set(request, kRawRequest, rawRequest);
14907
- }
14908
-
14909
- // node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs
14910
- function isNodeProcess() {
14911
- if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
14912
- return true;
14913
- }
14914
- if (typeof process !== "undefined") {
14915
- const type = process.type;
14916
- if (type === "renderer" || type === "worker") {
14917
- return false;
14918
- }
14919
- return !!(process.versions && process.versions.node);
14920
- }
14921
- return false;
14922
- }
14923
-
14924
- // node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs
14925
- var __defProp2 = Object.defineProperty;
14926
- var __export2 = (target, all) => {
14927
- for (var name in all)
14928
- __defProp2(target, name, { get: all[name], enumerable: true });
14929
- };
14930
- var colors_exports = {};
14931
- __export2(colors_exports, {
14932
- blue: () => blue,
14933
- gray: () => gray,
14934
- green: () => green,
14935
- red: () => red,
14936
- yellow: () => yellow
14937
- });
14938
- function yellow(text) {
14939
- return `\x1B[33m${text}\x1B[0m`;
14940
- }
14941
- function blue(text) {
14942
- return `\x1B[34m${text}\x1B[0m`;
14943
- }
14944
- function gray(text) {
14945
- return `\x1B[90m${text}\x1B[0m`;
14946
- }
14947
- function red(text) {
14948
- return `\x1B[31m${text}\x1B[0m`;
14949
- }
14950
- function green(text) {
14951
- return `\x1B[32m${text}\x1B[0m`;
14952
- }
14953
- var IS_NODE = isNodeProcess();
14954
- var Logger = class {
14955
- constructor(name) {
14956
- this.name = name;
14957
- this.prefix = `[${this.name}]`;
14958
- const LOGGER_NAME = getVariable("DEBUG");
14959
- const LOGGER_LEVEL = getVariable("LOG_LEVEL");
14960
- const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME);
14961
- if (isLoggingEnabled) {
14962
- this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug;
14963
- this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info;
14964
- this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success;
14965
- this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning;
14966
- this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error;
14967
- } else {
14968
- this.info = noop;
14969
- this.success = noop;
14970
- this.warning = noop;
14971
- this.error = noop;
14972
- this.only = noop;
14973
- }
14974
- }
14975
- prefix;
14976
- extend(domain) {
14977
- return new Logger(`${this.name}:${domain}`);
14978
- }
14979
- /**
14980
- * Print a debug message.
14981
- * @example
14982
- * logger.debug('no duplicates found, creating a document...')
14983
- */
14984
- debug(message4, ...positionals) {
14985
- this.logEntry({
14986
- level: "debug",
14987
- message: gray(message4),
14988
- positionals,
14989
- prefix: this.prefix,
14990
- colors: {
14991
- prefix: "gray"
14992
- }
14993
- });
14994
- }
14995
- /**
14996
- * Print an info message.
14997
- * @example
14998
- * logger.info('start parsing...')
14999
- */
15000
- info(message4, ...positionals) {
15001
- this.logEntry({
15002
- level: "info",
15003
- message: message4,
15004
- positionals,
15005
- prefix: this.prefix,
15006
- colors: {
15007
- prefix: "blue"
15008
- }
15009
- });
15010
- const performance2 = new PerformanceEntry();
15011
- return (message22, ...positionals2) => {
15012
- performance2.measure();
15013
- this.logEntry({
15014
- level: "info",
15015
- message: `${message22} ${gray(`${performance2.deltaTime}ms`)}`,
15016
- positionals: positionals2,
15017
- prefix: this.prefix,
15018
- colors: {
15019
- prefix: "blue"
15020
- }
15021
- });
15022
- };
15023
- }
15024
- /**
15025
- * Print a success message.
15026
- * @example
15027
- * logger.success('successfully created document')
15028
- */
15029
- success(message4, ...positionals) {
15030
- this.logEntry({
15031
- level: "info",
15032
- message: message4,
15033
- positionals,
15034
- prefix: `\u2714 ${this.prefix}`,
15035
- colors: {
15036
- timestamp: "green",
15037
- prefix: "green"
15038
- }
15039
- });
14959
+ /**
14960
+ * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.
14961
+ */
14962
+ append(name, value) {
14963
+ if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return;
14964
+ const normalizedName = normalizeHeaderName(name);
14965
+ const normalizedValue = normalizeHeaderValue(value);
14966
+ let resolvedValue = this.has(normalizedName) ? `${this.get(normalizedName)}, ${normalizedValue}` : normalizedValue;
14967
+ this.set(name, resolvedValue);
15040
14968
  }
15041
14969
  /**
15042
- * Print a warning.
15043
- * @example
15044
- * logger.warning('found legacy document format')
15045
- */
15046
- warning(message4, ...positionals) {
15047
- this.logEntry({
15048
- level: "warning",
15049
- message: message4,
15050
- positionals,
15051
- prefix: `\u26A0 ${this.prefix}`,
15052
- colors: {
15053
- timestamp: "yellow",
15054
- prefix: "yellow"
15055
- }
15056
- });
14970
+ * Deletes a header from the `Headers` object.
14971
+ */
14972
+ delete(name) {
14973
+ if (!isValidHeaderName(name)) return;
14974
+ if (!this.has(name)) return;
14975
+ const normalizedName = normalizeHeaderName(name);
14976
+ delete this[NORMALIZED_HEADERS][normalizedName];
14977
+ this[RAW_HEADER_NAMES].delete(normalizedName);
15057
14978
  }
15058
14979
  /**
15059
- * Print an error message.
15060
- * @example
15061
- * logger.error('something went wrong')
15062
- */
15063
- error(message4, ...positionals) {
15064
- this.logEntry({
15065
- level: "error",
15066
- message: message4,
15067
- positionals,
15068
- prefix: `\u2716 ${this.prefix}`,
15069
- colors: {
15070
- timestamp: "red",
15071
- prefix: "red"
15072
- }
15073
- });
14980
+ * Traverses the `Headers` object,
14981
+ * calling the given callback for each header.
14982
+ */
14983
+ forEach(callback, thisArg) {
14984
+ for (const [name, value] of this.entries()) callback.call(thisArg, value, name, this);
15074
14985
  }
15075
14986
  /**
15076
- * Execute the given callback only when the logging is enabled.
15077
- * This is skipped in its entirety and has no runtime cost otherwise.
15078
- * This executes regardless of the log level.
15079
- * @example
15080
- * logger.only(() => {
15081
- * logger.info('additional info')
15082
- * })
15083
- */
15084
- only(callback) {
15085
- callback();
15086
- }
15087
- createEntry(level, message4) {
15088
- return {
15089
- timestamp: /* @__PURE__ */ new Date(),
15090
- level,
15091
- message: message4
15092
- };
15093
- }
15094
- logEntry(args) {
15095
- const {
15096
- level,
15097
- message: message4,
15098
- prefix,
15099
- colors: customColors,
15100
- positionals = []
15101
- } = args;
15102
- const entry = this.createEntry(level, message4);
15103
- const timestampColor = customColors?.timestamp || "gray";
15104
- const prefixColor = customColors?.prefix || "gray";
15105
- const colorize = {
15106
- timestamp: colors_exports[timestampColor],
15107
- prefix: colors_exports[prefixColor]
15108
- };
15109
- const write = this.getWriter(level);
15110
- write(
15111
- [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message4)).join(" "),
15112
- ...positionals.map(serializeInput)
15113
- );
15114
- }
15115
- formatTimestamp(timestamp) {
15116
- return `${timestamp.toLocaleTimeString(
15117
- "en-GB"
15118
- )}:${timestamp.getMilliseconds()}`;
15119
- }
15120
- getWriter(level) {
15121
- switch (level) {
15122
- case "debug":
15123
- case "success":
15124
- case "info": {
15125
- return log;
15126
- }
15127
- case "warning": {
15128
- return warn2;
15129
- }
15130
- case "error": {
15131
- return error2;
15132
- }
15133
- }
15134
- }
15135
- };
15136
- var PerformanceEntry = class {
15137
- startTime;
15138
- endTime;
15139
- deltaTime;
15140
- constructor() {
15141
- this.startTime = performance.now();
15142
- }
15143
- measure() {
15144
- this.endTime = performance.now();
15145
- const deltaTime = this.endTime - this.startTime;
15146
- this.deltaTime = deltaTime.toFixed(2);
14987
+ * Returns an array containing the values
14988
+ * of all Set-Cookie headers associated
14989
+ * with a response
14990
+ */
14991
+ getSetCookie() {
14992
+ const setCookieHeader = this.get("set-cookie");
14993
+ if (setCookieHeader === null) return [];
14994
+ if (setCookieHeader === "") return [""];
14995
+ return splitCookiesString(setCookieHeader);
15147
14996
  }
15148
14997
  };
15149
- var noop = () => void 0;
15150
- function log(message4, ...positionals) {
15151
- if (IS_NODE) {
15152
- process.stdout.write(format(message4, ...positionals) + "\n");
15153
- return;
15154
- }
15155
- console.log(message4, ...positionals);
14998
+ function stringToHeaders(str) {
14999
+ return str.trim().split(/[\r\n]+/).reduce((headers, line) => {
15000
+ if (line.trim() === "") return headers;
15001
+ const parts = line.split(": ");
15002
+ const name = parts.shift();
15003
+ const value = parts.join(": ");
15004
+ headers.append(name, value);
15005
+ return headers;
15006
+ }, new Headers2());
15156
15007
  }
15157
- function warn2(message4, ...positionals) {
15158
- if (IS_NODE) {
15159
- process.stderr.write(format(message4, ...positionals) + "\n");
15008
+
15009
+ // src/core/utils/internal/getCallFrame.ts
15010
+ var SOURCE_FRAME = /[/\\]msw[/\\]src[/\\](.+)/;
15011
+ var BUILD_FRAME = /(node_modules)?[/\\]lib[/\\](core|browser|node|native|iife)[/\\]|^[^/\\]*$/;
15012
+ function getCallFrame(error3) {
15013
+ const stack = error3.stack;
15014
+ if (!stack) {
15160
15015
  return;
15161
15016
  }
15162
- console.warn(message4, ...positionals);
15163
- }
15164
- function error2(message4, ...positionals) {
15165
- if (IS_NODE) {
15166
- process.stderr.write(format(message4, ...positionals) + "\n");
15017
+ const frames = stack.split("\n").slice(1);
15018
+ const declarationFrame = frames.find((frame) => {
15019
+ return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame));
15020
+ });
15021
+ if (!declarationFrame) {
15167
15022
  return;
15168
15023
  }
15169
- console.error(message4, ...positionals);
15170
- }
15171
- function getVariable(variableName) {
15172
- if (IS_NODE) {
15173
- return process.env[variableName];
15174
- }
15175
- return globalThis[variableName]?.toString();
15176
- }
15177
- function isDefinedAndNotEquals(value, expected) {
15178
- return value !== void 0 && value !== expected;
15024
+ const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, "");
15025
+ return declarationPath;
15179
15026
  }
15180
- function serializeInput(message4) {
15181
- if (typeof message4 === "undefined") {
15182
- return "undefined";
15183
- }
15184
- if (message4 === null) {
15185
- return "null";
15186
- }
15187
- if (typeof message4 === "string") {
15188
- return message4;
15189
- }
15190
- if (typeof message4 === "object") {
15191
- return JSON.stringify(message4);
15027
+
15028
+ // src/core/utils/internal/isIterable.ts
15029
+ function isIterable(fn) {
15030
+ if (!fn) {
15031
+ return false;
15192
15032
  }
15193
- return message4.toString();
15033
+ return Reflect.has(fn, Symbol.iterator) || Reflect.has(fn, Symbol.asyncIterator);
15194
15034
  }
15195
15035
 
15196
- // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
15197
- var MemoryLeakError = class extends Error {
15198
- constructor(emitter, type, count) {
15199
- super(
15200
- `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`
15201
- );
15202
- this.emitter = emitter;
15203
- this.type = type;
15204
- this.count = count;
15205
- this.name = "MaxListenersExceededWarning";
15206
- }
15207
- };
15208
- var _Emitter = class {
15209
- static listenerCount(emitter, eventName) {
15210
- return emitter.listenerCount(eventName);
15211
- }
15212
- constructor() {
15213
- this.events = /* @__PURE__ */ new Map();
15214
- this.maxListeners = _Emitter.defaultMaxListeners;
15215
- this.hasWarnedAboutPotentialMemoryLeak = false;
15216
- }
15217
- _emitInternalEvent(internalEventName, eventName, listener) {
15218
- this.emit(
15219
- internalEventName,
15220
- ...[eventName, listener]
15221
- );
15222
- }
15223
- _getListeners(eventName) {
15224
- return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
15225
- }
15226
- _removeListener(listeners, listener) {
15227
- const index = listeners.indexOf(listener);
15228
- if (index > -1) {
15229
- listeners.splice(index, 1);
15230
- }
15231
- return [];
15232
- }
15233
- _wrapOnceListener(eventName, listener) {
15234
- const onceListener = (...data) => {
15235
- this.removeListener(eventName, onceListener);
15236
- return listener.apply(this, data);
15036
+ // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
15037
+ function createDeferredExecutor() {
15038
+ const executor = (resolve, reject) => {
15039
+ executor.state = "pending";
15040
+ executor.resolve = (data) => {
15041
+ if (executor.state !== "pending") {
15042
+ return;
15043
+ }
15044
+ executor.result = data;
15045
+ const onFulfilled = (value) => {
15046
+ executor.state = "fulfilled";
15047
+ return value;
15048
+ };
15049
+ return resolve(
15050
+ data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
15051
+ );
15237
15052
  };
15238
- Object.defineProperty(onceListener, "name", { value: listener.name });
15239
- return onceListener;
15240
- }
15241
- setMaxListeners(maxListeners) {
15242
- this.maxListeners = maxListeners;
15243
- return this;
15244
- }
15245
- /**
15246
- * Returns the current max listener value for the `Emitter` which is
15247
- * either set by `emitter.setMaxListeners(n)` or defaults to
15248
- * `Emitter.defaultMaxListeners`.
15249
- */
15250
- getMaxListeners() {
15251
- return this.maxListeners;
15053
+ executor.reject = (reason) => {
15054
+ if (executor.state !== "pending") {
15055
+ return;
15056
+ }
15057
+ queueMicrotask(() => {
15058
+ executor.state = "rejected";
15059
+ });
15060
+ return reject(executor.rejectionReason = reason);
15061
+ };
15062
+ };
15063
+ return executor;
15064
+ }
15065
+ var DeferredPromise = class extends Promise {
15066
+ #executor;
15067
+ resolve;
15068
+ reject;
15069
+ constructor(executor = null) {
15070
+ const deferredExecutor = createDeferredExecutor();
15071
+ super((originalResolve, originalReject) => {
15072
+ deferredExecutor(originalResolve, originalReject);
15073
+ executor?.(deferredExecutor.resolve, deferredExecutor.reject);
15074
+ });
15075
+ this.#executor = deferredExecutor;
15076
+ this.resolve = this.#executor.resolve;
15077
+ this.reject = this.#executor.reject;
15252
15078
  }
15253
- /**
15254
- * Returns an array listing the events for which the emitter has registered listeners.
15255
- * The values in the array will be strings or Symbols.
15256
- */
15257
- eventNames() {
15258
- return Array.from(this.events.keys());
15079
+ get state() {
15080
+ return this.#executor.state;
15259
15081
  }
15260
- /**
15261
- * Synchronously calls each of the listeners registered for the event named `eventName`,
15262
- * in the order they were registered, passing the supplied arguments to each.
15263
- * Returns `true` if the event has listeners, `false` otherwise.
15264
- *
15265
- * @example
15266
- * const emitter = new Emitter<{ hello: [string] }>()
15267
- * emitter.emit('hello', 'John')
15268
- */
15269
- emit(eventName, ...data) {
15270
- const listeners = this._getListeners(eventName);
15271
- listeners.forEach((listener) => {
15272
- listener.apply(this, data);
15273
- });
15274
- return listeners.length > 0;
15082
+ get rejectionReason() {
15083
+ return this.#executor.rejectionReason;
15275
15084
  }
15276
- addListener(eventName, listener) {
15277
- this._emitInternalEvent("newListener", eventName, listener);
15278
- const nextListeners = this._getListeners(eventName).concat(listener);
15279
- this.events.set(eventName, nextListeners);
15280
- if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) {
15281
- this.hasWarnedAboutPotentialMemoryLeak = true;
15282
- const memoryLeakWarning = new MemoryLeakError(
15283
- this,
15284
- eventName,
15285
- this.listenerCount(eventName)
15286
- );
15287
- console.warn(memoryLeakWarning);
15288
- }
15289
- return this;
15085
+ then(onFulfilled, onRejected) {
15086
+ return this.#decorate(super.then(onFulfilled, onRejected));
15290
15087
  }
15291
- on(eventName, listener) {
15292
- return this.addListener(eventName, listener);
15088
+ catch(onRejected) {
15089
+ return this.#decorate(super.catch(onRejected));
15293
15090
  }
15294
- once(eventName, listener) {
15295
- return this.addListener(
15296
- eventName,
15297
- this._wrapOnceListener(eventName, listener)
15298
- );
15091
+ finally(onfinally) {
15092
+ return this.#decorate(super.finally(onfinally));
15299
15093
  }
15300
- prependListener(eventName, listener) {
15301
- const listeners = this._getListeners(eventName);
15302
- if (listeners.length > 0) {
15303
- const nextListeners = [listener].concat(listeners);
15304
- this.events.set(eventName, nextListeners);
15305
- } else {
15306
- this.events.set(eventName, listeners.concat(listener));
15307
- }
15308
- return this;
15094
+ #decorate(promise) {
15095
+ return Object.defineProperties(promise, {
15096
+ resolve: { configurable: true, value: this.resolve },
15097
+ reject: { configurable: true, value: this.reject }
15098
+ });
15309
15099
  }
15310
- prependOnceListener(eventName, listener) {
15311
- return this.prependListener(
15312
- eventName,
15313
- this._wrapOnceListener(eventName, listener)
15314
- );
15100
+ };
15101
+
15102
+ // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-BTaNLFr0.mjs
15103
+ var IS_PATCHED_MODULE = Symbol("isPatchedModule");
15104
+ var InterceptorError = class InterceptorError2 extends Error {
15105
+ constructor(message4) {
15106
+ super(message4);
15107
+ this.name = "InterceptorError";
15108
+ Object.setPrototypeOf(this, InterceptorError2.prototype);
15315
15109
  }
15316
- removeListener(eventName, listener) {
15317
- const listeners = this._getListeners(eventName);
15318
- if (listeners.length > 0) {
15319
- this._removeListener(listeners, listener);
15320
- this.events.set(eventName, listeners);
15321
- this._emitInternalEvent("removeListener", eventName, listener);
15322
- }
15323
- return this;
15110
+ };
15111
+ var RequestController = class RequestController2 {
15112
+ static {
15113
+ this.PENDING = 0;
15324
15114
  }
15325
- /**
15326
- * Alias for `emitter.removeListener()`.
15327
- *
15328
- * @example
15329
- * emitter.off('hello', listener)
15330
- */
15331
- off(eventName, listener) {
15332
- return this.removeListener(eventName, listener);
15115
+ static {
15116
+ this.PASSTHROUGH = 1;
15333
15117
  }
15334
- removeAllListeners(eventName) {
15335
- if (eventName) {
15336
- this.events.delete(eventName);
15337
- } else {
15338
- this.events.clear();
15339
- }
15340
- return this;
15118
+ static {
15119
+ this.RESPONSE = 2;
15120
+ }
15121
+ static {
15122
+ this.ERROR = 3;
15123
+ }
15124
+ constructor(request, source) {
15125
+ this.request = request;
15126
+ this.source = source;
15127
+ this.readyState = RequestController2.PENDING;
15128
+ this.handled = new DeferredPromise();
15129
+ }
15130
+ get #handled() {
15131
+ return this.handled;
15341
15132
  }
15342
15133
  /**
15343
- * Returns a copy of the array of listeners for the event named `eventName`.
15344
- */
15345
- listeners(eventName) {
15346
- return Array.from(this._getListeners(eventName));
15134
+ * Perform this request as-is.
15135
+ */
15136
+ async passthrough() {
15137
+ invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to passthrough the "%s %s" request: the request has already been handled', this.request.method, this.request.url);
15138
+ this.readyState = RequestController2.PASSTHROUGH;
15139
+ await this.source.passthrough();
15140
+ this.#handled.resolve();
15347
15141
  }
15348
15142
  /**
15349
- * Returns the number of listeners listening to the event named `eventName`.
15350
- */
15351
- listenerCount(eventName) {
15352
- return this._getListeners(eventName).length;
15143
+ * Respond to this request with the given `Response` instance.
15144
+ *
15145
+ * @example
15146
+ * controller.respondWith(new Response())
15147
+ * controller.respondWith(Response.json({ id }))
15148
+ * controller.respondWith(Response.error())
15149
+ */
15150
+ respondWith(response) {
15151
+ invariant.as(InterceptorError, this.readyState === RequestController2.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);
15152
+ this.readyState = RequestController2.RESPONSE;
15153
+ this.#handled.resolve();
15154
+ this.source.respondWith(response);
15353
15155
  }
15354
- rawListeners(eventName) {
15355
- return this.listeners(eventName);
15156
+ /**
15157
+ * Error this request with the given reason.
15158
+ *
15159
+ * @example
15160
+ * controller.errorWith()
15161
+ * controller.errorWith(new Error('Oops!'))
15162
+ * controller.errorWith({ message: 'Oops!'})
15163
+ */
15164
+ errorWith(reason) {
15165
+ invariant.as(InterceptorError, this.readyState === RequestController2.PENDING, 'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)', this.request.method, this.request.url, reason?.toString(), this.readyState);
15166
+ this.readyState = RequestController2.ERROR;
15167
+ this.source.errorWith(reason);
15168
+ this.#handled.resolve();
15356
15169
  }
15357
15170
  };
15358
- var Emitter2 = _Emitter;
15359
- Emitter2.defaultMaxListeners = 10;
15360
-
15361
- // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DQcIlohW.mjs
15362
- var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id";
15363
- function getGlobalSymbol(symbol) {
15364
- return globalThis[symbol] || void 0;
15365
- }
15366
- function setGlobalSymbol(symbol, value) {
15367
- globalThis[symbol] = value;
15171
+ function canParseUrl(url) {
15172
+ try {
15173
+ new URL(url);
15174
+ return true;
15175
+ } catch (_error) {
15176
+ return false;
15177
+ }
15368
15178
  }
15369
- function deleteGlobalSymbol(symbol) {
15370
- delete globalThis[symbol];
15179
+ function getValueBySymbol(symbolName, source) {
15180
+ const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => {
15181
+ return symbol$1.description === symbolName;
15182
+ });
15183
+ if (symbol) return Reflect.get(source, symbol);
15371
15184
  }
15372
- var InterceptorReadyState = /* @__PURE__ */ (function(InterceptorReadyState$1) {
15373
- InterceptorReadyState$1["INACTIVE"] = "INACTIVE";
15374
- InterceptorReadyState$1["APPLYING"] = "APPLYING";
15375
- InterceptorReadyState$1["APPLIED"] = "APPLIED";
15376
- InterceptorReadyState$1["DISPOSING"] = "DISPOSING";
15377
- InterceptorReadyState$1["DISPOSED"] = "DISPOSED";
15378
- return InterceptorReadyState$1;
15379
- })({});
15380
- var Interceptor = class {
15381
- constructor(symbol) {
15382
- this.symbol = symbol;
15383
- this.readyState = InterceptorReadyState.INACTIVE;
15384
- this.emitter = new Emitter2();
15385
- this.subscriptions = [];
15386
- this.logger = new Logger(symbol.description);
15387
- this.emitter.setMaxListeners(0);
15388
- this.logger.info("constructing the interceptor...");
15185
+ var FetchResponse = class FetchResponse2 extends Response {
15186
+ static {
15187
+ this.STATUS_CODES_WITHOUT_BODY = [
15188
+ 101,
15189
+ 103,
15190
+ 204,
15191
+ 205,
15192
+ 304
15193
+ ];
15194
+ }
15195
+ static {
15196
+ this.STATUS_CODES_WITH_REDIRECT = [
15197
+ 301,
15198
+ 302,
15199
+ 303,
15200
+ 307,
15201
+ 308
15202
+ ];
15203
+ }
15204
+ static isConfigurableStatusCode(status) {
15205
+ return status >= 200 && status <= 599;
15206
+ }
15207
+ static isRedirectResponse(status) {
15208
+ return FetchResponse2.STATUS_CODES_WITH_REDIRECT.includes(status);
15389
15209
  }
15390
15210
  /**
15391
- * Determine if this interceptor can be applied
15392
- * in the current environment.
15211
+ * Returns a boolean indicating whether the given response status
15212
+ * code represents a response that can have a body.
15393
15213
  */
15394
- checkEnvironment() {
15395
- return true;
15214
+ static isResponseWithBody(status) {
15215
+ return !FetchResponse2.STATUS_CODES_WITHOUT_BODY.includes(status);
15216
+ }
15217
+ static setUrl(url, response) {
15218
+ if (!url || url === "about:" || !canParseUrl(url)) return;
15219
+ const state = getValueBySymbol("state", response);
15220
+ if (state) state.urlList.push(new URL(url));
15221
+ else Object.defineProperty(response, "url", {
15222
+ value: url,
15223
+ enumerable: true,
15224
+ configurable: true,
15225
+ writable: false
15226
+ });
15396
15227
  }
15397
15228
  /**
15398
- * Apply this interceptor to the current process.
15399
- * Returns an already running interceptor instance if it's present.
15229
+ * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
15400
15230
  */
15401
- apply() {
15402
- const logger = this.logger.extend("apply");
15403
- logger.info("applying the interceptor...");
15404
- if (this.readyState === InterceptorReadyState.APPLIED) {
15405
- logger.info("intercepted already applied!");
15406
- return;
15231
+ static parseRawHeaders(rawHeaders) {
15232
+ const headers = new Headers();
15233
+ for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]);
15234
+ return headers;
15235
+ }
15236
+ constructor(body, init = {}) {
15237
+ const status = init.status ?? 200;
15238
+ const safeStatus = FetchResponse2.isConfigurableStatusCode(status) ? status : 200;
15239
+ const finalBody = FetchResponse2.isResponseWithBody(status) ? body : null;
15240
+ super(finalBody, {
15241
+ status: safeStatus,
15242
+ statusText: init.statusText,
15243
+ headers: init.headers
15244
+ });
15245
+ if (status !== safeStatus) {
15246
+ const state = getValueBySymbol("state", this);
15247
+ if (state) state.status = status;
15248
+ else Object.defineProperty(this, "status", {
15249
+ value: status,
15250
+ enumerable: true,
15251
+ configurable: true,
15252
+ writable: false
15253
+ });
15407
15254
  }
15408
- if (!this.checkEnvironment()) {
15409
- logger.info("the interceptor cannot be applied in this environment!");
15410
- return;
15255
+ FetchResponse2.setUrl(init.url, this);
15256
+ }
15257
+ };
15258
+ var kRawRequest = Symbol("kRawRequest");
15259
+ function setRawRequest(request, rawRequest) {
15260
+ Reflect.set(request, kRawRequest, rawRequest);
15261
+ }
15262
+
15263
+ // node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs
15264
+ function isNodeProcess() {
15265
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
15266
+ return true;
15267
+ }
15268
+ if (typeof process !== "undefined") {
15269
+ const type = process.type;
15270
+ if (type === "renderer" || type === "worker") {
15271
+ return false;
15411
15272
  }
15412
- this.readyState = InterceptorReadyState.APPLYING;
15413
- const runningInstance = this.getInstance();
15414
- if (runningInstance) {
15415
- logger.info("found a running instance, reusing...");
15416
- this.on = (event, listener) => {
15417
- logger.info('proxying the "%s" listener', event);
15418
- runningInstance.emitter.addListener(event, listener);
15419
- this.subscriptions.push(() => {
15420
- runningInstance.emitter.removeListener(event, listener);
15421
- logger.info('removed proxied "%s" listener!', event);
15422
- });
15423
- return this;
15424
- };
15425
- this.readyState = InterceptorReadyState.APPLIED;
15426
- return;
15273
+ return !!(process.versions && process.versions.node);
15274
+ }
15275
+ return false;
15276
+ }
15277
+
15278
+ // node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs
15279
+ var __defProp2 = Object.defineProperty;
15280
+ var __export2 = (target, all) => {
15281
+ for (var name in all)
15282
+ __defProp2(target, name, { get: all[name], enumerable: true });
15283
+ };
15284
+ var colors_exports = {};
15285
+ __export2(colors_exports, {
15286
+ blue: () => blue,
15287
+ gray: () => gray,
15288
+ green: () => green,
15289
+ red: () => red,
15290
+ yellow: () => yellow
15291
+ });
15292
+ function yellow(text) {
15293
+ return `\x1B[33m${text}\x1B[0m`;
15294
+ }
15295
+ function blue(text) {
15296
+ return `\x1B[34m${text}\x1B[0m`;
15297
+ }
15298
+ function gray(text) {
15299
+ return `\x1B[90m${text}\x1B[0m`;
15300
+ }
15301
+ function red(text) {
15302
+ return `\x1B[31m${text}\x1B[0m`;
15303
+ }
15304
+ function green(text) {
15305
+ return `\x1B[32m${text}\x1B[0m`;
15306
+ }
15307
+ var IS_NODE = isNodeProcess();
15308
+ var Logger = class {
15309
+ constructor(name) {
15310
+ this.name = name;
15311
+ this.prefix = `[${this.name}]`;
15312
+ const LOGGER_NAME = getVariable("DEBUG");
15313
+ const LOGGER_LEVEL = getVariable("LOG_LEVEL");
15314
+ const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME);
15315
+ if (isLoggingEnabled) {
15316
+ this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug;
15317
+ this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info;
15318
+ this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success;
15319
+ this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning;
15320
+ this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error;
15321
+ } else {
15322
+ this.info = noop;
15323
+ this.success = noop;
15324
+ this.warning = noop;
15325
+ this.error = noop;
15326
+ this.only = noop;
15427
15327
  }
15428
- logger.info("no running instance found, setting up a new instance...");
15429
- this.setup();
15430
- this.setInstance();
15431
- this.readyState = InterceptorReadyState.APPLIED;
15432
15328
  }
15433
- /**
15434
- * Setup the module augments and stubs necessary for this interceptor.
15435
- * This method is not run if there's a running interceptor instance
15436
- * to prevent instantiating an interceptor multiple times.
15437
- */
15438
- setup() {
15329
+ prefix;
15330
+ extend(domain) {
15331
+ return new Logger(`${this.name}:${domain}`);
15439
15332
  }
15440
15333
  /**
15441
- * Listen to the interceptor's public events.
15442
- */
15443
- on(event, listener) {
15444
- const logger = this.logger.extend("on");
15445
- if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) {
15446
- logger.info("cannot listen to events, already disposed!");
15447
- return this;
15448
- }
15449
- logger.info('adding "%s" event listener:', event, listener);
15450
- this.emitter.on(event, listener);
15451
- return this;
15334
+ * Print a debug message.
15335
+ * @example
15336
+ * logger.debug('no duplicates found, creating a document...')
15337
+ */
15338
+ debug(message4, ...positionals) {
15339
+ this.logEntry({
15340
+ level: "debug",
15341
+ message: gray(message4),
15342
+ positionals,
15343
+ prefix: this.prefix,
15344
+ colors: {
15345
+ prefix: "gray"
15346
+ }
15347
+ });
15452
15348
  }
15453
- once(event, listener) {
15454
- this.emitter.once(event, listener);
15455
- return this;
15349
+ /**
15350
+ * Print an info message.
15351
+ * @example
15352
+ * logger.info('start parsing...')
15353
+ */
15354
+ info(message4, ...positionals) {
15355
+ this.logEntry({
15356
+ level: "info",
15357
+ message: message4,
15358
+ positionals,
15359
+ prefix: this.prefix,
15360
+ colors: {
15361
+ prefix: "blue"
15362
+ }
15363
+ });
15364
+ const performance2 = new PerformanceEntry();
15365
+ return (message22, ...positionals2) => {
15366
+ performance2.measure();
15367
+ this.logEntry({
15368
+ level: "info",
15369
+ message: `${message22} ${gray(`${performance2.deltaTime}ms`)}`,
15370
+ positionals: positionals2,
15371
+ prefix: this.prefix,
15372
+ colors: {
15373
+ prefix: "blue"
15374
+ }
15375
+ });
15376
+ };
15456
15377
  }
15457
- off(event, listener) {
15458
- this.emitter.off(event, listener);
15459
- return this;
15378
+ /**
15379
+ * Print a success message.
15380
+ * @example
15381
+ * logger.success('successfully created document')
15382
+ */
15383
+ success(message4, ...positionals) {
15384
+ this.logEntry({
15385
+ level: "info",
15386
+ message: message4,
15387
+ positionals,
15388
+ prefix: `\u2714 ${this.prefix}`,
15389
+ colors: {
15390
+ timestamp: "green",
15391
+ prefix: "green"
15392
+ }
15393
+ });
15460
15394
  }
15461
- removeAllListeners(event) {
15462
- this.emitter.removeAllListeners(event);
15463
- return this;
15395
+ /**
15396
+ * Print a warning.
15397
+ * @example
15398
+ * logger.warning('found legacy document format')
15399
+ */
15400
+ warning(message4, ...positionals) {
15401
+ this.logEntry({
15402
+ level: "warning",
15403
+ message: message4,
15404
+ positionals,
15405
+ prefix: `\u26A0 ${this.prefix}`,
15406
+ colors: {
15407
+ timestamp: "yellow",
15408
+ prefix: "yellow"
15409
+ }
15410
+ });
15464
15411
  }
15465
15412
  /**
15466
- * Disposes of any side-effects this interceptor has introduced.
15467
- */
15468
- dispose() {
15469
- const logger = this.logger.extend("dispose");
15470
- if (this.readyState === InterceptorReadyState.DISPOSED) {
15471
- logger.info("cannot dispose, already disposed!");
15472
- return;
15473
- }
15474
- logger.info("disposing the interceptor...");
15475
- this.readyState = InterceptorReadyState.DISPOSING;
15476
- if (!this.getInstance()) {
15477
- logger.info("no interceptors running, skipping dispose...");
15478
- return;
15479
- }
15480
- this.clearInstance();
15481
- logger.info("global symbol deleted:", getGlobalSymbol(this.symbol));
15482
- if (this.subscriptions.length > 0) {
15483
- logger.info("disposing of %d subscriptions...", this.subscriptions.length);
15484
- for (const dispose of this.subscriptions) dispose();
15485
- this.subscriptions = [];
15486
- logger.info("disposed of all subscriptions!", this.subscriptions.length);
15487
- }
15488
- this.emitter.removeAllListeners();
15489
- logger.info("destroyed the listener!");
15490
- this.readyState = InterceptorReadyState.DISPOSED;
15413
+ * Print an error message.
15414
+ * @example
15415
+ * logger.error('something went wrong')
15416
+ */
15417
+ error(message4, ...positionals) {
15418
+ this.logEntry({
15419
+ level: "error",
15420
+ message: message4,
15421
+ positionals,
15422
+ prefix: `\u2716 ${this.prefix}`,
15423
+ colors: {
15424
+ timestamp: "red",
15425
+ prefix: "red"
15426
+ }
15427
+ });
15491
15428
  }
15492
- getInstance() {
15493
- const instance = getGlobalSymbol(this.symbol);
15494
- this.logger.info("retrieved global instance:", instance?.constructor?.name);
15495
- return instance;
15429
+ /**
15430
+ * Execute the given callback only when the logging is enabled.
15431
+ * This is skipped in its entirety and has no runtime cost otherwise.
15432
+ * This executes regardless of the log level.
15433
+ * @example
15434
+ * logger.only(() => {
15435
+ * logger.info('additional info')
15436
+ * })
15437
+ */
15438
+ only(callback) {
15439
+ callback();
15496
15440
  }
15497
- setInstance() {
15498
- setGlobalSymbol(this.symbol, this);
15499
- this.logger.info("set global instance!", this.symbol.description);
15441
+ createEntry(level, message4) {
15442
+ return {
15443
+ timestamp: /* @__PURE__ */ new Date(),
15444
+ level,
15445
+ message: message4
15446
+ };
15500
15447
  }
15501
- clearInstance() {
15502
- deleteGlobalSymbol(this.symbol);
15503
- this.logger.info("cleared global instance!", this.symbol.description);
15448
+ logEntry(args) {
15449
+ const {
15450
+ level,
15451
+ message: message4,
15452
+ prefix,
15453
+ colors: customColors,
15454
+ positionals = []
15455
+ } = args;
15456
+ const entry = this.createEntry(level, message4);
15457
+ const timestampColor = customColors?.timestamp || "gray";
15458
+ const prefixColor = customColors?.prefix || "gray";
15459
+ const colorize = {
15460
+ timestamp: colors_exports[timestampColor],
15461
+ prefix: colors_exports[prefixColor]
15462
+ };
15463
+ const write = this.getWriter(level);
15464
+ write(
15465
+ [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message4)).join(" "),
15466
+ ...positionals.map(serializeInput)
15467
+ );
15504
15468
  }
15505
- };
15506
- function createRequestId() {
15507
- return Math.random().toString(16).slice(2);
15508
- }
15509
-
15510
- // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs
15511
- var encoder = new TextEncoder();
15512
- function encodeBuffer(text) {
15513
- return encoder.encode(text);
15514
- }
15515
- function decodeBuffer(buffer, encoding) {
15516
- return new TextDecoder(encoding).decode(buffer);
15517
- }
15518
- function toArrayBuffer(array) {
15519
- return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength);
15520
- }
15521
-
15522
- // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs
15523
- function resolveWebSocketUrl(url) {
15524
- if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0));
15525
- if (url.protocol === "http:") url.protocol = "ws:";
15526
- else if (url.protocol === "https:") url.protocol = "wss:";
15527
- if (url.protocol !== "ws:" && url.protocol !== "wss:")
15528
- throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`);
15529
- if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`);
15530
- return url.href;
15531
- }
15532
-
15533
- // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/index.mjs
15534
- var BatchInterceptor = class BatchInterceptor2 extends Interceptor {
15535
- constructor(options) {
15536
- BatchInterceptor2.symbol = Symbol(options.name);
15537
- super(BatchInterceptor2.symbol);
15538
- this.interceptors = options.interceptors;
15469
+ formatTimestamp(timestamp) {
15470
+ return `${timestamp.toLocaleTimeString(
15471
+ "en-GB"
15472
+ )}:${timestamp.getMilliseconds()}`;
15539
15473
  }
15540
- setup() {
15541
- const logger = this.logger.extend("setup");
15542
- logger.info("applying all %d interceptors...", this.interceptors.length);
15543
- for (const interceptor of this.interceptors) {
15544
- logger.info('applying "%s" interceptor...', interceptor.constructor.name);
15545
- interceptor.apply();
15546
- logger.info("adding interceptor dispose subscription");
15547
- this.subscriptions.push(() => interceptor.dispose());
15474
+ getWriter(level) {
15475
+ switch (level) {
15476
+ case "debug":
15477
+ case "success":
15478
+ case "info": {
15479
+ return log;
15480
+ }
15481
+ case "warning": {
15482
+ return warn2;
15483
+ }
15484
+ case "error": {
15485
+ return error2;
15486
+ }
15548
15487
  }
15549
15488
  }
15550
- on(event, listener) {
15551
- for (const interceptor of this.interceptors) interceptor.on(event, listener);
15552
- return this;
15489
+ };
15490
+ var PerformanceEntry = class {
15491
+ startTime;
15492
+ endTime;
15493
+ deltaTime;
15494
+ constructor() {
15495
+ this.startTime = performance.now();
15553
15496
  }
15554
- once(event, listener) {
15555
- for (const interceptor of this.interceptors) interceptor.once(event, listener);
15556
- return this;
15497
+ measure() {
15498
+ this.endTime = performance.now();
15499
+ const deltaTime = this.endTime - this.startTime;
15500
+ this.deltaTime = deltaTime.toFixed(2);
15557
15501
  }
15558
- off(event, listener) {
15559
- for (const interceptor of this.interceptors) interceptor.off(event, listener);
15560
- return this;
15502
+ };
15503
+ var noop = () => void 0;
15504
+ function log(message4, ...positionals) {
15505
+ if (IS_NODE) {
15506
+ process.stdout.write(format(message4, ...positionals) + "\n");
15507
+ return;
15561
15508
  }
15562
- removeAllListeners(event) {
15563
- for (const interceptors of this.interceptors) interceptors.removeAllListeners(event);
15564
- return this;
15509
+ console.log(message4, ...positionals);
15510
+ }
15511
+ function warn2(message4, ...positionals) {
15512
+ if (IS_NODE) {
15513
+ process.stderr.write(format(message4, ...positionals) + "\n");
15514
+ return;
15565
15515
  }
15566
- };
15567
- function getCleanUrl(url, isAbsolute = true) {
15568
- return [isAbsolute && url.origin, url.pathname].filter(Boolean).join("");
15516
+ console.warn(message4, ...positionals);
15569
15517
  }
15570
-
15571
- // src/shims/statuses.ts
15572
- var allStatuses = __toESM(require_statuses(), 1);
15573
- var statuses = allStatuses.default || allStatuses;
15574
- var message = statuses.message;
15575
- var statuses_default = statuses;
15576
-
15577
- // node_modules/.pnpm/set-cookie-parser@3.1.0/node_modules/set-cookie-parser/lib/set-cookie.js
15578
- var defaultParseOptions = {
15579
- decodeValues: true,
15580
- map: false,
15581
- silent: false,
15582
- split: "auto"
15583
- // auto = split strings but not arrays
15584
- };
15585
- function isForbiddenKey(key) {
15586
- return typeof key !== "string" || key in {};
15518
+ function error2(message4, ...positionals) {
15519
+ if (IS_NODE) {
15520
+ process.stderr.write(format(message4, ...positionals) + "\n");
15521
+ return;
15522
+ }
15523
+ console.error(message4, ...positionals);
15587
15524
  }
15588
- function createNullObj() {
15589
- return /* @__PURE__ */ Object.create(null);
15525
+ function getVariable(variableName) {
15526
+ if (IS_NODE) {
15527
+ return process.env[variableName];
15528
+ }
15529
+ return globalThis[variableName]?.toString();
15590
15530
  }
15591
- function isNonEmptyString(str) {
15592
- return typeof str === "string" && !!str.trim();
15531
+ function isDefinedAndNotEquals(value, expected) {
15532
+ return value !== void 0 && value !== expected;
15593
15533
  }
15594
- function parseString(setCookieValue, options) {
15595
- var parts = setCookieValue.split(";").filter(isNonEmptyString);
15596
- var nameValuePairStr = parts.shift();
15597
- var parsed = parseNameValuePair(nameValuePairStr);
15598
- var name = parsed.name;
15599
- var value = parsed.value;
15600
- options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
15601
- if (isForbiddenKey(name)) {
15602
- return null;
15534
+ function serializeInput(message4) {
15535
+ if (typeof message4 === "undefined") {
15536
+ return "undefined";
15603
15537
  }
15604
- try {
15605
- value = options.decodeValues ? decodeURIComponent(value) : value;
15606
- } catch (e) {
15607
- console.error(
15608
- "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",
15609
- e
15610
- );
15538
+ if (message4 === null) {
15539
+ return "null";
15611
15540
  }
15612
- var cookie2 = createNullObj();
15613
- cookie2.name = name;
15614
- cookie2.value = value;
15615
- parts.forEach(function(part) {
15616
- var sides = part.split("=");
15617
- var key = sides.shift().trimLeft().toLowerCase();
15618
- if (isForbiddenKey(key)) {
15619
- return;
15620
- }
15621
- var value2 = sides.join("=");
15622
- if (key === "expires") {
15623
- cookie2.expires = new Date(value2);
15624
- } else if (key === "max-age") {
15625
- var n = parseInt(value2, 10);
15626
- if (!Number.isNaN(n)) cookie2.maxAge = n;
15627
- } else if (key === "secure") {
15628
- cookie2.secure = true;
15629
- } else if (key === "httponly") {
15630
- cookie2.httpOnly = true;
15631
- } else if (key === "samesite") {
15632
- cookie2.sameSite = value2;
15633
- } else if (key === "partitioned") {
15634
- cookie2.partitioned = true;
15635
- } else if (key) {
15636
- cookie2[key] = value2;
15637
- }
15638
- });
15639
- return cookie2;
15640
- }
15641
- function parseNameValuePair(nameValuePairStr) {
15642
- var name = "";
15643
- var value = "";
15644
- var nameValueArr = nameValuePairStr.split("=");
15645
- if (nameValueArr.length > 1) {
15646
- name = nameValueArr.shift();
15647
- value = nameValueArr.join("=");
15648
- } else {
15649
- value = nameValuePairStr;
15541
+ if (typeof message4 === "string") {
15542
+ return message4;
15650
15543
  }
15651
- return { name, value };
15544
+ if (typeof message4 === "object") {
15545
+ return JSON.stringify(message4);
15546
+ }
15547
+ return message4.toString();
15652
15548
  }
15653
- function parseSetCookie(input, options) {
15654
- options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
15655
- if (!input) {
15656
- if (!options.map) {
15657
- return [];
15658
- } else {
15659
- return createNullObj();
15660
- }
15549
+
15550
+ // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
15551
+ var MemoryLeakError = class extends Error {
15552
+ constructor(emitter, type, count) {
15553
+ super(
15554
+ `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`
15555
+ );
15556
+ this.emitter = emitter;
15557
+ this.type = type;
15558
+ this.count = count;
15559
+ this.name = "MaxListenersExceededWarning";
15661
15560
  }
15662
- if (input.headers) {
15663
- if (typeof input.headers.getSetCookie === "function") {
15664
- input = input.headers.getSetCookie();
15665
- } else if (input.headers["set-cookie"]) {
15666
- input = input.headers["set-cookie"];
15667
- } else {
15668
- var sch = input.headers[Object.keys(input.headers).find(function(key) {
15669
- return key.toLowerCase() === "set-cookie";
15670
- })];
15671
- if (!sch && input.headers.cookie && !options.silent) {
15672
- console.warn(
15673
- "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
15674
- );
15675
- }
15676
- input = sch;
15677
- }
15561
+ };
15562
+ var _Emitter = class {
15563
+ static listenerCount(emitter, eventName) {
15564
+ return emitter.listenerCount(eventName);
15678
15565
  }
15679
- var split = options.split;
15680
- var isArray = Array.isArray(input);
15681
- if (split === "auto") {
15682
- split = !isArray;
15566
+ constructor() {
15567
+ this.events = /* @__PURE__ */ new Map();
15568
+ this.maxListeners = _Emitter.defaultMaxListeners;
15569
+ this.hasWarnedAboutPotentialMemoryLeak = false;
15683
15570
  }
15684
- if (!isArray) {
15685
- input = [input];
15571
+ _emitInternalEvent(internalEventName, eventName, listener) {
15572
+ this.emit(
15573
+ internalEventName,
15574
+ ...[eventName, listener]
15575
+ );
15686
15576
  }
15687
- input = input.filter(isNonEmptyString);
15688
- if (split) {
15689
- input = input.map(splitCookiesString).flat();
15577
+ _getListeners(eventName) {
15578
+ return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
15690
15579
  }
15691
- if (!options.map) {
15692
- return input.map(function(str) {
15693
- return parseString(str, options);
15694
- }).filter(Boolean);
15695
- } else {
15696
- var cookies = createNullObj();
15697
- return input.reduce(function(cookies2, str) {
15698
- var cookie2 = parseString(str, options);
15699
- if (cookie2 && !isForbiddenKey(cookie2.name)) {
15700
- cookies2[cookie2.name] = cookie2;
15701
- }
15702
- return cookies2;
15703
- }, cookies);
15580
+ _removeListener(listeners, listener) {
15581
+ const index = listeners.indexOf(listener);
15582
+ if (index > -1) {
15583
+ listeners.splice(index, 1);
15584
+ }
15585
+ return [];
15704
15586
  }
15705
- }
15706
- function splitCookiesString(cookiesString) {
15707
- if (Array.isArray(cookiesString)) {
15708
- return cookiesString;
15587
+ _wrapOnceListener(eventName, listener) {
15588
+ const onceListener = (...data) => {
15589
+ this.removeListener(eventName, onceListener);
15590
+ return listener.apply(this, data);
15591
+ };
15592
+ Object.defineProperty(onceListener, "name", { value: listener.name });
15593
+ return onceListener;
15709
15594
  }
15710
- if (typeof cookiesString !== "string") {
15711
- return [];
15595
+ setMaxListeners(maxListeners) {
15596
+ this.maxListeners = maxListeners;
15597
+ return this;
15712
15598
  }
15713
- var cookiesStrings = [];
15714
- var pos = 0;
15715
- var start;
15716
- var ch;
15717
- var lastComma;
15718
- var nextStart;
15719
- var cookiesSeparatorFound;
15720
- function skipWhitespace() {
15721
- while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
15722
- pos += 1;
15723
- }
15724
- return pos < cookiesString.length;
15599
+ /**
15600
+ * Returns the current max listener value for the `Emitter` which is
15601
+ * either set by `emitter.setMaxListeners(n)` or defaults to
15602
+ * `Emitter.defaultMaxListeners`.
15603
+ */
15604
+ getMaxListeners() {
15605
+ return this.maxListeners;
15725
15606
  }
15726
- function notSpecialChar() {
15727
- ch = cookiesString.charAt(pos);
15728
- return ch !== "=" && ch !== ";" && ch !== ",";
15607
+ /**
15608
+ * Returns an array listing the events for which the emitter has registered listeners.
15609
+ * The values in the array will be strings or Symbols.
15610
+ */
15611
+ eventNames() {
15612
+ return Array.from(this.events.keys());
15729
15613
  }
15730
- while (pos < cookiesString.length) {
15731
- start = pos;
15732
- cookiesSeparatorFound = false;
15733
- while (skipWhitespace()) {
15734
- ch = cookiesString.charAt(pos);
15735
- if (ch === ",") {
15736
- lastComma = pos;
15737
- pos += 1;
15738
- skipWhitespace();
15739
- nextStart = pos;
15740
- while (pos < cookiesString.length && notSpecialChar()) {
15741
- pos += 1;
15742
- }
15743
- if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
15744
- cookiesSeparatorFound = true;
15745
- pos = nextStart;
15746
- cookiesStrings.push(cookiesString.substring(start, lastComma));
15747
- start = pos;
15748
- } else {
15749
- pos = lastComma + 1;
15750
- }
15751
- } else {
15752
- pos += 1;
15753
- }
15754
- }
15755
- if (!cookiesSeparatorFound || pos >= cookiesString.length) {
15756
- cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
15614
+ /**
15615
+ * Synchronously calls each of the listeners registered for the event named `eventName`,
15616
+ * in the order they were registered, passing the supplied arguments to each.
15617
+ * Returns `true` if the event has listeners, `false` otherwise.
15618
+ *
15619
+ * @example
15620
+ * const emitter = new Emitter<{ hello: [string] }>()
15621
+ * emitter.emit('hello', 'John')
15622
+ */
15623
+ emit(eventName, ...data) {
15624
+ const listeners = this._getListeners(eventName);
15625
+ listeners.forEach((listener) => {
15626
+ listener.apply(this, data);
15627
+ });
15628
+ return listeners.length > 0;
15629
+ }
15630
+ addListener(eventName, listener) {
15631
+ this._emitInternalEvent("newListener", eventName, listener);
15632
+ const nextListeners = this._getListeners(eventName).concat(listener);
15633
+ this.events.set(eventName, nextListeners);
15634
+ if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) {
15635
+ this.hasWarnedAboutPotentialMemoryLeak = true;
15636
+ const memoryLeakWarning = new MemoryLeakError(
15637
+ this,
15638
+ eventName,
15639
+ this.listenerCount(eventName)
15640
+ );
15641
+ console.warn(memoryLeakWarning);
15757
15642
  }
15643
+ return this;
15758
15644
  }
15759
- return cookiesStrings;
15760
- }
15761
- parseSetCookie.parseSetCookie = parseSetCookie;
15762
- parseSetCookie.parse = parseSetCookie;
15763
- parseSetCookie.parseString = parseString;
15764
- parseSetCookie.splitCookiesString = splitCookiesString;
15765
-
15766
- // node_modules/.pnpm/headers-polyfill@5.0.1/node_modules/headers-polyfill/lib/index.mjs
15767
- var HEADERS_INVALID_CHARACTERS = /[^a-z0-9\-#$%&'*+.^_`|~]/i;
15768
- function normalizeHeaderName(name) {
15769
- if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === "") throw new TypeError("Invalid character in header field name");
15770
- return name.trim().toLowerCase();
15771
- }
15772
- var charCodesToRemove = [
15773
- String.fromCharCode(10),
15774
- String.fromCharCode(13),
15775
- String.fromCharCode(9),
15776
- String.fromCharCode(32)
15777
- ];
15778
- var HEADER_VALUE_REMOVE_REGEXP = new RegExp(`(^[${charCodesToRemove.join("")}]|$[${charCodesToRemove.join("")}])`, "g");
15779
- function normalizeHeaderValue(value) {
15780
- return value.replace(HEADER_VALUE_REMOVE_REGEXP, "");
15781
- }
15782
- function isValidHeaderName(value) {
15783
- if (typeof value !== "string") return false;
15784
- if (value.length === 0) return false;
15785
- for (let i = 0; i < value.length; i++) {
15786
- const character = value.charCodeAt(i);
15787
- if (character > 127 || !isToken(character)) return false;
15645
+ on(eventName, listener) {
15646
+ return this.addListener(eventName, listener);
15788
15647
  }
15789
- return true;
15790
- }
15791
- function isToken(value) {
15792
- return ![
15793
- 127,
15794
- 32,
15795
- "(",
15796
- ")",
15797
- "<",
15798
- ">",
15799
- "@",
15800
- ",",
15801
- ";",
15802
- ":",
15803
- "\\",
15804
- '"',
15805
- "/",
15806
- "[",
15807
- "]",
15808
- "?",
15809
- "=",
15810
- "{",
15811
- "}"
15812
- ].includes(value);
15813
- }
15814
- function isValidHeaderValue(value) {
15815
- if (typeof value !== "string") return false;
15816
- if (value.trim() !== value) return false;
15817
- for (let i = 0; i < value.length; i++) {
15818
- const character = value.charCodeAt(i);
15819
- if (character === 0 || character === 10 || character === 13) return false;
15648
+ once(eventName, listener) {
15649
+ return this.addListener(
15650
+ eventName,
15651
+ this._wrapOnceListener(eventName, listener)
15652
+ );
15820
15653
  }
15821
- return true;
15822
- }
15823
- var _Symbol$toStringTag;
15824
- var NORMALIZED_HEADERS = Symbol("normalizedHeaders");
15825
- var RAW_HEADER_NAMES = Symbol("rawHeaderNames");
15826
- var HEADER_VALUE_DELIMITER = ", ";
15827
- var Headers2 = class Headers3 {
15828
- constructor(init) {
15829
- this[NORMALIZED_HEADERS] = {};
15830
- this[RAW_HEADER_NAMES] = /* @__PURE__ */ new Map();
15831
- this[_Symbol$toStringTag] = "Headers";
15832
- if (["Headers", "HeadersPolyfill"].includes(init?.constructor?.name) || init instanceof Headers3 || typeof globalThis.Headers !== "undefined" && init instanceof globalThis.Headers) init.forEach((value, name) => {
15833
- this.append(name, value);
15834
- }, this);
15835
- else if (Array.isArray(init)) init.forEach(([name, value]) => {
15836
- this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value);
15837
- });
15838
- else if (init) Object.getOwnPropertyNames(init).forEach((name) => {
15839
- const value = init[name];
15840
- this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value);
15841
- });
15654
+ prependListener(eventName, listener) {
15655
+ const listeners = this._getListeners(eventName);
15656
+ if (listeners.length > 0) {
15657
+ const nextListeners = [listener].concat(listeners);
15658
+ this.events.set(eventName, nextListeners);
15659
+ } else {
15660
+ this.events.set(eventName, listeners.concat(listener));
15661
+ }
15662
+ return this;
15842
15663
  }
15843
- [(_Symbol$toStringTag = Symbol.toStringTag, Symbol.iterator)]() {
15844
- return this.entries();
15664
+ prependOnceListener(eventName, listener) {
15665
+ return this.prependListener(
15666
+ eventName,
15667
+ this._wrapOnceListener(eventName, listener)
15668
+ );
15845
15669
  }
15846
- *keys() {
15847
- for (const [name] of this.entries()) yield name;
15670
+ removeListener(eventName, listener) {
15671
+ const listeners = this._getListeners(eventName);
15672
+ if (listeners.length > 0) {
15673
+ this._removeListener(listeners, listener);
15674
+ this.events.set(eventName, listeners);
15675
+ this._emitInternalEvent("removeListener", eventName, listener);
15676
+ }
15677
+ return this;
15848
15678
  }
15849
- *values() {
15850
- for (const [, value] of this.entries()) yield value;
15679
+ /**
15680
+ * Alias for `emitter.removeListener()`.
15681
+ *
15682
+ * @example
15683
+ * emitter.off('hello', listener)
15684
+ */
15685
+ off(eventName, listener) {
15686
+ return this.removeListener(eventName, listener);
15851
15687
  }
15852
- *entries() {
15853
- let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) => a.localeCompare(b));
15854
- for (const name of sortedKeys) if (name === "set-cookie") for (const value of this.getSetCookie()) yield [name, value];
15855
- else yield [name, this.get(name)];
15688
+ removeAllListeners(eventName) {
15689
+ if (eventName) {
15690
+ this.events.delete(eventName);
15691
+ } else {
15692
+ this.events.clear();
15693
+ }
15694
+ return this;
15856
15695
  }
15857
15696
  /**
15858
- * Returns a boolean stating whether a `Headers` object contains a certain header.
15859
- */
15860
- has(name) {
15861
- if (!isValidHeaderName(name)) throw new TypeError(`Invalid header name "${name}"`);
15862
- return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name));
15697
+ * Returns a copy of the array of listeners for the event named `eventName`.
15698
+ */
15699
+ listeners(eventName) {
15700
+ return Array.from(this._getListeners(eventName));
15863
15701
  }
15864
15702
  /**
15865
- * Returns a `ByteString` sequence of all the values of a header with a given name.
15866
- */
15867
- get(name) {
15868
- if (!isValidHeaderName(name)) throw TypeError(`Invalid header name "${name}"`);
15869
- return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null;
15703
+ * Returns the number of listeners listening to the event named `eventName`.
15704
+ */
15705
+ listenerCount(eventName) {
15706
+ return this._getListeners(eventName).length;
15707
+ }
15708
+ rawListeners(eventName) {
15709
+ return this.listeners(eventName);
15710
+ }
15711
+ };
15712
+ var Emitter2 = _Emitter;
15713
+ Emitter2.defaultMaxListeners = 10;
15714
+
15715
+ // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DQcIlohW.mjs
15716
+ var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id";
15717
+ function getGlobalSymbol(symbol) {
15718
+ return globalThis[symbol] || void 0;
15719
+ }
15720
+ function setGlobalSymbol(symbol, value) {
15721
+ globalThis[symbol] = value;
15722
+ }
15723
+ function deleteGlobalSymbol(symbol) {
15724
+ delete globalThis[symbol];
15725
+ }
15726
+ var InterceptorReadyState = /* @__PURE__ */ (function(InterceptorReadyState$1) {
15727
+ InterceptorReadyState$1["INACTIVE"] = "INACTIVE";
15728
+ InterceptorReadyState$1["APPLYING"] = "APPLYING";
15729
+ InterceptorReadyState$1["APPLIED"] = "APPLIED";
15730
+ InterceptorReadyState$1["DISPOSING"] = "DISPOSING";
15731
+ InterceptorReadyState$1["DISPOSED"] = "DISPOSED";
15732
+ return InterceptorReadyState$1;
15733
+ })({});
15734
+ var Interceptor = class {
15735
+ constructor(symbol) {
15736
+ this.symbol = symbol;
15737
+ this.readyState = InterceptorReadyState.INACTIVE;
15738
+ this.emitter = new Emitter2();
15739
+ this.subscriptions = [];
15740
+ this.logger = new Logger(symbol.description);
15741
+ this.emitter.setMaxListeners(0);
15742
+ this.logger.info("constructing the interceptor...");
15870
15743
  }
15871
15744
  /**
15872
- * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.
15745
+ * Determine if this interceptor can be applied
15746
+ * in the current environment.
15873
15747
  */
15874
- set(name, value) {
15875
- if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return;
15876
- const normalizedName = normalizeHeaderName(name);
15877
- const normalizedValue = normalizeHeaderValue(value);
15878
- this[NORMALIZED_HEADERS][normalizedName] = normalizeHeaderValue(normalizedValue);
15879
- this[RAW_HEADER_NAMES].set(normalizedName, name);
15748
+ checkEnvironment() {
15749
+ return true;
15880
15750
  }
15881
15751
  /**
15882
- * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.
15752
+ * Apply this interceptor to the current process.
15753
+ * Returns an already running interceptor instance if it's present.
15883
15754
  */
15884
- append(name, value) {
15885
- if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return;
15886
- const normalizedName = normalizeHeaderName(name);
15887
- const normalizedValue = normalizeHeaderValue(value);
15888
- let resolvedValue = this.has(normalizedName) ? `${this.get(normalizedName)}, ${normalizedValue}` : normalizedValue;
15889
- this.set(name, resolvedValue);
15755
+ apply() {
15756
+ const logger = this.logger.extend("apply");
15757
+ logger.info("applying the interceptor...");
15758
+ if (this.readyState === InterceptorReadyState.APPLIED) {
15759
+ logger.info("intercepted already applied!");
15760
+ return;
15761
+ }
15762
+ if (!this.checkEnvironment()) {
15763
+ logger.info("the interceptor cannot be applied in this environment!");
15764
+ return;
15765
+ }
15766
+ this.readyState = InterceptorReadyState.APPLYING;
15767
+ const runningInstance = this.getInstance();
15768
+ if (runningInstance) {
15769
+ logger.info("found a running instance, reusing...");
15770
+ this.on = (event, listener) => {
15771
+ logger.info('proxying the "%s" listener', event);
15772
+ runningInstance.emitter.addListener(event, listener);
15773
+ this.subscriptions.push(() => {
15774
+ runningInstance.emitter.removeListener(event, listener);
15775
+ logger.info('removed proxied "%s" listener!', event);
15776
+ });
15777
+ return this;
15778
+ };
15779
+ this.readyState = InterceptorReadyState.APPLIED;
15780
+ return;
15781
+ }
15782
+ logger.info("no running instance found, setting up a new instance...");
15783
+ this.setup();
15784
+ this.setInstance();
15785
+ this.readyState = InterceptorReadyState.APPLIED;
15890
15786
  }
15891
15787
  /**
15892
- * Deletes a header from the `Headers` object.
15788
+ * Setup the module augments and stubs necessary for this interceptor.
15789
+ * This method is not run if there's a running interceptor instance
15790
+ * to prevent instantiating an interceptor multiple times.
15893
15791
  */
15894
- delete(name) {
15895
- if (!isValidHeaderName(name)) return;
15896
- if (!this.has(name)) return;
15897
- const normalizedName = normalizeHeaderName(name);
15898
- delete this[NORMALIZED_HEADERS][normalizedName];
15899
- this[RAW_HEADER_NAMES].delete(normalizedName);
15792
+ setup() {
15900
15793
  }
15901
15794
  /**
15902
- * Traverses the `Headers` object,
15903
- * calling the given callback for each header.
15795
+ * Listen to the interceptor's public events.
15904
15796
  */
15905
- forEach(callback, thisArg) {
15906
- for (const [name, value] of this.entries()) callback.call(thisArg, value, name, this);
15797
+ on(event, listener) {
15798
+ const logger = this.logger.extend("on");
15799
+ if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) {
15800
+ logger.info("cannot listen to events, already disposed!");
15801
+ return this;
15802
+ }
15803
+ logger.info('adding "%s" event listener:', event, listener);
15804
+ this.emitter.on(event, listener);
15805
+ return this;
15806
+ }
15807
+ once(event, listener) {
15808
+ this.emitter.once(event, listener);
15809
+ return this;
15810
+ }
15811
+ off(event, listener) {
15812
+ this.emitter.off(event, listener);
15813
+ return this;
15814
+ }
15815
+ removeAllListeners(event) {
15816
+ this.emitter.removeAllListeners(event);
15817
+ return this;
15907
15818
  }
15908
15819
  /**
15909
- * Returns an array containing the values
15910
- * of all Set-Cookie headers associated
15911
- * with a response
15820
+ * Disposes of any side-effects this interceptor has introduced.
15912
15821
  */
15913
- getSetCookie() {
15914
- const setCookieHeader = this.get("set-cookie");
15915
- if (setCookieHeader === null) return [];
15916
- if (setCookieHeader === "") return [""];
15917
- return splitCookiesString(setCookieHeader);
15822
+ dispose() {
15823
+ const logger = this.logger.extend("dispose");
15824
+ if (this.readyState === InterceptorReadyState.DISPOSED) {
15825
+ logger.info("cannot dispose, already disposed!");
15826
+ return;
15827
+ }
15828
+ logger.info("disposing the interceptor...");
15829
+ this.readyState = InterceptorReadyState.DISPOSING;
15830
+ if (!this.getInstance()) {
15831
+ logger.info("no interceptors running, skipping dispose...");
15832
+ return;
15833
+ }
15834
+ this.clearInstance();
15835
+ logger.info("global symbol deleted:", getGlobalSymbol(this.symbol));
15836
+ if (this.subscriptions.length > 0) {
15837
+ logger.info("disposing of %d subscriptions...", this.subscriptions.length);
15838
+ for (const dispose of this.subscriptions) dispose();
15839
+ this.subscriptions = [];
15840
+ logger.info("disposed of all subscriptions!", this.subscriptions.length);
15841
+ }
15842
+ this.emitter.removeAllListeners();
15843
+ logger.info("destroyed the listener!");
15844
+ this.readyState = InterceptorReadyState.DISPOSED;
15845
+ }
15846
+ getInstance() {
15847
+ const instance = getGlobalSymbol(this.symbol);
15848
+ this.logger.info("retrieved global instance:", instance?.constructor?.name);
15849
+ return instance;
15850
+ }
15851
+ setInstance() {
15852
+ setGlobalSymbol(this.symbol, this);
15853
+ this.logger.info("set global instance!", this.symbol.description);
15854
+ }
15855
+ clearInstance() {
15856
+ deleteGlobalSymbol(this.symbol);
15857
+ this.logger.info("cleared global instance!", this.symbol.description);
15918
15858
  }
15919
15859
  };
15920
- function stringToHeaders(str) {
15921
- return str.trim().split(/[\r\n]+/).reduce((headers, line) => {
15922
- if (line.trim() === "") return headers;
15923
- const parts = line.split(": ");
15924
- const name = parts.shift();
15925
- const value = parts.join(": ");
15926
- headers.append(name, value);
15927
- return headers;
15928
- }, new Headers2());
15860
+ function createRequestId() {
15861
+ return Math.random().toString(16).slice(2);
15862
+ }
15863
+
15864
+ // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs
15865
+ var encoder = new TextEncoder();
15866
+ function encodeBuffer(text) {
15867
+ return encoder.encode(text);
15868
+ }
15869
+ function decodeBuffer(buffer, encoding) {
15870
+ return new TextDecoder(encoding).decode(buffer);
15871
+ }
15872
+ function toArrayBuffer(array) {
15873
+ return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength);
15874
+ }
15875
+
15876
+ // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs
15877
+ function resolveWebSocketUrl(url) {
15878
+ if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0));
15879
+ if (url.protocol === "http:") url.protocol = "ws:";
15880
+ else if (url.protocol === "https:") url.protocol = "wss:";
15881
+ if (url.protocol !== "ws:" && url.protocol !== "wss:")
15882
+ throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`);
15883
+ if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`);
15884
+ return url.href;
15885
+ }
15886
+
15887
+ // node_modules/.pnpm/@mswjs+interceptors@0.41.3/node_modules/@mswjs/interceptors/lib/browser/index.mjs
15888
+ var BatchInterceptor = class BatchInterceptor2 extends Interceptor {
15889
+ constructor(options) {
15890
+ BatchInterceptor2.symbol = Symbol(options.name);
15891
+ super(BatchInterceptor2.symbol);
15892
+ this.interceptors = options.interceptors;
15893
+ }
15894
+ setup() {
15895
+ const logger = this.logger.extend("setup");
15896
+ logger.info("applying all %d interceptors...", this.interceptors.length);
15897
+ for (const interceptor of this.interceptors) {
15898
+ logger.info('applying "%s" interceptor...', interceptor.constructor.name);
15899
+ interceptor.apply();
15900
+ logger.info("adding interceptor dispose subscription");
15901
+ this.subscriptions.push(() => interceptor.dispose());
15902
+ }
15903
+ }
15904
+ on(event, listener) {
15905
+ for (const interceptor of this.interceptors) interceptor.on(event, listener);
15906
+ return this;
15907
+ }
15908
+ once(event, listener) {
15909
+ for (const interceptor of this.interceptors) interceptor.once(event, listener);
15910
+ return this;
15911
+ }
15912
+ off(event, listener) {
15913
+ for (const interceptor of this.interceptors) interceptor.off(event, listener);
15914
+ return this;
15915
+ }
15916
+ removeAllListeners(event) {
15917
+ for (const interceptors of this.interceptors) interceptors.removeAllListeners(event);
15918
+ return this;
15919
+ }
15920
+ };
15921
+ function getCleanUrl(url, isAbsolute = true) {
15922
+ return [isAbsolute && url.origin, url.pathname].filter(Boolean).join("");
15929
15923
  }
15930
15924
 
15925
+ // src/shims/statuses.ts
15926
+ var allStatuses = __toESM(require_statuses(), 1);
15927
+ var statuses = allStatuses.default || allStatuses;
15928
+ var message = statuses.message;
15929
+ var statuses_default = statuses;
15930
+
15931
15931
  // src/core/utils/HttpResponse/decorators.ts
15932
15932
  var { message: message2 } = statuses_default;
15933
15933
  var kSetCookie = Symbol("kSetCookie");
@@ -15957,17 +15957,12 @@ ${operationTypes.join("\n")}
15957
15957
  enumerable: false,
15958
15958
  writable: false
15959
15959
  });
15960
- if (typeof document !== "undefined") {
15961
- const responseCookiePairs = Headers2.prototype.getSetCookie.call(
15962
- init.headers
15963
- );
15964
- for (const cookieString of responseCookiePairs) {
15965
- document.cookie = cookieString;
15966
- }
15967
- }
15968
15960
  }
15969
15961
  return response;
15970
15962
  }
15963
+ function getRawSetCookie(response) {
15964
+ return Reflect.get(response, kSetCookie);
15965
+ }
15971
15966
 
15972
15967
  // src/core/HttpResponse.ts
15973
15968
  var bodyType = Symbol("bodyType");
@@ -16249,6 +16244,9 @@ ${operationTypes.join("\n")}
16249
16244
  throw errorOrResponse;
16250
16245
  });
16251
16246
  const mockedResponse = await mockedResponsePromise;
16247
+ if (mockedResponse) {
16248
+ forwardResponseCookies(mockedResponse);
16249
+ }
16252
16250
  const executionResult = this.createExecutionResult({
16253
16251
  // Pass the cloned request to the result so that logging
16254
16252
  // and other consumers could read its body once more.
@@ -16291,6 +16289,21 @@ ${operationTypes.join("\n")}
16291
16289
  };
16292
16290
  }
16293
16291
  };
16292
+ function forwardResponseCookies(response) {
16293
+ if (typeof document === "undefined") {
16294
+ return;
16295
+ }
16296
+ const responseCookies = getRawSetCookie(response);
16297
+ if (!responseCookies) {
16298
+ return;
16299
+ }
16300
+ const allResponseCookies = Headers2.prototype.getSetCookie.call(
16301
+ new Headers([["set-cookie", responseCookies]])
16302
+ );
16303
+ for (const cookieString of allResponseCookies) {
16304
+ document.cookie = cookieString;
16305
+ }
16306
+ }
16294
16307
 
16295
16308
  // node_modules/.pnpm/path-to-regexp@6.3.0/node_modules/path-to-regexp/dist.es2015/index.js
16296
16309
  function lexer(str) {
@@ -16963,19 +16976,19 @@ ${operationTypes.join("\n")}
16963
16976
  predicate(args) {
16964
16977
  return args.parsedResult.match.matches;
16965
16978
  }
16979
+ test(url, resolutionContext) {
16980
+ return this.#match(url, resolutionContext) != null;
16981
+ }
16966
16982
  async run(connection, resolutionContext) {
16967
- const parsedResult = this.parse({
16968
- url: connection.client.url,
16969
- resolutionContext
16970
- });
16971
- if (!this.predicate({ url: connection.client.url, parsedResult })) {
16983
+ const parsedResult = this.#match(connection.client.url, resolutionContext);
16984
+ if (parsedResult == null) {
16972
16985
  return null;
16973
16986
  }
16974
16987
  const resolvedConnection = {
16975
16988
  ...connection,
16976
16989
  params: parsedResult.match.params || {}
16977
16990
  };
16978
- if (resolutionContext?.[kAutoConnect]) {
16991
+ if (resolutionContext?.[kAutoConnect] ?? true) {
16979
16992
  if (this[kConnect](resolvedConnection)) {
16980
16993
  return resolvedConnection;
16981
16994
  }
@@ -16983,6 +16996,23 @@ ${operationTypes.join("\n")}
16983
16996
  }
16984
16997
  return resolvedConnection;
16985
16998
  }
16999
+ #match(url, resolutionContext) {
17000
+ const resolvedUrl = this.#resolveWebSocketUrl(
17001
+ url.toString(),
17002
+ resolutionContext?.baseUrl
17003
+ );
17004
+ const parsedResult = this.parse({
17005
+ url: resolvedUrl,
17006
+ resolutionContext
17007
+ });
17008
+ if (this.predicate({
17009
+ url,
17010
+ parsedResult
17011
+ })) {
17012
+ return parsedResult;
17013
+ }
17014
+ return null;
17015
+ }
16986
17016
  [kConnect](connection) {
16987
17017
  connection.client.addEventListener(
16988
17018
  "message",
@@ -17058,12 +17088,40 @@ ${operationTypes.join("\n")}
17058
17088
  };
17059
17089
  }
17060
17090
 
17091
+ // src/core/utils/internal/attachSiblingHandlers.ts
17092
+ var kSiblingHandlers = Symbol("kSiblingHandlers");
17093
+ function attachSiblingHandlers(owner, siblings) {
17094
+ invariant(
17095
+ getSiblingHandlers(owner).length === 0,
17096
+ 'Failed to merge handlers: the owner "%s" handler is already merged',
17097
+ owner.kind
17098
+ );
17099
+ Object.defineProperty(owner, kSiblingHandlers, {
17100
+ value: siblings,
17101
+ enumerable: false,
17102
+ writable: false,
17103
+ configurable: false
17104
+ });
17105
+ return owner;
17106
+ }
17107
+ function getSiblingHandlers(owner) {
17108
+ return Reflect.get(owner, kSiblingHandlers) || [];
17109
+ }
17110
+
17061
17111
  // src/core/experimental/handlers-controller.ts
17062
17112
  function groupHandlersByKind(handlers) {
17063
17113
  const groups = {};
17114
+ const pushUnique = (kind, handler) => {
17115
+ const bucket = groups[kind] ||= [];
17116
+ if (!bucket.includes(handler)) {
17117
+ bucket.push(handler);
17118
+ }
17119
+ };
17064
17120
  for (const handler of handlers) {
17065
- ;
17066
- (groups[handler.kind] ||= []).push(handler);
17121
+ pushUnique(handler.kind, handler);
17122
+ for (const sibling of getSiblingHandlers(handler)) {
17123
+ pushUnique(sibling.kind, sibling);
17124
+ }
17067
17125
  }
17068
17126
  return groups;
17069
17127
  }
@@ -17098,9 +17156,11 @@ ${operationTypes.join("\n")}
17098
17156
  return;
17099
17157
  }
17100
17158
  const { handlers } = this.getState();
17101
- for (let i = nextHandlers.length - 1; i >= 0; i--) {
17102
- const handler = nextHandlers[i];
17103
- handlers[handler.kind] = handlers[handler.kind] ? [handler, ...handlers[handler.kind]] : [handler];
17159
+ const overrides = groupHandlersByKind(nextHandlers);
17160
+ for (const kind in overrides) {
17161
+ const overridesForKind = overrides[kind];
17162
+ const existingForKind = handlers[kind];
17163
+ handlers[kind] = existingForKind ? [...overridesForKind, ...existingForKind] : overridesForKind;
17104
17164
  }
17105
17165
  this.setState({ handlers });
17106
17166
  }
@@ -20921,17 +20981,20 @@ Consider naming this operation or using "graphql.operation()" request handler to
20921
20981
  typeof url
20922
20982
  );
20923
20983
  const clientManager = new WebSocketClientManager(webSocketChannel);
20984
+ const upgradeHandler = http.get(({ request }) => {
20985
+ return request.headers.get("upgrade")?.toLowerCase() === "websocket" && matchRequestUrl(new URL(resolveWebSocketUrl(request.url)), url).matches;
20986
+ }, ws.onUpgrade);
20924
20987
  return {
20925
20988
  get clients() {
20926
20989
  return clientManager.clients;
20927
20990
  },
20928
20991
  addEventListener(event, listener) {
20929
- const handler = new WebSocketHandler(url);
20930
- handler[kEmitter].on("connection", async ({ client }) => {
20992
+ const webSocketHandler = new WebSocketHandler(url);
20993
+ webSocketHandler[kEmitter].on("connection", async ({ client }) => {
20931
20994
  await clientManager.addConnection(client);
20932
20995
  });
20933
- handler[kEmitter].on(event, listener);
20934
- return handler;
20996
+ webSocketHandler[kEmitter].on(event, listener);
20997
+ return attachSiblingHandlers(webSocketHandler, [upgradeHandler]);
20935
20998
  },
20936
20999
  broadcast(data) {
20937
21000
  this.broadcastExcept([], data);
@@ -20946,8 +21009,27 @@ Consider naming this operation or using "graphql.operation()" request handler to
20946
21009
  }
20947
21010
  };
20948
21011
  }
21012
+ var WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
20949
21013
  var ws = {
20950
- link: createWebSocketLinkHandler
21014
+ link: createWebSocketLinkHandler,
21015
+ async onUpgrade({ request }) {
21016
+ const key = request.headers.get("sec-websocket-key");
21017
+ if (!key) {
21018
+ return;
21019
+ }
21020
+ const keyBytes = new TextEncoder().encode(key + WEBSOCKET_GUID);
21021
+ const digest = await crypto.subtle.digest("SHA-1", keyBytes);
21022
+ const acceptValue = btoa(String.fromCharCode(...new Uint8Array(digest)));
21023
+ new WebSocket(resolveWebSocketUrl(request.url));
21024
+ return new FetchResponse(null, {
21025
+ status: 101,
21026
+ headers: {
21027
+ upgrade: "websocket",
21028
+ connection: "upgrade",
21029
+ "sec-websocket-accept": acceptValue
21030
+ }
21031
+ });
21032
+ }
20951
21033
  };
20952
21034
 
20953
21035
  // src/core/delay.ts
@@ -21712,7 +21794,7 @@ Read more: https://mswjs.io/docs/http/intercepting-requests`;
21712
21794
 
21713
21795
  // src/core/utils/request/storeResponseCookies.ts
21714
21796
  async function storeResponseCookies(request, response) {
21715
- const responseCookies = Reflect.get(response, kSetCookie);
21797
+ const responseCookies = getRawSetCookie(response);
21716
21798
  if (responseCookies) {
21717
21799
  await cookieStore.setCookie(responseCookies, request.url);
21718
21800
  }
@@ -22534,8 +22616,9 @@ Read more: https://mswjs.io/docs/http/intercepting-requests`;
22534
22616
  this.passthrough();
22535
22617
  return null;
22536
22618
  }
22619
+ const responseCloneForLogs = resolutionContext?.quiet ? null : response.clone();
22537
22620
  await storeResponseCookies(request, response);
22538
- this.respondWith(response.clone());
22621
+ this.respondWith(response);
22539
22622
  this.events.emit(
22540
22623
  new RequestEvent("request:end", {
22541
22624
  requestId,
@@ -22545,7 +22628,7 @@ Read more: https://mswjs.io/docs/http/intercepting-requests`;
22545
22628
  if (!resolutionContext?.quiet) {
22546
22629
  handler.log({
22547
22630
  request: requestCloneForLogs,
22548
- response,
22631
+ response: responseCloneForLogs,
22549
22632
  parsedResult
22550
22633
  });
22551
22634
  }