msw 2.0.13 → 2.1.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 (142) hide show
  1. package/cli/index.js +11 -3
  2. package/cli/init.js +126 -73
  3. package/config/scripts/postinstall.js +8 -20
  4. package/lib/browser/index.js +111 -176
  5. package/lib/browser/index.js.map +1 -1
  6. package/lib/browser/index.mjs +111 -179
  7. package/lib/browser/index.mjs.map +1 -1
  8. package/lib/core/{GraphQLHandler-SHlRCcy4.d.ts → GraphQLHandler-LZ8jH42-.d.ts} +4 -2
  9. package/lib/core/{GraphQLHandler-zlmUDnN6.d.mts → GraphQLHandler-c0pfLv8e.d.mts} +4 -2
  10. package/lib/core/HttpResponse.d.mts +1 -1
  11. package/lib/core/HttpResponse.d.ts +1 -1
  12. package/lib/core/{RequestHandler-rBDJQrEf.d.ts → RequestHandler-SdFwV297.d.ts} +11 -4
  13. package/lib/core/{RequestHandler-vxZdj6Tw.d.mts → RequestHandler-hEwneHZE.d.mts} +11 -4
  14. package/lib/core/SetupApi.d.mts +1 -1
  15. package/lib/core/SetupApi.d.ts +1 -1
  16. package/lib/core/SetupApi.js +5 -0
  17. package/lib/core/SetupApi.js.map +1 -1
  18. package/lib/core/SetupApi.mjs +5 -0
  19. package/lib/core/SetupApi.mjs.map +1 -1
  20. package/lib/core/delay.js +24 -46
  21. package/lib/core/delay.js.map +1 -1
  22. package/lib/core/delay.mjs +24 -46
  23. package/lib/core/delay.mjs.map +1 -1
  24. package/lib/core/graphql.d.mts +11 -9
  25. package/lib/core/graphql.d.ts +11 -9
  26. package/lib/core/graphql.js +3 -19
  27. package/lib/core/graphql.js.map +1 -1
  28. package/lib/core/graphql.mjs +3 -21
  29. package/lib/core/graphql.mjs.map +1 -1
  30. package/lib/core/handlers/GraphQLHandler.d.mts +2 -2
  31. package/lib/core/handlers/GraphQLHandler.d.ts +2 -2
  32. package/lib/core/handlers/GraphQLHandler.js +52 -77
  33. package/lib/core/handlers/GraphQLHandler.js.map +1 -1
  34. package/lib/core/handlers/GraphQLHandler.mjs +52 -77
  35. package/lib/core/handlers/GraphQLHandler.mjs.map +1 -1
  36. package/lib/core/handlers/HttpHandler.d.mts +1 -1
  37. package/lib/core/handlers/HttpHandler.d.ts +1 -1
  38. package/lib/core/handlers/HttpHandler.js +29 -55
  39. package/lib/core/handlers/HttpHandler.js.map +1 -1
  40. package/lib/core/handlers/HttpHandler.mjs +29 -55
  41. package/lib/core/handlers/HttpHandler.mjs.map +1 -1
  42. package/lib/core/handlers/RequestHandler.d.mts +1 -1
  43. package/lib/core/handlers/RequestHandler.d.ts +1 -1
  44. package/lib/core/handlers/RequestHandler.js +79 -103
  45. package/lib/core/handlers/RequestHandler.js.map +1 -1
  46. package/lib/core/handlers/RequestHandler.mjs +79 -105
  47. package/lib/core/handlers/RequestHandler.mjs.map +1 -1
  48. package/lib/core/http.d.mts +13 -11
  49. package/lib/core/http.d.ts +13 -11
  50. package/lib/core/http.js.map +1 -1
  51. package/lib/core/http.mjs.map +1 -1
  52. package/lib/core/index.d.mts +4 -4
  53. package/lib/core/index.d.ts +4 -4
  54. package/lib/core/index.js.map +1 -1
  55. package/lib/core/index.mjs.map +1 -1
  56. package/lib/core/sharedOptions.d.mts +1 -1
  57. package/lib/core/sharedOptions.d.ts +1 -1
  58. package/lib/core/utils/HttpResponse/decorators.d.mts +1 -1
  59. package/lib/core/utils/HttpResponse/decorators.d.ts +1 -1
  60. package/lib/core/utils/HttpResponse/decorators.js +7 -24
  61. package/lib/core/utils/HttpResponse/decorators.js.map +1 -1
  62. package/lib/core/utils/HttpResponse/decorators.mjs +7 -26
  63. package/lib/core/utils/HttpResponse/decorators.mjs.map +1 -1
  64. package/lib/core/utils/getResponse.d.mts +1 -1
  65. package/lib/core/utils/getResponse.d.ts +1 -1
  66. package/lib/core/utils/getResponse.js +11 -26
  67. package/lib/core/utils/getResponse.js.map +1 -1
  68. package/lib/core/utils/getResponse.mjs +11 -26
  69. package/lib/core/utils/getResponse.mjs.map +1 -1
  70. package/lib/core/utils/handleRequest.d.mts +1 -1
  71. package/lib/core/utils/handleRequest.d.ts +1 -1
  72. package/lib/core/utils/handleRequest.js +49 -72
  73. package/lib/core/utils/handleRequest.js.map +1 -1
  74. package/lib/core/utils/handleRequest.mjs +49 -72
  75. package/lib/core/utils/handleRequest.mjs.map +1 -1
  76. package/lib/core/utils/internal/Disposable.js +3 -27
  77. package/lib/core/utils/internal/Disposable.js.map +1 -1
  78. package/lib/core/utils/internal/Disposable.mjs +3 -27
  79. package/lib/core/utils/internal/Disposable.mjs.map +1 -1
  80. package/lib/core/utils/internal/parseGraphQLRequest.d.mts +2 -2
  81. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +2 -2
  82. package/lib/core/utils/internal/parseGraphQLRequest.js +72 -112
  83. package/lib/core/utils/internal/parseGraphQLRequest.js.map +1 -1
  84. package/lib/core/utils/internal/parseGraphQLRequest.mjs +72 -113
  85. package/lib/core/utils/internal/parseGraphQLRequest.mjs.map +1 -1
  86. package/lib/core/utils/internal/parseMultipartData.d.mts +1 -1
  87. package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
  88. package/lib/core/utils/internal/parseMultipartData.js +3 -4
  89. package/lib/core/utils/internal/parseMultipartData.js.map +1 -1
  90. package/lib/core/utils/internal/parseMultipartData.mjs +3 -4
  91. package/lib/core/utils/internal/parseMultipartData.mjs.map +1 -1
  92. package/lib/core/utils/internal/requestHandlerUtils.d.mts +1 -1
  93. package/lib/core/utils/internal/requestHandlerUtils.d.ts +1 -1
  94. package/lib/core/utils/internal/tryCatch.js +1 -1
  95. package/lib/core/utils/internal/tryCatch.js.map +1 -1
  96. package/lib/core/utils/internal/tryCatch.mjs +1 -1
  97. package/lib/core/utils/internal/tryCatch.mjs.map +1 -1
  98. package/lib/core/utils/logging/serializeRequest.js +9 -31
  99. package/lib/core/utils/logging/serializeRequest.js.map +1 -1
  100. package/lib/core/utils/logging/serializeRequest.mjs +9 -31
  101. package/lib/core/utils/logging/serializeRequest.mjs.map +1 -1
  102. package/lib/core/utils/logging/serializeResponse.js +11 -33
  103. package/lib/core/utils/logging/serializeResponse.js.map +1 -1
  104. package/lib/core/utils/logging/serializeResponse.mjs +11 -33
  105. package/lib/core/utils/logging/serializeResponse.mjs.map +1 -1
  106. package/lib/core/utils/request/getRequestCookies.js +9 -18
  107. package/lib/core/utils/request/getRequestCookies.js.map +1 -1
  108. package/lib/core/utils/request/getRequestCookies.mjs +9 -20
  109. package/lib/core/utils/request/getRequestCookies.mjs.map +1 -1
  110. package/lib/core/utils/request/onUnhandledRequest.d.mts +1 -1
  111. package/lib/core/utils/request/onUnhandledRequest.d.ts +1 -1
  112. package/lib/core/utils/request/onUnhandledRequest.js +62 -84
  113. package/lib/core/utils/request/onUnhandledRequest.js.map +1 -1
  114. package/lib/core/utils/request/onUnhandledRequest.mjs +62 -84
  115. package/lib/core/utils/request/onUnhandledRequest.mjs.map +1 -1
  116. package/lib/core/utils/request/readResponseCookies.js +1 -18
  117. package/lib/core/utils/request/readResponseCookies.js.map +1 -1
  118. package/lib/core/utils/request/readResponseCookies.mjs +1 -20
  119. package/lib/core/utils/request/readResponseCookies.mjs.map +1 -1
  120. package/lib/iife/index.js +679 -958
  121. package/lib/iife/index.js.map +1 -1
  122. package/lib/mockServiceWorker.js +2 -2
  123. package/lib/native/index.js +5 -23
  124. package/lib/native/index.js.map +1 -1
  125. package/lib/native/index.mjs +5 -24
  126. package/lib/native/index.mjs.map +1 -1
  127. package/lib/node/index.js +5 -23
  128. package/lib/node/index.js.map +1 -1
  129. package/lib/node/index.mjs +5 -24
  130. package/lib/node/index.mjs.map +1 -1
  131. package/package.json +32 -37
  132. package/src/browser/setupWorker/setupWorker.ts +6 -0
  133. package/src/browser/setupWorker/start/createStartHandler.ts +0 -8
  134. package/src/core/graphql.ts +24 -16
  135. package/src/core/handlers/GraphQLHandler.test.ts +15 -0
  136. package/src/core/handlers/GraphQLHandler.ts +8 -5
  137. package/src/core/handlers/RequestHandler.ts +37 -13
  138. package/src/core/http.ts +27 -14
  139. package/src/core/index.ts +3 -0
  140. package/src/core/utils/getResponse.ts +12 -6
  141. package/src/core/utils/handleRequest.test.ts +20 -0
  142. package/src/core/utils/handleRequest.ts +4 -3
package/lib/iife/index.js CHANGED
@@ -1,38 +1,9 @@
1
1
  "use strict";
