@zimic/interceptor 1.5.2-canary.0 → 1.5.2-canary.2

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 (44) hide show
  1. package/dist/{chunk-3WCEMV5U.js → chunk-UJTX22M5.js} +71 -20
  2. package/dist/chunk-UJTX22M5.js.map +1 -0
  3. package/dist/{chunk-YQNDAJTN.mjs → chunk-V5VFQ6WK.mjs} +71 -20
  4. package/dist/chunk-V5VFQ6WK.mjs.map +1 -0
  5. package/dist/cli.js +16 -16
  6. package/dist/cli.js.map +1 -1
  7. package/dist/cli.mjs +2 -2
  8. package/dist/cli.mjs.map +1 -1
  9. package/dist/http.d.ts +17 -5
  10. package/dist/http.js +366 -293
  11. package/dist/http.js.map +1 -1
  12. package/dist/http.mjs +365 -292
  13. package/dist/http.mjs.map +1 -1
  14. package/dist/server.js +6 -6
  15. package/dist/server.mjs +1 -1
  16. package/package.json +1 -1
  17. package/src/http/errors/HttpTimesCheckError.ts +9 -9
  18. package/src/http/index.ts +6 -1
  19. package/src/http/interceptor/HttpInterceptorImplementation.ts +74 -21
  20. package/src/http/interceptor/HttpInterceptorStore.ts +11 -13
  21. package/src/http/interceptor/LocalHttpInterceptor.ts +1 -10
  22. package/src/http/interceptor/RemoteHttpInterceptor.ts +16 -22
  23. package/src/http/interceptor/types/options.ts +1 -1
  24. package/src/http/interceptorWorker/HttpInterceptorWorker.ts +14 -3
  25. package/src/http/interceptorWorker/LocalHttpInterceptorWorker.ts +25 -93
  26. package/src/http/requestHandler/HttpRequestHandlerImplementation.ts +5 -9
  27. package/src/http/requestHandler/LocalHttpRequestHandler.ts +2 -5
  28. package/src/http/requestHandler/RemoteHttpRequestHandler.ts +17 -20
  29. package/src/http/requestHandler/types/public.ts +3 -8
  30. package/src/http/requestHandler/types/requests.ts +31 -3
  31. package/src/http/utils/logging.ts +54 -0
  32. package/src/interceptor/LocalMSWWorkerStore.ts +123 -0
  33. package/src/{http/interceptorWorker → interceptor}/types/msw.ts +1 -2
  34. package/src/server/utils/auth.ts +1 -1
  35. package/src/utils/fetch.ts +2 -2
  36. package/src/utils/logging.ts +0 -54
  37. package/src/utils/webSocket/WebSocketHandler.ts +9 -2
  38. package/src/utils/webSocket/WebSocketServer.ts +58 -12
  39. package/src/utils/webSocket/constants.ts +7 -0
  40. package/src/utils/webSocket/types.ts +1 -2
  41. package/src/utils/webSocket.ts +2 -2
  42. package/dist/chunk-3WCEMV5U.js.map +0 -1
  43. package/dist/chunk-YQNDAJTN.mjs.map +0 -1
  44. /package/src/{http/interceptorWorker → interceptor}/errors/UnregisteredBrowserServiceWorkerError.ts +0 -0
package/dist/http.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { InvalidFormDataError as InvalidFormDataError$1, InvalidJSONError as InvalidJSONError$1, HTTP_METHODS, HttpHeaders, HttpSearchParams, HttpFormData, parseHttpBody } from '@zimic/http';
2
- import color2 from 'picocolors';
2
+ import color from 'picocolors';
3
3
  import { http, bypass, passthrough } from 'msw';
4
4
  import ClientSocket from 'isomorphic-ws';
5
5
 
@@ -82,7 +82,7 @@ var RequestSavingSafeLimitExceededError_default = RequestSavingSafeLimitExceeded
82
82
  // src/cli/browser/shared/constants.ts
83
83
  var SERVICE_WORKER_FILE_NAME = "mockServiceWorker.js";
84
84
 
