msw 2.11.1 → 2.11.3

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 (72) hide show
  1. package/lib/browser/index.d.mts +0 -3
  2. package/lib/browser/index.d.ts +0 -3
  3. package/lib/browser/index.js +536 -318
  4. package/lib/browser/index.js.map +1 -1
  5. package/lib/browser/index.mjs +536 -318
  6. package/lib/browser/index.mjs.map +1 -1
  7. package/lib/core/handlers/GraphQLHandler.js.map +1 -1
  8. package/lib/core/handlers/GraphQLHandler.mjs.map +1 -1
  9. package/lib/core/handlers/HttpHandler.js.map +1 -1
  10. package/lib/core/handlers/HttpHandler.mjs.map +1 -1
  11. package/lib/core/utils/handleRequest.js +8 -8
  12. package/lib/core/utils/handleRequest.js.map +1 -1
  13. package/lib/core/utils/handleRequest.mjs +8 -8
  14. package/lib/core/utils/handleRequest.mjs.map +1 -1
  15. package/lib/core/utils/internal/devUtils.js.map +1 -1
  16. package/lib/core/utils/internal/devUtils.mjs.map +1 -1
  17. package/lib/core/utils/internal/getCallFrame.js +2 -2
  18. package/lib/core/utils/internal/getCallFrame.js.map +1 -1
  19. package/lib/core/utils/internal/getCallFrame.mjs +2 -2
  20. package/lib/core/utils/internal/getCallFrame.mjs.map +1 -1
  21. package/lib/core/utils/internal/parseGraphQLRequest.js +1 -0
  22. package/lib/core/utils/internal/parseGraphQLRequest.js.map +1 -1
  23. package/lib/core/utils/internal/parseGraphQLRequest.mjs +1 -0
  24. package/lib/core/utils/internal/parseGraphQLRequest.mjs.map +1 -1
  25. package/lib/core/utils/matching/matchRequestUrl.js +1 -1
  26. package/lib/core/utils/matching/matchRequestUrl.js.map +1 -1
  27. package/lib/core/utils/matching/matchRequestUrl.mjs +1 -1
  28. package/lib/core/utils/matching/matchRequestUrl.mjs.map +1 -1
  29. package/lib/core/utils/url/cleanUrl.js +1 -1
  30. package/lib/core/utils/url/cleanUrl.js.map +1 -1
  31. package/lib/core/utils/url/cleanUrl.mjs +1 -1
  32. package/lib/core/utils/url/cleanUrl.mjs.map +1 -1
  33. package/lib/core/utils/url/isAbsoluteUrl.js +1 -1
  34. package/lib/core/utils/url/isAbsoluteUrl.js.map +1 -1
  35. package/lib/core/utils/url/isAbsoluteUrl.mjs +1 -1
  36. package/lib/core/utils/url/isAbsoluteUrl.mjs.map +1 -1
  37. package/lib/core/ws/WebSocketIndexedDBClientStore.js.map +1 -1
  38. package/lib/core/ws/WebSocketIndexedDBClientStore.mjs.map +1 -1
  39. package/lib/core/ws/utils/attachWebSocketLogger.js.map +1 -1
  40. package/lib/core/ws/utils/attachWebSocketLogger.mjs.map +1 -1
  41. package/lib/iife/index.js +2536 -2314
  42. package/lib/iife/index.js.map +1 -1
  43. package/lib/mockServiceWorker.js +16 -12
  44. package/package.json +22 -15
  45. package/src/browser/setupWorker/glossary.ts +9 -114
  46. package/src/browser/setupWorker/setupWorker.ts +82 -119
  47. package/src/browser/setupWorker/start/createRequestListener.ts +20 -24
  48. package/src/browser/setupWorker/start/createResponseListener.ts +15 -22
  49. package/src/browser/setupWorker/start/createStartHandler.ts +24 -18
  50. package/src/browser/setupWorker/start/utils/enableMocking.ts +18 -21
  51. package/src/browser/setupWorker/start/utils/getWorkerInstance.ts +17 -16
  52. package/src/browser/setupWorker/start/utils/printStartMessage.ts +0 -2
  53. package/src/browser/utils/checkWorkerIntegrity.ts +22 -14
  54. package/src/browser/utils/deferNetworkRequestsUntil.ts +1 -1
  55. package/src/browser/utils/workerChannel.ts +146 -0
  56. package/src/core/handlers/GraphQLHandler.ts +0 -3
  57. package/src/core/handlers/HttpHandler.ts +0 -2
  58. package/src/core/utils/handleRequest.ts +8 -8
  59. package/src/core/utils/internal/devUtils.ts +0 -2
  60. package/src/core/utils/internal/getCallFrame.ts +2 -2
  61. package/src/core/utils/internal/parseGraphQLRequest.ts +1 -0
  62. package/src/core/utils/matching/matchRequestUrl.ts +2 -2
  63. package/src/core/utils/request/onUnhandledRequest.test.ts +1 -1
  64. package/src/core/utils/url/cleanUrl.ts +1 -1
  65. package/src/core/utils/url/isAbsoluteUrl.ts +1 -1
  66. package/src/core/ws/WebSocketIndexedDBClientStore.ts +0 -4
  67. package/src/core/ws/utils/attachWebSocketLogger.ts +0 -14
  68. package/src/mockServiceWorker.js +14 -10
  69. package/src/browser/setupWorker/start/createFallbackStart.ts +0 -21
  70. package/src/browser/setupWorker/start/utils/createMessageChannel.ts +0 -32
  71. package/src/browser/setupWorker/stop/createFallbackStop.ts +0 -11
  72. package/src/browser/setupWorker/stop/createStop.ts +0 -35
@@ -124,20 +124,34 @@ function isNodeProcess() {
124
124
  return false;
125
125
  }
126
126
 
127
+ // src/browser/setupWorker/start/utils/prepareStartHandler.ts
128
+ var import_mergeRight = require("../core/utils/internal/mergeRight");
129
+ var DEFAULT_START_OPTIONS = {
130
+ serviceWorker: {
131
+ url: "/mockServiceWorker.js",
132
+ options: null
133
+ },
134
+ quiet: false,
135
+ waitUntilReady: true,
136
+ onUnhandledRequest: "warn",
137
+ findWorker(scriptURL, mockServiceWorkerUrl) {
138
+ return scriptURL === mockServiceWorkerUrl;
139
+ }
140
+ };
141
+
127
142
  // src/browser/setupWorker/start/createStartHandler.ts
128
- var import_devUtils7 = require("../core/utils/internal/devUtils");
143
+ var import_devUtils6 = require("../core/utils/internal/devUtils");
129
144
 