2
2
  var MockServiceWorker = (() => {
3
3
  var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __spreadValues = (a, b) => {
13
- for (var prop in b || (b = {}))
14
- if (__hasOwnProp.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- if (__getOwnPropSymbols)
17
- for (var prop of __getOwnPropSymbols(b)) {
18
- if (__propIsEnum.call(b, prop))
19
- __defNormalProp(a, prop, b[prop]);
20
- }
21
- return a;
22
- };
23
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
- var __objRest = (source, exclude) => {
25
- var target = {};
26
- for (var prop in source)
27
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
28
- target[prop] = source[prop];
29
- if (source != null && __getOwnPropSymbols)
30
- for (var prop of __getOwnPropSymbols(source)) {
31
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
32
- target[prop] = source[prop];
33
- }
34
- return target;
35
- };
36
7
  var __export = (target, all) => {
37
8
  for (var name in all)
38
9
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -46,52 +17,6 @@ var MockServiceWorker = (() => {
46
17
  return to;
47
18
  };
48
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
49
- var __publicField = (obj, key, value) => {
50
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
51
- return value;
52
- };
53
- var __accessCheck = (obj, member, msg) => {
54
- if (!member.has(obj))
55
- throw TypeError("Cannot " + msg);
56
- };
57
- var __privateGet = (obj, member, getter) => {
58
- __accessCheck(obj, member, "read from private field");
59
- return getter ? getter.call(obj) : member.get(obj);
60
- };
61
- var __privateAdd = (obj, member, value) => {
62
- if (member.has(obj))
63
- throw TypeError("Cannot add the same private member more than once");
64
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
65
- };
66
- var __privateSet = (obj, member, value, setter) => {
67
- __accessCheck(obj, member, "write to private field");
68
- setter ? setter.call(obj, value) : member.set(obj, value);
69
- return value;
70
- };
71
- var __privateMethod = (obj, member, method) => {
72
- __accessCheck(obj, member, "access private method");
73
- return method;
74
- };
75
- var __async = (__this, __arguments, generator) => {
76
- return new Promise((resolve, reject) => {
77
- var fulfilled = (value) => {
78
- try {
79
- step(generator.next(value));
80
- } catch (e) {
81
- reject(e);
82
- }
83
- };
84
- var rejected = (value) => {
85
- try {
86
- step(generator.throw(value));
87
- } catch (e) {
88
- reject(e);
89
- }
90
- };
91
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
92
- step((generator = generator.apply(__this, __arguments)).next());
93
- });
94
- };
95
20
 
96
21
  // src/iife/index.ts
97
22
  var iife_exports = {};
@@ -118,8 +43,8 @@ var MockServiceWorker = (() => {
118
43
  setupWorker: () => setupWorker
119
44
  });
120
45
 
121
- // node_modules/.pnpm/outvariant@1.4.0/node_modules/outvariant/lib/index.mjs
122
- var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
46
+ // node_modules/.pnpm/outvariant@1.4.2/node_modules/outvariant/lib/index.mjs
47
+ var POSITIONALS_EXP = /(%?)(%([sdijo]))/g;
123
48
  function serializePositional(positional, flag) {
124
49
  switch (flag) {
125
50
  case "s":
@@ -189,8 +114,13 @@ var MockServiceWorker = (() => {
189
114
  };
190
115
  invariant.as = (ErrorConstructor, predicate, message3, ...positionals) => {
191
116
  if (!predicate) {
192
- const isConstructor = ErrorConstructor.prototype.name != null;
193
- const error3 = isConstructor ? new ErrorConstructor(format(message3, positionals)) : ErrorConstructor(format(message3, positionals));
117
+ const formatMessage2 = positionals.length === 0 ? message3 : format(message3, positionals);
118
+ let error3;
119
+ try {
120
+ error3 = Reflect.construct(ErrorConstructor, [formatMessage2]);
121
+ } catch (err) {
122
+ error3 = ErrorConstructor(formatMessage2);
123
+ }
194
124
  throw error3;
195
125
  }
196
126
  };
@@ -223,7 +153,7 @@ var MockServiceWorker = (() => {
223
153
  );
224
154
  }
225
155
 
226
- // node_modules/.pnpm/strict-event-emitter@0.5.0/node_modules/strict-event-emitter/lib/index.mjs
156
+ // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
227
157
  var MemoryLeakError = class extends Error {
228
158
  constructor(emitter, type, count) {
229
159
  super(
@@ -251,7 +181,7 @@ var MockServiceWorker = (() => {
251
181
  );
252
182
  }
253
183
  _getListeners(eventName) {
254
- return this.events.get(eventName) || [];
184
+ return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
255
185
  }
256
186
  _removeListener(listeners, listener) {
257
187
  const index = listeners.indexOf(listener);
@@ -263,8 +193,9 @@ var MockServiceWorker = (() => {
263
193
  _wrapOnceListener(eventName, listener) {
264
194
  const onceListener = (...data) => {
265
195
  this.removeListener(eventName, onceListener);
266
- listener.apply(this, data);
196
+ return listener.apply(this, data);
267
197
  };
198
+ Object.defineProperty(onceListener, "name", { value: listener.name });
268
199
  return onceListener;
269
200
  }
270
201
  setMaxListeners(maxListeners) {
@@ -410,18 +341,19 @@ var MockServiceWorker = (() => {
410
341
 
411
342
  // src/core/utils/internal/Disposable.ts
412
343
  var Disposable = class {
413
- constructor() {
414
- this.subscriptions = [];
415
- }
416
- dispose() {
417
- return __async(this, null, function* () {
418
- yield Promise.all(this.subscriptions.map((subscription) => subscription()));
419
- });
344
+ subscriptions = [];
345
+ async dispose() {
346
+ await Promise.all(this.subscriptions.map((subscription) => subscription()));
420
347
  }
421
348
  };
422
349
 
423
350
  // src/core/SetupApi.ts
424
351
  var SetupApi = class extends Disposable {
352
+ initialHandlers;
353
+ currentHandlers;
354
+ emitter;
355
+ publicEmitter;
356
+ events;
425
357
  constructor(...initialHandlers) {
426
358
  super();
427
359
  invariant(
@@ -507,24 +439,34 @@ var MockServiceWorker = (() => {
507
439
  }
508
440
 
509
441
  // src/core/handlers/RequestHandler.ts
510
- var _RequestHandler = class _RequestHandler {
442
+ var RequestHandler = class _RequestHandler {
443
+ static cache = /* @__PURE__ */ new WeakMap();
444
+ info;
445
+ /**
446
+ * Indicates whether this request handler has been used
447
+ * (its resolver has successfully executed).
448
+ */
449
+ isUsed;
450
+ resolver;
451
+ resolverGenerator;
452
+ resolverGeneratorResult;
453
+ options;
511
454
  constructor(args) {
512
455
  this.resolver = args.resolver;
513
456
  this.options = args.options;
514
457
  const callFrame = getCallFrame(new Error());
515
- this.info = __spreadProps(__spreadValues({}, args.info), {
458
+ this.info = {
459
+ ...args.info,
516
460
  callFrame
517
- });
461
+ };
518
462
  this.isUsed = false;
519
463
  }
520
464
  /**
521
465
  * Parse the intercepted request to extract additional information from it.
522
466
  * Parsed result is then exposed to other methods of this request handler.
523
467
  */
524
- parse(_args) {
525
- return __async(this, null, function* () {
526
- return {};
527
- });
468
+ async parse(_args) {
469
+ return {};
528
470
  }
529
471
  /**
530
472
  * Test if this handler matches the given request.
@@ -533,17 +475,15 @@ var MockServiceWorker = (() => {
533
475
  * as a convenience method for consumers writing custom
534
476
  * handlers.
535
477
  */
536
- test(args) {
537
- return __async(this, null, function* () {
538
- const parsedResult = yield this.parse({
539
- request: args.request,
540
- resolutionContext: args.resolutionContext
541
- });
542
- return this.predicate({
543
- request: args.request,
544
- parsedResult,
545
- resolutionContext: args.resolutionContext
546
- });
478
+ async test(args) {
479
+ const parsedResult = await this.parse({
480
+ request: args.request,
481
+ resolutionContext: args.resolutionContext
482
+ });
483
+ return this.predicate({
484
+ request: args.request,
485
+ parsedResult,
486
+ resolutionContext: args.resolutionContext
547
487
  });
548
488
  }
549
489
  extendResolverArgs(_args) {
@@ -565,54 +505,60 @@ var MockServiceWorker = (() => {
565
505
  * Execute this request handler and produce a mocked response
566
506
  * using the given resolver function.
567
507
  */
568
- run(args) {
569
- return __async(this, null, function* () {
570
- var _a3, _b2;
571
- if (this.isUsed && ((_a3 = this.options) == null ? void 0 : _a3.once)) {
572
- return null;
573
- }
574
- const requestClone = this.cloneRequestOrGetFromCache(args.request);
575
- const parsedResult = yield this.parse({
576
- request: args.request,
577
- resolutionContext: args.resolutionContext
578
- });
579
- const shouldInterceptRequest = this.predicate({
580
- request: args.request,
581
- parsedResult,
582
- resolutionContext: args.resolutionContext
583
- });
584
- if (!shouldInterceptRequest) {
585
- return null;
586
- }
587
- if (this.isUsed && ((_b2 = this.options) == null ? void 0 : _b2.once)) {
588
- return null;
508
+ async run(args) {
509
+ if (this.isUsed && this.options?.once) {
510
+ return null;
511
+ }
512
+ const requestClone = this.cloneRequestOrGetFromCache(args.request);
513
+ const parsedResult = await this.parse({
514
+ request: args.request,
515
+ resolutionContext: args.resolutionContext
516
+ });
517
+ const shouldInterceptRequest = this.predicate({
518
+ request: args.request,
519
+ parsedResult,
520
+ resolutionContext: args.resolutionContext
521
+ });
522
+ if (!shouldInterceptRequest) {
523
+ return null;
524
+ }
525
+ if (this.isUsed && this.options?.once) {
526
+ return null;
527
+ }
528
+ this.isUsed = true;
529
+ const executeResolver = this.wrapResolver(this.resolver);
530
+ const resolverExtras = this.extendResolverArgs({
531
+ request: args.request,
532
+ parsedResult
533
+ });
534
+ const mockedResponsePromise = executeResolver({
535
+ ...resolverExtras,
536
+ requestId: args.requestId,
537
+ request: args.request
538
+ }).catch((errorOrResponse) => {
539
+ if (errorOrResponse instanceof Response) {
540
+ return errorOrResponse;
589
541
  }
590
- this.isUsed = true;
591
- const executeResolver = this.wrapResolver(this.resolver);
592
- const resolverExtras = this.extendResolverArgs({
593
- request: args.request,
594
- parsedResult
595
- });
596
- const mockedResponse = yield executeResolver(__spreadProps(__spreadValues({}, resolverExtras), {
597
- request: args.request
598
- }));
599
- const executionResult = this.createExecutionResult({
600
- // Pass the cloned request to the result so that logging
601
- // and other consumers could read its body once more.
602
- request: requestClone,
603
- response: mockedResponse,
604
- parsedResult
605
- });
606
- return executionResult;
542
+ throw errorOrResponse;
607
543
  });
544
+ const mockedResponse = await mockedResponsePromise;
545
+ const executionResult = this.createExecutionResult({
546
+ // Pass the cloned request to the result so that logging
547
+ // and other consumers could read its body once more.
548
+ request: requestClone,
549
+ requestId: args.requestId,
550
+ response: mockedResponse,
551
+ parsedResult
552
+ });
553
+ return executionResult;
608
554
  }
609
555
  wrapResolver(resolver) {
610
- return (info) => __async(this, null, function* () {
611
- const result = this.resolverGenerator || (yield resolver(info));
556
+ return async (info) => {
557
+ const result = this.resolverGenerator || await resolver(info);
612
558
  if (isIterable(result)) {
613
559
  this.isUsed = false;
614
560
  const { value, done } = result[Symbol.iterator]().next();
615
- const nextResponse = yield value;
561
+ const nextResponse = await value;
616
562
  if (done) {
617
563
  this.isUsed = true;
618
564
  }
@@ -627,24 +573,23 @@ var MockServiceWorker = (() => {
627
573
  this.resolverGenerator = result;
628
574
  }
629
575
  if (nextResponse) {
630
- this.resolverGeneratorResult = nextResponse == null ? void 0 : nextResponse.clone();
576
+ this.resolverGeneratorResult = nextResponse?.clone();
631
577
  }
632
578
  return nextResponse;
633
579
  }
634
580
  return result;
635
- });
581
+ };
636
582
  }
637
583
  createExecutionResult(args) {
638
584
  return {
639
585
  handler: this,
640
586
  request: args.request,
587
+ requestId: args.requestId,
641
588
  response: args.response,
642
589
  parsedResult: args.parsedResult
643
590
  };
644
591
  }
645
592
  };
646
- _RequestHandler.cache = /* @__PURE__ */ new WeakMap();
647
- var RequestHandler = _RequestHandler;
648
593
 
649
594
  // src/core/utils/internal/isStringEqual.ts
650
595
  function isStringEqual(actual, expected) {
@@ -669,17 +614,15 @@ var MockServiceWorker = (() => {
669
614
  }
670
615
 
671
616
  // src/core/utils/logging/serializeRequest.ts
672
- function serializeRequest(request) {
673
- return __async(this, null, function* () {
674
- const requestClone = request.clone();
675
- const requestText = yield requestClone.text();
676
- return {
677
- url: new URL(request.url),
678
- method: request.method,
679
- headers: Object.fromEntries(request.headers.entries()),
680
- body: requestText
681
- };
682
- });
617
+ async function serializeRequest(request) {
618
+ const requestClone = request.clone();
619
+ const requestText = await requestClone.text();
620
+ return {
621
+ url: new URL(request.url),
622
+ method: request.method,
623
+ headers: Object.fromEntries(request.headers.entries()),
624
+ body: requestText
625
+ };
683
626
  }
684
627
 
685
628
  // node_modules/.pnpm/@bundled-es-modules+statuses@1.0.1/node_modules/@bundled-es-modules/statuses/index-esm.js
@@ -851,19 +794,17 @@ var MockServiceWorker = (() => {
851
794
 
852
795
  // src/core/utils/logging/serializeResponse.ts
853
796
  var { message } = source_default;
854
- function serializeResponse(response) {
855
- return __async(this, null, function* () {
856
- const responseClone = response.clone();
857
- const responseText = yield responseClone.text();
858
- const responseStatus = responseClone.status || 200;
859
- const responseStatusText = responseClone.statusText || message[responseStatus] || "OK";
860
- return {
861
- status: responseStatus,
862
- statusText: responseStatusText,
863
- headers: Object.fromEntries(responseClone.headers.entries()),
864
- body: responseText
865
- };
866
- });
797
+ async function serializeResponse(response) {
798
+ const responseClone = response.clone();
799
+ const responseText = await responseClone.text();
800
+ const responseStatus = responseClone.status || 200;
801
+ const responseStatusText = responseClone.statusText || message[responseStatus] || "OK";
802
+ return {
803
+ status: responseStatus,
804
+ statusText: responseStatusText,
805
+ headers: Object.fromEntries(responseClone.headers.entries()),
806
+ body: responseText
807
+ };
867
808
  }
868
809
 
869
810
  // node_modules/.pnpm/path-to-regexp@6.2.1/node_modules/path-to-regexp/dist.es2015/index.js
@@ -955,7 +896,7 @@ var MockServiceWorker = (() => {
955
896
  options = {};
956
897
  }
957
898
  var tokens = lexer(str);
958
- var _a3 = options.prefixes, prefixes = _a3 === void 0 ? "./" : _a3;
899
+ var _a2 = options.prefixes, prefixes = _a2 === void 0 ? "./" : _a2;
959
900
  var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
960
901
  var result = [];
961
902
  var key = 0;
@@ -969,7 +910,7 @@ var MockServiceWorker = (() => {
969
910
  var value2 = tryConsume(type);
970
911
  if (value2 !== void 0)
971
912
  return value2;
972
- var _a4 = tokens[i], nextType = _a4.type, index = _a4.index;
913
+ var _a3 = tokens[i], nextType = _a3.type, index = _a3.index;
973
914
  throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
974
915
  };
975
916
  var consumeText = function() {
@@ -1041,9 +982,9 @@ var MockServiceWorker = (() => {
1041
982
  if (options === void 0) {
1042
983
  options = {};
1043
984
  }
1044
- var _a3 = options.decode, decode = _a3 === void 0 ? function(x) {
985
+ var _a2 = options.decode, decode = _a2 === void 0 ? function(x) {
1045
986
  return x;
1046
- } : _a3;
987
+ } : _a2;
1047
988
  return function(pathname) {
1048
989
  var m = re.exec(pathname);
1049
990
  if (!m)
@@ -1106,7 +1047,7 @@ var MockServiceWorker = (() => {
1106
1047
  if (options === void 0) {
1107
1048
  options = {};
1108
1049
  }
1109
- var _a3 = options.strict, strict = _a3 === void 0 ? false : _a3, _b2 = options.start, start = _b2 === void 0 ? true : _b2, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function(x) {
1050
+ var _a2 = options.strict, strict = _a2 === void 0 ? false : _a2, _b2 = options.start, start = _b2 === void 0 ? true : _b2, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function(x) {
1110
1051
  return x;
1111
1052
  } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
1112
1053
  var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
@@ -1238,7 +1179,6 @@ var MockServiceWorker = (() => {
1238
1179
  var IS_NODE = isNodeProcess();
1239
1180
  var Logger = class {
1240
1181
  constructor(name) {
1241
- __publicField(this, "prefix");
1242
1182
  this.name = name;
1243
1183
  this.prefix = `[${this.name}]`;
1244
1184
  const LOGGER_NAME = getVariable("DEBUG");
@@ -1258,6 +1198,7 @@ var MockServiceWorker = (() => {
1258
1198
  this.only = noop;
1259
1199
  }
1260
1200
  }
1201
+ prefix;
1261
1202
  extend(domain) {
1262
1203
  return new Logger(`${this.name}:${domain}`);
1263
1204
  }
@@ -1385,8 +1326,8 @@ var MockServiceWorker = (() => {
1385
1326
  positionals = []
1386
1327
  } = args;
1387
1328
  const entry = this.createEntry(level, message3);
1388
- const timestampColor = (customColors == null ? void 0 : customColors.timestamp) || "gray";
1389
- const prefixColor = (customColors == null ? void 0 : customColors.prefix) || "gray";
1329
+ const timestampColor = customColors?.timestamp || "gray";
1330
+ const prefixColor = customColors?.prefix || "gray";
1390
1331
  const colorize = {
1391
1332
  timestamp: colors_exports[timestampColor],
1392
1333
  prefix: colors_exports[prefixColor]
@@ -1419,10 +1360,10 @@ var MockServiceWorker = (() => {
1419
1360
  }
1420
1361
  };
1421
1362
  var PerformanceEntry = class {
1363
+ startTime;
1364
+ endTime;
1365
+ deltaTime;
1422
1366
  constructor() {
1423
- __publicField(this, "startTime");
1424
- __publicField(this, "endTime");
1425
- __publicField(this, "deltaTime");
1426
1367
  this.startTime = performance.now();
1427
1368
  }
1428
1369
  measure() {
@@ -1454,11 +1395,10 @@ var MockServiceWorker = (() => {
1454
1395
  console.error(message3, ...positionals);
1455
1396
  }
1456
1397
  function getVariable(variableName) {
1457
- var _a3;
1458
1398
  if (IS_NODE) {
1459
1399
  return process.env[variableName];
1460
1400
  }
1461
- return (_a3 = globalThis[variableName]) == null ? void 0 : _a3.toString();
1401
+ return globalThis[variableName]?.toString();
1462
1402
  }
1463
1403
  function isDefinedAndNotEquals(value, expected) {
1464
1404
  return value !== void 0 && value !== expected;
@@ -1479,171 +1419,6 @@ var MockServiceWorker = (() => {
1479
1419
  return message3.toString();
1480
1420
  }
1481
1421
 
1482
- // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
1483
- var MemoryLeakError2 = class extends Error {
1484
- constructor(emitter, type, count) {
1485
- super(
1486
- `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`
1487
- );
1488
- this.emitter = emitter;
1489
- this.type = type;
1490
- this.count = count;
1491
- this.name = "MaxListenersExceededWarning";
1492
- }
1493
- };
1494
- var _Emitter2 = class {
1495
- static listenerCount(emitter, eventName) {
1496
- return emitter.listenerCount(eventName);
1497
- }
1498
- constructor() {
1499
- this.events = /* @__PURE__ */ new Map();
1500
- this.maxListeners = _Emitter2.defaultMaxListeners;
1501
- this.hasWarnedAboutPotentialMemoryLeak = false;
1502
- }
1503
- _emitInternalEvent(internalEventName, eventName, listener) {
1504
- this.emit(
1505
- internalEventName,
1506
- ...[eventName, listener]
1507
- );
1508
- }
1509
- _getListeners(eventName) {
1510
- return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
1511
- }
1512
- _removeListener(listeners, listener) {
1513
- const index = listeners.indexOf(listener);
1514
- if (index > -1) {
1515
- listeners.splice(index, 1);
1516
- }
1517
- return [];
1518
- }
1519
- _wrapOnceListener(eventName, listener) {
1520
- const onceListener = (...data) => {
1521
- this.removeListener(eventName, onceListener);
1522
- return listener.apply(this, data);
1523
- };
1524
- Object.defineProperty(onceListener, "name", { value: listener.name });
1525
- return onceListener;
1526
- }
1527
- setMaxListeners(maxListeners) {
1528
- this.maxListeners = maxListeners;
1529
- return this;
1530
- }
1531
- /**
1532
- * Returns the current max listener value for the `Emitter` which is
1533
- * either set by `emitter.setMaxListeners(n)` or defaults to
1534
- * `Emitter.defaultMaxListeners`.
1535
- */
1536
- getMaxListeners() {
1537
- return this.maxListeners;
1538
- }
1539
- /**
1540
- * Returns an array listing the events for which the emitter has registered listeners.
1541
- * The values in the array will be strings or Symbols.
1542
- */
1543
- eventNames() {
1544
- return Array.from(this.events.keys());
1545
- }
1546
- /**
1547
- * Synchronously calls each of the listeners registered for the event named `eventName`,
1548
- * in the order they were registered, passing the supplied arguments to each.
1549
- * Returns `true` if the event has listeners, `false` otherwise.
1550
- *
1551
- * @example
1552
- * const emitter = new Emitter<{ hello: [string] }>()
1553
- * emitter.emit('hello', 'John')
1554
- */
1555
- emit(eventName, ...data) {
1556
- const listeners = this._getListeners(eventName);
1557
- listeners.forEach((listener) => {
1558
- listener.apply(this, data);
1559
- });
1560
- return listeners.length > 0;
1561
- }
1562
- addListener(eventName, listener) {
1563
- this._emitInternalEvent("newListener", eventName, listener);
1564
- const nextListeners = this._getListeners(eventName).concat(listener);
1565
- this.events.set(eventName, nextListeners);
1566
- if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) {
1567
- this.hasWarnedAboutPotentialMemoryLeak = true;
1568
- const memoryLeakWarning = new MemoryLeakError2(
1569
- this,
1570
- eventName,
1571
- this.listenerCount(eventName)
1572
- );
1573
- console.warn(memoryLeakWarning);
1574
- }
1575
- return this;
1576
- }
1577
- on(eventName, listener) {
1578
- return this.addListener(eventName, listener);
1579
- }
1580
- once(eventName, listener) {
1581
- return this.addListener(
1582
- eventName,
1583
- this._wrapOnceListener(eventName, listener)
1584
- );
1585
- }
1586
- prependListener(eventName, listener) {
1587
- const listeners = this._getListeners(eventName);
1588
- if (listeners.length > 0) {
1589
- const nextListeners = [listener].concat(listeners);
1590
- this.events.set(eventName, nextListeners);
1591
- } else {
1592
- this.events.set(eventName, listeners.concat(listener));
1593
- }
1594
- return this;
1595
- }
1596
- prependOnceListener(eventName, listener) {
1597
- return this.prependListener(
1598
- eventName,
1599
- this._wrapOnceListener(eventName, listener)
1600
- );
1601
- }
1602
- removeListener(eventName, listener) {
1603
- const listeners = this._getListeners(eventName);
1604
- if (listeners.length > 0) {
1605
- this._removeListener(listeners, listener);
1606
- this.events.set(eventName, listeners);
1607
- this._emitInternalEvent("removeListener", eventName, listener);
1608
- }
1609
- return this;
1610
- }
1611
- /**
1612
- * Alias for `emitter.removeListener()`.
1613
- *
1614
- * @example
1615
- * emitter.off('hello', listener)
1616
- */
1617
- off(eventName, listener) {
1618
- return this.removeListener(eventName, listener);
1619
- }
1620
- removeAllListeners(eventName) {
1621
- if (eventName) {
1622
- this.events.delete(eventName);
1623
- } else {
1624
- this.events.clear();
1625
- }
1626
- return this;
1627
- }
1628
- /**
1629
- * Returns a copy of the array of listeners for the event named `eventName`.
1630
- */
1631
- listeners(eventName) {
1632
- return Array.from(this._getListeners(eventName));
1633
- }
1634
- /**
1635
- * Returns the number of listeners listening to the event named `eventName`.
1636
- */
1637
- listenerCount(eventName) {
1638
- return this._getListeners(eventName).length;
1639
- }
1640
- rawListeners(eventName) {
1641
- return this.listeners(eventName);
1642
- }
1643
- };
1644
- var Emitter2 = _Emitter2;
1645
- Emitter2.defaultMaxListeners = 10;
1646
-
1647
1422
  // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-WZQN3FMY.mjs
1648
1423
  var IS_PATCHED_MODULE = Symbol("isPatchedModule");
1649
1424
  function getGlobalSymbol(symbol) {
@@ -1662,7 +1437,7 @@ var MockServiceWorker = (() => {
1662
1437
  constructor(symbol) {
1663
1438
  this.symbol = symbol;
1664
1439
  this.readyState = "INACTIVE";
1665
- this.emitter = new Emitter2();
1440
+ this.emitter = new Emitter();
1666
1441
  this.subscriptions = [];
1667
1442
  this.logger = new Logger(symbol.description);
1668
1443
  this.emitter.setMaxListeners(0);
@@ -1774,9 +1549,9 @@ var MockServiceWorker = (() => {
1774
1549
  this.readyState = "DISPOSED";
1775
1550
  }
1776
1551
  getInstance() {
1777
- var _a3;
1552
+ var _a2;
1778
1553
  const instance = getGlobalSymbol(this.symbol);
1779
- this.logger.info("retrieved global instance:", (_a3 = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a3.name);
1554
+ this.logger.info("retrieved global instance:", (_a2 = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a2.name);
1780
1555
  return instance;
1781
1556
  }
1782
1557
  setInstance() {
@@ -2284,7 +2059,7 @@ var MockServiceWorker = (() => {
2284
2059
  try {
2285
2060
  object[method];
2286
2061
  return true;
2287
- } catch (e) {
2062
+ } catch {
2288
2063
  return false;
2289
2064
  }
2290
2065
  }
@@ -2303,13 +2078,11 @@ var MockServiceWorker = (() => {
2303
2078
  }
2304
2079
  const now = Date.now();
2305
2080
  const parsedResponseCookies = (0, import_set_cookie_parser.parse)(responseCookies).map(
2306
- (_a3) => {
2307
- var _b2 = _a3, { maxAge } = _b2, cookie = __objRest(_b2, ["maxAge"]);
2308
- return __spreadProps(__spreadValues({}, cookie), {
2309
- expires: maxAge === void 0 ? cookie.expires : new Date(now + maxAge * 1e3),
2310
- maxAge
2311
- });
2312
- }
2081
+ ({ maxAge, ...cookie }) => ({
2082
+ ...cookie,
2083
+ expires: maxAge === void 0 ? cookie.expires : new Date(now + maxAge * 1e3),
2084
+ maxAge
2085
+ })
2313
2086
  );
2314
2087
  const prevCookies = this.store.get(requestUrl.origin) || /* @__PURE__ */ new Map();
2315
2088
  parsedResponseCookies.forEach((cookie) => {
@@ -2366,13 +2139,10 @@ var MockServiceWorker = (() => {
2366
2139
  this.store.set(
2367
2140
  origin,
2368
2141
  new Map(
2369
- cookies.map((_a3) => {
2370
- var [token, _b2] = _a3, _c = _b2, { expires } = _c, cookie = __objRest(_c, ["expires"]);
2371
- return [
2372
- token,
2373
- expires === void 0 ? cookie : __spreadProps(__spreadValues({}, cookie), { expires: new Date(expires) })
2374
- ];
2375
- })
2142
+ cookies.map(([token, { expires, ...cookie }]) => [
2143
+ token,
2144
+ expires === void 0 ? cookie : { ...cookie, expires: new Date(expires) }
2145
+ ])
2376
2146
  )
2377
2147
  );
2378
2148
  });
@@ -2439,19 +2209,24 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2439
2209
  }
2440
2210
  }
2441
2211
  function getAllRequestCookies(request) {
2442
- var _a3;
2443
2212
  const requestCookiesString = request.headers.get("cookie");
2444
2213
  const cookiesFromHeaders = requestCookiesString ? source_default2.parse(requestCookiesString) : {};
2445
2214
  store.hydrate();
2446
- const cookiesFromStore = Array.from((_a3 = store.get(request)) == null ? void 0 : _a3.entries()).reduce((cookies, [name, { value }]) => {
2215
+ const cookiesFromStore = Array.from(store.get(request)?.entries()).reduce((cookies, [name, { value }]) => {
2447
2216
  return Object.assign(cookies, { [name.trim()]: value });
2448
2217
  }, {});
2449
2218
  const cookiesFromDocument = getRequestCookies(request);
2450
- const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
2219
+ const forwardedCookies = {
2220
+ ...cookiesFromDocument,
2221
+ ...cookiesFromStore
2222
+ };
2451
2223
  for (const [name, value] of Object.entries(forwardedCookies)) {
2452
2224
  request.headers.append("cookie", source_default2.serialize(name, value));
2453
2225
  }
2454
- return __spreadValues(__spreadValues({}, forwardedCookies), cookiesFromHeaders);
2226
+ return {
2227
+ ...forwardedCookies,
2228
+ ...cookiesFromHeaders
2229
+ };
2455
2230
  }
2456
2231
 
2457
2232
  // src/core/handlers/HttpHandler.ts
@@ -2496,21 +2271,18 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2496
2271
  `Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`
2497
2272
  );
2498
2273
  }
2499
- parse(args) {
2500
- return __async(this, null, function* () {
2501
- var _a3;
2502
- const url = new URL(args.request.url);
2503
- const match2 = matchRequestUrl(
2504
- url,
2505
- this.info.path,
2506
- (_a3 = args.resolutionContext) == null ? void 0 : _a3.baseUrl
2507
- );
2508
- const cookies = getAllRequestCookies(args.request);
2509
- return {
2510
- match: match2,
2511
- cookies
2512
- };
2513
- });
2274
+ async parse(args) {
2275
+ const url = new URL(args.request.url);
2276
+ const match2 = matchRequestUrl(
2277
+ url,
2278
+ this.info.path,
2279
+ args.resolutionContext?.baseUrl
2280
+ );
2281
+ const cookies = getAllRequestCookies(args.request);
2282
+ return {
2283
+ match: match2,
2284
+ cookies
2285
+ };
2514
2286
  }
2515
2287
  predicate(args) {
2516
2288
  const hasMatchingMethod = this.matchMethod(args.request.method);
@@ -2521,30 +2293,27 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2521
2293
  return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : isStringEqual(this.info.method, actualMethod);
2522
2294
  }
2523
2295
  extendResolverArgs(args) {
2524
- var _a3;
2525
2296
  return {
2526
- params: ((_a3 = args.parsedResult.match) == null ? void 0 : _a3.params) || {},
2297
+ params: args.parsedResult.match?.params || {},
2527
2298
  cookies: args.parsedResult.cookies
2528
2299
  };
2529
2300
  }
2530
- log(args) {
2531
- return __async(this, null, function* () {
2532
- const publicUrl = getPublicUrlFromRequest(args.request);
2533
- const loggedRequest = yield serializeRequest(args.request);
2534
- const loggedResponse = yield serializeResponse(args.response);
2535
- const statusColor = getStatusCodeColor(loggedResponse.status);
2536
- console.groupCollapsed(
2537
- devUtils.formatMessage(
2538
- `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
2539
- ),
2540
- `color:${statusColor}`,
2541
- "color:inherit"
2542
- );
2543
- console.log("Request", loggedRequest);
2544
- console.log("Handler:", this);
2545
- console.log("Response", loggedResponse);
2546
- console.groupEnd();
2547
- });
2301
+ async log(args) {
2302
+ const publicUrl = getPublicUrlFromRequest(args.request);
2303
+ const loggedRequest = await serializeRequest(args.request);
2304
+ const loggedResponse = await serializeResponse(args.response);
2305
+ const statusColor = getStatusCodeColor(loggedResponse.status);
2306
+ console.groupCollapsed(
2307
+ devUtils.formatMessage(
2308
+ `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
2309
+ ),
2310
+ `color:${statusColor}`,
2311
+ "color:inherit"
2312
+ );
2313
+ console.log("Request", loggedRequest);
2314
+ console.log("Handler:", this);
2315
+ console.log("Response", loggedResponse);
2316
+ console.groupEnd();
2548
2317
  }
2549
2318
  };
2550
2319
 
@@ -5032,7 +4801,7 @@ spurious results.`);
5032
4801
  }
5033
4802
  }
5034
4803
 
5035
- // node_modules/.pnpm/headers-polyfill@4.0.1/node_modules/headers-polyfill/lib/index.mjs
4804
+ // node_modules/.pnpm/headers-polyfill@4.0.2/node_modules/headers-polyfill/lib/index.mjs
5036
4805
  var __create4 = Object.create;
5037
4806
  var __defProp6 = Object.defineProperty;
5038
4807
  var __getOwnPropDesc5 = Object.getOwnPropertyDescriptor;
@@ -5312,7 +5081,7 @@ spurious results.`);
5312
5081
  constructor(init) {
5313
5082
  this[_a] = {};
5314
5083
  this[_b] = /* @__PURE__ */ new Map();
5315
- if (["Headers", "HeadersPolyfill"].includes(init == null ? void 0 : init.constructor.name) || init instanceof _Headers) {
5084
+ if (["Headers", "HeadersPolyfill"].includes(init?.constructor.name) || init instanceof _Headers || typeof globalThis.Headers !== "undefined" && init instanceof globalThis.Headers) {
5316
5085
  const initialHeaders = init;
5317
5086
  initialHeaders.forEach((value, name) => {
5318
5087
  this.append(name, value);
@@ -5374,11 +5143,10 @@ spurious results.`);
5374
5143
  * Returns a `ByteString` sequence of all the values of a header with a given name.
5375
5144
  */
5376
5145
  get(name) {
5377
- var _a3;
5378
5146
  if (!isValidHeaderName(name)) {
5379
5147
  throw TypeError(`Invalid header name "${name}"`);
5380
5148
  }
5381
- return (_a3 = this[NORMALIZED_HEADERS][normalizeHeaderName(name)]) != null ? _a3 : null;
5149
+ return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null;
5382
5150
  }
5383
5151
  /**
5384
5152
  * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.
@@ -5459,7 +5227,6 @@ spurious results.`);
5459
5227
 
5460
5228
  // src/core/utils/internal/parseMultipartData.ts
5461
5229
  function parseContentHeaders(headersString) {
5462
- var _a3, _b2;
5463
5230
  const headers = stringToHeaders(headersString);
5464
5231
  const contentType = headers.get("content-type") || "text/plain";
5465
5232
  const disposition = headers.get("content-disposition");
@@ -5471,8 +5238,8 @@ spurious results.`);
5471
5238
  acc[name2] = rest.join("=");
5472
5239
  return acc;
5473
5240
  }, {});
5474
- const name = (_a3 = directives.name) == null ? void 0 : _a3.slice(1, -1);
5475
- const filename = (_b2 = directives.filename) == null ? void 0 : _b2.slice(1, -1);
5241
+ const name = directives.name?.slice(1, -1);
5242
+ const filename = directives.filename?.slice(1, -1);
5476
5243
  return {
5477
5244
  name,
5478
5245
  filename,
@@ -5480,7 +5247,7 @@ spurious results.`);
5480
5247
  };
5481
5248
  }
5482
5249
  function parseMultipartData(data, headers) {
5483
- const contentType = headers == null ? void 0 : headers.get("content-type");
5250
+ const contentType = headers?.get("content-type");
5484
5251
  if (!contentType) {
5485
5252
  return void 0;
5486
5253
  }
@@ -5518,13 +5285,12 @@ spurious results.`);
5518
5285
 
5519
5286
  // src/core/utils/internal/parseGraphQLRequest.ts
5520
5287
  function parseDocumentNode(node) {
5521
- var _a3;
5522
5288
  const operationDef = node.definitions.find((definition) => {
5523
5289
  return definition.kind === "OperationDefinition";
5524
5290
  });
5525
5291
  return {
5526
- operationType: operationDef == null ? void 0 : operationDef.operation,
5527
- operationName: (_a3 = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a3.value
5292
+ operationType: operationDef?.operation,
5293
+ operationName: operationDef?.name?.value
5528
5294
  };
5529
5295
  }
5530
5296
  function parseQuery(query) {
@@ -5556,87 +5322,82 @@ spurious results.`);
5556
5322
  }
5557
5323
  return operations.variables;
5558
5324
  }
5559
- function getGraphQLInput(request) {
5560
- return __async(this, null, function* () {
5561
- var _a3;
5562
- switch (request.method) {
5563
- case "GET": {
5564
- const url = new URL(request.url);
5565
- const query = url.searchParams.get("query");
5566
- const variables = url.searchParams.get("variables") || "";
5567
- return {
5568
- query,
5569
- variables: jsonParse(variables)
5570
- };
5571
- }
5572
- case "POST": {
5573
- const requestClone = request.clone();
5574
- if ((_a3 = request.headers.get("content-type")) == null ? void 0 : _a3.includes("multipart/form-data")) {
5575
- const responseJson = parseMultipartData(
5576
- yield requestClone.text(),
5577
- request.headers
5578
- );
5579
- if (!responseJson) {
5580
- return null;
5581
- }
5582
- const _b2 = responseJson, { operations, map } = _b2, files = __objRest(_b2, ["operations", "map"]);
5583
- const parsedOperations = jsonParse(
5584
- operations
5585
- ) || {};
5586
- if (!parsedOperations.query) {
5587
- return null;
5588
- }
5589
- const parsedMap = jsonParse(map || "") || {};
5590
- const variables = parsedOperations.variables ? extractMultipartVariables(
5591
- parsedOperations.variables,
5592
- parsedMap,
5593
- files
5594
- ) : {};
5595
- return {
5596
- query: parsedOperations.query,
5597
- variables
5598
- };
5325
+ async function getGraphQLInput(request) {
5326
+ switch (request.method) {
5327
+ case "GET": {
5328
+ const url = new URL(request.url);
5329
+ const query = url.searchParams.get("query");
5330
+ const variables = url.searchParams.get("variables") || "";
5331
+ return {
5332
+ query,
5333
+ variables: jsonParse(variables)
5334
+ };
5335
+ }
5336
+ case "POST": {
5337
+ const requestClone = request.clone();
5338
+ if (request.headers.get("content-type")?.includes("multipart/form-data")) {
5339
+ const responseJson = parseMultipartData(
5340
+ await requestClone.text(),
5341
+ request.headers
5342
+ );
5343
+ if (!responseJson) {
5344
+ return null;
5599
5345
  }
5600
- const requestJson = yield requestClone.json().catch(() => null);
5601
- if (requestJson == null ? void 0 : requestJson.query) {
5602
- const { query, variables } = requestJson;
5603
- return {
5604
- query,
5605
- variables
5606
- };
5346
+ const { operations, map, ...files } = responseJson;
5347
+ const parsedOperations = jsonParse(
5348
+ operations
5349
+ ) || {};
5350
+ if (!parsedOperations.query) {
5351
+ return null;
5607
5352
  }
5353
+ const parsedMap = jsonParse(map || "") || {};
5354
+ const variables = parsedOperations.variables ? extractMultipartVariables(
5355
+ parsedOperations.variables,
5356
+ parsedMap,
5357
+ files
5358
+ ) : {};
5359
+ return {
5360
+ query: parsedOperations.query,
5361
+ variables
5362
+ };
5363
+ }
5364
+ const requestJson = await requestClone.json().catch(() => null);
5365
+ if (requestJson?.query) {
5366
+ const { query, variables } = requestJson;
5367
+ return {
5368
+ query,
5369
+ variables
5370
+ };
5608
5371
  }
5609
- default:
5610
- return null;
5611
5372
  }
5612
- });
5373
+ default:
5374
+ return null;
5375
+ }
5613
5376
  }
5614
- function parseGraphQLRequest(request) {
5615
- return __async(this, null, function* () {
5616
- const input = yield getGraphQLInput(request);
5617
- if (!input || !input.query) {
5618
- return;
5619
- }
5620
- const { query, variables } = input;
5621
- const parsedResult = parseQuery(query);
5622
- if (parsedResult instanceof Error) {
5623
- const requestPublicUrl = getPublicUrlFromRequest(request);
5624
- throw new Error(
5625
- devUtils.formatMessage(
5626
- 'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
5627
- request.method,
5628
- requestPublicUrl,
5629
- parsedResult.message
5630
- )
5631
- );
5632
- }
5633
- return {
5634
- query: input.query,
5635
- operationType: parsedResult.operationType,
5636
- operationName: parsedResult.operationName,
5637
- variables
5638
- };
5639
- });
5377
+ async function parseGraphQLRequest(request) {
5378
+ const input = await getGraphQLInput(request);
5379
+ if (!input || !input.query) {
5380
+ return;
5381
+ }
5382
+ const { query, variables } = input;
5383
+ const parsedResult = parseQuery(query);
5384
+ if (parsedResult instanceof Error) {
5385
+ const requestPublicUrl = getPublicUrlFromRequest(request);
5386
+ throw new Error(
5387
+ devUtils.formatMessage(
5388
+ 'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
5389
+ request.method,
5390
+ requestPublicUrl,
5391
+ parsedResult.message
5392
+ )
5393
+ );
5394
+ }
5395
+ return {
5396
+ query: input.query,
5397
+ operationType: parsedResult.operationType,
5398
+ operationName: parsedResult.operationName,
5399
+ variables
5400
+ };
5640
5401
  }
5641
5402
 
5642
5403
  // src/core/handlers/GraphQLHandler.ts
@@ -5646,7 +5407,9 @@ spurious results.`);
5646
5407
  }
5647
5408
  return typeof value === "object" && "kind" in value && "definitions" in value;
5648
5409
  }
5649
- var _GraphQLHandler = class _GraphQLHandler extends RequestHandler {
5410
+ var GraphQLHandler = class _GraphQLHandler extends RequestHandler {
5411
+ endpoint;
5412
+ static parsedRequestCache = /* @__PURE__ */ new WeakMap();
5650
5413
  constructor(operationType, operationName, endpoint, resolver, options) {
5651
5414
  let resolvedOperationName = operationName;
5652
5415
  if (isDocumentNode(operationName)) {
@@ -5680,40 +5443,38 @@ spurious results.`);
5680
5443
  * GraphQL handlers. This is done to avoid multiple parsing of the
5681
5444
  * request body, which each requires a clone of the request.
5682
5445
  */
5683
- parseGraphQLRequestOrGetFromCache(request) {
5684
- return __async(this, null, function* () {
5685
- if (!_GraphQLHandler.parsedRequestCache.has(request)) {
5686
- _GraphQLHandler.parsedRequestCache.set(
5687
- request,
5688
- yield parseGraphQLRequest(request).catch((error3) => {
5689
- console.error(error3);
5690
- return void 0;
5691
- })
5692
- );
5693
- }
5694
- return _GraphQLHandler.parsedRequestCache.get(request);
5695
- });
5696
- }
5697
- parse(args) {
5698
- return __async(this, null, function* () {
5699
- const match2 = matchRequestUrl(new URL(args.request.url), this.endpoint);
5700
- if (!match2.matches) {
5701
- return { match: match2 };
5702
- }
5703
- const parsedResult = yield this.parseGraphQLRequestOrGetFromCache(
5704
- args.request
5446
+ async parseGraphQLRequestOrGetFromCache(request) {
5447
+ if (!_GraphQLHandler.parsedRequestCache.has(request)) {
5448
+ _GraphQLHandler.parsedRequestCache.set(
5449
+ request,
5450
+ await parseGraphQLRequest(request).catch((error3) => {
5451
+ console.error(error3);
5452
+ return void 0;
5453
+ })
5705
5454
  );
5706
- if (typeof parsedResult === "undefined") {
5707
- return { match: match2 };
5708
- }
5709
- return {
5710
- match: match2,
5711
- query: parsedResult.query,
5712
- operationType: parsedResult.operationType,
5713
- operationName: parsedResult.operationName,
5714
- variables: parsedResult.variables
5715
- };
5716
- });
5455
+ }
5456
+ return _GraphQLHandler.parsedRequestCache.get(request);
5457
+ }
5458
+ async parse(args) {
5459
+ const match2 = matchRequestUrl(new URL(args.request.url), this.endpoint);
5460
+ const cookies = getAllRequestCookies(args.request);
5461
+ if (!match2.matches) {
5462
+ return { match: match2, cookies };
5463
+ }
5464
+ const parsedResult = await this.parseGraphQLRequestOrGetFromCache(
5465
+ args.request
5466
+ );
5467
+ if (typeof parsedResult === "undefined") {
5468
+ return { match: match2, cookies };
5469
+ }
5470
+ return {
5471
+ match: match2,
5472
+ cookies,
5473
+ query: parsedResult.query,
5474
+ operationType: parsedResult.operationType,
5475
+ operationName: parsedResult.operationName,
5476
+ variables: parsedResult.variables
5477
+ };
5717
5478
  }
5718
5479
  predicate(args) {
5719
5480
  if (args.parsedResult.operationType === void 0) {
@@ -5731,36 +5492,31 @@ Consider naming this operation or using "graphql.operation()" request handler to
5731
5492
  return args.parsedResult.match.matches && hasMatchingOperationType && hasMatchingOperationName;
5732
5493
  }
5733
5494
  extendResolverArgs(args) {
5734
- const cookies = getAllRequestCookies(args.request);
5735
5495
  return {
5736
5496
  query: args.parsedResult.query || "",
5737
5497
  operationName: args.parsedResult.operationName || "",
5738
5498
  variables: args.parsedResult.variables || {},
5739
- cookies
5499
+ cookies: args.parsedResult.cookies
5740
5500
  };
5741
5501
  }
5742
- log(args) {
5743
- return __async(this, null, function* () {
5744
- const loggedRequest = yield serializeRequest(args.request);
5745
- const loggedResponse = yield serializeResponse(args.response);
5746
- const statusColor = getStatusCodeColor(loggedResponse.status);
5747
- const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`;
5748
- console.groupCollapsed(
5749
- devUtils.formatMessage(
5750
- `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
5751
- ),
5752
- `color:${statusColor}`,
5753
- "color:inherit"
5754
- );
5755
- console.log("Request:", loggedRequest);
5756
- console.log("Handler:", this);
5757
- console.log("Response:", loggedResponse);
5758
- console.groupEnd();
5759
- });
5502
+ async log(args) {
5503
+ const loggedRequest = await serializeRequest(args.request);
5504
+ const loggedResponse = await serializeResponse(args.response);
5505
+ const statusColor = getStatusCodeColor(loggedResponse.status);
5506
+ const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`;
5507
+ console.groupCollapsed(
5508
+ devUtils.formatMessage(
5509
+ `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
5510
+ ),
5511
+ `color:${statusColor}`,
5512
+ "color:inherit"
5513
+ );
5514
+ console.log("Request:", loggedRequest);
5515
+ console.log("Handler:", this);
5516
+ console.log("Response:", loggedResponse);
5517
+ console.groupEnd();
5760
5518
  }
5761
5519
  };
5762
- _GraphQLHandler.parsedRequestCache = /* @__PURE__ */ new WeakMap();
5763
- var GraphQLHandler = _GraphQLHandler;
5764
5520
 
5765
5521
  // src/core/graphql.ts
5766
5522
  function createScopedGraphQLHandler(operationType, url) {
@@ -5822,7 +5578,8 @@ Consider naming this operation or using "graphql.operation()" request handler to
5822
5578
  mutation: createScopedGraphQLHandler("mutation", url)
5823
5579
  };
5824
5580
  }
5825
- var graphql = __spreadProps(__spreadValues({}, standardGraphQLHandlers), {
5581
+ var graphql = {
5582
+ ...standardGraphQLHandlers,
5826
5583
  /**
5827
5584
  * Intercepts GraphQL operations scoped by the given URL.
5828
5585
  *
@@ -5833,42 +5590,47 @@ Consider naming this operation or using "graphql.operation()" request handler to
5833
5590
  * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}
5834
5591
  */
5835
5592
  link: createGraphQLLink
5836
- });
5593
+ };
5837
5594
 
5838
5595
  // node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs
5839
- var until = (promise) => __async(void 0, null, function* () {
5596
+ var until = async (promise) => {
5840
5597
  try {
5841
- const data = yield promise().catch((error3) => {
5598
+ const data = await promise().catch((error3) => {
5842
5599
  throw error3;
5843
5600
  });
5844
5601
  return { error: null, data };
5845
5602
  } catch (error3) {
5846
5603
  return { error: error3, data: null };
5847
5604
  }
5848
- });
5605
+ };
5849
5606
 
5850
5607
  // src/core/utils/getResponse.ts
5851
- var getResponse = (request, handlers, resolutionContext) => __async(void 0, null, function* () {
5608
+ var getResponse = async ({
5609
+ request,
5610
+ requestId,
5611
+ handlers,
5612
+ resolutionContext
5613
+ }) => {
5852
5614
  let matchingHandler = null;
5853
5615
  let result = null;
5854
5616
  for (const handler of handlers) {
5855
- result = yield handler.run({ request, resolutionContext });
5617
+ result = await handler.run({ request, requestId, resolutionContext });
5856
5618
  if (result !== null) {
5857
5619
  matchingHandler = handler;
5858
5620
  }
5859
- if (result == null ? void 0 : result.response) {
5621
+ if (result?.response) {
5860
5622
  break;
5861
5623
  }
5862
5624
  }
5863
5625
  if (matchingHandler) {
5864
5626
  return {
5865
5627
  handler: matchingHandler,
5866
- parsedResult: result == null ? void 0 : result.parsedResult,
5867
- response: result == null ? void 0 : result.response
5628
+ parsedResult: result?.parsedResult,
5629
+ response: result?.response
5868
5630
  };
5869
5631
  }
5870
5632
  return null;
5871
- });
5633
+ };
5872
5634
 
5873
5635
  // node_modules/.pnpm/@bundled-es-modules+js-levenshtein@2.0.1/node_modules/@bundled-es-modules/js-levenshtein/index-esm.js
5874
5636
  var __create5 = Object.create;
@@ -6048,154 +5810,149 @@ ${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
6048
5810
  }
6049
5811
  return `Did you mean to request "${handlers[0].info.header}" instead?`;
6050
5812
  }
6051
- function onUnhandledRequest(request, handlers, strategy = "warn") {
6052
- return __async(this, null, function* () {
6053
- const parsedGraphQLQuery = yield parseGraphQLRequest(request).catch(
6054
- () => null
5813
+ async function onUnhandledRequest(request, handlers, strategy = "warn") {
5814
+ const parsedGraphQLQuery = await parseGraphQLRequest(request).catch(
5815
+ () => null
5816
+ );
5817
+ const publicUrl = getPublicUrlFromRequest(request);
5818
+ function generateHandlerSuggestion() {
5819
+ const handlerGroups = groupHandlersByType(handlers);
5820
+ const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.http;
5821
+ const suggestedHandlers = getSuggestedHandler(
5822
+ request,
5823
+ relevantHandlers,
5824
+ parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getHttpHandlerScore()
6055
5825
  );
6056
- const publicUrl = getPublicUrlFromRequest(request);
6057
- function generateHandlerSuggestion() {
6058
- const handlerGroups = groupHandlersByType(handlers);
6059
- const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.http;
6060
- const suggestedHandlers = getSuggestedHandler(
6061
- request,
6062
- relevantHandlers,
6063
- parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getHttpHandlerScore()
6064
- );
6065
- return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
6066
- }
6067
- function getGraphQLRequestHeader(parsedGraphQLRequest) {
6068
- if (!(parsedGraphQLRequest == null ? void 0 : parsedGraphQLRequest.operationName)) {
6069
- return `anonymous ${parsedGraphQLRequest == null ? void 0 : parsedGraphQLRequest.operationType} (${request.method} ${publicUrl})`;
6070
- }
6071
- return `${parsedGraphQLRequest.operationType} ${parsedGraphQLRequest.operationName} (${request.method} ${publicUrl})`;
6072
- }
6073
- function generateUnhandledRequestMessage() {
6074
- const requestHeader = parsedGraphQLQuery ? getGraphQLRequestHeader(parsedGraphQLQuery) : `${request.method} ${publicUrl}`;
6075
- const handlerSuggestion = generateHandlerSuggestion();
6076
- const messageTemplate = [
6077
- `intercepted a request without a matching request handler:`,
6078
- ` \u2022 ${requestHeader}`,
6079
- handlerSuggestion,
6080
- `If you still wish to intercept this unhandled request, please create a request handler for it.
5826
+ return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
5827
+ }
5828
+ function getGraphQLRequestHeader(parsedGraphQLRequest) {
5829
+ if (!parsedGraphQLRequest?.operationName) {
5830
+ return `anonymous ${parsedGraphQLRequest?.operationType} (${request.method} ${publicUrl})`;
5831
+ }
5832
+ return `${parsedGraphQLRequest.operationType} ${parsedGraphQLRequest.operationName} (${request.method} ${publicUrl})`;
5833
+ }
5834
+ function generateUnhandledRequestMessage() {
5835
+ const requestHeader = parsedGraphQLQuery ? getGraphQLRequestHeader(parsedGraphQLQuery) : `${request.method} ${publicUrl}`;
5836
+ const handlerSuggestion = generateHandlerSuggestion();
5837
+ const messageTemplate = [
5838
+ `intercepted a request without a matching request handler:`,
5839
+ ` \u2022 ${requestHeader}`,
5840
+ handlerSuggestion,
5841
+ `If you still wish to intercept this unhandled request, please create a request handler for it.
6081
5842
  Read more: https://mswjs.io/docs/getting-started/mocks`
6082
- ].filter(Boolean);
6083
- return messageTemplate.join("\n\n");
6084
- }
6085
- function applyStrategy(strategy2) {
6086
- const message3 = generateUnhandledRequestMessage();
6087
- switch (strategy2) {
6088
- case "error": {
6089
- devUtils.error("Error: %s", message3);
6090
- throw new Error(
6091
- devUtils.formatMessage(
6092
- 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'
6093
- )
6094
- );
6095
- }
6096
- case "warn": {
6097
- devUtils.warn("Warning: %s", message3);
6098
- break;
6099
- }
6100
- case "bypass":
6101
- break;
6102
- default:
6103
- throw new Error(
6104
- devUtils.formatMessage(
6105
- 'Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.',
6106
- strategy2
6107
- )
6108
- );
5843
+ ].filter(Boolean);
5844
+ return messageTemplate.join("\n\n");
5845
+ }
5846
+ function applyStrategy(strategy2) {
5847
+ const message3 = generateUnhandledRequestMessage();
5848
+ switch (strategy2) {
5849
+ case "error": {
5850
+ devUtils.error("Error: %s", message3);
5851
+ throw new Error(
5852
+ devUtils.formatMessage(
5853
+ 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'
5854
+ )
5855
+ );
6109
5856
  }
5857
+ case "warn": {
5858
+ devUtils.warn("Warning: %s", message3);
5859
+ break;
5860
+ }
5861
+ case "bypass":
5862
+ break;
5863
+ default:
5864
+ throw new Error(
5865
+ devUtils.formatMessage(
5866
+ 'Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.',
5867
+ strategy2
5868
+ )
5869
+ );
6110
5870
  }
6111
- if (typeof strategy === "function") {
6112
- strategy(request, {
6113
- warning: applyStrategy.bind(null, "warn"),
6114
- error: applyStrategy.bind(null, "error")
6115
- });
6116
- return;
6117
- }
6118
- applyStrategy(strategy);
6119
- });
5871
+ }
5872
+ if (typeof strategy === "function") {
5873
+ strategy(request, {
5874
+ warning: applyStrategy.bind(null, "warn"),
5875
+ error: applyStrategy.bind(null, "error")
5876
+ });
5877
+ return;
5878
+ }
5879
+ applyStrategy(strategy);
6120
5880
  }
6121
5881
 
6122
5882
  // src/core/utils/request/readResponseCookies.ts
6123
5883
  function readResponseCookies(request, response) {
6124
- store.add(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }), response);
5884
+ store.add({ ...request, url: request.url.toString() }, response);
6125
5885
  store.persist();
6126
5886
  }
6127
5887
 
6128
5888
  // src/core/utils/handleRequest.ts
6129
- function handleRequest(request, requestId, handlers, options, emitter, handleRequestOptions) {
6130
- return __async(this, null, function* () {
6131
- var _a3, _b2, _c, _d, _e, _f;
6132
- emitter.emit("request:start", { request, requestId });
6133
- if (request.headers.get("x-msw-intention") === "bypass") {
6134
- emitter.emit("request:end", { request, requestId });
6135
- (_a3 = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _a3.call(handleRequestOptions, request);
6136
- return;
6137
- }
6138
- const lookupResult = yield until(() => {
6139
- return getResponse(
6140
- request,
6141
- handlers,
6142
- handleRequestOptions == null ? void 0 : handleRequestOptions.resolutionContext
6143
- );
6144
- });
6145
- if (lookupResult.error) {
6146
- emitter.emit("unhandledException", {
6147
- error: lookupResult.error,
6148
- request,
6149
- requestId
6150
- });
6151
- throw lookupResult.error;
6152
- }
6153
- if (!lookupResult.data) {
6154
- yield onUnhandledRequest(request, handlers, options.onUnhandledRequest);
6155
- emitter.emit("request:unhandled", { request, requestId });
6156
- emitter.emit("request:end", { request, requestId });
6157
- (_b2 = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _b2.call(handleRequestOptions, request);
6158
- return;
6159
- }
6160
- const { response } = lookupResult.data;
6161
- if (!response) {
6162
- emitter.emit("request:end", { request, requestId });
6163
- (_c = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _c.call(handleRequestOptions, request);
6164
- return;
6165
- }
6166
- if (response.status === 302 && response.headers.get("x-msw-intention") === "passthrough") {
6167
- emitter.emit("request:end", { request, requestId });
6168
- (_d = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _d.call(handleRequestOptions, request);
6169
- return;
6170
- }
6171
- readResponseCookies(request, response);
6172
- emitter.emit("request:match", { request, requestId });
6173
- const requiredLookupResult = lookupResult.data;
6174
- const transformedResponse = ((_e = handleRequestOptions == null ? void 0 : handleRequestOptions.transformResponse) == null ? void 0 : _e.call(handleRequestOptions, response)) || response;
6175
- (_f = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponse) == null ? void 0 : _f.call(
6176
- handleRequestOptions,
6177
- transformedResponse,
6178
- requiredLookupResult
6179
- );
5889
+ async function handleRequest(request, requestId, handlers, options, emitter, handleRequestOptions) {
5890
+ emitter.emit("request:start", { request, requestId });
5891
+ if (request.headers.get("x-msw-intention") === "bypass") {
6180
5892
  emitter.emit("request:end", { request, requestId });
6181
- return transformedResponse;
5893
+ handleRequestOptions?.onPassthroughResponse?.(request);
5894
+ return;
5895
+ }
5896
+ const lookupResult = await until(() => {
5897
+ return getResponse({
5898
+ request,
5899
+ requestId,
5900
+ handlers,
5901
+ resolutionContext: handleRequestOptions?.resolutionContext
5902
+ });
6182
5903
  });
5904
+ if (lookupResult.error) {
5905
+ emitter.emit("unhandledException", {
5906
+ error: lookupResult.error,
5907
+ request,
5908
+ requestId
5909
+ });
5910
+ throw lookupResult.error;
5911
+ }
5912
+ if (!lookupResult.data) {
5913
+ await onUnhandledRequest(request, handlers, options.onUnhandledRequest);
5914
+ emitter.emit("request:unhandled", { request, requestId });
5915
+ emitter.emit("request:end", { request, requestId });
5916
+ handleRequestOptions?.onPassthroughResponse?.(request);
5917
+ return;
5918
+ }
5919
+ const { response } = lookupResult.data;
5920
+ if (!response) {
5921
+ emitter.emit("request:end", { request, requestId });
5922
+ handleRequestOptions?.onPassthroughResponse?.(request);
5923
+ return;
5924
+ }
5925
+ if (response.status === 302 && response.headers.get("x-msw-intention") === "passthrough") {
5926
+ emitter.emit("request:end", { request, requestId });
5927
+ handleRequestOptions?.onPassthroughResponse?.(request);
5928
+ return;
5929
+ }
5930
+ readResponseCookies(request, response);
5931
+ emitter.emit("request:match", { request, requestId });
5932
+ const requiredLookupResult = lookupResult.data;
5933
+ const transformedResponse = handleRequestOptions?.transformResponse?.(response) || response;
5934
+ handleRequestOptions?.onMockedResponse?.(
5935
+ transformedResponse,
5936
+ requiredLookupResult
5937
+ );
5938
+ emitter.emit("request:end", { request, requestId });
5939
+ return transformedResponse;
6183
5940
  }
6184
5941
 
6185
5942
  // src/core/utils/HttpResponse/decorators.ts
6186
5943
  var { message: message2 } = source_default;
6187
5944
  function normalizeResponseInit(init = {}) {
6188
- const status = (init == null ? void 0 : init.status) || 200;
6189
- const statusText = (init == null ? void 0 : init.statusText) || message2[status] || "";
6190
- const headers = new Headers(init == null ? void 0 : init.headers);
6191
- return __spreadProps(__spreadValues({}, init), {
5945
+ const status = init?.status || 200;
5946
+ const statusText = init?.statusText || message2[status] || "";
5947
+ const headers = new Headers(init?.headers);
5948
+ return {
5949
+ ...init,
6192
5950
  headers,
6193
5951
  status,
6194
5952
  statusText
6195
- });
5953
+ };
6196
5954
  }
6197
5955
  function decorateResponse(response, init) {
6198
- var _a3;
6199
5956
  if (init.type) {
6200
5957
  Object.defineProperty(response, "type", {
6201
5958
  value: init.type,
@@ -6204,7 +5961,7 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6204
5961
  });
6205
5962
  }
6206
5963
  if (typeof document !== "undefined") {
6207
- const responseCookies = ((_a3 = init.headers.get("Set-Cookie")) == null ? void 0 : _a3.split(",")) || [];
5964
+ const responseCookies = init.headers.get("Set-Cookie")?.split(",") || [];
6208
5965
  for (const cookieString of responseCookies) {
6209
5966
  document.cookie = cookieString;
6210
5967
  }
@@ -6303,37 +6060,35 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6303
6060
  Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
6304
6061
  );
6305
6062
  }
6306
- function delay(durationOrMode) {
6307
- return __async(this, null, function* () {
6308
- let delayTime;
6309
- if (typeof durationOrMode === "string") {
6310
- switch (durationOrMode) {
6311
- case "infinite": {
6312
- delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
6313
- break;
6314
- }
6315
- case "real": {
6316
- delayTime = getRealisticResponseTime();
6317
- break;
6318
- }
6319
- default: {
6320
- throw new Error(
6321
- `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
6322
- );
6323
- }
6063
+ async function delay(durationOrMode) {
6064
+ let delayTime;
6065
+ if (typeof durationOrMode === "string") {
6066
+ switch (durationOrMode) {
6067
+ case "infinite": {
6068
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
6069
+ break;
6324
6070
  }
6325
- } else if (typeof durationOrMode === "undefined") {
6326
- delayTime = getRealisticResponseTime();
6327
- } else {
6328
- if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
6071
+ case "real": {
6072
+ delayTime = getRealisticResponseTime();
6073
+ break;
6074
+ }
6075
+ default: {
6329
6076
  throw new Error(
6330
- `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
6077
+ `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
6331
6078
  );
6332
6079
  }
6333
- delayTime = durationOrMode;
6334
6080
  }
6335
- return new Promise((resolve) => setTimeout(resolve, delayTime));
6336
- });
6081
+ } else if (typeof durationOrMode === "undefined") {
6082
+ delayTime = getRealisticResponseTime();
6083
+ } else {
6084
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
6085
+ throw new Error(
6086
+ `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
6087
+ );
6088
+ }
6089
+ delayTime = durationOrMode;
6090
+ }
6091
+ return new Promise((resolve) => setTimeout(resolve, delayTime));
6337
6092
  }
6338
6093
 
6339
6094
  // src/core/bypass.ts
@@ -6386,9 +6141,9 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6386
6141
  }
6387
6142
 
6388
6143
  // src/browser/setupWorker/start/utils/getWorkerInstance.ts
6389
- var getWorkerInstance = (_0, ..._1) => __async(void 0, [_0, ..._1], function* (url, options = {}, findWorker) {
6144
+ var getWorkerInstance = async (url, options = {}, findWorker) => {
6390
6145
  const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
6391
- const mockRegistrations = yield navigator.serviceWorker.getRegistrations().then(
6146
+ const mockRegistrations = await navigator.serviceWorker.getRegistrations().then(
6392
6147
  (registrations) => registrations.filter(
6393
6148
  (registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker)
6394
6149
  )
@@ -6409,21 +6164,21 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6409
6164
  ];
6410
6165
  });
6411
6166
  }
6412
- const registrationResult = yield until(
6413
- () => __async(void 0, null, function* () {
6414
- const registration = yield navigator.serviceWorker.register(url, options);
6167
+ const registrationResult = await until(
6168
+ async () => {
6169
+ const registration = await navigator.serviceWorker.register(url, options);
6415
6170
  return [
6416
6171
  // Compare existing worker registration by its worker URL,
6417
6172
  // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
6418
6173
  getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
6419
6174
  registration
6420
6175
  ];
6421
- })
6176
+ }
6422
6177
  );
6423
6178
  if (registrationResult.error) {
6424
6179
  const isWorkerMissing = registrationResult.error.message.includes("(404)");
6425
6180
  if (isWorkerMissing) {
6426
- const scopeUrl = new URL((options == null ? void 0 : options.scope) || "/", location.href);
6181
+ const scopeUrl = new URL(options?.scope || "/", location.href);
6427
6182
  throw new Error(
6428
6183
  devUtils.formatMessage(`Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
6429
6184
 
@@ -6440,7 +6195,7 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6440
6195
  );
6441
6196
  }
6442
6197
  return registrationResult.data;
6443
- });
6198
+ };
6444
6199
 
6445
6200
  // src/browser/setupWorker/start/utils/printStartMessage.ts
6446
6201
  function printStartMessage(args = {}) {
@@ -6468,23 +6223,20 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6468
6223
  }
6469
6224
 
6470
6225
  // src/browser/setupWorker/start/utils/enableMocking.ts
6471
- function enableMocking(context, options) {
6472
- return __async(this, null, function* () {
6473
- var _a3, _b2;
6474
- context.workerChannel.send("MOCK_ACTIVATE");
6475
- yield context.events.once("MOCKING_ENABLED");
6476
- if (context.isMockingEnabled) {
6477
- devUtils.warn(
6478
- `Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`
6479
- );
6480
- return;
6481
- }
6482
- context.isMockingEnabled = true;
6483
- printStartMessage({
6484
- quiet: options.quiet,
6485
- workerScope: (_a3 = context.registration) == null ? void 0 : _a3.scope,
6486
- workerUrl: (_b2 = context.worker) == null ? void 0 : _b2.scriptURL
6487
- });
6226
+ async function enableMocking(context, options) {
6227
+ context.workerChannel.send("MOCK_ACTIVATE");
6228
+ await context.events.once("MOCKING_ENABLED");
6229
+ if (context.isMockingEnabled) {
6230
+ devUtils.warn(
6231
+ `Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`
6232
+ );
6233
+ return;
6234
+ }
6235
+ context.isMockingEnabled = true;
6236
+ printStartMessage({
6237
+ quiet: options.quiet,
6238
+ workerScope: context.registration?.scope,
6239
+ workerUrl: context.worker?.scriptURL
6488
6240
  });
6489
6241
  }
6490
6242
 
@@ -6509,9 +6261,10 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6509
6261
 
6510
6262
  // src/browser/utils/parseWorkerRequest.ts
6511
6263
  function parseWorkerRequest(incomingRequest) {
6512
- return new Request(incomingRequest.url, __spreadProps(__spreadValues({}, incomingRequest), {
6264
+ return new Request(incomingRequest.url, {
6265
+ ...incomingRequest,
6513
6266
  body: pruneGetRequestBody(incomingRequest)
6514
- }));
6267
+ });
6515
6268
  }
6516
6269
 
6517
6270
  // src/core/utils/toResponseInit.ts
@@ -6525,15 +6278,13 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6525
6278
 
6526
6279
  // src/browser/setupWorker/start/createRequestListener.ts
6527
6280
  var createRequestListener = (context, options) => {
6528
- return (event, message3) => __async(void 0, null, function* () {
6529
- var _b2;
6281
+ return async (event, message3) => {
6530
6282
  const messageChannel = new WorkerChannel(event.ports[0]);
6531
6283
  const requestId = message3.payload.id;
6532
6284
  const request = parseWorkerRequest(message3.payload);
6533
6285
  const requestCloneForLogs = request.clone();
6534
6286
  try {
6535
- let _a3;
6536
- yield handleRequest(
6287
+ await handleRequest(
6537
6288
  request,
6538
6289
  requestId,
6539
6290
  context.requestHandlers,
@@ -6543,36 +6294,36 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6543
6294
  onPassthroughResponse() {
6544
6295
  messageChannel.postMessage("NOT_FOUND");
6545
6296
  },
6546
- onMockedResponse(_0, _1) {
6547
- return __async(this, arguments, function* (response, { handler, parsedResult }) {
6548
- const responseClone = response.clone();
6549
- const responseCloneForLogs = response.clone();
6550
- const responseInit = toResponseInit(response);
6551
- if (context.supports.readableStreamTransfer) {
6552
- const responseStreamOrNull = response.body;
6553
- messageChannel.postMessage(
6554
- "MOCK_RESPONSE",
6555
- __spreadProps(__spreadValues({}, responseInit), {
6556
- body: responseStreamOrNull
6557
- }),
6558
- responseStreamOrNull ? [responseStreamOrNull] : void 0
6559
- );
6560
- } else {
6561
- const responseBufferOrNull = response.body === null ? null : yield responseClone.arrayBuffer();
6562
- messageChannel.postMessage("MOCK_RESPONSE", __spreadProps(__spreadValues({}, responseInit), {
6563
- body: responseBufferOrNull
6564
- }));
6565
- }
6566
- if (!options.quiet) {
6567
- context.emitter.once("response:mocked", () => {
6568
- handler.log({
6569
- request: requestCloneForLogs,
6570
- response: responseCloneForLogs,
6571
- parsedResult
6572
- });
6297
+ async onMockedResponse(response, { handler, parsedResult }) {
6298
+ const responseClone = response.clone();
6299
+ const responseCloneForLogs = response.clone();
6300
+ const responseInit = toResponseInit(response);
6301
+ if (context.supports.readableStreamTransfer) {
6302
+ const responseStreamOrNull = response.body;
6303
+ messageChannel.postMessage(
6304
+ "MOCK_RESPONSE",
6305
+ {
6306
+ ...responseInit,
6307
+ body: responseStreamOrNull
6308
+ },
6309
+ responseStreamOrNull ? [responseStreamOrNull] : void 0
6310
+ );
6311
+ } else {
6312
+ const responseBufferOrNull = response.body === null ? null : await responseClone.arrayBuffer();
6313
+ messageChannel.postMessage("MOCK_RESPONSE", {
6314
+ ...responseInit,
6315
+ body: responseBufferOrNull
6316
+ });
6317
+ }
6318
+ if (!options.quiet) {
6319
+ context.emitter.once("response:mocked", () => {
6320
+ handler.log({
6321
+ request: requestCloneForLogs,
6322
+ response: responseCloneForLogs,
6323
+ parsedResult
6573
6324
  });
6574
- }
6575
- });
6325
+ });
6326
+ }
6576
6327
  }
6577
6328
  }
6578
6329
  );
@@ -6586,7 +6337,7 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6586
6337
  This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses`,
6587
6338
  request.method,
6588
6339
  request.url,
6589
- (_b2 = error3.stack) != null ? _b2 : error3
6340
+ error3.stack ?? error3
6590
6341
  );
6591
6342
  messageChannel.postMessage("MOCK_RESPONSE", {
6592
6343
  status: 500,
@@ -6602,48 +6353,28 @@ This exception has been gracefully handled as a 500 response, however, it's stro
6602
6353
  });
6603
6354
  }
6604
6355
  }
6605
- });
6356
+ };
6606
6357
  };
6607
6358
 
6608
6359
  // src/browser/utils/requestIntegrityCheck.ts
6609
- function requestIntegrityCheck(context, serviceWorker) {
6610
- return __async(this, null, function* () {
6611
- context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
6612
- const { payload: actualChecksum } = yield context.events.once(
6613
- "INTEGRITY_CHECK_RESPONSE"
6360
+ async function requestIntegrityCheck(context, serviceWorker) {
6361
+ context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
6362
+ const { payload: actualChecksum } = await context.events.once(
6363
+ "INTEGRITY_CHECK_RESPONSE"
6364
+ );
6365
+ if (actualChecksum !== "223d191a56023cd36aa88c802961b911") {
6366
+ throw new Error(
6367
+ `Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"223d191a56023cd36aa88c802961b911"}).`
6614
6368
  );
6615
- if (actualChecksum !== "c5f7f8e188b673ea4e677df7ea3c5a39") {
6616
- throw new Error(
6617
- `Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"c5f7f8e188b673ea4e677df7ea3c5a39"}).`
6618
- );
6619
- }
6620
- return serviceWorker;
6621
- });
6622
- }
6623
-
6624
- // src/browser/utils/deferNetworkRequestsUntil.ts
6625
- function deferNetworkRequestsUntil(predicatePromise) {
6626
- const originalXhrSend = window.XMLHttpRequest.prototype.send;
6627
- window.XMLHttpRequest.prototype.send = function(...args) {
6628
- until(() => predicatePromise).then(() => {
6629
- window.XMLHttpRequest.prototype.send = originalXhrSend;
6630
- this.send(...args);
6631
- });
6632
- };
6633
- const originalFetch = window.fetch;
6634
- window.fetch = (...args) => __async(this, null, function* () {
6635
- yield until(() => predicatePromise);
6636
- window.fetch = originalFetch;
6637
- return window.fetch(...args);
6638
- });
6369
+ }
6370
+ return serviceWorker;
6639
6371
  }
6640
6372
 
6641
6373
  // src/browser/setupWorker/start/createResponseListener.ts
6642
6374
  function createResponseListener(context) {
6643
6375
  return (_, message3) => {
6644
- var _a3;
6645
6376
  const { payload: responseJson } = message3;
6646
- if ((_a3 = responseJson.type) == null ? void 0 : _a3.includes("opaque")) {
6377
+ if (responseJson.type?.includes("opaque")) {
6647
6378
  return;
6648
6379
  }
6649
6380
  const response = responseJson.status === 0 ? Response.error() : new Response(
@@ -6673,7 +6404,7 @@ This exception has been gracefully handled as a 500 response, however, it's stro
6673
6404
 
6674
6405
  // src/browser/setupWorker/start/utils/validateWorkerScope.ts
6675
6406
  function validateWorkerScope(registration, options) {
6676
- if (!(options == null ? void 0 : options.quiet) && !location.href.startsWith(registration.scope)) {
6407
+ if (!options?.quiet && !location.href.startsWith(registration.scope)) {
6677
6408
  devUtils.warn(
6678
6409
  `Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue.
6679
6410
 
@@ -6686,21 +6417,21 @@ This exception has been gracefully handled as a 500 response, however, it's stro
6686
6417
  // src/browser/setupWorker/start/createStartHandler.ts
6687
6418
  var createStartHandler = (context) => {
6688
6419
  return function start(options, customOptions) {
6689
- const startWorkerInstance = () => __async(this, null, function* () {
6420
+ const startWorkerInstance = async () => {
6690
6421
  context.events.removeAllListeners();
6691
6422
  context.workerChannel.on(
6692
6423
  "REQUEST",
6693
6424
  createRequestListener(context, options)
6694
6425
  );
6695
6426
  context.workerChannel.on("RESPONSE", createResponseListener(context));
6696
- const instance = yield getWorkerInstance(
6427
+ const instance = await getWorkerInstance(
6697
6428
  options.serviceWorker.url,
6698
6429
  options.serviceWorker.options,
6699
6430
  options.findWorker
6700
6431
  );
6701
6432
  const [worker, registration] = instance;
6702
6433
  if (!worker) {
6703
- const missingWorkerMessage = (customOptions == null ? void 0 : customOptions.findWorker) ? devUtils.formatMessage(
6434
+ const missingWorkerMessage = customOptions?.findWorker ? devUtils.formatMessage(
6704
6435
  `Failed to locate the Service Worker registration using a custom "findWorker" predicate.
6705
6436
 
6706
6437
  Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
@@ -6726,7 +6457,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
6726
6457
  }
6727
6458
  window.clearInterval(context.keepAliveInterval);
6728
6459
  });
6729
- const integrityCheckResult = yield until(
6460
+ const integrityCheckResult = await until(
6730
6461
  () => requestIntegrityCheck(context, worker)
6731
6462
  );
6732
6463
  if (integrityCheckResult.error) {
@@ -6745,12 +6476,12 @@ If this message still persists after updating, please report an issue: https://g
6745
6476
  );
6746
6477
  validateWorkerScope(registration, context.startOptions);
6747
6478
  return registration;
6748
- });
6479
+ };
6749
6480
  const workerRegistration = startWorkerInstance().then(
6750
- (registration) => __async(this, null, function* () {
6481
+ async (registration) => {
6751
6482
  const pendingInstance = registration.installing || registration.waiting;
6752
6483
  if (pendingInstance) {
6753
- yield new Promise((resolve) => {
6484
+ await new Promise((resolve) => {
6754
6485
  pendingInstance.addEventListener("statechange", () => {
6755
6486
  if (pendingInstance.state === "activated") {
6756
6487
  return resolve();
@@ -6758,15 +6489,12 @@ If this message still persists after updating, please report an issue: https://g
6758
6489
  });
6759
6490
  });
6760
6491
  }
6761
- yield enableMocking(context, options).catch((error3) => {
6762
- throw new Error(`Failed to enable mocking: ${error3 == null ? void 0 : error3.message}`);
6492
+ await enableMocking(context, options).catch((error3) => {
6493
+ throw new Error(`Failed to enable mocking: ${error3?.message}`);
6763
6494
  });
6764
6495
  return registration;
6765
- })
6496
+ }
6766
6497
  );
6767
- if (options.waitUntilReady) {
6768
- deferNetworkRequestsUntil(workerRegistration);
6769
- }
6770
6498
  return workerRegistration;
6771
6499
  };
6772
6500
  };
@@ -6785,7 +6513,6 @@ If this message still persists after updating, please report an issue: https://g
6785
6513
  // src/browser/setupWorker/stop/createStop.ts
6786
6514
  var createStop = (context) => {
6787
6515
  return function stop() {
6788
- var _a3;
6789
6516
  if (!context.isMockingEnabled) {
6790
6517
  devUtils.warn(
6791
6518
  'Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.'
@@ -6795,7 +6522,7 @@ If this message still persists after updating, please report an issue: https://g
6795
6522
  context.workerChannel.send("MOCK_DEACTIVATE");
6796
6523
  context.isMockingEnabled = false;
6797
6524
  window.clearInterval(context.keepAliveInterval);
6798
- printStopMessage({ quiet: (_a3 = context.startOptions) == null ? void 0 : _a3.quiet });
6525
+ printStopMessage({ quiet: context.startOptions?.quiet });
6799
6526
  };
6800
6527
  };
6801
6528
 
@@ -6864,43 +6591,42 @@ If this message still persists after updating, please report an issue: https://g
6864
6591
  };
6865
6592
  return executor;
6866
6593
  }
6867
- var _executor, _decorate, decorate_fn, _a2;
6868
- var DeferredPromise = (_a2 = class extends Promise {
6594
+ var DeferredPromise = class extends Promise {
6595
+ #executor;
6596
+ resolve;
6597
+ reject;
6869
6598
  constructor(executor = null) {
6870
6599
  const deferredExecutor = createDeferredExecutor();
6871
6600
  super((originalResolve, originalReject) => {
6872
6601
  deferredExecutor(originalResolve, originalReject);
6873
- executor == null ? void 0 : executor(deferredExecutor.resolve, deferredExecutor.reject);
6602
+ executor?.(deferredExecutor.resolve, deferredExecutor.reject);
6874
6603
  });
6875
- __privateAdd(this, _decorate);
6876
- __privateAdd(this, _executor, void 0);
6877
- __publicField(this, "resolve");
6878
- __publicField(this, "reject");
6879
- __privateSet(this, _executor, deferredExecutor);
6880
- this.resolve = __privateGet(this, _executor).resolve;
6881
- this.reject = __privateGet(this, _executor).reject;
6604
+ this.#executor = deferredExecutor;
6605
+ this.resolve = this.#executor.resolve;
6606
+ this.reject = this.#executor.reject;
6882
6607
  }
6883
6608
  get state() {
6884
- return __privateGet(this, _executor).state;
6609
+ return this.#executor.state;
6885
6610
  }
6886
6611
  get rejectionReason() {
6887
- return __privateGet(this, _executor).rejectionReason;
6612
+ return this.#executor.rejectionReason;
6888
6613
  }
6889
6614
  then(onFulfilled, onRejected) {
6890
- return __privateMethod(this, _decorate, decorate_fn).call(this, super.then(onFulfilled, onRejected));
6615
+ return this.#decorate(super.then(onFulfilled, onRejected));
6891
6616
  }
6892
6617
  catch(onRejected) {
6893
- return __privateMethod(this, _decorate, decorate_fn).call(this, super.catch(onRejected));
6618
+ return this.#decorate(super.catch(onRejected));
6894
6619
  }
6895
6620
  finally(onfinally) {
6896
- return __privateMethod(this, _decorate, decorate_fn).call(this, super.finally(onfinally));
6621
+ return this.#decorate(super.finally(onfinally));
6897
6622
  }
6898
- }, _executor = new WeakMap(), _decorate = new WeakSet(), decorate_fn = function(promise) {
6899
- return Object.defineProperties(promise, {
6900
- resolve: { configurable: true, value: this.resolve },
6901
- reject: { configurable: true, value: this.reject }
6902
- });
6903
- }, _a2);
6623
+ #decorate(promise) {
6624
+ return Object.defineProperties(promise, {
6625
+ resolve: { configurable: true, value: this.resolve },
6626
+ reject: { configurable: true, value: this.reject }
6627
+ });
6628
+ }
6629
+ };
6904
6630
 
6905
6631
  // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-72HT65NX.mjs
6906
6632
  function uuidv4() {
@@ -6937,16 +6663,14 @@ If this message still persists after updating, please report an issue: https://g
6937
6663
  requestController
6938
6664
  };
6939
6665
  }
6940
- function emitAsync(emitter, eventName, ...data) {
6941
- return __async(this, null, function* () {
6942
- const listners = emitter.listeners(eventName);
6943
- if (listners.length === 0) {
6944
- return;
6945
- }
6946
- for (const listener of listners) {
6947
- yield listener.apply(emitter, data);
6948
- }
6949
- });
6666
+ async function emitAsync(emitter, eventName, ...data) {
6667
+ const listners = emitter.listeners(eventName);
6668
+ if (listners.length === 0) {
6669
+ return;
6670
+ }
6671
+ for (const listener of listners) {
6672
+ await listener.apply(emitter, data);
6673
+ }
6950
6674
  }
6951
6675
 
6952
6676
  // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-KDHQ3KDO.mjs
@@ -6971,8 +6695,8 @@ If this message still persists after updating, please report an issue: https://g
6971
6695
  !pureFetch[IS_PATCHED_MODULE],
6972
6696
  'Failed to patch the "fetch" module: already patched.'
6973
6697
  );
6974
- globalThis.fetch = (input, init) => __async(this, null, function* () {
6975
- var _a3;
6698
+ globalThis.fetch = async (input, init) => {
6699
+ var _a2;
6976
6700
  const requestId = uuidv4();
6977
6701
  const request = new Request(input, init);
6978
6702
  this.logger.info("[%s] %s", request.method, request.url);
@@ -6999,12 +6723,12 @@ If this message still persists after updating, please report an issue: https://g
6999
6723
  },
7000
6724
  { once: true }
7001
6725
  );
7002
- const resolverResult = yield until(() => __async(this, null, function* () {
6726
+ const resolverResult = await until(async () => {
7003
6727
  const listenersFinished = emitAsync(this.emitter, "request", {
7004
6728
  request: interactiveRequest,
7005
6729
  requestId
7006
6730
  });
7007
- yield Promise.race([
6731
+ await Promise.race([
7008
6732
  requestAborted,
7009
6733
  // Put the listeners invocation Promise in the same race condition
7010
6734
  // with the request abort Promise because otherwise awaiting the listeners
@@ -7013,10 +6737,10 @@ If this message still persists after updating, please report an issue: https://g
7013
6737
  requestController.responsePromise
7014
6738
  ]);
7015
6739
  this.logger.info("all request listeners have been resolved!");
7016
- const mockedResponse2 = yield requestController.responsePromise;
6740
+ const mockedResponse2 = await requestController.responsePromise;
7017
6741
  this.logger.info("event.respondWith called with:", mockedResponse2);
7018
6742
  return mockedResponse2;
7019
- }));
6743
+ });
7020
6744
  if (requestAborted.state === "rejected") {
7021
6745
  return Promise.reject(requestAborted.rejectionReason);
7022
6746
  }
@@ -7024,7 +6748,7 @@ If this message still persists after updating, please report an issue: https://g
7024
6748
  return Promise.reject(createNetworkError(resolverResult.error));
7025
6749
  }
7026
6750
  const mockedResponse = resolverResult.data;
7027
- if (mockedResponse && !((_a3 = request.signal) == null ? void 0 : _a3.aborted)) {
6751
+ if (mockedResponse && !((_a2 = request.signal) == null ? void 0 : _a2.aborted)) {
7028
6752
  this.logger.info("received mocked response:", mockedResponse);
7029
6753
  if (isPropertyAccessible2(mockedResponse, "type") && mockedResponse.type === "error") {
7030
6754
  this.logger.info(
@@ -7060,7 +6784,7 @@ If this message still persists after updating, please report an issue: https://g
7060
6784
  });
7061
6785
  return response;
7062
6786
  });
7063
- });
6787
+ };
7064
6788
  Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
7065
6789
  enumerable: true,
7066
6790
  configurable: true,
@@ -7299,7 +7023,7 @@ If this message still persists after updating, please report an issue: https://g
7299
7023
  }
7300
7024
  },
7301
7025
  methodCall: ([methodName, args], invoke) => {
7302
- var _a3;
7026
+ var _a2;
7303
7027
  switch (methodName) {
7304
7028
  case "open": {
7305
7029
  const [method, url] = args;
@@ -7351,7 +7075,7 @@ If this message still persists after updating, please report an issue: https://g
7351
7075
  }
7352
7076
  });
7353
7077
  const fetchRequest = this.toFetchApiRequest();
7354
- const onceRequestSettled = ((_a3 = this.onRequest) == null ? void 0 : _a3.call(this, {
7078
+ const onceRequestSettled = ((_a2 = this.onRequest) == null ? void 0 : _a2.call(this, {
7355
7079
  request: fetchRequest,
7356
7080
  requestId: this.requestId
7357
7081
  })) || Promise.resolve();
@@ -7475,8 +7199,8 @@ If this message still persists after updating, please report an issue: https://g
7475
7199
  if (response.body) {
7476
7200
  this.logger.info("mocked response has body, streaming...");
7477
7201
  const reader = response.body.getReader();
7478
- const readNextResponseBodyChunk = () => __async(this, null, function* () {
7479
- const { value, done } = yield reader.read();
7202
+ const readNextResponseBodyChunk = async () => {
7203
+ const { value, done } = await reader.read();
7480
7204
  if (done) {
7481
7205
  this.logger.info("response body stream done!");
7482
7206
  finalizeResponse();
@@ -7491,7 +7215,7 @@ If this message still persists after updating, please report an issue: https://g
7491
7215
  });
7492
7216
  }
7493
7217
  readNextResponseBodyChunk();
7494
- });
7218
+ };
7495
7219
  readNextResponseBodyChunk();
7496
7220
  } else {
7497
7221
  finalizeResponse();
@@ -7700,78 +7424,74 @@ If this message still persists after updating, please report an issue: https://g
7700
7424
  originalRequest,
7701
7425
  logger
7702
7426
  );
7703
- xhrRequestController.onRequest = function(_0) {
7704
- return __async(this, arguments, function* ({ request, requestId }) {
7705
- const { interactiveRequest, requestController } = toInteractiveRequest(request);
7706
- this.logger.info("awaiting mocked response...");
7707
- emitter.once("request", ({ requestId: pendingRequestId }) => {
7708
- if (pendingRequestId !== requestId) {
7709
- return;
7710
- }
7711
- if (requestController.responsePromise.state === "pending") {
7712
- requestController.respondWith(void 0);
7713
- }
7714
- });
7715
- const resolverResult = yield until(() => __async(this, null, function* () {
7716
- this.logger.info(
7717
- 'emitting the "request" event for %s listener(s)...',
7718
- emitter.listenerCount("request")
7719
- );
7720
- yield emitAsync(emitter, "request", {
7721
- request: interactiveRequest,
7722
- requestId
7723
- });
7724
- this.logger.info('all "request" listeners settled!');
7725
- const mockedResponse2 = yield requestController.responsePromise;
7726
- this.logger.info("event.respondWith called with:", mockedResponse2);
7727
- return mockedResponse2;
7728
- }));
7729
- if (resolverResult.error) {
7730
- this.logger.info(
7731
- "request listener threw an exception, aborting request...",
7732
- resolverResult.error
7733
- );
7734
- xhrRequestController.errorWith(resolverResult.error);
7427
+ xhrRequestController.onRequest = async function({ request, requestId }) {
7428
+ const { interactiveRequest, requestController } = toInteractiveRequest(request);
7429
+ this.logger.info("awaiting mocked response...");
7430
+ emitter.once("request", ({ requestId: pendingRequestId }) => {
7431
+ if (pendingRequestId !== requestId) {
7735
7432
  return;
7736
7433
  }
7737
- const mockedResponse = resolverResult.data;
7738
- if (typeof mockedResponse !== "undefined") {
7739
- this.logger.info(
7740
- "received mocked response: %d %s",
7741
- mockedResponse.status,
7742
- mockedResponse.statusText
7743
- );
7744
- if (mockedResponse.type === "error") {
7745
- this.logger.info(
7746
- "received a network error response, rejecting the request promise..."
7747
- );
7748
- xhrRequestController.errorWith(new TypeError("Network error"));
7749
- return;
7750
- }
7751
- return xhrRequestController.respondWith(mockedResponse);
7434
+ if (requestController.responsePromise.state === "pending") {
7435
+ requestController.respondWith(void 0);
7752
7436
  }
7437
+ });
7438
+ const resolverResult = await until(async () => {
7753
7439
  this.logger.info(
7754
- "no mocked response received, performing request as-is..."
7440
+ 'emitting the "request" event for %s listener(s)...',
7441
+ emitter.listenerCount("request")
7755
7442
  );
7443
+ await emitAsync(emitter, "request", {
7444
+ request: interactiveRequest,
7445
+ requestId
7446
+ });
7447
+ this.logger.info('all "request" listeners settled!');
7448
+ const mockedResponse2 = await requestController.responsePromise;
7449
+ this.logger.info("event.respondWith called with:", mockedResponse2);
7450
+ return mockedResponse2;
7756
7451
  });
7452
+ if (resolverResult.error) {
7453
+ this.logger.info(
7454
+ "request listener threw an exception, aborting request...",
7455
+ resolverResult.error
7456
+ );
7457
+ xhrRequestController.errorWith(resolverResult.error);
7458
+ return;
7459
+ }
7460
+ const mockedResponse = resolverResult.data;
7461
+ if (typeof mockedResponse !== "undefined") {
7462
+ this.logger.info(
7463
+ "received mocked response: %d %s",
7464
+ mockedResponse.status,
7465
+ mockedResponse.statusText
7466
+ );
7467
+ if (mockedResponse.type === "error") {
7468
+ this.logger.info(
7469
+ "received a network error response, rejecting the request promise..."
7470
+ );
7471
+ xhrRequestController.errorWith(new TypeError("Network error"));
7472
+ return;
7473
+ }
7474
+ return xhrRequestController.respondWith(mockedResponse);
7475
+ }
7476
+ this.logger.info(
7477
+ "no mocked response received, performing request as-is..."
7478
+ );
7757
7479
  };
7758
- xhrRequestController.onResponse = function(_0) {
7759
- return __async(this, arguments, function* ({
7480
+ xhrRequestController.onResponse = async function({
7481
+ response,
7482
+ isMockedResponse,
7483
+ request,
7484
+ requestId
7485
+ }) {
7486
+ this.logger.info(
7487
+ 'emitting the "response" event for %s listener(s)...',
7488
+ emitter.listenerCount("response")
7489
+ );
7490
+ emitter.emit("response", {
7760
7491
  response,
7761
7492
  isMockedResponse,
7762
7493
  request,
7763
7494
  requestId
7764
- }) {
7765
- this.logger.info(
7766
- 'emitting the "response" event for %s listener(s)...',
7767
- emitter.listenerCount("response")
7768
- );
7769
- emitter.emit("response", {
7770
- response,
7771
- isMockedResponse,
7772
- request,
7773
- requestId
7774
- });
7775
7495
  });
7776
7496
  };
7777
7497
  return xhrRequestController.request;
@@ -7828,9 +7548,9 @@ If this message still persists after updating, please report an issue: https://g
7828
7548
  name: "fallback",
7829
7549
  interceptors: [new FetchInterceptor(), new XMLHttpRequestInterceptor()]
7830
7550
  });
7831
- interceptor.on("request", (_0) => __async(this, [_0], function* ({ request, requestId }) {
7551
+ interceptor.on("request", async ({ request, requestId }) => {
7832
7552
  const requestCloneForLogs = request.clone();
7833
- const response = yield handleRequest(
7553
+ const response = await handleRequest(
7834
7554
  request,
7835
7555
  requestId,
7836
7556
  context.requestHandlers,
@@ -7853,7 +7573,7 @@ If this message still persists after updating, please report an issue: https://g
7853
7573
  if (response) {
7854
7574
  request.respondWith(response);
7855
7575
  }
7856
- }));
7576
+ });
7857
7577
  interceptor.on(
7858
7578
  "response",
7859
7579
  ({ response, isMockedResponse, request, requestId }) => {
@@ -7873,27 +7593,24 @@ If this message still persists after updating, please report an issue: https://g
7873
7593
 
7874
7594
  // src/browser/setupWorker/start/createFallbackStart.ts
7875
7595
  function createFallbackStart(context) {
7876
- return function start(options) {
7877
- return __async(this, null, function* () {
7878
- context.fallbackInterceptor = createFallbackRequestListener(
7879
- context,
7880
- options
7881
- );
7882
- printStartMessage({
7883
- message: "Mocking enabled (fallback mode).",
7884
- quiet: options.quiet
7885
- });
7886
- return void 0;
7596
+ return async function start(options) {
7597
+ context.fallbackInterceptor = createFallbackRequestListener(
7598
+ context,
7599
+ options
7600
+ );
7601
+ printStartMessage({
7602
+ message: "Mocking enabled (fallback mode).",
7603
+ quiet: options.quiet
7887
7604
  });
7605
+ return void 0;
7888
7606
  };
7889
7607
  }
7890
7608
 
7891
7609
  // src/browser/setupWorker/stop/createFallbackStop.ts
7892
7610
  function createFallbackStop(context) {
7893
7611
  return function stop() {
7894
- var _a3, _b2;
7895
- (_a3 = context.fallbackInterceptor) == null ? void 0 : _a3.dispose();
7896
- printStopMessage({ quiet: (_b2 = context.startOptions) == null ? void 0 : _b2.quiet });
7612
+ context.fallbackInterceptor?.dispose();
7613
+ printStopMessage({ quiet: context.startOptions?.quiet });
7897
7614
  };
7898
7615
  }
7899
7616
 
@@ -7913,10 +7630,12 @@ If this message still persists after updating, please report an issue: https://g
7913
7630
 
7914
7631
  // src/browser/setupWorker/setupWorker.ts
7915
7632
  var SetupWorkerApi = class extends SetupApi {
7633
+ context;
7634
+ startHandler = null;
7635
+ stopHandler = null;
7636
+ listeners;
7916
7637
  constructor(...handlers) {
7917
7638
  super(...handlers);
7918
- this.startHandler = null;
7919
- this.stopHandler = null;
7920
7639
  invariant(
7921
7640
  !isNodeProcess(),
7922
7641
  devUtils.formatMessage(
@@ -7952,8 +7671,7 @@ If this message still persists after updating, please report an issue: https://g
7952
7671
  });
7953
7672
  },
7954
7673
  send: (type) => {
7955
- var _a3;
7956
- (_a3 = this.context.worker) == null ? void 0 : _a3.postMessage(type);
7674
+ this.context.worker?.postMessage(type);
7957
7675
  }
7958
7676
  },
7959
7677
  events: {
@@ -8018,14 +7736,17 @@ If this message still persists after updating, please report an issue: https://g
8018
7736
  this.stopHandler = context.supports.serviceWorkerApi ? createFallbackStop(context) : createStop(context);
8019
7737
  return context;
8020
7738
  }
8021
- start() {
8022
- return __async(this, arguments, function* (options = {}) {
8023
- this.context.startOptions = mergeRight(
8024
- DEFAULT_START_OPTIONS,
8025
- options
7739
+ async start(options = {}) {
7740
+ if (options.waitUntilReady === true) {
7741
+ devUtils.warn(
7742
+ 'The "waitUntilReady" option has been deprecated. Please remove it from this "worker.start()" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.'
8026
7743
  );
8027
- return yield this.startHandler(this.context.startOptions, options);
8028
- });
7744
+ }
7745
+ this.context.startOptions = mergeRight(
7746
+ DEFAULT_START_OPTIONS,
7747
+ options
7748
+ );
7749
+ return await this.startHandler(this.context.startOptions, options);
8029
7750
  }
8030
7751
  stop() {
8031
7752
  super.dispose();