85
- // src/http/interceptorWorker/errors/UnregisteredBrowserServiceWorkerError.ts
85
+ // src/interceptor/errors/UnregisteredBrowserServiceWorkerError.ts
86
86
  var UnregisteredBrowserServiceWorkerError = class extends Error {
87
87
  constructor() {
88
88
  super(
@@ -247,130 +247,31 @@ function jsonEquals(value, otherValue) {
247
247
  });
248
248
  }
249
249
  var jsonEquals_default = jsonEquals;
250
-
251
- // ../zimic-utils/dist/chunk-W66SQPEM.mjs
252
- function createCachedDynamicImport(importModuleDynamically) {
253
- let cachedImportResult;
254
- return async function importModuleDynamicallyWithCache() {
255
- cachedImportResult ??= await importModuleDynamically();
256
- return cachedImportResult;
257
- };
258
- }
259
- var createCachedDynamicImport_default = createCachedDynamicImport;
260
-
261
- // ../zimic-utils/dist/logging.mjs
262
- var Logger = class _Logger {
263
- prefix;
264
- raw;
265
- constructor(options = {}) {
266
- const { prefix } = options;
267
- this.prefix = prefix;
268
- this.raw = prefix ? new _Logger({ ...options, prefix: void 0 }) : this;
269
- }
270
- logWithLevel(level, ...messages) {
271
- if (this.prefix) {
272
- console[level](this.prefix, ...messages);
273
- } else {
274
- console[level](...messages);
275
- }
276
- }
277
- info(...messages) {
278
- this.logWithLevel("log", ...messages);
279
- }
280
- warn(...messages) {
281
- this.logWithLevel("warn", ...messages);
282
- }
283
- error(...messages) {
284
- this.logWithLevel("error", ...messages);
285
- }
286
- table(headers, rows) {
287
- const columnLengths = headers.map((header) => {
288
- let maxValueLength = header.title.length;
289
- for (const row of rows) {
290
- const value = row[header.property];
291
- if (value.length > maxValueLength) {
292
- maxValueLength = value.length;
293
- }
294
- }
295
- return maxValueLength;
296
- });
297
- const formattedRows = [];
298
- const horizontalLine = columnLengths.map((length) => "\u2500".repeat(length));
299
- formattedRows.push(horizontalLine, []);
300
- for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
301
- const header = headers[headerIndex];
302
- const columnLength = columnLengths[headerIndex];
303
- const value = header.title;
304
- formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
305
- }
306
- formattedRows.push(horizontalLine);
307
- for (const row of rows) {
308
- formattedRows.push([]);
309
- for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
310
- const header = headers[headerIndex];
311
- const columnLength = columnLengths[headerIndex];
312
- const value = row[header.property];
313
- formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
314
- }
315
- }
316
- formattedRows.push(horizontalLine);
317
- const formattedTable = formattedRows.map((row, index) => {
318
- const isFirstLine = index === 0;
319
- if (isFirstLine) {
320
- return `\u250C\u2500${row.join("\u2500\u252C\u2500")}\u2500\u2510`;
321
- }
322
- const isLineAfterHeaders = index === 2;
323
- if (isLineAfterHeaders) {
324
- return `\u251C\u2500${row.join("\u2500\u253C\u2500")}\u2500\u2524`;
325
- }
326
- const isLastLine = index === formattedRows.length - 1;
327
- if (isLastLine) {
328
- return `\u2514\u2500${row.join("\u2500\u2534\u2500")}\u2500\u2518`;
329
- }
330
- return `\u2502 ${row.join(" \u2502 ")} \u2502`;
331
- }).join("\n");
332
- this.logWithLevel("log", formattedTable);
333
- }
334
- };
335
- var Logger_default = Logger;
336
-
337
- // src/utils/environment.ts
338
- function isServerSide() {
339
- return typeof process !== "undefined" && typeof process.versions !== "undefined";
340
- }
341
- function isClientSide() {
342
- return typeof window !== "undefined" && typeof document !== "undefined";
343
- }
344
-
345
- // src/utils/logging.ts
346
- var logger = new Logger_default({
347
- prefix: color2.cyan("[@zimic/interceptor]")
348
- });
349
- function stringifyJSONToLog(value) {
250
+ function stringifyHttpJSONToLog(value) {
350
251
  return JSON.stringify(
351
252
  value,
352
253
  (_key, value2) => {
353
- return stringifyValueToLog(value2, {
254
+ return stringifyHttpValueToLog(value2, {
354
255
  fallback: (value3) => value3
355
256
  });
356
257
  },
357
258
  2
358
259
  ).replace(/\n\s*/g, " ").replace(/"(File { name: '.*?', type: '.*?', size: \d*? })"/g, "$1").replace(/"(Blob { type: '.*?', size: \d*? })"/g, "$1");
359
260
  }
360
- function stringifyValueToLog(value, options = {}) {
361
- const { fallback = stringifyJSONToLog, includeClassName } = options;
261
+ function stringifyHttpValueToLog(value, options = {}) {
262
+ const { fallback = stringifyHttpJSONToLog, includeClassName } = options;
362
263
  if (value === null || value === void 0 || typeof value !== "object") {
363
264
  return String(value);
364
265
  }
365
266
  if (value instanceof HttpHeaders) {
366
- return stringifyValueToLog(value.toObject());
267
+ return stringifyHttpValueToLog(value.toObject());
367
268
  }
368
- if (value instanceof HttpHeaders || value instanceof HttpSearchParams) {
269
+ if (value instanceof HttpSearchParams) {
369
270
  const prefix = includeClassName?.searchParams ?? false ? "URLSearchParams " : "";
370
- return `${prefix}${stringifyValueToLog(value.toObject())}`;
271
+ return `${prefix}${stringifyHttpValueToLog(value.toObject())}`;
371
272
  }
372
273
  if (value instanceof HttpFormData) {
373
- return `FormData ${stringifyValueToLog(value.toObject())}`;
274
+ return `FormData ${stringifyHttpValueToLog(value.toObject())}`;
374
275
  }
375
276
  if (value instanceof File) {
376
277
  return `File { name: '${value.name}', type: '${value.type}', size: ${value.size} }`;
@@ -380,23 +281,6 @@ function stringifyValueToLog(value, options = {}) {
380
281
  }
381
282
  return fallback(value);
382
283
  }
383
- var importUtil = createCachedDynamicImport_default(() => import('util'));
384
- async function formatValueToLog(value, options = {}) {
385
- if (isClientSide()) {
386
- return value;
387
- }
388
- const { colors = true } = options;
389
- const util = await importUtil();
390
- return util.inspect(value, {
391
- colors,
392
- compact: true,
393
- depth: Infinity,
394
- maxArrayLength: Infinity,
395
- maxStringLength: Infinity,
396
- breakLength: Infinity,
397
- sorted: true
398
- });
399
- }
400
284
 
401
285
  // src/http/errors/HttpTimesCheckError.ts
402
286
  function createMessageHeader({
@@ -420,8 +304,8 @@ function createMessageHeader({
420
304
 
421
305
  Requests evaluated by this handler:
422
306
 
423
- ${color2.green("- Expected")}
424
- ${color2.red("+ Received")}`
307
+ ${color.green("- Expected")}
308
+ ${color.red("+ Received")}`
425
309
  ].filter((part) => part !== false).join("");
426
310
  }
427
311
  function createMessageDiffs({ requestSaving, unmatchedRequestGroups }) {
@@ -433,35 +317,35 @@ function createMessageDiffs({ requestSaving, unmatchedRequestGroups }) {
433
317
  const messageParts = [`${requestNumber}: ${request.method} ${request.url}`];
434
318
  if (diff.computed) {
435
319
  messageParts.push("Computed restriction:");
436
- const stringifiedExpected = stringifyValueToLog(diff.computed.expected);
437
- const stringifiedReceived = stringifyValueToLog(diff.computed.received);
438
- messageParts.push(` ${color2.green(`- return ${stringifiedExpected}`)}`);
439
- messageParts.push(` ${color2.red(`+ return ${stringifiedReceived}`)}`);
320
+ const stringifiedExpected = stringifyHttpValueToLog(diff.computed.expected);
321
+ const stringifiedReceived = stringifyHttpValueToLog(diff.computed.received);
322
+ messageParts.push(` ${color.green(`- return ${stringifiedExpected}`)}`);
323
+ messageParts.push(` ${color.red(`+ return ${stringifiedReceived}`)}`);
440
324
  }
441
325
  if (diff.headers) {
442
326
  messageParts.push("Headers:");
443
- const stringifiedExpected = stringifyValueToLog(diff.headers.expected);
444
- const stringifiedReceived = stringifyValueToLog(diff.headers.received);
445
- messageParts.push(` ${color2.green(`- ${stringifiedExpected}`)}`);
446
- messageParts.push(` ${color2.red(`+ ${stringifiedReceived}`)}`);
327
+ const stringifiedExpected = stringifyHttpValueToLog(diff.headers.expected);
328
+ const stringifiedReceived = stringifyHttpValueToLog(diff.headers.received);
329
+ messageParts.push(` ${color.green(`- ${stringifiedExpected}`)}`);
330
+ messageParts.push(` ${color.red(`+ ${stringifiedReceived}`)}`);
447
331
  }
448
332
  if (diff.searchParams) {
449
333
  messageParts.push("Search params:");
450
- const stringifiedExpected = stringifyValueToLog(diff.searchParams.expected);
451
- const stringifiedReceived = stringifyValueToLog(diff.searchParams.received);
452
- messageParts.push(` ${color2.green(`- ${stringifiedExpected}`)}`);
453
- messageParts.push(` ${color2.red(`+ ${stringifiedReceived}`)}`);
334
+ const stringifiedExpected = stringifyHttpValueToLog(diff.searchParams.expected);
335
+ const stringifiedReceived = stringifyHttpValueToLog(diff.searchParams.received);
336
+ messageParts.push(` ${color.green(`- ${stringifiedExpected}`)}`);
337
+ messageParts.push(` ${color.red(`+ ${stringifiedReceived}`)}`);
454
338
  }
455
339
  if (diff.body) {
456
340
  messageParts.push("Body:");
457
- const stringifiedExpected = stringifyValueToLog(diff.body.expected, {
341
+ const stringifiedExpected = stringifyHttpValueToLog(diff.body.expected, {
458
342
  includeClassName: { searchParams: true }
459
343
  });
460
- const stringifiedReceived = stringifyValueToLog(diff.body.received, {
344
+ const stringifiedReceived = stringifyHttpValueToLog(diff.body.received, {
461
345
  includeClassName: { searchParams: true }
462
346
  });
463
- messageParts.push(` ${color2.green(`- ${stringifiedExpected}`)}`);
464
- messageParts.push(` ${color2.red(`+ ${stringifiedReceived}`)}`);
347
+ messageParts.push(` ${color.green(`- ${stringifiedExpected}`)}`);
348
+ messageParts.push(` ${color.red(`+ ${stringifiedReceived}`)}`);
465
349
  }
466
350
  return messageParts.join("\n ");
467
351
  }).join("\n\n");
@@ -491,6 +375,16 @@ var HttpTimesCheckError = class extends TimesCheckError {
491
375
  };
492
376
  var HttpTimesCheckError_default = HttpTimesCheckError;
493
377
 
378
+ // ../zimic-utils/dist/chunk-W66SQPEM.mjs
379
+ function createCachedDynamicImport(importModuleDynamically) {
380
+ let cachedImportResult;
381
+ return async function importModuleDynamicallyWithCache() {
382
+ cachedImportResult ??= await importModuleDynamically();
383
+ return cachedImportResult;
384
+ };
385
+ }
386
+ var createCachedDynamicImport_default = createCachedDynamicImport;
387
+
494
388
  // ../zimic-utils/dist/time.mjs
495
389
  function waitForDelay(milliseconds) {
496
390
  return new Promise((resolve) => {
@@ -499,6 +393,14 @@ function waitForDelay(milliseconds) {
499
393
  }
500
394
  var waitForDelay_default = waitForDelay;
501
395
 
396
+ // src/utils/environment.ts
397
+ function isServerSide() {
398
+ return typeof process !== "undefined" && typeof process.versions !== "undefined";
399
+ }
400
+ function isClientSide() {
401
+ return typeof window !== "undefined" && typeof document !== "undefined";
402
+ }
403
+
502
404
  // src/utils/data.ts
503
405
  async function convertReadableStreamToBlob(stream, options) {
504
406
  const chunks = [];
@@ -1042,6 +944,102 @@ function methodCanHaveResponseBody(method) {
1042
944
  return HTTP_METHODS_WITH_RESPONSE_BODY.has(method);
1043
945
  }
1044
946
 
947
+ // ../zimic-utils/dist/logging.mjs
948
+ var Logger = class _Logger {
949
+ prefix;
950
+ raw;
951
+ constructor(options = {}) {
952
+ const { prefix } = options;
953
+ this.prefix = prefix;
954
+ this.raw = prefix ? new _Logger({ ...options, prefix: void 0 }) : this;
955
+ }
956
+ logWithLevel(level, ...messages) {
957
+ if (this.prefix) {
958
+ console[level](this.prefix, ...messages);
959
+ } else {
960
+ console[level](...messages);
961
+ }
962
+ }
963
+ info(...messages) {
964
+ this.logWithLevel("log", ...messages);
965
+ }
966
+ warn(...messages) {
967
+ this.logWithLevel("warn", ...messages);
968
+ }
969
+ error(...messages) {
970
+ this.logWithLevel("error", ...messages);
971
+ }
972
+ table(headers, rows) {
973
+ const columnLengths = headers.map((header) => {
974
+ let maxValueLength = header.title.length;
975
+ for (const row of rows) {
976
+ const value = row[header.property];
977
+ if (value.length > maxValueLength) {
978
+ maxValueLength = value.length;
979
+ }
980
+ }
981
+ return maxValueLength;
982
+ });
983
+ const formattedRows = [];
984
+ const horizontalLine = columnLengths.map((length) => "\u2500".repeat(length));
985
+ formattedRows.push(horizontalLine, []);
986
+ for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
987
+ const header = headers[headerIndex];
988
+ const columnLength = columnLengths[headerIndex];
989
+ const value = header.title;
990
+ formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
991
+ }
992
+ formattedRows.push(horizontalLine);
993
+ for (const row of rows) {
994
+ formattedRows.push([]);
995
+ for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
996
+ const header = headers[headerIndex];
997
+ const columnLength = columnLengths[headerIndex];
998
+ const value = row[header.property];
999
+ formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
1000
+ }
1001
+ }
1002
+ formattedRows.push(horizontalLine);
1003
+ const formattedTable = formattedRows.map((row, index) => {
1004
+ const isFirstLine = index === 0;
1005
+ if (isFirstLine) {
1006
+ return `\u250C\u2500${row.join("\u2500\u252C\u2500")}\u2500\u2510`;
1007
+ }
1008
+ const isLineAfterHeaders = index === 2;
1009
+ if (isLineAfterHeaders) {
1010
+ return `\u251C\u2500${row.join("\u2500\u253C\u2500")}\u2500\u2524`;
1011
+ }
1012
+ const isLastLine = index === formattedRows.length - 1;
1013
+ if (isLastLine) {
1014
+ return `\u2514\u2500${row.join("\u2500\u2534\u2500")}\u2500\u2518`;
1015
+ }
1016
+ return `\u2502 ${row.join(" \u2502 ")} \u2502`;
1017
+ }).join("\n");
1018
+ this.logWithLevel("log", formattedTable);
1019
+ }
1020
+ };
1021
+ var Logger_default = Logger;
1022
+ var logger = new Logger_default({
1023
+ prefix: color.cyan("[@zimic/interceptor]")
1024
+ });
1025
+ var importUtil = createCachedDynamicImport_default(() => import('util'));
1026
+ async function formatValueToLog(value, options = {}) {
1027
+ if (isClientSide()) {
1028
+ return value;
1029
+ }
1030
+ const { colors = true } = options;
1031
+ const util = await importUtil();
1032
+ return util.inspect(value, {
1033
+ colors,
1034
+ compact: true,
1035
+ depth: Infinity,
1036
+ maxArrayLength: Infinity,
1037
+ maxStringLength: Infinity,
1038
+ breakLength: Infinity,
1039
+ sorted: true
1040
+ });
1041
+ }
1042
+
1045
1043
  // src/http/requestHandler/types/requests.ts
1046
1044
  var HTTP_INTERCEPTOR_REQUEST_HIDDEN_PROPERTIES = Object.freeze(
1047
1045
  /* @__PURE__ */ new Set([
@@ -1080,7 +1078,13 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1080
1078
  startingPromise;
1081
1079
  stoppingPromise;
1082
1080
  runningInterceptors = [];
1081
+ get numberOfRunningInterceptors() {
1082
+ return this.runningInterceptors.length;
1083
+ }
1083
1084
  async sharedStart(internalStart) {
1085
+ if (this.stoppingPromise) {
1086
+ await this.stoppingPromise;
1087
+ }
1084
1088
  if (this.isRunning) {
1085
1089
  return;
1086
1090
  }
@@ -1109,9 +1113,12 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1109
1113
  const stoppingResult = internalStop();
1110
1114
  if (stoppingResult instanceof Promise) {
1111
1115
  this.stoppingPromise = stoppingResult;
1112
- await this.stoppingPromise;
1116
+ try {
1117
+ await this.stoppingPromise;
1118
+ } finally {
1119
+ this.stoppingPromise = void 0;
1120
+ }
1113
1121
  }
1114
- this.stoppingPromise = void 0;
1115
1122
  }
1116
1123
  async logUnhandledRequestIfNecessary(request, strategy) {
1117
1124
  if (strategy?.log) {
@@ -1349,7 +1356,7 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1349
1356
  formatValueToLog(request.body)
1350
1357
  ]);
1351
1358
  logger[action === "bypass" ? "warn" : "error"](
1352
- `${action === "bypass" ? "Warning:" : "Error:"} Request was not handled and was ${action === "bypass" ? color2.yellow("bypassed") : color2.red("rejected")}.
1359
+ `${action === "bypass" ? "Warning:" : "Error:"} Request was not handled and was ${action === "bypass" ? color.yellow("bypassed") : color.red("rejected")}.
1353
1360
 
1354
1361
  `,
1355
1362
  `${request.method} ${request.url}`,
@@ -1366,16 +1373,16 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1366
1373
  var HttpInterceptorWorker_default = HttpInterceptorWorker;
1367
1374
 
1368
1375
  // src/http/requestHandler/RemoteHttpRequestHandler.ts
1369
- var UNSYNCED_PROPERTIES = /* @__PURE__ */ new Set(["then"]);
1376
+ var PENDING_PROPERTIES = /* @__PURE__ */ new Set(["then"]);
1370
1377
  var RemoteHttpRequestHandler = class {
1371
1378
  type = "remote";
1372
1379
  implementation;
1373
1380
  syncPromises = [];
1374
- unsynced;
1381
+ pending;
1375
1382
  synced;
1376
1383
  constructor(interceptor, method, path) {
1377
1384
  this.implementation = new HttpRequestHandlerImplementation_default(interceptor, method, path, this);
1378
- this.unsynced = this;
1385
+ this.pending = this;
1379
1386
  this.synced = this.createSyncedProxy();
1380
1387
  }
1381
1388
  createSyncedProxy() {
@@ -1395,7 +1402,7 @@ var RemoteHttpRequestHandler = class {
1395
1402
  });
1396
1403
  }
1397
1404
  shouldBeHiddenPropertyWhenSynced(property) {
1398
- return UNSYNCED_PROPERTIES.has(property);
1405
+ return PENDING_PROPERTIES.has(property);
1399
1406
  }
1400
1407
  get method() {
1401
1408
  return this.implementation.method;
@@ -1405,16 +1412,16 @@ var RemoteHttpRequestHandler = class {
1405
1412
  }
1406
1413
  with(restriction) {
1407
1414
  this.implementation.with(restriction);
1408
- return this.unsynced;
1415
+ return this.pending;
1409
1416
  }
1410
1417
  delay(minMilliseconds, maxMilliseconds) {
1411
1418
  this.implementation.delay(minMilliseconds, maxMilliseconds);
1412
- return this.unsynced;
1419
+ return this.pending;
1413
1420
  }
1414
1421
  respond(declaration) {
1415
- const newUnsyncedThis = this.unsynced;
1416
- newUnsyncedThis.implementation.respond(declaration);
1417
- return newUnsyncedThis;
1422
+ const pending = this.pending;
1423
+ pending.implementation.respond(declaration);
1424
+ return pending;
1418
1425
  }
1419
1426
  times(minNumberOfRequests, maxNumberOfRequests) {
1420
1427
  this.implementation.times(minNumberOfRequests, maxNumberOfRequests);
@@ -1432,7 +1439,7 @@ var RemoteHttpRequestHandler = class {
1432
1439
  }
1433
1440
  clear() {
1434
1441
  this.implementation.clear();
1435
- return this.unsynced;
1442
+ return this.pending;
1436
1443
  }
1437
1444
  get requests() {
1438
1445
  return this.implementation.requests;
@@ -1464,7 +1471,7 @@ var RemoteHttpRequestHandler = class {
1464
1471
  const promisesToWait = new Set(this.syncPromises);
1465
1472
  return Promise.all(promisesToWait).then(() => {
1466
1473
  this.syncPromises = this.syncPromises.filter((promise) => !promisesToWait.has(promise));
1467
- return this.isSynced ? this.synced : this.unsynced;
1474
+ return this.isSynced ? this.synced : this.pending;
1468
1475
  }).then(onFulfilled, onRejected);
1469
1476
  }
1470
1477
  catch(onRejected) {
@@ -1485,6 +1492,9 @@ var HttpInterceptorImplementation = class {
1485
1492
  createWorker;
1486
1493
  deleteWorker;
1487
1494
  worker;
1495
+ startPromise;
1496
+ numberOfPendingStarts = 0;
1497
+ lifecycleQueue = Promise.resolve();
1488
1498
  requestSaving;
1489
1499
  numberOfSavedRequests = 0;
1490
1500
  onUnhandledRequest;
@@ -1518,7 +1528,7 @@ var HttpInterceptorImplementation = class {
1518
1528
  return this.#baseURL;
1519
1529
  }
1520
1530
  set baseURL(newBaseURL) {
1521
- if (this.isRunning) {
1531
+ if (this.isRunning || this.isStarting) {
1522
1532
  throw new RunningHttpInterceptorError_default(
1523
1533
  "Did you forget to call `await interceptor.stop()` before changing the base URL?"
1524
1534
  );
@@ -1542,27 +1552,67 @@ var HttpInterceptorImplementation = class {
1542
1552
  get platform() {
1543
1553
  return this.worker?.platform ?? null;
1544
1554
  }
1545
- async start() {
1555
+ start() {
1556
+ if (this.startPromise) {
1557
+ return this.startPromise;
1558
+ }
1559
+ this.numberOfPendingStarts++;
1560
+ const startPromise = this.enqueueLifecycleOperation(() => this.startOnce()).finally(() => {
1561
+ this.numberOfPendingStarts--;
1562
+ const isLastStartPromise = this.startPromise === startPromise;
1563
+ if (isLastStartPromise) {
1564
+ this.startPromise = void 0;
1565
+ }
1566
+ });
1567
+ this.startPromise = startPromise;
1568
+ return startPromise;
1569
+ }
1570
+ async startOnce() {
1571
+ if (this.isRunning) {
1572
+ return;
1573
+ }
1546
1574
  try {
1547
1575
  this.worker = this.createWorker();
1548
- await this.worker.start();
1549
1576
  this.worker.registerRunningInterceptor(this);
1577
+ await this.worker.start();
1550
1578
  this.markAsRunning(true);
1551
1579
  } catch (error) {
1552
- await this.stop();
1580
+ await this.stopWorker();
1553
1581
  throw error;
1554
1582
  }
1555
1583
  }
1556
- async stop() {
1584
+ get isStarting() {
1585
+ return this.numberOfPendingStarts > 0;
1586
+ }
1587
+ async stop(options) {
1588
+ this.startPromise = void 0;
1589
+ await this.enqueueLifecycleOperation(() => this.stopOnce(options));
1590
+ }
1591
+ async stopOnce(options) {
1592
+ if (!this.isRunning) {
1593
+ return;
1594
+ }
1595
+ await options.beforeStop?.();
1596
+ await this.stopWorker();
1597
+ }
1598
+ async stopWorker() {
1557
1599
  this.worker?.unregisterRunningInterceptor(this);
1558
- const isLastRunningInterceptor = this.numberOfRunningInterceptors === 0 || this.numberOfRunningInterceptors === 1;
1600
+ const isLastRunningInterceptor = this.worker?.numberOfRunningInterceptors === 0;
1559
1601
  if (isLastRunningInterceptor) {
1560
1602
  await this.worker?.stop();
1561
- this.deleteWorker();
1603
+ const isStillLastRunningInterceptor = this.worker?.numberOfRunningInterceptors === 0;
1604
+ if (isStillLastRunningInterceptor) {
1605
+ this.deleteWorker();
1606
+ }
1562
1607
  }
1563
1608
  this.markAsRunning(false);
1564
1609
  this.worker = void 0;
1565
1610
  }
1611
+ enqueueLifecycleOperation(operation) {
1612
+ const operationPromise = this.lifecycleQueue.then(operation);
1613
+ this.lifecycleQueue = operationPromise.catch(() => void 0);
1614
+ return operationPromise;
1615
+ }
1566
1616
  markAsRunning(isRunning) {
1567
1617
  if (this.workerOrThrow.type === "local") {
1568
1618
  this.store.markLocalInterceptorAsRunning(this, isRunning);
@@ -1571,16 +1621,6 @@ var HttpInterceptorImplementation = class {
1571
1621
  }
1572
1622
  this.isRunning = isRunning;
1573
1623
  }
1574
- get numberOfRunningInterceptors() {
1575
- if (!this.isRunning) {
1576
- return 0;
1577
- }
1578
- if (this.workerOrThrow.type === "local") {
1579
- return this.store.numberOfRunningLocalInterceptors;
1580
- } else {
1581
- return this.store.numberOfRunningRemoteInterceptors(this.baseURL);
1582
- }
1583
- }
1584
1624
  get(path) {
1585
1625
  return this.createHttpRequestHandler("GET", path);
1586
1626
  }
@@ -1729,13 +1769,91 @@ var HttpInterceptorImplementation = class {
1729
1769
  }
1730
1770
  };
1731
1771
  var HttpInterceptorImplementation_default = HttpInterceptorImplementation;
1772
+
1773
+ // src/interceptor/LocalMSWWorkerStore.ts
1732
1774
  var importMSWNode = createCachedDynamicImport_default(() => import('msw/node'));
1733
1775
  var importMSWBrowser = createCachedDynamicImport_default(() => import('msw/browser'));
1734
- var LocalHttpInterceptorWorker = class _LocalHttpInterceptorWorker extends HttpInterceptorWorker_default {
1735
- // Re-creating MSW workers may cause issues, so we should keep a single worker instance, even if all interceptor
1736
- // workers are stopped. See https://github.com/mswjs/msw/issues/2597.
1776
+ var LocalMSWWorkerStore = class _LocalMSWWorkerStore {
1737
1777
  static mswWorker;
1778
+ static creatingMSWWorkerPromise;
1779
+ static startingMSWWorkerPromise;
1780
+ static numberOfRunningWorkers = 0;
1738
1781
  static isMSWWorkerRunning = false;
1782
+ class = _LocalMSWWorkerStore;
1783
+ get mswWorker() {
1784
+ return this.class.mswWorker;
1785
+ }
1786
+ async getMSWWorkerOrCreate(options) {
1787
+ if (this.class.mswWorker) {
1788
+ return this.class.mswWorker;
1789
+ }
1790
+ this.class.creatingMSWWorkerPromise ??= this.createMSWWorker(options).then((mswWorker) => {
1791
+ this.class.mswWorker = mswWorker;
1792
+ return mswWorker;
1793
+ }).finally(() => {
1794
+ this.class.creatingMSWWorkerPromise = void 0;
1795
+ });
1796
+ return this.class.creatingMSWWorkerPromise;
1797
+ }
1798
+ async createMSWWorker(options) {
1799
+ if (isServerSide()) {
1800
+ const mswNode = await importMSWNode();
1801
+ if ("setupServer" in mswNode) {
1802
+ return mswNode.setupServer();
1803
+ }
1804
+ }
1805
+ if (isClientSide()) {
1806
+ const mswBrowser = await importMSWBrowser();
1807
+ if ("setupWorker" in mswBrowser) {
1808
+ return mswBrowser.setupWorker();
1809
+ }
1810
+ }
1811
+ throw options.createUnknownPlatformError();
1812
+ }
1813
+ async startMSWWorker(mswWorker, sharedOptions) {
1814
+ if (!this.class.isMSWWorkerRunning) {
1815
+ this.class.startingMSWWorkerPromise ??= this.startMSWWorkerOnce(mswWorker, sharedOptions).then(() => {
1816
+ this.class.isMSWWorkerRunning = true;
1817
+ }).finally(() => {
1818
+ this.class.startingMSWWorkerPromise = void 0;
1819
+ });
1820
+ await this.class.startingMSWWorkerPromise;
1821
+ }
1822
+ this.class.numberOfRunningWorkers++;
1823
+ }
1824
+ async startMSWWorkerOnce(mswWorker, sharedOptions) {
1825
+ if (this.isInternalBrowserWorker(mswWorker)) {
1826
+ try {
1827
+ await mswWorker.start({ ...sharedOptions, quiet: true });
1828
+ } catch (error) {
1829
+ if (UnregisteredBrowserServiceWorkerError_default.matchesRawError(error)) {
1830
+ throw new UnregisteredBrowserServiceWorkerError_default();
1831
+ } else {
1832
+ throw error;
1833
+ }
1834
+ }
1835
+ } else {
1836
+ mswWorker.listen(sharedOptions);
1837
+ }
1838
+ }
1839
+ stopMSWWorker(mswWorker) {
1840
+ this.class.numberOfRunningWorkers = Math.max(this.class.numberOfRunningWorkers - 1, 0);
1841
+ if (this.class.numberOfRunningWorkers > 0) {
1842
+ return;
1843
+ }
1844
+ if (this.isInternalBrowserWorker(mswWorker)) ; else {
1845
+ mswWorker.close();
1846
+ this.class.isMSWWorkerRunning = false;
1847
+ }
1848
+ }
1849
+ isInternalBrowserWorker(worker) {
1850
+ return "start" in worker && "stop" in worker;
1851
+ }
1852
+ };
1853
+ var LocalMSWWorkerStore_default = LocalMSWWorkerStore;
1854
+
1855
+ // src/http/interceptorWorker/LocalHttpInterceptorWorker.ts
1856
+ var LocalHttpInterceptorWorker = class extends HttpInterceptorWorker_default {
1739
1857
  mswHttpHandler;
1740
1858
  httpHandlersByMethod = {
1741
1859
  GET: [],
@@ -1746,39 +1864,28 @@ var LocalHttpInterceptorWorker = class _LocalHttpInterceptorWorker extends HttpI
1746
1864
  HEAD: [],
1747
1865
  OPTIONS: []
1748
1866
  };
1867
+ store = new LocalMSWWorkerStore_default();
1749
1868
  constructor(_options) {
1750
1869
  super();
1751
1870
  }
1752
- get class() {
1753
- return _LocalHttpInterceptorWorker;
1754
- }
1755
1871
  get type() {
1756
1872
  return "local";
1757
1873
  }
1758
1874
  get mswWorkerOrThrow() {
1759
- if (!this.class.mswWorker) {
1875
+ if (!this.store.mswWorker) {
1760
1876
  throw new NotRunningHttpInterceptorError_default();
1761
1877
  }
1762
- return this.class.mswWorker;
1878
+ return this.store.mswWorker;
1763
1879
  }
1764
1880
  async getMSWWorkerOrCreate() {
1765
- this.class.mswWorker ??= await this.createMSWWorker();
1766
- return this.class.mswWorker;
1767
- }
1768
- async createMSWWorker() {
1769
- if (isServerSide()) {
1770
- const mswNode = await importMSWNode();
1771
- if ("setupServer" in mswNode) {
1772
- return mswNode.setupServer();
1773
- }
1774
- }
1775
- if (isClientSide()) {
1776
- const mswBrowser = await importMSWBrowser();
1777
- if ("setupWorker" in mswBrowser) {
1778
- return mswBrowser.setupWorker();
1779
- }
1780
- }
1781
- throw new UnknownHttpInterceptorPlatformError_default();
1881
+ return this.store.getMSWWorkerOrCreate({
1882
+ createUnknownPlatformError: (
1883
+ // The unknown platform error is created here to prevent the store from relying on HTTP-specific resources.
1884
+ /* istanbul ignore next -- @preserve
1885
+ * Unknown runtime platforms are not part of the package test matrix. */
1886
+ () => new UnknownHttpInterceptorPlatformError_default()
1887
+ )
1888
+ });
1782
1889
  }
1783
1890
  async start() {
1784
1891
  await super.sharedStart(async () => {
@@ -1794,54 +1901,33 @@ var LocalHttpInterceptorWorker = class _LocalHttpInterceptorWorker extends HttpI
1794
1901
  mswWorker.use(this.mswHttpHandler);
1795
1902
  if (this.isInternalBrowserWorker(mswWorker)) {
1796
1903
  this.platform = "browser";
1797
- if (!this.class.isMSWWorkerRunning) {
1798
- await this.startInBrowser(mswWorker, sharedOptions);
1799
- this.class.isMSWWorkerRunning = true;
1800
- }
1801
1904
  } else {
1802
1905
  this.platform = "node";
1803
- this.startInNode(mswWorker, sharedOptions);
1804
- this.class.isMSWWorkerRunning = true;
1906
+ }
1907
+ try {
1908
+ await this.store.startMSWWorker(mswWorker, sharedOptions);
1909
+ } catch (error) {
1910
+ const newMSWHandlers = mswWorker.listHandlers().filter((handler) => handler !== this.mswHttpHandler);
1911
+ mswWorker.resetHandlers(...newMSWHandlers);
1912
+ this.mswHttpHandler = void 0;
1913
+ throw error;
1805
1914
  }
1806
1915
  this.isRunning = true;
1807
1916
  });
1808
1917
  }
1809
- async startInBrowser(mswWorker, sharedOptions) {
1810
- try {
1811
- await mswWorker.start({ ...sharedOptions, quiet: true });
1812
- } catch (error) {
1813
- this.handleBrowserWorkerStartError(error);
1814
- }
1815
- }
1816
- handleBrowserWorkerStartError(error) {
1817
- if (UnregisteredBrowserServiceWorkerError_default.matchesRawError(error)) {
1818
- throw new UnregisteredBrowserServiceWorkerError_default();
1819
- } else {
1820
- throw error;
1821
- }
1822
- }
1823
- startInNode(mswWorker, sharedOptions) {
1824
- mswWorker.listen(sharedOptions);
1825
- }
1826
1918
  async stop() {
1827
1919
  await super.sharedStop(async () => {
1828
1920
  const mswWorker = await this.getMSWWorkerOrCreate();
1829
1921
  this.clearHandlers();
1830
1922
  const newMSWHandlers = mswWorker.listHandlers().filter((handler) => handler !== this.mswHttpHandler);
1831
1923
  mswWorker.resetHandlers(...newMSWHandlers);
1832
- if (this.isInternalBrowserWorker(mswWorker)) ; else {
1833
- this.stopInNode(mswWorker);
1834
- this.class.isMSWWorkerRunning = false;
1835
- }
1924
+ this.store.stopMSWWorker(mswWorker);
1836
1925
  this.mswHttpHandler = void 0;
1837
1926
  this.isRunning = false;
1838
1927
  });
1839
1928
  }
1840
- stopInNode(mswWorker) {
1841
- mswWorker.close();
1842
- }
1843
1929
  isInternalBrowserWorker(worker) {
1844
- return "start" in worker && "stop" in worker;
1930
+ return this.store.isInternalBrowserWorker(worker);
1845
1931
  }
1846
1932
  hasInternalBrowserWorker() {
1847
1933
  return this.isInternalBrowserWorker(this.mswWorkerOrThrow);
@@ -1999,6 +2085,15 @@ async function serializeResponse(response) {
1999
2085
  };
2000
2086
  }
2001
2087
 
2088
+ // src/utils/webSocket/constants.ts
2089
+ var WEB_SOCKET_CONTROL_MESSAGES = Object.freeze(["socket:auth:valid"]);
2090
+ var WEB_SOCKET_CLOSE_CODES = Object.freeze({
2091
+ DEFAULT: 1e3,
2092
+ PROTOCOL_ERROR: 1002,
2093
+ POLICY_VIOLATION: 1008,
2094
+ INTERNAL_ERROR: 1011
2095
+ });
2096
+
2002
2097
  // src/utils/webSocket/errors/UnauthorizedWebSocketConnectionError.ts
2003
2098
  var UnauthorizedWebSocketConnectionError = class extends Error {
2004
2099
  constructor(event) {
@@ -2057,7 +2152,7 @@ async function waitForOpenClientSocket(socket, options = {}) {
2057
2152
  reject(error);
2058
2153
  }
2059
2154
  function handleClose(event) {
2060
- const isUnauthorized = event.code === 1008;
2155
+ const isUnauthorized = event.code === WEB_SOCKET_CLOSE_CODES.POLICY_VIOLATION;
2061
2156
  if (isUnauthorized) {
2062
2157
  const unauthorizedError = new UnauthorizedWebSocketConnectionError_default(event);
2063
2158
  handleOpenError(unauthorizedError);
@@ -2119,9 +2214,6 @@ async function closeClientSocket(socket, options = {}) {
2119
2214
  });
2120
2215
  }
2121
2216
 
2122
- // src/utils/webSocket/constants.ts
2123
- var WEB_SOCKET_CONTROL_MESSAGES = Object.freeze(["socket:auth:valid"]);
2124
-
2125
2217
  // src/utils/webSocket/errors/InvalidWebSocketMessageError.ts
2126
2218
  var InvalidWebSocketMessageError = class extends Error {
2127
2219
  constructor(message) {
@@ -2162,7 +2254,12 @@ var WebSocketHandler = class {
2162
2254
  await this.handleSocketMessage(socket, rawMessage);
2163
2255
  };
2164
2256
  socket.addEventListener("message", handleSocketMessage);
2165
- await openPromise;
2257
+ try {
2258
+ await openPromise;
2259
+ } catch (error) {
2260
+ socket.removeEventListener("message", handleSocketMessage);
2261
+ throw error;
2262
+ }
2166
2263
  function handleSocketError(error) {
2167
2264
  console.error(error);
2168
2265
  }
@@ -2177,6 +2274,7 @@ var WebSocketHandler = class {
2177
2274
  };
2178
2275
  socket.addEventListener("close", handleSocketClose);
2179
2276
  this.sockets.add(socket);
2277
+ return handleSocketClose;
2180
2278
  }
2181
2279
  handleSocketMessage = async (socket, rawMessage) => {
2182
2280
  try {
@@ -2572,24 +2670,15 @@ var RemoteHttpInterceptorWorker = class extends HttpInterceptorWorker_default {
2572
2670
  };
2573
2671
  var RemoteHttpInterceptorWorker_default = RemoteHttpInterceptorWorker;
2574
2672
 
2575
- // src/http/interceptorWorker/factory.ts
2576
- function createHttpInterceptorWorker(options) {
2577
- if (options.type === "local") {
2578
- return new LocalHttpInterceptorWorker_default(options);
2579
- } else {
2580
- return new RemoteHttpInterceptorWorker_default(options);
2581
- }
2582
- }
2583
-
2584
2673
  // src/http/interceptor/HttpInterceptorStore.ts
2585
2674
  var HttpInterceptorStore = class _HttpInterceptorStore {
2586
- static _localWorker;
2587
- static runningLocalInterceptors = /* @__PURE__ */ new Set();
2675
+ static localWorker;
2588
2676
  static remoteWorkers = /* @__PURE__ */ new Map();
2677
+ static runningLocalInterceptors = /* @__PURE__ */ new Set();
2589
2678
  static runningRemoteInterceptors = /* @__PURE__ */ new Map();
2590
2679
  class = _HttpInterceptorStore;
2591
2680
  get localWorker() {
2592
- return this.class._localWorker;
2681
+ return this.class.localWorker;
2593
2682
  }
2594
2683
  getRemoteWorkerKey(baseURL, options) {
2595
2684
  const key = [`${baseURL.origin}${baseURL.pathname}`];
@@ -2598,7 +2687,7 @@ var HttpInterceptorStore = class _HttpInterceptorStore {
2598
2687
  }
2599
2688
  return key.join(":");
2600
2689
  }
2601
- remoteWorker(baseURL, options) {
2690
+ getRemoteWorker(baseURL, options) {
2602
2691
  const remoteWorkerKey = this.getRemoteWorkerKey(baseURL, options);
2603
2692
  return this.class.remoteWorkers.get(remoteWorkerKey);
2604
2693
  }
@@ -2630,16 +2719,16 @@ var HttpInterceptorStore = class _HttpInterceptorStore {
2630
2719
  return runningInterceptors;
2631
2720
  }
2632
2721
  getOrCreateLocalWorker(workerOptions) {
2633
- const existingWorker = this.class._localWorker;
2722
+ const existingWorker = this.class.localWorker;
2634
2723
  if (existingWorker) {
2635
2724
  return existingWorker;
2636
2725
  }
2637
- const createdWorker = createHttpInterceptorWorker({ ...workerOptions, type: "local" });
2638
- this.class._localWorker = createdWorker;
2726
+ const createdWorker = new LocalHttpInterceptorWorker_default({ ...workerOptions, type: "local" });
2727
+ this.class.localWorker = createdWorker;
2639
2728
  return createdWorker;
2640
2729
  }
2641
2730
  deleteLocalWorker() {
2642
- this.class._localWorker = void 0;
2731
+ this.class.localWorker = void 0;
2643
2732
  }
2644
2733
  getOrCreateRemoteWorker(workerOptions) {
2645
2734
  const remoteWorkerKey = this.getRemoteWorkerKey(workerOptions.serverURL, { auth: workerOptions.auth });
@@ -2647,7 +2736,7 @@ var HttpInterceptorStore = class _HttpInterceptorStore {
2647
2736
  if (existingWorker) {
2648
2737
  return existingWorker;
2649
2738
  }
2650
- const createdWorker = createHttpInterceptorWorker({ ...workerOptions, type: "remote" });
2739
+ const createdWorker = new RemoteHttpInterceptorWorker_default({ ...workerOptions, type: "remote" });
2651
2740
  this.class.remoteWorkers.set(remoteWorkerKey, createdWorker);
2652
2741
  return createdWorker;
2653
2742
  }
@@ -2702,17 +2791,10 @@ var LocalHttpInterceptor = class {
2702
2791
  return this.implementation.isRunning;
2703
2792
  }
2704
2793
  async start() {
2705
- if (this.isRunning) {
2706
- return;
2707
- }
2708
2794
  await this.implementation.start();
2709
2795
  }
2710
2796
  async stop() {
2711
- if (!this.isRunning) {
2712
- return;
2713
- }
2714
- this.clear();
2715
- await this.implementation.stop();
2797
+ await this.implementation.stop({ beforeStop: () => this.clear() });
2716
2798
  }
2717
2799
  get = ((path) => {
2718
2800
  return this.implementation.get(path);
@@ -2750,24 +2832,24 @@ var RemoteHttpInterceptor = class {
2750
2832
  implementation;
2751
2833
  #auth;
2752
2834
  constructor(options) {
2753
- this.#auth = options.auth;
2754
2835
  const baseURL = new URL(options.baseURL);
2755
2836
  this.implementation = new HttpInterceptorImplementation_default({
2756
2837
  store: this.store,
2757
2838
  baseURL,
2758
2839
  createWorker: () => {
2759
2840
  return this.store.getOrCreateRemoteWorker({
2760
- serverURL: baseURL,
2841
+ serverURL: this.implementation.baseURL,
2761
2842
  auth: this.#auth
2762
2843
  });
2763
2844
  },
2764
2845
  deleteWorker: () => {
2765
- this.store.deleteRemoteWorker(baseURL, { auth: options.auth });
2846
+ this.store.deleteRemoteWorker(this.implementation.baseURL, { auth: this.#auth });
2766
2847
  },
2767
2848
  Handler: RemoteHttpRequestHandler_default,
2768
2849
  onUnhandledRequest: options.onUnhandledRequest,
2769
2850
  requestSaving: options.requestSaving
2770
2851
  });
2852
+ this.auth = options.auth;
2771
2853
  }
2772
2854
  get type() {
2773
2855
  return "remote";
@@ -2789,21 +2871,25 @@ var RemoteHttpInterceptor = class {
2789
2871
  }
2790
2872
  set auth(auth) {
2791
2873
  const cannotChangeAuthWhileRunningMessage = "Did you forget to call `await interceptor.stop()` before changing the authentication parameters?";
2792
- if (this.isRunning) {
2874
+ if (this.isRunning || this.implementation.isStarting) {
2793
2875
  throw new RunningHttpInterceptorError_default(cannotChangeAuthWhileRunningMessage);
2794
2876
  }
2795
2877
  if (!auth) {
2796
2878
  this.#auth = void 0;
2797
2879
  return;
2798
2880
  }
2799
- this.#auth = new Proxy(auth, {
2800
- set: (target, property, value) => {
2801
- if (this.isRunning) {
2802
- throw new RunningHttpInterceptorError_default(cannotChangeAuthWhileRunningMessage);
2881
+ this.#auth = new Proxy(
2882
+ { ...auth },
2883
+ // Copy object to ensure it's not mutated later without going though the proxy.
2884
+ {
2885
+ set: (target, property, value) => {
2886
+ if (this.isRunning || this.implementation.isStarting) {
2887
+ throw new RunningHttpInterceptorError_default(cannotChangeAuthWhileRunningMessage);
2888
+ }
2889
+ return Reflect.set(target, property, value);
2803
2890
  }
2804
- return Reflect.set(target, property, value);
2805
2891
  }
2806
- });
2892
+ );
2807
2893
  }
2808
2894
  get onUnhandledRequest() {
2809
2895
  return this.implementation.onUnhandledRequest;
@@ -2818,17 +2904,10 @@ var RemoteHttpInterceptor = class {
2818
2904
  return this.implementation.isRunning;
2819
2905
  }
2820
2906
  async start() {
2821
- if (this.isRunning) {
2822
- return;
2823
- }
2824
2907
  await this.implementation.start();
2825
2908
  }
2826
2909
  async stop() {
2827
- if (!this.isRunning) {
2828
- return;
2829
- }
2830
- await this.clear();
2831
- await this.implementation.stop();
2910
+ await this.implementation.stop({ beforeStop: () => this.clear() });
2832
2911
  }
2833
2912
  get = ((path) => {
2834
2913
  return this.implementation.get(path);
@@ -2899,19 +2978,12 @@ var InvalidJSONError = class extends InvalidJSONError$1 {
2899
2978
  * This is just a type guard to ensure the value is valid. In practice, this condition should never be true. */
2900
2979
  /* istanbul ignore next -- @preserve
2901
2980
  * Ignoring because there will always be a handler for the given method and path at this point. */
2902
- /* istanbul ignore if -- @preserve
2903
- * Trying to access the internal worker when it does not exist should not happen. */
2904
- /* istanbul ignore else -- @preserve
2905
- * We still check if we actually imported the server module in case our `isServerSide()` check returns true, but
2906
- * the environment actually resolves the browser module. */
2907
2981
  /* istanbul ignore else -- @preserve */
2982
+ /* istanbul ignore next -- @preserve */
2908
2983
  /* istanbul ignore else -- @preserve
2909
- * We still check if we actually imported the browser module in case our `isClientSide()` check returns true, but
2910
- * the environment actually resolves the server module. */
2911
- /* istanbul ignore next -- @preserve
2912
- * Ignoring because checking unknown platforms is not configured in our test setup. */
2913
- /* istanbul ignore else -- @preserve
2914
- * Since we start the internal worker once and do not stop it, tests may not be able exercise this branch. */
2984
+ * Browser worker start errors other than unregistered service workers come from MSW internals. */
2985
+ /* istanbul ignore if -- @preserve
2986
+ * Trying to access the internal worker when it does not exist should not happen. */
2915
2987
  /* istanbul ignore else -- @preserve
2916
2988
  * An unauthorized close event is the only one we expect to happen here. */
2917
2989
  /* istanbul ignore else -- @preserve
@@ -2925,6 +2997,8 @@ var InvalidJSONError = class extends InvalidJSONError$1 {
2925
2997
  * would reach a timeout and not be responded. The empty set serves as a fallback. */
2926
2998
  /* istanbul ignore if -- @preserve
2927
2999
  * Aborting requests is highly non-deterministic because it depends on specific timing of socket events. */
3000
+ /* istanbul ignore next -- @preserve
3001
+ * Ignoring because checking unknown platforms is not configured in our test setup. */
2928
3002
  /* istanbul ignore next -- @preserve
2929
3003
  *
2930
3004
  * If the socket is closed before receiving a response, the message is aborted with an error. This can happen if
@@ -2933,7 +3007,6 @@ var InvalidJSONError = class extends InvalidJSONError$1 {
2933
3007
  * necessary.
2934
3008
  *
2935
3009
  * Due to the rare nature of this edge case, we can't reliably reproduce it in tests. */
2936
- /* istanbul ignore next -- @preserve */
2937
3010
 
2938
3011
  export { DisabledRequestSavingError_default as DisabledRequestSavingError, HttpTimesCheckError_default as HttpTimesCheckError, InvalidFormDataError, InvalidJSONError, NotRunningHttpInterceptorError_default as NotRunningHttpInterceptorError, RequestSavingSafeLimitExceededError_default as RequestSavingSafeLimitExceededError, RunningHttpInterceptorError_default as RunningHttpInterceptorError, TimesCheckError, UnknownHttpInterceptorPlatformError_default as UnknownHttpInterceptorPlatformError, UnknownHttpInterceptorTypeError_default as UnknownHttpInterceptorTypeError, UnregisteredBrowserServiceWorkerError_default as UnregisteredBrowserServiceWorkerError, createHttpInterceptor };
2939
3012
  //# sourceMappingURL=http.mjs.map