130
- // node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs
131
- var until = async (promise) => {
145
+ // node_modules/.pnpm/until-async@3.0.2/node_modules/until-async/lib/index.js
146
+ async function until(callback) {
132
147
  try {
133
- const data = await promise().catch((error2) => {
148
+ return [null, await callback().catch((error2) => {
134
149
  throw error2;
135
- });
136
- return { error: null, data };
150
+ })];
137
151
  } catch (error2) {
138
- return { error: error2, data: null };
152
+ return [error2, null];
139
153
  }
140
- };
154
+ }
141
155
 
142
156
  // src/browser/setupWorker/start/utils/getWorkerInstance.ts
143
157
  var import_devUtils = require("../core/utils/internal/devUtils");
@@ -186,19 +200,17 @@ var getWorkerInstance = async (url, options = {}, findWorker) => {
186
200
  existingRegistration
187
201
  ];
188
202
  }
189
- const registrationResult = await until(
190
- async () => {
191
- const registration = await navigator.serviceWorker.register(url, options);
192
- return [
193
- // Compare existing worker registration by its worker URL,
194
- // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
195
- getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
196
- registration
197
- ];
198
- }
199
- );
200
- if (registrationResult.error) {
201
- const isWorkerMissing = registrationResult.error.message.includes("(404)");
203
+ const [registrationError, registrationResult] = await until(async () => {
204
+ const registration = await navigator.serviceWorker.register(url, options);
205
+ return [
206
+ // Compare existing worker registration by its worker URL,
207
+ // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
208
+ getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
209
+ registration
210
+ ];
211
+ });
212
+ if (registrationError) {
213
+ const isWorkerMissing = registrationError.message.includes("(404)");
202
214
  if (isWorkerMissing) {
203
215
  const scopeUrl = new URL(options?.scope || "/", location.href);
204
216
  throw new Error(
@@ -212,15 +224,78 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
212
224
  throw new Error(
213
225
  import_devUtils.devUtils.formatMessage(
214
226
  "Failed to register the Service Worker:\n\n%s",
215
- registrationResult.error.message
227
+ registrationError.message
216
228
  )
217
229
  );
218
230
  }
219
- return registrationResult.data;
231
+ return registrationResult;
220
232
  };
221
233
 
222
- // src/browser/setupWorker/start/utils/enableMocking.ts
223
- var import_devUtils3 = require("../core/utils/internal/devUtils");
234
+ // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
235
+ function createDeferredExecutor() {
236
+ const executor = (resolve, reject) => {
237
+ executor.state = "pending";
238
+ executor.resolve = (data) => {
239
+ if (executor.state !== "pending") {
240
+ return;
241
+ }
242
+ executor.result = data;
243
+ const onFulfilled = (value) => {
244
+ executor.state = "fulfilled";
245
+ return value;
246
+ };
247
+ return resolve(
248
+ data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
249
+ );
250
+ };
251
+ executor.reject = (reason) => {
252
+ if (executor.state !== "pending") {
253
+ return;
254
+ }
255
+ queueMicrotask(() => {
256
+ executor.state = "rejected";
257
+ });
258
+ return reject(executor.rejectionReason = reason);
259
+ };
260
+ };
261
+ return executor;
262
+ }
263
+ var DeferredPromise = class extends Promise {
264
+ #executor;
265
+ resolve;
266
+ reject;
267
+ constructor(executor = null) {
268
+ const deferredExecutor = createDeferredExecutor();
269
+ super((originalResolve, originalReject) => {
270
+ deferredExecutor(originalResolve, originalReject);
271
+ executor?.(deferredExecutor.resolve, deferredExecutor.reject);
272
+ });
273
+ this.#executor = deferredExecutor;
274
+ this.resolve = this.#executor.resolve;
275
+ this.reject = this.#executor.reject;
276
+ }
277
+ get state() {
278
+ return this.#executor.state;
279
+ }
280
+ get rejectionReason() {
281
+ return this.#executor.rejectionReason;
282
+ }
283
+ then(onFulfilled, onRejected) {
284
+ return this.#decorate(super.then(onFulfilled, onRejected));
285
+ }
286
+ catch(onRejected) {
287
+ return this.#decorate(super.catch(onRejected));
288
+ }
289
+ finally(onfinally) {
290
+ return this.#decorate(super.finally(onfinally));
291
+ }
292
+ #decorate(promise) {
293
+ return Object.defineProperties(promise, {
294
+ resolve: { configurable: true, value: this.resolve },
295
+ reject: { configurable: true, value: this.reject }
296
+ });
297
+ }
298
+ };
224
299
 
225
300
  // src/browser/setupWorker/start/utils/printStartMessage.ts
226
301
  var import_devUtils2 = require("../core/utils/internal/devUtils");
@@ -252,35 +327,23 @@ function printStartMessage(args = {}) {
252
327
  }
253
328
 
254
329
  // src/browser/setupWorker/start/utils/enableMocking.ts
255
- async function enableMocking(context, options) {
256
- context.workerChannel.send("MOCK_ACTIVATE");
257
- const { payload } = await context.events.once("MOCKING_ENABLED");
258
- if (context.isMockingEnabled) {
259
- import_devUtils3.devUtils.warn(
260
- `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.`
261
- );
262
- return;
263
- }
264
- context.isMockingEnabled = true;
265
- printStartMessage({
266
- quiet: options.quiet,
267
- workerScope: context.registration?.scope,
268
- workerUrl: context.worker?.scriptURL,
269
- client: payload.client
330
+ function enableMocking(context, options) {
331
+ const mockingEnabledPromise = new DeferredPromise();
332
+ context.workerChannel.postMessage("MOCK_ACTIVATE");
333
+ context.workerChannel.once("MOCKING_ENABLED", async (event) => {
334
+ context.isMockingEnabled = true;
335
+ const worker = await context.workerPromise;
336
+ printStartMessage({
337
+ quiet: options.quiet,
338
+ workerScope: context.registration?.scope,
339
+ workerUrl: worker.scriptURL,
340
+ client: event.data.client
341
+ });
342
+ mockingEnabledPromise.resolve(true);
270
343
  });
344
+ return mockingEnabledPromise;
271
345
  }
272
346
 
273
- // src/browser/setupWorker/start/utils/createMessageChannel.ts
274
- var WorkerChannel = class {
275
- constructor(port) {
276
- this.port = port;
277
- }
278
- postMessage(event, ...rest) {
279
- const [data, transfer] = rest;
280
- this.port.postMessage({ type: event, data }, { transfer });
281
- }
282
- };
283
-
284
347
  // src/browser/utils/pruneGetRequestBody.ts
285
348
  function pruneGetRequestBody(request) {
286
349
  if (["HEAD", "GET"].includes(request.method)) {
@@ -300,14 +363,17 @@ function deserializeRequest(serializedRequest) {
300
363
  // src/browser/setupWorker/start/createRequestListener.ts
301
364
  var import_RequestHandler = require("../core/handlers/RequestHandler");
302
365
  var import_handleRequest = require("../core/utils/handleRequest");
303
- var import_devUtils4 = require("../core/utils/internal/devUtils");
366
+ var import_devUtils3 = require("../core/utils/internal/devUtils");
304
367
  var import_toResponseInit = require("../core/utils/toResponseInit");
305
368
  var import_isHandlerKind = require("../core/utils/internal/isHandlerKind");
306
369
  var createRequestListener = (context, options) => {
307
- return async (event, message) => {
308
- const messageChannel = new WorkerChannel(event.ports[0]);
309
- const requestId = message.payload.id;
310
- const request = deserializeRequest(message.payload);
370
+ return async (event) => {
371
+ if (!context.isMockingEnabled && context.workerStoppedAt && event.data.interceptedAt > context.workerStoppedAt) {
372
+ event.postMessage("PASSTHROUGH");
373
+ return;
374
+ }
375
+ const requestId = event.data.id;
376
+ const request = deserializeRequest(event.data);
311
377
  const requestCloneForLogs = request.clone();
312
378
  const requestClone = request.clone();
313
379
  import_RequestHandler.RequestHandler.cache.set(request, requestClone);
@@ -320,7 +386,7 @@ var createRequestListener = (context, options) => {
320
386
  context.emitter,
321
387
  {
322
388
  onPassthroughResponse() {
323
- messageChannel.postMessage("PASSTHROUGH");
389
+ event.postMessage("PASSTHROUGH");
324
390
  },
325
391
  async onMockedResponse(response, { handler, parsedResult }) {
326
392
  const responseClone = response.clone();
@@ -328,7 +394,7 @@ var createRequestListener = (context, options) => {
328
394
  const responseInit = (0, import_toResponseInit.toResponseInit)(response);
329
395
  if (context.supports.readableStreamTransfer) {
330
396
  const responseStreamOrNull = response.body;
331
- messageChannel.postMessage(
397
+ event.postMessage(
332
398
  "MOCK_RESPONSE",
333
399
  {
334
400
  ...responseInit,
@@ -338,7 +404,7 @@ var createRequestListener = (context, options) => {
338
404
  );
339
405
  } else {
340
406
  const responseBufferOrNull = response.body === null ? null : await responseClone.arrayBuffer();
341
- messageChannel.postMessage("MOCK_RESPONSE", {
407
+ event.postMessage("MOCK_RESPONSE", {
342
408
  ...responseInit,
343
409
  body: responseBufferOrNull
344
410
  });
@@ -357,7 +423,7 @@ var createRequestListener = (context, options) => {
357
423
  );
358
424
  } catch (error2) {
359
425
  if (error2 instanceof Error) {
360
- import_devUtils4.devUtils.error(
426
+ import_devUtils3.devUtils.error(
361
427
  `Uncaught exception in the request handler for "%s %s":
362
428
 
363
429
  %s
@@ -367,7 +433,7 @@ This exception has been gracefully handled as a 500 response, however, it's stro
367
433
  request.url,
368
434
  error2.stack ?? error2
369
435
  );
370
- messageChannel.postMessage("MOCK_RESPONSE", {
436
+ event.postMessage("MOCK_RESPONSE", {
371
437
  status: 500,
372
438
  statusText: "Request Handler Error",
373
439
  headers: {
@@ -385,21 +451,26 @@ This exception has been gracefully handled as a 500 response, however, it's stro
385
451
  };
386
452
 
387
453
  // src/browser/utils/checkWorkerIntegrity.ts
388
- var import_devUtils5 = require("../core/utils/internal/devUtils");
389
- async function checkWorkerIntegrity(context) {
390
- context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
391
- const { payload } = await context.events.once("INTEGRITY_CHECK_RESPONSE");
392
- if (payload.checksum !== "f5825c521429caf22a4dd13b66e243af") {
393
- import_devUtils5.devUtils.warn(
394
- `The currently registered Service Worker has been generated by a different version of MSW (${payload.packageVersion}) and may not be fully compatible with the installed version.
454
+ var import_devUtils4 = require("../core/utils/internal/devUtils");
455
+ function checkWorkerIntegrity(context) {
456
+ const integrityCheckPromise = new DeferredPromise();
457
+ context.workerChannel.postMessage("INTEGRITY_CHECK_REQUEST");
458
+ context.workerChannel.once("INTEGRITY_CHECK_RESPONSE", (event) => {
459
+ const { checksum, packageVersion } = event.data;
460
+ if (checksum !== "4db4a41e972cec1b64cc569c66952d82") {
461
+ import_devUtils4.devUtils.warn(
462
+ `The currently registered Service Worker has been generated by a different version of MSW (${packageVersion}) and may not be fully compatible with the installed version.
395
463
 
396
464
  It's recommended you update your worker script by running this command:
397
465
 
398
466
  \u2022 npx msw init <PUBLIC_DIR>
399
467
 
400
468
  You can also automate this process and make the worker script update automatically upon the library installations. Read more: https://mswjs.io/docs/cli/init.`
401
- );
402
- }
469
+ );
470
+ }
471
+ integrityCheckPromise.resolve();
472
+ });
473
+ return integrityCheckPromise;
403
474
  }
404
475
 
405
476
  // node_modules/.pnpm/@mswjs+interceptors@0.39.1/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs
@@ -1142,22 +1213,22 @@ var BatchInterceptor = class extends Interceptor {
1142
1213
 
1143
1214
  // src/browser/setupWorker/start/createResponseListener.ts
1144
1215
  function createResponseListener(context) {
1145
- return (_, message) => {
1146
- const { payload: responseJson } = message;
1147
- const request = deserializeRequest(responseJson.request);
1148
- if (responseJson.response.type?.includes("opaque")) {
1216
+ return (event) => {
1217
+ const responseMessage = event.data;
1218
+ const request = deserializeRequest(responseMessage.request);
1219
+ if (responseMessage.response.type?.includes("opaque")) {
1149
1220
  return;
1150
1221
  }
1151
- const response = responseJson.response.status === 0 ? Response.error() : new FetchResponse(
1222
+ const response = responseMessage.response.status === 0 ? Response.error() : new FetchResponse(
1152
1223
  /**
1153
1224
  * Responses may be streams here, but when we create a response object
1154
1225
  * with null-body status codes, like 204, 205, 304 Response will
1155
1226
  * throw when passed a non-null body, so ensure it's null here
1156
1227
  * for those codes
1157
1228
  */
1158
- FetchResponse.isResponseWithBody(responseJson.response.status) ? responseJson.response.body : null,
1229
+ FetchResponse.isResponseWithBody(responseMessage.response.status) ? responseMessage.response.body : null,
1159
1230
  {
1160
- ...responseJson,
1231
+ ...responseMessage,
1161
1232
  /**
1162
1233
  * Set response URL if it's not set already.
1163
1234
  * @see https://github.com/mswjs/msw/issues/2030
@@ -1167,9 +1238,9 @@ function createResponseListener(context) {
1167
1238
  }
1168
1239
  );
1169
1240
  context.emitter.emit(
1170
- responseJson.isMockedResponse ? "response:mocked" : "response:bypass",
1241
+ responseMessage.isMockedResponse ? "response:mocked" : "response:bypass",
1171
1242
  {
1172
- requestId: responseJson.request.id,
1243
+ requestId: responseMessage.request.id,
1173
1244
  request,
1174
1245
  response
1175
1246
  }
@@ -1178,10 +1249,10 @@ function createResponseListener(context) {
1178
1249
  }
1179
1250
 
1180
1251
  // src/browser/setupWorker/start/utils/validateWorkerScope.ts
1181
- var import_devUtils6 = require("../core/utils/internal/devUtils");
1252
+ var import_devUtils5 = require("../core/utils/internal/devUtils");
1182
1253
  function validateWorkerScope(registration, options) {
1183
1254
  if (!options?.quiet && !location.href.startsWith(registration.scope)) {
1184
- import_devUtils6.devUtils.warn(
1255
+ import_devUtils5.devUtils.warn(
1185
1256
  `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.
1186
1257
 
1187
1258
  - (Recommended) Register the worker at the root level ("/") of your application.
@@ -1194,7 +1265,7 @@ function validateWorkerScope(registration, options) {
1194
1265
  var createStartHandler = (context) => {
1195
1266
  return function start(options, customOptions) {
1196
1267
  const startWorkerInstance = async () => {
1197
- context.events.removeAllListeners();
1268
+ context.workerChannel.removeAllListeners();
1198
1269
  context.workerChannel.on(
1199
1270
  "REQUEST",
1200
1271
  createRequestListener(context, options)
@@ -1207,14 +1278,14 @@ var createStartHandler = (context) => {
1207
1278
  );
1208
1279
  const [worker, registration] = instance;
1209
1280
  if (!worker) {
1210
- const missingWorkerMessage = customOptions?.findWorker ? import_devUtils7.devUtils.formatMessage(
1281
+ const missingWorkerMessage = customOptions?.findWorker ? import_devUtils6.devUtils.formatMessage(
1211
1282
  `Failed to locate the Service Worker registration using a custom "findWorker" predicate.
1212
1283
 
1213
1284
  Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
1214
1285
  More details: https://mswjs.io/docs/api/setup-worker/start#findworker
1215
1286
  `,
1216
1287
  options.serviceWorker.url
1217
- ) : import_devUtils7.devUtils.formatMessage(
1288
+ ) : import_devUtils6.devUtils.formatMessage(
1218
1289
  `Failed to locate the Service Worker registration.
1219
1290
 
1220
1291
  This most likely means that the worker script URL "%s" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname.
@@ -1225,23 +1296,23 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
1225
1296
  );
1226
1297
  throw new Error(missingWorkerMessage);
1227
1298
  }
1228
- context.worker = worker;
1299
+ context.workerPromise.resolve(worker);
1229
1300
  context.registration = registration;
1230
- context.events.addListener(window, "beforeunload", () => {
1301
+ window.addEventListener("beforeunload", () => {
1231
1302
  if (worker.state !== "redundant") {
1232
- context.workerChannel.send("CLIENT_CLOSED");
1303
+ context.workerChannel.postMessage("CLIENT_CLOSED");
1233
1304
  }
1234
1305
  window.clearInterval(context.keepAliveInterval);
1235
1306
  window.postMessage({ type: "msw/worker:stop" });
1236
1307
  });
1237
1308
  await checkWorkerIntegrity(context).catch((error2) => {
1238
- import_devUtils7.devUtils.error(
1239
- "Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues), including the original error below."
1309
+ import_devUtils6.devUtils.error(
1310
+ "Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues) and include the original error below."
1240
1311
  );
1241
1312
  console.error(error2);
1242
1313
  });
1243
1314
  context.keepAliveInterval = window.setInterval(
1244
- () => context.workerChannel.send("KEEPALIVE_REQUEST"),
1315
+ () => context.workerChannel.postMessage("KEEPALIVE_REQUEST"),
1245
1316
  5e3
1246
1317
  );
1247
1318
  validateWorkerScope(registration, context.startOptions);
@@ -1251,16 +1322,19 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
1251
1322
  async (registration) => {
1252
1323
  const pendingInstance = registration.installing || registration.waiting;
1253
1324
  if (pendingInstance) {
1254
- await new Promise((resolve) => {
1255
- pendingInstance.addEventListener("statechange", () => {
1256
- if (pendingInstance.state === "activated") {
1257
- return resolve();
1258
- }
1259
- });
1325
+ const activationPromise = new DeferredPromise();
1326
+ pendingInstance.addEventListener("statechange", () => {
1327
+ if (pendingInstance.state === "activated") {
1328
+ activationPromise.resolve();
1329
+ }
1260
1330
  });
1331
+ await activationPromise;
1261
1332
  }
1262
1333
  await enableMocking(context, options).catch((error2) => {
1263
- throw new Error(`Failed to enable mocking: ${error2?.message}`);
1334
+ import_devUtils6.devUtils.error(
1335
+ "Failed to enable mocking. Please report this on GitHub (https://github.com/mswjs/msw/issues) and include the original error below."
1336
+ );
1337
+ throw error2;
1264
1338
  });
1265
1339
  return registration;
1266
1340
  }
@@ -1269,116 +1343,324 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
1269
1343
  };
1270
1344
  };
1271
1345
 
1272
- // src/browser/setupWorker/stop/createStop.ts
1273
- var import_devUtils9 = require("../core/utils/internal/devUtils");
1274
-
1275
- // src/browser/setupWorker/stop/utils/printStopMessage.ts
1346
+ // src/browser/setupWorker/setupWorker.ts
1276
1347
  var import_devUtils8 = require("../core/utils/internal/devUtils");
1277
- function printStopMessage(args = {}) {
1278
- if (args.quiet) {
1279
- return;
1348
+ var import_SetupApi = require("../core/SetupApi");
1349
+ var import_mergeRight2 = require("../core/utils/internal/mergeRight");
1350
+
1351
+ // src/browser/utils/supportsReadableStreamTransfer.ts
1352
+ function supportsReadableStreamTransfer() {
1353
+ try {
1354
+ const stream = new ReadableStream({
1355
+ start: (controller) => controller.close()
1356
+ });
1357
+ const message = new MessageChannel();
1358
+ message.port1.postMessage(stream, [stream]);
1359
+ return true;
1360
+ } catch {
1361
+ return false;
1280
1362
  }
1281
- console.log(
1282
- `%c${import_devUtils8.devUtils.formatMessage("Mocking disabled.")}`,
1283
- "color:orangered;font-weight:bold;"
1284
- );
1285
1363
  }
1286
1364
 
1287
- // src/browser/setupWorker/stop/createStop.ts
1288
- var createStop = (context) => {
1289
- return function stop() {
1290
- if (!context.isMockingEnabled) {
1291
- import_devUtils9.devUtils.warn(
1292
- 'Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.'
1293
- );
1294
- return;
1295
- }
1296
- context.workerChannel.send("MOCK_DEACTIVATE");
1297
- context.isMockingEnabled = false;
1298
- window.clearInterval(context.keepAliveInterval);
1299
- window.postMessage({ type: "msw/worker:stop" });
1300
- printStopMessage({ quiet: context.startOptions?.quiet });
1301
- };
1302
- };
1365
+ // src/browser/setupWorker/setupWorker.ts
1366
+ var import_webSocketInterceptor = require("../core/ws/webSocketInterceptor");
1367
+ var import_handleWebSocketEvent = require("../core/ws/handleWebSocketEvent");
1368
+ var import_attachWebSocketLogger = require("../core/ws/utils/attachWebSocketLogger");
1303
1369
 
1304
- // src/browser/setupWorker/start/utils/prepareStartHandler.ts
1305
- var import_mergeRight = require("../core/utils/internal/mergeRight");
1306
- var DEFAULT_START_OPTIONS = {
1307
- serviceWorker: {
1308
- url: "/mockServiceWorker.js",
1309
- options: null
1310
- },
1311
- quiet: false,
1312
- waitUntilReady: true,
1313
- onUnhandledRequest: "warn",
1314
- findWorker(scriptURL, mockServiceWorkerUrl) {
1315
- return scriptURL === mockServiceWorkerUrl;
1370
+ // node_modules/.pnpm/rettime@0.7.0/node_modules/rettime/build/index.js
1371
+ var kDefaultPrevented = Symbol("kDefaultPrevented");
1372
+ var kPropagationStopped = Symbol("kPropagationStopped");
1373
+ var kImmediatePropagationStopped = Symbol("kImmediatePropagationStopped");
1374
+ var TypedEvent = class extends MessageEvent {
1375
+ /**
1376
+ * @note Keep a placeholder property with the return type
1377
+ * because the type must be set somewhere in order to be
1378
+ * correctly associated and inferred from the event.
1379
+ */
1380
+ #returnType;
1381
+ [kDefaultPrevented];
1382
+ [kPropagationStopped];
1383
+ [kImmediatePropagationStopped];
1384
+ constructor(...args) {
1385
+ super(args[0], args[1]);
1386
+ this[kDefaultPrevented] = false;
1387
+ }
1388
+ get defaultPrevented() {
1389
+ return this[kDefaultPrevented];
1390
+ }
1391
+ preventDefault() {
1392
+ super.preventDefault();
1393
+ this[kDefaultPrevented] = true;
1394
+ }
1395
+ stopImmediatePropagation() {
1396
+ super.stopImmediatePropagation();
1397
+ this[kImmediatePropagationStopped] = true;
1316
1398
  }
1317
1399
  };
1318
-
1319
- // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
1320
- function createDeferredExecutor() {
1321
- const executor = (resolve, reject) => {
1322
- executor.state = "pending";
1323
- executor.resolve = (data) => {
1324
- if (executor.state !== "pending") {
1325
- return;
1400
+ var kListenerOptions = Symbol("kListenerOptions");
1401
+ var Emitter2 = class {
1402
+ #listeners;
1403
+ constructor() {
1404
+ this.#listeners = {};
1405
+ }
1406
+ /**
1407
+ * Adds a listener for the given event type.
1408
+ *
1409
+ * @returns {AbortController} An `AbortController` that can be used to remove the listener.
1410
+ */
1411
+ on(type, listener, options) {
1412
+ return this.#addListener(type, listener, options);
1413
+ }
1414
+ /**
1415
+ * Adds a one-time listener for the given event type.
1416
+ *
1417
+ * @returns {AbortController} An `AbortController` that can be used to remove the listener.
1418
+ */
1419
+ once(type, listener, options) {
1420
+ return this.on(type, listener, { ...options || {}, once: true });
1421
+ }
1422
+ /**
1423
+ * Prepends a listener for the given event type.
1424
+ *
1425
+ * @returns {AbortController} An `AbortController` that can be used to remove the listener.
1426
+ */
1427
+ earlyOn(type, listener, options) {
1428
+ return this.#addListener(type, listener, options, "prepend");
1429
+ }
1430
+ /**
1431
+ * Prepends a one-time listener for the given event type.
1432
+ */
1433
+ earlyOnce(type, listener, options) {
1434
+ return this.earlyOn(type, listener, { ...options || {}, once: true });
1435
+ }
1436
+ /**
1437
+ * Emits the given typed event.
1438
+ *
1439
+ * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise.
1440
+ */
1441
+ emit(event) {
1442
+ if (this.listenerCount(event.type) === 0) {
1443
+ return false;
1444
+ }
1445
+ const proxiedEvent = this.#proxyEvent(event);
1446
+ for (const listener of this.#listeners[event.type]) {
1447
+ if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) {
1448
+ return false;
1326
1449
  }
1327
- executor.result = data;
1328
- const onFulfilled = (value) => {
1329
- executor.state = "fulfilled";
1330
- return value;
1331
- };
1332
- return resolve(
1333
- data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
1450
+ if (proxiedEvent.event[kImmediatePropagationStopped]) {
1451
+ break;
1452
+ }
1453
+ this.#callListener(proxiedEvent.event, listener);
1454
+ }
1455
+ proxiedEvent.revoke();
1456
+ return true;
1457
+ }
1458
+ /**
1459
+ * Emits the given typed event and returns a promise that resolves
1460
+ * when all the listeners for that event have settled.
1461
+ *
1462
+ * @returns {Promise<Array<Emitter.ListenerReturnType>>} A promise that resolves
1463
+ * with the return values of all listeners.
1464
+ */
1465
+ async emitAsPromise(event) {
1466
+ if (this.listenerCount(event.type) === 0) {
1467
+ return [];
1468
+ }
1469
+ const pendingListeners = [];
1470
+ const proxiedEvent = this.#proxyEvent(event);
1471
+ for (const listener of this.#listeners[event.type]) {
1472
+ if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) {
1473
+ return [];
1474
+ }
1475
+ if (proxiedEvent.event[kImmediatePropagationStopped]) {
1476
+ break;
1477
+ }
1478
+ pendingListeners.push(
1479
+ // Awaiting individual listeners guarantees their call order.
1480
+ await Promise.resolve(this.#callListener(proxiedEvent.event, listener))
1334
1481
  );
1335
- };
1336
- executor.reject = (reason) => {
1337
- if (executor.state !== "pending") {
1482
+ }
1483
+ proxiedEvent.revoke();
1484
+ return Promise.allSettled(pendingListeners).then((results) => {
1485
+ return results.map(
1486
+ (result) => result.status === "fulfilled" ? result.value : result.reason
1487
+ );
1488
+ });
1489
+ }
1490
+ /**
1491
+ * Emits the given event and returns a generator that yields
1492
+ * the result of each listener in the order of their registration.
1493
+ * This way, you stop exhausting the listeners once you get the expected value.
1494
+ */
1495
+ *emitAsGenerator(event) {
1496
+ if (this.listenerCount(event.type) === 0) {
1497
+ return;
1498
+ }
1499
+ const proxiedEvent = this.#proxyEvent(event);
1500
+ for (const listener of this.#listeners[event.type]) {
1501
+ if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) {
1338
1502
  return;
1339
1503
  }
1340
- queueMicrotask(() => {
1341
- executor.state = "rejected";
1504
+ if (proxiedEvent.event[kImmediatePropagationStopped]) {
1505
+ break;
1506
+ }
1507
+ yield this.#callListener(proxiedEvent.event, listener);
1508
+ }
1509
+ proxiedEvent.revoke();
1510
+ }
1511
+ /**
1512
+ * Removes a listener for the given event type.
1513
+ */
1514
+ removeListener(type, listener) {
1515
+ if (this.listenerCount(type) === 0) {
1516
+ return;
1517
+ }
1518
+ const nextListeners = [];
1519
+ for (const existingListener of this.#listeners[type]) {
1520
+ if (existingListener !== listener) {
1521
+ nextListeners.push(existingListener);
1522
+ }
1523
+ }
1524
+ this.#listeners[type] = nextListeners;
1525
+ }
1526
+ /**
1527
+ * Removes all listeners for the given event type.
1528
+ * If no event type is provided, removes all existing listeners.
1529
+ */
1530
+ removeAllListeners(type) {
1531
+ if (type == null) {
1532
+ this.#listeners = {};
1533
+ return;
1534
+ }
1535
+ this.#listeners[type] = [];
1536
+ }
1537
+ /**
1538
+ * Returns the list of listeners for the given event type.
1539
+ * If no even type is provided, returns all listeners.
1540
+ */
1541
+ listeners(type) {
1542
+ if (type == null) {
1543
+ return Object.values(this.#listeners).flat();
1544
+ }
1545
+ return this.#listeners[type] || [];
1546
+ }
1547
+ /**
1548
+ * Returns the number of listeners for the given event type.
1549
+ * If no even type is provided, returns the total number of listeners.
1550
+ */
1551
+ listenerCount(type) {
1552
+ return this.listeners(type).length;
1553
+ }
1554
+ #addListener(type, listener, options, insertMode = "append") {
1555
+ this.#listeners[type] ??= [];
1556
+ if (insertMode === "prepend") {
1557
+ this.#listeners[type].unshift(listener);
1558
+ } else {
1559
+ this.#listeners[type].push(listener);
1560
+ }
1561
+ if (options) {
1562
+ Object.defineProperty(listener, kListenerOptions, {
1563
+ value: options,
1564
+ enumerable: false,
1565
+ writable: false
1342
1566
  });
1343
- return reject(executor.rejectionReason = reason);
1344
- };
1345
- };
1346
- return executor;
1347
- }
1348
- var DeferredPromise = class extends Promise {
1349
- #executor;
1350
- resolve;
1351
- reject;
1352
- constructor(executor = null) {
1353
- const deferredExecutor = createDeferredExecutor();
1354
- super((originalResolve, originalReject) => {
1355
- deferredExecutor(originalResolve, originalReject);
1356
- executor?.(deferredExecutor.resolve, deferredExecutor.reject);
1567
+ if (options.signal) {
1568
+ options.signal.addEventListener(
1569
+ "abort",
1570
+ () => {
1571
+ this.removeListener(type, listener);
1572
+ },
1573
+ { once: true }
1574
+ );
1575
+ }
1576
+ }
1577
+ return this;
1578
+ }
1579
+ #proxyEvent(event) {
1580
+ const { stopPropagation } = event;
1581
+ event.stopPropagation = new Proxy(event.stopPropagation, {
1582
+ apply: (target, thisArg, argArray) => {
1583
+ event[kPropagationStopped] = this;
1584
+ return Reflect.apply(target, thisArg, argArray);
1585
+ }
1357
1586
  });
1358
- this.#executor = deferredExecutor;
1359
- this.resolve = this.#executor.resolve;
1360
- this.reject = this.#executor.reject;
1587
+ return {
1588
+ event,
1589
+ revoke() {
1590
+ event.stopPropagation = stopPropagation;
1591
+ }
1592
+ };
1361
1593
  }
1362
- get state() {
1363
- return this.#executor.state;
1594
+ #callListener(event, listener) {
1595
+ const returnValue = listener.call(this, event);
1596
+ if (listener[kListenerOptions]?.once) {
1597
+ this.removeListener(event.type, listener);
1598
+ }
1599
+ return returnValue;
1364
1600
  }
1365
- get rejectionReason() {
1366
- return this.#executor.rejectionReason;
1601
+ };
1602
+
1603
+ // src/browser/utils/workerChannel.ts
1604
+ var import_isObject = require("../core/utils/internal/isObject");
1605
+ var WorkerEvent = class extends TypedEvent {
1606
+ #workerEvent;
1607
+ constructor(workerEvent) {
1608
+ const type = workerEvent.data.type;
1609
+ const data = workerEvent.data.payload;
1610
+ super(
1611
+ // @ts-expect-error Troublesome `TypedEvent` extension.
1612
+ type,
1613
+ { data }
1614
+ );
1615
+ this.#workerEvent = workerEvent;
1367
1616
  }
1368
- then(onFulfilled, onRejected) {
1369
- return this.#decorate(super.then(onFulfilled, onRejected));
1617
+ get ports() {
1618
+ return this.#workerEvent.ports;
1370
1619
  }
1371
- catch(onRejected) {
1372
- return this.#decorate(super.catch(onRejected));
1620
+ /**
1621
+ * Reply directly to this event using its `MessagePort`.
1622
+ */
1623
+ postMessage(type, ...rest) {
1624
+ this.#workerEvent.ports[0].postMessage(
1625
+ { type, data: rest[0] },
1626
+ { transfer: rest[1] }
1627
+ );
1373
1628
  }
1374
- finally(onfinally) {
1375
- return this.#decorate(super.finally(onfinally));
1629
+ };
1630
+ var WorkerChannel = class extends Emitter2 {
1631
+ constructor(options) {
1632
+ super();
1633
+ this.options = options;
1634
+ navigator.serviceWorker.addEventListener("message", async (event) => {
1635
+ const worker = await this.options.worker;
1636
+ if (event.source != null && event.source !== worker) {
1637
+ return;
1638
+ }
1639
+ if (event.data && (0, import_isObject.isObject)(event.data) && "type" in event.data) {
1640
+ this.emit(new WorkerEvent(event));
1641
+ }
1642
+ });
1376
1643
  }
1377
- #decorate(promise) {
1378
- return Object.defineProperties(promise, {
1379
- resolve: { configurable: true, value: this.resolve },
1380
- reject: { configurable: true, value: this.reject }
1644
+ /**
1645
+ * Send data to the Service Worker controlling this client.
1646
+ * This triggers the `message` event listener on ServiceWorkerGlobalScope.
1647
+ */
1648
+ postMessage(type) {
1649
+ this.options.worker.then((worker) => {
1650
+ worker.postMessage(type);
1651
+ });
1652
+ }
1653
+ };
1654
+
1655
+ // node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs
1656
+ var until2 = async (promise) => {
1657
+ try {
1658
+ const data = await promise().catch((error2) => {
1659
+ throw error2;
1381
1660
  });
1661
+ return { error: null, data };
1662
+ } catch (error2) {
1663
+ return { error: error2, data: null };
1382
1664
  }
1383
1665
  };
1384
1666
 
@@ -1445,7 +1727,7 @@ async function emitAsync(emitter, eventName, ...data) {
1445
1727
  await listener.apply(emitter, data);
1446
1728
  }
1447
1729
  }
1448
- function isObject(value, loose = false) {
1730
+ function isObject2(value, loose = false) {
1449
1731
  return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]";
1450
1732
  }
1451
1733
  function isPropertyAccessible(obj, key) {
@@ -1478,7 +1760,7 @@ function isResponseError(response) {
1478
1760
  return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error";
1479
1761
  }
1480
1762
  function isResponseLike(value) {
1481
- return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed");
1763
+ return isObject2(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed");
1482
1764
  }
1483
1765
  function isNodeLikeError(error2) {
1484
1766
  if (error2 == null) {
@@ -1503,7 +1785,7 @@ async function handleRequest2(options) {
1503
1785
  await options.onResponse(response);
1504
1786
  return true;
1505
1787
  }
1506
- if (isObject(response)) {
1788
+ if (isObject2(response)) {
1507
1789
  options.onError(response);
1508
1790
  return true;
1509
1791
  }
@@ -1544,7 +1826,7 @@ async function handleRequest2(options) {
1544
1826
  );
1545
1827
  }
1546
1828
  }
1547
- const result = await until(async () => {
1829
+ const result = await until2(async () => {
1548
1830
  const requestListenersPromise = emitAsync(options.emitter, "request", {
1549
1831
  requestId: options.requestId,
1550
1832
  request: options.request,
@@ -1580,7 +1862,7 @@ async function handleRequest2(options) {
1580
1862
  unhandledExceptionController[kResponsePromise].resolve(void 0);
1581
1863
  }
1582
1864
  });
1583
- const nextResult = await until(
1865
+ const nextResult = await until2(
1584
1866
  () => unhandledExceptionController[kResponsePromise]
1585
1867
  );
1586
1868
  if (nextResult.error) {
@@ -2714,162 +2996,66 @@ function createFallbackRequestListener(context, options) {
2714
2996
  return interceptor;
2715
2997
  }
2716
2998
 
2717
- // src/browser/setupWorker/start/createFallbackStart.ts
2718
- function createFallbackStart(context) {
2719
- return async function start(options) {
2720
- context.fallbackInterceptor = createFallbackRequestListener(
2721
- context,
2722
- options
2723
- );
2724
- printStartMessage({
2725
- message: "Mocking enabled (fallback mode).",
2726
- quiet: options.quiet
2727
- });
2728
- return void 0;
2729
- };
2730
- }
2731
-
2732
- // src/browser/setupWorker/stop/createFallbackStop.ts
2733
- function createFallbackStop(context) {
2734
- return function stop() {
2735
- context.fallbackInterceptor?.dispose();
2736
- printStopMessage({ quiet: context.startOptions?.quiet });
2737
- };
2738
- }
2739
-
2740
- // src/browser/setupWorker/setupWorker.ts
2741
- var import_devUtils10 = require("../core/utils/internal/devUtils");
2742
- var import_SetupApi = require("../core/SetupApi");
2743
- var import_mergeRight2 = require("../core/utils/internal/mergeRight");
2744
-
2745
- // src/browser/utils/supportsReadableStreamTransfer.ts
2746
- function supportsReadableStreamTransfer() {
2747
- try {
2748
- const stream = new ReadableStream({
2749
- start: (controller) => controller.close()
2750
- });
2751
- const message = new MessageChannel();
2752
- message.port1.postMessage(stream, [stream]);
2753
- return true;
2754
- } catch {
2755
- return false;
2999
+ // src/browser/setupWorker/stop/utils/printStopMessage.ts
3000
+ var import_devUtils7 = require("../core/utils/internal/devUtils");
3001
+ function printStopMessage(args = {}) {
3002
+ if (args.quiet) {
3003
+ return;
2756
3004
  }
3005
+ console.log(
3006
+ `%c${import_devUtils7.devUtils.formatMessage("Mocking disabled.")}`,
3007
+ "color:orangered;font-weight:bold;"
3008
+ );
2757
3009
  }
2758
3010
 
2759
3011
  // src/browser/setupWorker/setupWorker.ts
2760
- var import_webSocketInterceptor = require("../core/ws/webSocketInterceptor");
2761
- var import_handleWebSocketEvent = require("../core/ws/handleWebSocketEvent");
2762
- var import_attachWebSocketLogger = require("../core/ws/utils/attachWebSocketLogger");
2763
3012
  var SetupWorkerApi = class extends import_SetupApi.SetupApi {
2764
3013
  context;
2765
- startHandler = null;
2766
- stopHandler = null;
2767
- listeners;
2768
3014
  constructor(...handlers) {
2769
3015
  super(...handlers);
2770
3016
  invariant(
2771
3017
  !isNodeProcess(),
2772
- import_devUtils10.devUtils.formatMessage(
3018
+ import_devUtils8.devUtils.formatMessage(
2773
3019
  "Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead."
2774
3020
  )
2775
3021
  );
2776
- this.listeners = [];
2777
3022
  this.context = this.createWorkerContext();
2778
3023
  }
2779
3024
  createWorkerContext() {
2780
- const context = {
3025
+ const workerPromise = new DeferredPromise();
3026
+ return {
2781
3027
  // Mocking is not considered enabled until the worker
2782
3028
  // signals back the successful activation event.
2783
3029
  isMockingEnabled: false,
2784
3030
  startOptions: null,
2785
- worker: null,
3031
+ workerPromise,
3032
+ registration: void 0,
2786
3033
  getRequestHandlers: () => {
2787
3034
  return this.handlersController.currentHandlers();
2788
3035
  },
2789
- registration: null,
2790
3036
  emitter: this.emitter,
2791
- workerChannel: {
2792
- on: (eventType, callback) => {
2793
- this.context.events.addListener(navigator.serviceWorker, "message", (event) => {
2794
- if (event.source !== this.context.worker) {
2795
- return;
2796
- }
2797
- const message = event.data;
2798
- if (!message) {
2799
- return;
2800
- }
2801
- if (message.type === eventType) {
2802
- callback(event, message);
2803
- }
2804
- });
2805
- },
2806
- send: (type) => {
2807
- this.context.worker?.postMessage(type);
2808
- }
2809
- },
2810
- events: {
2811
- addListener: (target, eventType, callback) => {
2812
- target.addEventListener(eventType, callback);
2813
- this.listeners.push({
2814
- eventType,
2815
- target,
2816
- callback
2817
- });
2818
- return () => {
2819
- target.removeEventListener(eventType, callback);
2820
- };
2821
- },
2822
- removeAllListeners: () => {
2823
- for (const { target, eventType, callback } of this.listeners) {
2824
- target.removeEventListener(eventType, callback);
2825
- }
2826
- this.listeners = [];
2827
- },
2828
- once: (eventType) => {
2829
- const bindings = [];
2830
- return new Promise((resolve, reject) => {
2831
- const handleIncomingMessage = (event) => {
2832
- try {
2833
- const message = event.data;
2834
- if (message.type === eventType) {
2835
- resolve(message);
2836
- }
2837
- } catch (error2) {
2838
- reject(error2);
2839
- }
2840
- };
2841
- bindings.push(
2842
- this.context.events.addListener(
2843
- navigator.serviceWorker,
2844
- "message",
2845
- handleIncomingMessage
2846
- ),
2847
- this.context.events.addListener(
2848
- navigator.serviceWorker,
2849
- "messageerror",
2850
- reject
2851
- )
2852
- );
2853
- }).finally(() => {
2854
- bindings.forEach((unbind) => unbind());
2855
- });
2856
- }
2857
- },
3037
+ workerChannel: new WorkerChannel({
3038
+ worker: workerPromise
3039
+ }),
2858
3040
  supports: {
2859
- serviceWorkerApi: !("serviceWorker" in navigator) || location.protocol === "file:",
3041
+ serviceWorkerApi: "serviceWorker" in navigator && location.protocol !== "file:",
2860
3042
  readableStreamTransfer: supportsReadableStreamTransfer()
2861
3043
  }
2862
3044
  };
2863
- this.startHandler = context.supports.serviceWorkerApi ? createFallbackStart(context) : createStartHandler(context);
2864
- this.stopHandler = context.supports.serviceWorkerApi ? createFallbackStop(context) : createStop(context);
2865
- return context;
2866
3045
  }
2867
3046
  async start(options = {}) {
2868
- if (options.waitUntilReady === true) {
2869
- import_devUtils10.devUtils.warn(
3047
+ if ("waitUntilReady" in options) {
3048
+ import_devUtils8.devUtils.warn(
2870
3049
  '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.'
2871
3050
  );
2872
3051
  }
3052
+ if (this.context.isMockingEnabled) {
3053
+ import_devUtils8.devUtils.warn(
3054
+ `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.`
3055
+ );
3056
+ return this.context.registration;
3057
+ }
3058
+ this.context.workerStoppedAt = void 0;
2873
3059
  this.context.startOptions = (0, import_mergeRight2.mergeRight)(
2874
3060
  DEFAULT_START_OPTIONS,
2875
3061
  options
@@ -2893,13 +3079,45 @@ var SetupWorkerApi = class extends import_SetupApi.SetupApi {
2893
3079
  this.subscriptions.push(() => {
2894
3080
  import_webSocketInterceptor.webSocketInterceptor.dispose();
2895
3081
  });
2896
- return await this.startHandler(this.context.startOptions, options);
3082
+ if (!this.context.supports.serviceWorkerApi) {
3083
+ const fallbackInterceptor = createFallbackRequestListener(
3084
+ this.context,
3085
+ this.context.startOptions
3086
+ );
3087
+ this.subscriptions.push(() => {
3088
+ fallbackInterceptor.dispose();
3089
+ });
3090
+ this.context.isMockingEnabled = true;
3091
+ printStartMessage({
3092
+ message: "Mocking enabled (fallback mode).",
3093
+ quiet: this.context.startOptions.quiet
3094
+ });
3095
+ return void 0;
3096
+ }
3097
+ const startHandler = createStartHandler(this.context);
3098
+ const registration = await startHandler(this.context.startOptions, options);
3099
+ this.context.isMockingEnabled = true;
3100
+ return registration;
2897
3101
  }
2898
3102
  stop() {
2899
3103
  super.dispose();
2900
- this.context.events.removeAllListeners();
3104
+ if (!this.context.isMockingEnabled) {
3105
+ import_devUtils8.devUtils.warn(
3106
+ 'Found a redundant "worker.stop()" call. Notice that stopping the worker after it has already been stopped has no effect. Consider removing this "worker.stop()" call.'
3107
+ );
3108
+ return;
3109
+ }
3110
+ this.context.isMockingEnabled = false;
3111
+ this.context.workerStoppedAt = Date.now();
2901
3112
  this.context.emitter.removeAllListeners();
2902
- this.stopHandler();
3113
+ if (this.context.supports.serviceWorkerApi) {
3114
+ this.context.workerChannel.removeAllListeners("RESPONSE");
3115
+ window.clearInterval(this.context.keepAliveInterval);
3116
+ }
3117
+ window.postMessage({ type: "msw/worker:stop" });
3118
+ printStopMessage({
3119
+ quiet: this.context.startOptions?.quiet
3120
+ });
2903
3121
  }
2904
3122
  };
2905
3123
  function setupWorker(...handlers) {