@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.js CHANGED
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  var http = require('@zimic/http');
4
- var color2 = require('picocolors');
4
+ var color = require('picocolors');
5
5
  var msw = require('msw');
6
6
  var ClientSocket = require('isomorphic-ws');
7
7
 
8
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
9
 
10
- var color2__default = /*#__PURE__*/_interopDefault(color2);
10
+ var color__default = /*#__PURE__*/_interopDefault(color);
11
11
  var ClientSocket__default = /*#__PURE__*/_interopDefault(ClientSocket);
12
12
 
13
13
  // src/http/index.ts
@@ -89,7 +89,7 @@ var RequestSavingSafeLimitExceededError_default = RequestSavingSafeLimitExceeded
89
89
  // src/cli/browser/shared/constants.ts
90
90
  var SERVICE_WORKER_FILE_NAME = "mockServiceWorker.js";
91
91
 
92
- // src/http/interceptorWorker/errors/UnregisteredBrowserServiceWorkerError.ts
92
+ // src/interceptor/errors/UnregisteredBrowserServiceWorkerError.ts
93
93
  var UnregisteredBrowserServiceWorkerError = class extends Error {
94
94
  constructor() {
95
95
  super(
@@ -254,130 +254,31 @@ function jsonEquals(value, otherValue) {
254
254
  });
255
255
  }
256
256
  var jsonEquals_default = jsonEquals;
257
-
258
- // ../zimic-utils/dist/chunk-W66SQPEM.mjs
259
- function createCachedDynamicImport(importModuleDynamically) {
260
- let cachedImportResult;
261
- return async function importModuleDynamicallyWithCache() {
262
- cachedImportResult ??= await importModuleDynamically();
263
- return cachedImportResult;
264
- };
265
- }
266
- var createCachedDynamicImport_default = createCachedDynamicImport;
267
-
268
- // ../zimic-utils/dist/logging.mjs
269
- var Logger = class _Logger {
270
- prefix;
271
- raw;
272
- constructor(options = {}) {
273
- const { prefix } = options;
274
- this.prefix = prefix;
275
- this.raw = prefix ? new _Logger({ ...options, prefix: void 0 }) : this;
276
- }
277
- logWithLevel(level, ...messages) {
278
- if (this.prefix) {
279
- console[level](this.prefix, ...messages);
280
- } else {
281
- console[level](...messages);
282
- }
283
- }
284
- info(...messages) {
285
- this.logWithLevel("log", ...messages);
286
- }
287
- warn(...messages) {
288
- this.logWithLevel("warn", ...messages);
289
- }
290
- error(...messages) {
291
- this.logWithLevel("error", ...messages);
292
- }
293
- table(headers, rows) {
294
- const columnLengths = headers.map((header) => {
295
- let maxValueLength = header.title.length;
296
- for (const row of rows) {
297
- const value = row[header.property];
298
- if (value.length > maxValueLength) {
299
- maxValueLength = value.length;
300
- }
301
- }
302
- return maxValueLength;
303
- });
304
- const formattedRows = [];
305
- const horizontalLine = columnLengths.map((length) => "\u2500".repeat(length));
306
- formattedRows.push(horizontalLine, []);
307
- for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
308
- const header = headers[headerIndex];
309
- const columnLength = columnLengths[headerIndex];
310
- const value = header.title;
311
- formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
312
- }
313
- formattedRows.push(horizontalLine);
314
- for (const row of rows) {
315
- formattedRows.push([]);
316
- for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
317
- const header = headers[headerIndex];
318
- const columnLength = columnLengths[headerIndex];
319
- const value = row[header.property];
320
- formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
321
- }
322
- }
323
- formattedRows.push(horizontalLine);
324
- const formattedTable = formattedRows.map((row, index) => {
325
- const isFirstLine = index === 0;
326
- if (isFirstLine) {
327
- return `\u250C\u2500${row.join("\u2500\u252C\u2500")}\u2500\u2510`;
328
- }
329
- const isLineAfterHeaders = index === 2;
330
- if (isLineAfterHeaders) {
331
- return `\u251C\u2500${row.join("\u2500\u253C\u2500")}\u2500\u2524`;
332
- }
333
- const isLastLine = index === formattedRows.length - 1;
334
- if (isLastLine) {
335
- return `\u2514\u2500${row.join("\u2500\u2534\u2500")}\u2500\u2518`;
336
- }
337
- return `\u2502 ${row.join(" \u2502 ")} \u2502`;
338
- }).join("\n");
339
- this.logWithLevel("log", formattedTable);
340
- }
341
- };
342
- var Logger_default = Logger;
343
-
344
- // src/utils/environment.ts
345
- function isServerSide() {
346
- return typeof process !== "undefined" && typeof process.versions !== "undefined";
347
- }
348
- function isClientSide() {
349
- return typeof window !== "undefined" && typeof document !== "undefined";
350
- }
351
-
352
- // src/utils/logging.ts
353
- var logger = new Logger_default({
354
- prefix: color2__default.default.cyan("[@zimic/interceptor]")
355
- });
356
- function stringifyJSONToLog(value) {
257
+ function stringifyHttpJSONToLog(value) {
357
258
  return JSON.stringify(
358
259
  value,
359
260
  (_key, value2) => {
360
- return stringifyValueToLog(value2, {
261
+ return stringifyHttpValueToLog(value2, {
361
262
  fallback: (value3) => value3
362
263
  });
363
264
  },
364
265
  2
365
266
  ).replace(/\n\s*/g, " ").replace(/"(File { name: '.*?', type: '.*?', size: \d*? })"/g, "$1").replace(/"(Blob { type: '.*?', size: \d*? })"/g, "$1");
366
267
  }
367
- function stringifyValueToLog(value, options = {}) {
368
- const { fallback = stringifyJSONToLog, includeClassName } = options;
268
+ function stringifyHttpValueToLog(value, options = {}) {
269
+ const { fallback = stringifyHttpJSONToLog, includeClassName } = options;
369
270
  if (value === null || value === void 0 || typeof value !== "object") {
370
271
  return String(value);
371
272
  }
372
273
  if (value instanceof http.HttpHeaders) {
373
- return stringifyValueToLog(value.toObject());
274
+ return stringifyHttpValueToLog(value.toObject());
374
275
  }
375
- if (value instanceof http.HttpHeaders || value instanceof http.HttpSearchParams) {
276
+ if (value instanceof http.HttpSearchParams) {
376
277
  const prefix = includeClassName?.searchParams ?? false ? "URLSearchParams " : "";
377
- return `${prefix}${stringifyValueToLog(value.toObject())}`;
278
+ return `${prefix}${stringifyHttpValueToLog(value.toObject())}`;
378
279
  }
379
280
  if (value instanceof http.HttpFormData) {
380
- return `FormData ${stringifyValueToLog(value.toObject())}`;
281
+ return `FormData ${stringifyHttpValueToLog(value.toObject())}`;
381
282
  }
382
283
  if (value instanceof File) {
383
284
  return `File { name: '${value.name}', type: '${value.type}', size: ${value.size} }`;
@@ -387,23 +288,6 @@ function stringifyValueToLog(value, options = {}) {
387
288
  }
388
289
  return fallback(value);
389
290
  }
390
- var importUtil = createCachedDynamicImport_default(() => import('util'));
391
- async function formatValueToLog(value, options = {}) {
392
- if (isClientSide()) {
393
- return value;
394
- }
395
- const { colors = true } = options;
396
- const util = await importUtil();
397
- return util.inspect(value, {
398
- colors,
399
- compact: true,
400
- depth: Infinity,
401
- maxArrayLength: Infinity,
402
- maxStringLength: Infinity,
403
- breakLength: Infinity,
404
- sorted: true
405
- });
406
- }
407
291
 
408
292
  // src/http/errors/HttpTimesCheckError.ts
409
293
  function createMessageHeader({
@@ -427,8 +311,8 @@ function createMessageHeader({
427
311
 
428
312
  Requests evaluated by this handler:
429
313
 
430
- ${color2__default.default.green("- Expected")}
431
- ${color2__default.default.red("+ Received")}`
314
+ ${color__default.default.green("- Expected")}
315
+ ${color__default.default.red("+ Received")}`
432
316
  ].filter((part) => part !== false).join("");
433
317
  }
434
318
  function createMessageDiffs({ requestSaving, unmatchedRequestGroups }) {
@@ -440,35 +324,35 @@ function createMessageDiffs({ requestSaving, unmatchedRequestGroups }) {
440
324
  const messageParts = [`${requestNumber}: ${request.method} ${request.url}`];
441
325
  if (diff.computed) {
442
326
  messageParts.push("Computed restriction:");
443
- const stringifiedExpected = stringifyValueToLog(diff.computed.expected);
444
- const stringifiedReceived = stringifyValueToLog(diff.computed.received);
445
- messageParts.push(` ${color2__default.default.green(`- return ${stringifiedExpected}`)}`);
446
- messageParts.push(` ${color2__default.default.red(`+ return ${stringifiedReceived}`)}`);
327
+ const stringifiedExpected = stringifyHttpValueToLog(diff.computed.expected);
328
+ const stringifiedReceived = stringifyHttpValueToLog(diff.computed.received);
329
+ messageParts.push(` ${color__default.default.green(`- return ${stringifiedExpected}`)}`);
330
+ messageParts.push(` ${color__default.default.red(`+ return ${stringifiedReceived}`)}`);
447
331
  }
448
332
  if (diff.headers) {
449
333
  messageParts.push("Headers:");
450
- const stringifiedExpected = stringifyValueToLog(diff.headers.expected);
451
- const stringifiedReceived = stringifyValueToLog(diff.headers.received);
452
- messageParts.push(` ${color2__default.default.green(`- ${stringifiedExpected}`)}`);
453
- messageParts.push(` ${color2__default.default.red(`+ ${stringifiedReceived}`)}`);
334
+ const stringifiedExpected = stringifyHttpValueToLog(diff.headers.expected);
335
+ const stringifiedReceived = stringifyHttpValueToLog(diff.headers.received);
336
+ messageParts.push(` ${color__default.default.green(`- ${stringifiedExpected}`)}`);
337
+ messageParts.push(` ${color__default.default.red(`+ ${stringifiedReceived}`)}`);
454
338
  }
455
339
  if (diff.searchParams) {
456
340
  messageParts.push("Search params:");
457
- const stringifiedExpected = stringifyValueToLog(diff.searchParams.expected);
458
- const stringifiedReceived = stringifyValueToLog(diff.searchParams.received);
459
- messageParts.push(` ${color2__default.default.green(`- ${stringifiedExpected}`)}`);
460
- messageParts.push(` ${color2__default.default.red(`+ ${stringifiedReceived}`)}`);
341
+ const stringifiedExpected = stringifyHttpValueToLog(diff.searchParams.expected);
342
+ const stringifiedReceived = stringifyHttpValueToLog(diff.searchParams.received);
343
+ messageParts.push(` ${color__default.default.green(`- ${stringifiedExpected}`)}`);
344
+ messageParts.push(` ${color__default.default.red(`+ ${stringifiedReceived}`)}`);
461
345
  }
462
346
  if (diff.body) {
463
347
  messageParts.push("Body:");
464
- const stringifiedExpected = stringifyValueToLog(diff.body.expected, {
348
+ const stringifiedExpected = stringifyHttpValueToLog(diff.body.expected, {
465
349
  includeClassName: { searchParams: true }
466
350
  });
467
- const stringifiedReceived = stringifyValueToLog(diff.body.received, {
351
+ const stringifiedReceived = stringifyHttpValueToLog(diff.body.received, {
468
352
  includeClassName: { searchParams: true }
469
353
  });
470
- messageParts.push(` ${color2__default.default.green(`- ${stringifiedExpected}`)}`);
471
- messageParts.push(` ${color2__default.default.red(`+ ${stringifiedReceived}`)}`);
354
+ messageParts.push(` ${color__default.default.green(`- ${stringifiedExpected}`)}`);
355
+ messageParts.push(` ${color__default.default.red(`+ ${stringifiedReceived}`)}`);
472
356
  }
473
357
  return messageParts.join("\n ");
474
358
  }).join("\n\n");
@@ -498,6 +382,16 @@ var HttpTimesCheckError = class extends TimesCheckError {
498
382
  };
499
383
  var HttpTimesCheckError_default = HttpTimesCheckError;
500
384
 
385
+ // ../zimic-utils/dist/chunk-W66SQPEM.mjs
386
+ function createCachedDynamicImport(importModuleDynamically) {
387
+ let cachedImportResult;
388
+ return async function importModuleDynamicallyWithCache() {
389
+ cachedImportResult ??= await importModuleDynamically();
390
+ return cachedImportResult;
391
+ };
392
+ }
393
+ var createCachedDynamicImport_default = createCachedDynamicImport;
394
+
501
395
  // ../zimic-utils/dist/time.mjs
502
396
  function waitForDelay(milliseconds) {
503
397
  return new Promise((resolve) => {
@@ -506,6 +400,14 @@ function waitForDelay(milliseconds) {
506
400
  }
507
401
  var waitForDelay_default = waitForDelay;
508
402
 
403
+ // src/utils/environment.ts
404
+ function isServerSide() {
405
+ return typeof process !== "undefined" && typeof process.versions !== "undefined";
406
+ }
407
+ function isClientSide() {
408
+ return typeof window !== "undefined" && typeof document !== "undefined";
409
+ }
410
+
509
411
  // src/utils/data.ts
510
412
  async function convertReadableStreamToBlob(stream, options) {
511
413
  const chunks = [];
@@ -1049,6 +951,102 @@ function methodCanHaveResponseBody(method) {
1049
951
  return HTTP_METHODS_WITH_RESPONSE_BODY.has(method);
1050
952
  }
1051
953
 
954
+ // ../zimic-utils/dist/logging.mjs
955
+ var Logger = class _Logger {
956
+ prefix;
957
+ raw;
958
+ constructor(options = {}) {
959
+ const { prefix } = options;
960
+ this.prefix = prefix;
961
+ this.raw = prefix ? new _Logger({ ...options, prefix: void 0 }) : this;
962
+ }
963
+ logWithLevel(level, ...messages) {
964
+ if (this.prefix) {
965
+ console[level](this.prefix, ...messages);
966
+ } else {
967
+ console[level](...messages);
968
+ }
969
+ }
970
+ info(...messages) {
971
+ this.logWithLevel("log", ...messages);
972
+ }
973
+ warn(...messages) {
974
+ this.logWithLevel("warn", ...messages);
975
+ }
976
+ error(...messages) {
977
+ this.logWithLevel("error", ...messages);
978
+ }
979
+ table(headers, rows) {
980
+ const columnLengths = headers.map((header) => {
981
+ let maxValueLength = header.title.length;
982
+ for (const row of rows) {
983
+ const value = row[header.property];
984
+ if (value.length > maxValueLength) {
985
+ maxValueLength = value.length;
986
+ }
987
+ }
988
+ return maxValueLength;
989
+ });
990
+ const formattedRows = [];
991
+ const horizontalLine = columnLengths.map((length) => "\u2500".repeat(length));
992
+ formattedRows.push(horizontalLine, []);
993
+ for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
994
+ const header = headers[headerIndex];
995
+ const columnLength = columnLengths[headerIndex];
996
+ const value = header.title;
997
+ formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
998
+ }
999
+ formattedRows.push(horizontalLine);
1000
+ for (const row of rows) {
1001
+ formattedRows.push([]);
1002
+ for (let headerIndex = 0; headerIndex < headers.length; headerIndex++) {
1003
+ const header = headers[headerIndex];
1004
+ const columnLength = columnLengths[headerIndex];
1005
+ const value = row[header.property];
1006
+ formattedRows.at(-1)?.push(value.padEnd(columnLength, " "));
1007
+ }
1008
+ }
1009
+ formattedRows.push(horizontalLine);
1010
+ const formattedTable = formattedRows.map((row, index) => {
1011
+ const isFirstLine = index === 0;
1012
+ if (isFirstLine) {
1013
+ return `\u250C\u2500${row.join("\u2500\u252C\u2500")}\u2500\u2510`;
1014
+ }
1015
+ const isLineAfterHeaders = index === 2;
1016
+ if (isLineAfterHeaders) {
1017
+ return `\u251C\u2500${row.join("\u2500\u253C\u2500")}\u2500\u2524`;
1018
+ }
1019
+ const isLastLine = index === formattedRows.length - 1;
1020
+ if (isLastLine) {
1021
+ return `\u2514\u2500${row.join("\u2500\u2534\u2500")}\u2500\u2518`;
1022
+ }
1023
+ return `\u2502 ${row.join(" \u2502 ")} \u2502`;
1024
+ }).join("\n");
1025
+ this.logWithLevel("log", formattedTable);
1026
+ }
1027
+ };
1028
+ var Logger_default = Logger;
1029
+ var logger = new Logger_default({
1030
+ prefix: color__default.default.cyan("[@zimic/interceptor]")
1031
+ });
1032
+ var importUtil = createCachedDynamicImport_default(() => import('util'));
1033
+ async function formatValueToLog(value, options = {}) {
1034
+ if (isClientSide()) {
1035
+ return value;
1036
+ }
1037
+ const { colors = true } = options;
1038
+ const util = await importUtil();
1039
+ return util.inspect(value, {
1040
+ colors,
1041
+ compact: true,
1042
+ depth: Infinity,
1043
+ maxArrayLength: Infinity,
1044
+ maxStringLength: Infinity,
1045
+ breakLength: Infinity,
1046
+ sorted: true
1047
+ });
1048
+ }
1049
+
1052
1050
  // src/http/requestHandler/types/requests.ts
1053
1051
  var HTTP_INTERCEPTOR_REQUEST_HIDDEN_PROPERTIES = Object.freeze(
1054
1052
  /* @__PURE__ */ new Set([
@@ -1087,7 +1085,13 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1087
1085
  startingPromise;
1088
1086
  stoppingPromise;
1089
1087
  runningInterceptors = [];
1088
+ get numberOfRunningInterceptors() {
1089
+ return this.runningInterceptors.length;
1090
+ }
1090
1091
  async sharedStart(internalStart) {
1092
+ if (this.stoppingPromise) {
1093
+ await this.stoppingPromise;
1094
+ }
1091
1095
  if (this.isRunning) {
1092
1096
  return;
1093
1097
  }
@@ -1116,9 +1120,12 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1116
1120
  const stoppingResult = internalStop();
1117
1121
  if (stoppingResult instanceof Promise) {
1118
1122
  this.stoppingPromise = stoppingResult;
1119
- await this.stoppingPromise;
1123
+ try {
1124
+ await this.stoppingPromise;
1125
+ } finally {
1126
+ this.stoppingPromise = void 0;
1127
+ }
1120
1128
  }
1121
- this.stoppingPromise = void 0;
1122
1129
  }
1123
1130
  async logUnhandledRequestIfNecessary(request, strategy) {
1124
1131
  if (strategy?.log) {
@@ -1356,7 +1363,7 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1356
1363
  formatValueToLog(request.body)
1357
1364
  ]);
1358
1365
  logger[action === "bypass" ? "warn" : "error"](
1359
- `${action === "bypass" ? "Warning:" : "Error:"} Request was not handled and was ${action === "bypass" ? color2__default.default.yellow("bypassed") : color2__default.default.red("rejected")}.
1366
+ `${action === "bypass" ? "Warning:" : "Error:"} Request was not handled and was ${action === "bypass" ? color__default.default.yellow("bypassed") : color__default.default.red("rejected")}.
1360
1367
 
1361
1368
  `,
1362
1369
  `${request.method} ${request.url}`,
@@ -1373,16 +1380,16 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1373
1380
  var HttpInterceptorWorker_default = HttpInterceptorWorker;
1374
1381
 
1375
1382
  // src/http/requestHandler/RemoteHttpRequestHandler.ts
1376
- var UNSYNCED_PROPERTIES = /* @__PURE__ */ new Set(["then"]);
1383
+ var PENDING_PROPERTIES = /* @__PURE__ */ new Set(["then"]);
1377
1384
  var RemoteHttpRequestHandler = class {
1378
1385
  type = "remote";
1379
1386
  implementation;
1380
1387
  syncPromises = [];
1381
- unsynced;
1388
+ pending;
1382
1389
  synced;
1383
1390
  constructor(interceptor, method, path) {
1384
1391
  this.implementation = new HttpRequestHandlerImplementation_default(interceptor, method, path, this);
1385
- this.unsynced = this;
1392
+ this.pending = this;
1386
1393
  this.synced = this.createSyncedProxy();
1387
1394
  }
1388
1395
  createSyncedProxy() {
@@ -1402,7 +1409,7 @@ var RemoteHttpRequestHandler = class {
1402
1409
  });
1403
1410
  }
1404
1411
  shouldBeHiddenPropertyWhenSynced(property) {
1405
- return UNSYNCED_PROPERTIES.has(property);
1412
+ return PENDING_PROPERTIES.has(property);
1406
1413
  }
1407
1414
  get method() {
1408
1415
  return this.implementation.method;
@@ -1412,16 +1419,16 @@ var RemoteHttpRequestHandler = class {
1412
1419
  }
1413
1420
  with(restriction) {
1414
1421
  this.implementation.with(restriction);
1415
- return this.unsynced;
1422
+ return this.pending;
1416
1423
  }
1417
1424
  delay(minMilliseconds, maxMilliseconds) {
1418
1425
  this.implementation.delay(minMilliseconds, maxMilliseconds);
1419
- return this.unsynced;
1426
+ return this.pending;
1420
1427
  }
1421
1428
  respond(declaration) {
1422
- const newUnsyncedThis = this.unsynced;
1423
- newUnsyncedThis.implementation.respond(declaration);
1424
- return newUnsyncedThis;
1429
+ const pending = this.pending;
1430
+ pending.implementation.respond(declaration);
1431
+ return pending;
1425
1432
  }
1426
1433
  times(minNumberOfRequests, maxNumberOfRequests) {
1427
1434
  this.implementation.times(minNumberOfRequests, maxNumberOfRequests);
@@ -1439,7 +1446,7 @@ var RemoteHttpRequestHandler = class {
1439
1446
  }
1440
1447
  clear() {
1441
1448
  this.implementation.clear();
1442
- return this.unsynced;
1449
+ return this.pending;
1443
1450
  }
1444
1451
  get requests() {
1445
1452
  return this.implementation.requests;
@@ -1471,7 +1478,7 @@ var RemoteHttpRequestHandler = class {
1471
1478
  const promisesToWait = new Set(this.syncPromises);
1472
1479
  return Promise.all(promisesToWait).then(() => {
1473
1480
  this.syncPromises = this.syncPromises.filter((promise) => !promisesToWait.has(promise));
1474
- return this.isSynced ? this.synced : this.unsynced;
1481
+ return this.isSynced ? this.synced : this.pending;
1475
1482
  }).then(onFulfilled, onRejected);
1476
1483
  }
1477
1484
  catch(onRejected) {
@@ -1492,6 +1499,9 @@ var HttpInterceptorImplementation = class {
1492
1499
  createWorker;
1493
1500
  deleteWorker;
1494
1501
  worker;
1502
+ startPromise;
1503
+ numberOfPendingStarts = 0;
1504
+ lifecycleQueue = Promise.resolve();
1495
1505
  requestSaving;
1496
1506
  numberOfSavedRequests = 0;
1497
1507
  onUnhandledRequest;
@@ -1525,7 +1535,7 @@ var HttpInterceptorImplementation = class {
1525
1535
  return this.#baseURL;
1526
1536
  }
1527
1537
  set baseURL(newBaseURL) {
1528
- if (this.isRunning) {
1538
+ if (this.isRunning || this.isStarting) {
1529
1539
  throw new RunningHttpInterceptorError_default(
1530
1540
  "Did you forget to call `await interceptor.stop()` before changing the base URL?"
1531
1541
  );
@@ -1549,27 +1559,67 @@ var HttpInterceptorImplementation = class {
1549
1559
  get platform() {
1550
1560
  return this.worker?.platform ?? null;
1551
1561
  }
1552
- async start() {
1562
+ start() {
1563
+ if (this.startPromise) {
1564
+ return this.startPromise;
1565
+ }
1566
+ this.numberOfPendingStarts++;
1567
+ const startPromise = this.enqueueLifecycleOperation(() => this.startOnce()).finally(() => {
1568
+ this.numberOfPendingStarts--;
1569
+ const isLastStartPromise = this.startPromise === startPromise;
1570
+ if (isLastStartPromise) {
1571
+ this.startPromise = void 0;
1572
+ }
1573
+ });
1574
+ this.startPromise = startPromise;
1575
+ return startPromise;
1576
+ }
1577
+ async startOnce() {
1578
+ if (this.isRunning) {
1579
+ return;
1580
+ }
1553
1581
  try {
1554
1582
  this.worker = this.createWorker();
1555
- await this.worker.start();
1556
1583
  this.worker.registerRunningInterceptor(this);
1584
+ await this.worker.start();
1557
1585
  this.markAsRunning(true);
1558
1586
  } catch (error) {
1559
- await this.stop();
1587
+ await this.stopWorker();
1560
1588
  throw error;
1561
1589
  }
1562
1590
  }
1563
- async stop() {
1591
+ get isStarting() {
1592
+ return this.numberOfPendingStarts > 0;
1593
+ }
1594
+ async stop(options) {
1595
+ this.startPromise = void 0;
1596
+ await this.enqueueLifecycleOperation(() => this.stopOnce(options));
1597
+ }
1598
+ async stopOnce(options) {
1599
+ if (!this.isRunning) {
1600
+ return;
1601
+ }
1602
+ await options.beforeStop?.();
1603
+ await this.stopWorker();
1604
+ }
1605
+ async stopWorker() {
1564
1606
  this.worker?.unregisterRunningInterceptor(this);
1565
- const isLastRunningInterceptor = this.numberOfRunningInterceptors === 0 || this.numberOfRunningInterceptors === 1;
1607
+ const isLastRunningInterceptor = this.worker?.numberOfRunningInterceptors === 0;
1566
1608
  if (isLastRunningInterceptor) {
1567
1609
  await this.worker?.stop();
1568
- this.deleteWorker();
1610
+ const isStillLastRunningInterceptor = this.worker?.numberOfRunningInterceptors === 0;
1611
+ if (isStillLastRunningInterceptor) {
1612
+ this.deleteWorker();
1613
+ }
1569
1614
  }
1570
1615
  this.markAsRunning(false);
1571
1616
  this.worker = void 0;
1572
1617
  }
1618
+ enqueueLifecycleOperation(operation) {
1619
+ const operationPromise = this.lifecycleQueue.then(operation);
1620
+ this.lifecycleQueue = operationPromise.catch(() => void 0);
1621
+ return operationPromise;
1622
+ }
1573
1623
  markAsRunning(isRunning) {
1574
1624
  if (this.workerOrThrow.type === "local") {
1575
1625
  this.store.markLocalInterceptorAsRunning(this, isRunning);
@@ -1578,16 +1628,6 @@ var HttpInterceptorImplementation = class {
1578
1628
  }
1579
1629
  this.isRunning = isRunning;
1580
1630
  }
1581
- get numberOfRunningInterceptors() {
1582
- if (!this.isRunning) {
1583
- return 0;
1584
- }
1585
- if (this.workerOrThrow.type === "local") {
1586
- return this.store.numberOfRunningLocalInterceptors;
1587
- } else {
1588
- return this.store.numberOfRunningRemoteInterceptors(this.baseURL);
1589
- }
1590
- }
1591
1631
  get(path) {
1592
1632
  return this.createHttpRequestHandler("GET", path);
1593
1633
  }
@@ -1736,13 +1776,91 @@ var HttpInterceptorImplementation = class {
1736
1776
  }
1737
1777
  };
1738
1778
  var HttpInterceptorImplementation_default = HttpInterceptorImplementation;
1779
+
1780
+ // src/interceptor/LocalMSWWorkerStore.ts
1739
1781
  var importMSWNode = createCachedDynamicImport_default(() => import('msw/node'));
1740
1782
  var importMSWBrowser = createCachedDynamicImport_default(() => import('msw/browser'));
1741
- var LocalHttpInterceptorWorker = class _LocalHttpInterceptorWorker extends HttpInterceptorWorker_default {
1742
- // Re-creating MSW workers may cause issues, so we should keep a single worker instance, even if all interceptor
1743
- // workers are stopped. See https://github.com/mswjs/msw/issues/2597.
1783
+ var LocalMSWWorkerStore = class _LocalMSWWorkerStore {
1744
1784
  static mswWorker;
1785
+ static creatingMSWWorkerPromise;
1786
+ static startingMSWWorkerPromise;
1787
+ static numberOfRunningWorkers = 0;
1745
1788
  static isMSWWorkerRunning = false;
1789
+ class = _LocalMSWWorkerStore;
1790
+ get mswWorker() {
1791
+ return this.class.mswWorker;
1792
+ }
1793
+ async getMSWWorkerOrCreate(options) {
1794
+ if (this.class.mswWorker) {
1795
+ return this.class.mswWorker;
1796
+ }
1797
+ this.class.creatingMSWWorkerPromise ??= this.createMSWWorker(options).then((mswWorker) => {
1798
+ this.class.mswWorker = mswWorker;
1799
+ return mswWorker;
1800
+ }).finally(() => {
1801
+ this.class.creatingMSWWorkerPromise = void 0;
1802
+ });
1803
+ return this.class.creatingMSWWorkerPromise;
1804
+ }
1805
+ async createMSWWorker(options) {
1806
+ if (isServerSide()) {
1807
+ const mswNode = await importMSWNode();
1808
+ if ("setupServer" in mswNode) {
1809
+ return mswNode.setupServer();
1810
+ }
1811
+ }
1812
+ if (isClientSide()) {
1813
+ const mswBrowser = await importMSWBrowser();
1814
+ if ("setupWorker" in mswBrowser) {
1815
+ return mswBrowser.setupWorker();
1816
+ }
1817
+ }
1818
+ throw options.createUnknownPlatformError();
1819
+ }
1820
+ async startMSWWorker(mswWorker, sharedOptions) {
1821
+ if (!this.class.isMSWWorkerRunning) {
1822
+ this.class.startingMSWWorkerPromise ??= this.startMSWWorkerOnce(mswWorker, sharedOptions).then(() => {
1823
+ this.class.isMSWWorkerRunning = true;
1824
+ }).finally(() => {
1825
+ this.class.startingMSWWorkerPromise = void 0;
1826
+ });
1827
+ await this.class.startingMSWWorkerPromise;
1828
+ }
1829
+ this.class.numberOfRunningWorkers++;
1830
+ }
1831
+ async startMSWWorkerOnce(mswWorker, sharedOptions) {
1832
+ if (this.isInternalBrowserWorker(mswWorker)) {
1833
+ try {
1834
+ await mswWorker.start({ ...sharedOptions, quiet: true });
1835
+ } catch (error) {
1836
+ if (UnregisteredBrowserServiceWorkerError_default.matchesRawError(error)) {
1837
+ throw new UnregisteredBrowserServiceWorkerError_default();
1838
+ } else {
1839
+ throw error;
1840
+ }
1841
+ }
1842
+ } else {
1843
+ mswWorker.listen(sharedOptions);
1844
+ }
1845
+ }
1846
+ stopMSWWorker(mswWorker) {
1847
+ this.class.numberOfRunningWorkers = Math.max(this.class.numberOfRunningWorkers - 1, 0);
1848
+ if (this.class.numberOfRunningWorkers > 0) {
1849
+ return;
1850
+ }
1851
+ if (this.isInternalBrowserWorker(mswWorker)) ; else {
1852
+ mswWorker.close();
1853
+ this.class.isMSWWorkerRunning = false;
1854
+ }
1855
+ }
1856
+ isInternalBrowserWorker(worker) {
1857
+ return "start" in worker && "stop" in worker;
1858
+ }
1859
+ };
1860
+ var LocalMSWWorkerStore_default = LocalMSWWorkerStore;
1861
+
1862
+ // src/http/interceptorWorker/LocalHttpInterceptorWorker.ts
1863
+ var LocalHttpInterceptorWorker = class extends HttpInterceptorWorker_default {
1746
1864
  mswHttpHandler;
1747
1865
  httpHandlersByMethod = {
1748
1866
  GET: [],
@@ -1753,39 +1871,28 @@ var LocalHttpInterceptorWorker = class _LocalHttpInterceptorWorker extends HttpI
1753
1871
  HEAD: [],
1754
1872
  OPTIONS: []
1755
1873
  };
1874
+ store = new LocalMSWWorkerStore_default();
1756
1875
  constructor(_options) {
1757
1876
  super();
1758
1877
  }
1759
- get class() {
1760
- return _LocalHttpInterceptorWorker;
1761
- }
1762
1878
  get type() {
1763
1879
  return "local";
1764
1880
  }
1765
1881
  get mswWorkerOrThrow() {
1766
- if (!this.class.mswWorker) {
1882
+ if (!this.store.mswWorker) {
1767
1883
  throw new NotRunningHttpInterceptorError_default();
1768
1884
  }
1769
- return this.class.mswWorker;
1885
+ return this.store.mswWorker;
1770
1886
  }
1771
1887
  async getMSWWorkerOrCreate() {
1772
- this.class.mswWorker ??= await this.createMSWWorker();
1773
- return this.class.mswWorker;
1774
- }
1775
- async createMSWWorker() {
1776
- if (isServerSide()) {
1777
- const mswNode = await importMSWNode();
1778
- if ("setupServer" in mswNode) {
1779
- return mswNode.setupServer();
1780
- }
1781
- }
1782
- if (isClientSide()) {
1783
- const mswBrowser = await importMSWBrowser();
1784
- if ("setupWorker" in mswBrowser) {
1785
- return mswBrowser.setupWorker();
1786
- }
1787
- }
1788
- throw new UnknownHttpInterceptorPlatformError_default();
1888
+ return this.store.getMSWWorkerOrCreate({
1889
+ createUnknownPlatformError: (
1890
+ // The unknown platform error is created here to prevent the store from relying on HTTP-specific resources.
1891
+ /* istanbul ignore next -- @preserve
1892
+ * Unknown runtime platforms are not part of the package test matrix. */
1893
+ () => new UnknownHttpInterceptorPlatformError_default()
1894
+ )
1895
+ });
1789
1896
  }
1790
1897
  async start() {
1791
1898
  await super.sharedStart(async () => {
@@ -1801,54 +1908,33 @@ var LocalHttpInterceptorWorker = class _LocalHttpInterceptorWorker extends HttpI
1801
1908
  mswWorker.use(this.mswHttpHandler);
1802
1909
  if (this.isInternalBrowserWorker(mswWorker)) {
1803
1910
  this.platform = "browser";
1804
- if (!this.class.isMSWWorkerRunning) {
1805
- await this.startInBrowser(mswWorker, sharedOptions);
1806
- this.class.isMSWWorkerRunning = true;
1807
- }
1808
1911
  } else {
1809
1912
  this.platform = "node";
1810
- this.startInNode(mswWorker, sharedOptions);
1811
- this.class.isMSWWorkerRunning = true;
1913
+ }
1914
+ try {
1915
+ await this.store.startMSWWorker(mswWorker, sharedOptions);
1916
+ } catch (error) {
1917
+ const newMSWHandlers = mswWorker.listHandlers().filter((handler) => handler !== this.mswHttpHandler);
1918
+ mswWorker.resetHandlers(...newMSWHandlers);
1919
+ this.mswHttpHandler = void 0;
1920
+ throw error;
1812
1921
  }
1813
1922
  this.isRunning = true;
1814
1923
  });
1815
1924
  }
1816
- async startInBrowser(mswWorker, sharedOptions) {
1817
- try {
1818
- await mswWorker.start({ ...sharedOptions, quiet: true });
1819
- } catch (error) {
1820
- this.handleBrowserWorkerStartError(error);
1821
- }
1822
- }
1823
- handleBrowserWorkerStartError(error) {
1824
- if (UnregisteredBrowserServiceWorkerError_default.matchesRawError(error)) {
1825
- throw new UnregisteredBrowserServiceWorkerError_default();
1826
- } else {
1827
- throw error;
1828
- }
1829
- }
1830
- startInNode(mswWorker, sharedOptions) {
1831
- mswWorker.listen(sharedOptions);
1832
- }
1833
1925
  async stop() {
1834
1926
  await super.sharedStop(async () => {
1835
1927
  const mswWorker = await this.getMSWWorkerOrCreate();
1836
1928
  this.clearHandlers();
1837
1929
  const newMSWHandlers = mswWorker.listHandlers().filter((handler) => handler !== this.mswHttpHandler);
1838
1930
  mswWorker.resetHandlers(...newMSWHandlers);
1839
- if (this.isInternalBrowserWorker(mswWorker)) ; else {
1840
- this.stopInNode(mswWorker);
1841
- this.class.isMSWWorkerRunning = false;
1842
- }
1931
+ this.store.stopMSWWorker(mswWorker);
1843
1932
  this.mswHttpHandler = void 0;
1844
1933
  this.isRunning = false;
1845
1934
  });
1846
1935
  }
1847
- stopInNode(mswWorker) {
1848
- mswWorker.close();
1849
- }
1850
1936
  isInternalBrowserWorker(worker) {
1851
- return "start" in worker && "stop" in worker;
1937
+ return this.store.isInternalBrowserWorker(worker);
1852
1938
  }
1853
1939
  hasInternalBrowserWorker() {
1854
1940
  return this.isInternalBrowserWorker(this.mswWorkerOrThrow);
@@ -2006,6 +2092,15 @@ async function serializeResponse(response) {
2006
2092
  };
2007
2093
  }
2008
2094
 
2095
+ // src/utils/webSocket/constants.ts
2096
+ var WEB_SOCKET_CONTROL_MESSAGES = Object.freeze(["socket:auth:valid"]);
2097
+ var WEB_SOCKET_CLOSE_CODES = Object.freeze({
2098
+ DEFAULT: 1e3,
2099
+ PROTOCOL_ERROR: 1002,
2100
+ POLICY_VIOLATION: 1008,
2101
+ INTERNAL_ERROR: 1011
2102
+ });
2103
+
2009
2104
  // src/utils/webSocket/errors/UnauthorizedWebSocketConnectionError.ts
2010
2105
  var UnauthorizedWebSocketConnectionError = class extends Error {
2011
2106
  constructor(event) {
@@ -2064,7 +2159,7 @@ async function waitForOpenClientSocket(socket, options = {}) {
2064
2159
  reject(error);
2065
2160
  }
2066
2161
  function handleClose(event) {
2067
- const isUnauthorized = event.code === 1008;
2162
+ const isUnauthorized = event.code === WEB_SOCKET_CLOSE_CODES.POLICY_VIOLATION;
2068
2163
  if (isUnauthorized) {
2069
2164
  const unauthorizedError = new UnauthorizedWebSocketConnectionError_default(event);
2070
2165
  handleOpenError(unauthorizedError);
@@ -2126,9 +2221,6 @@ async function closeClientSocket(socket, options = {}) {
2126
2221
  });
2127
2222
  }
2128
2223
 
2129
- // src/utils/webSocket/constants.ts
2130
- var WEB_SOCKET_CONTROL_MESSAGES = Object.freeze(["socket:auth:valid"]);
2131
-
2132
2224
  // src/utils/webSocket/errors/InvalidWebSocketMessageError.ts
2133
2225
  var InvalidWebSocketMessageError = class extends Error {
2134
2226
  constructor(message) {
@@ -2169,7 +2261,12 @@ var WebSocketHandler = class {
2169
2261
  await this.handleSocketMessage(socket, rawMessage);
2170
2262
  };
2171
2263
  socket.addEventListener("message", handleSocketMessage);
2172
- await openPromise;
2264
+ try {
2265
+ await openPromise;
2266
+ } catch (error) {
2267
+ socket.removeEventListener("message", handleSocketMessage);
2268
+ throw error;
2269
+ }
2173
2270
  function handleSocketError(error) {
2174
2271
  console.error(error);
2175
2272
  }
@@ -2184,6 +2281,7 @@ var WebSocketHandler = class {
2184
2281
  };
2185
2282
  socket.addEventListener("close", handleSocketClose);
2186
2283
  this.sockets.add(socket);
2284
+ return handleSocketClose;
2187
2285
  }
2188
2286
  handleSocketMessage = async (socket, rawMessage) => {
2189
2287
  try {
@@ -2579,24 +2677,15 @@ var RemoteHttpInterceptorWorker = class extends HttpInterceptorWorker_default {
2579
2677
  };
2580
2678
  var RemoteHttpInterceptorWorker_default = RemoteHttpInterceptorWorker;
2581
2679
 
2582
- // src/http/interceptorWorker/factory.ts
2583
- function createHttpInterceptorWorker(options) {
2584
- if (options.type === "local") {
2585
- return new LocalHttpInterceptorWorker_default(options);
2586
- } else {
2587
- return new RemoteHttpInterceptorWorker_default(options);
2588
- }
2589
- }
2590
-
2591
2680
  // src/http/interceptor/HttpInterceptorStore.ts
2592
2681
  var HttpInterceptorStore = class _HttpInterceptorStore {
2593
- static _localWorker;
2594
- static runningLocalInterceptors = /* @__PURE__ */ new Set();
2682
+ static localWorker;
2595
2683
  static remoteWorkers = /* @__PURE__ */ new Map();
2684
+ static runningLocalInterceptors = /* @__PURE__ */ new Set();
2596
2685
  static runningRemoteInterceptors = /* @__PURE__ */ new Map();
2597
2686
  class = _HttpInterceptorStore;
2598
2687
  get localWorker() {
2599
- return this.class._localWorker;
2688
+ return this.class.localWorker;
2600
2689
  }
2601
2690
  getRemoteWorkerKey(baseURL, options) {
2602
2691
  const key = [`${baseURL.origin}${baseURL.pathname}`];
@@ -2605,7 +2694,7 @@ var HttpInterceptorStore = class _HttpInterceptorStore {
2605
2694
  }
2606
2695
  return key.join(":");
2607
2696
  }
2608
- remoteWorker(baseURL, options) {
2697
+ getRemoteWorker(baseURL, options) {
2609
2698
  const remoteWorkerKey = this.getRemoteWorkerKey(baseURL, options);
2610
2699
  return this.class.remoteWorkers.get(remoteWorkerKey);
2611
2700
  }
@@ -2637,16 +2726,16 @@ var HttpInterceptorStore = class _HttpInterceptorStore {
2637
2726
  return runningInterceptors;
2638
2727
  }
2639
2728
  getOrCreateLocalWorker(workerOptions) {
2640
- const existingWorker = this.class._localWorker;
2729
+ const existingWorker = this.class.localWorker;
2641
2730
  if (existingWorker) {
2642
2731
  return existingWorker;
2643
2732
  }
2644
- const createdWorker = createHttpInterceptorWorker({ ...workerOptions, type: "local" });
2645
- this.class._localWorker = createdWorker;
2733
+ const createdWorker = new LocalHttpInterceptorWorker_default({ ...workerOptions, type: "local" });
2734
+ this.class.localWorker = createdWorker;
2646
2735
  return createdWorker;
2647
2736
  }
2648
2737
  deleteLocalWorker() {
2649
- this.class._localWorker = void 0;
2738
+ this.class.localWorker = void 0;
2650
2739
  }
2651
2740
  getOrCreateRemoteWorker(workerOptions) {
2652
2741
  const remoteWorkerKey = this.getRemoteWorkerKey(workerOptions.serverURL, { auth: workerOptions.auth });
@@ -2654,7 +2743,7 @@ var HttpInterceptorStore = class _HttpInterceptorStore {
2654
2743
  if (existingWorker) {
2655
2744
  return existingWorker;
2656
2745
  }
2657
- const createdWorker = createHttpInterceptorWorker({ ...workerOptions, type: "remote" });
2746
+ const createdWorker = new RemoteHttpInterceptorWorker_default({ ...workerOptions, type: "remote" });
2658
2747
  this.class.remoteWorkers.set(remoteWorkerKey, createdWorker);
2659
2748
  return createdWorker;
2660
2749
  }
@@ -2709,17 +2798,10 @@ var LocalHttpInterceptor = class {
2709
2798
  return this.implementation.isRunning;
2710
2799
  }
2711
2800
  async start() {
2712
- if (this.isRunning) {
2713
- return;
2714
- }
2715
2801
  await this.implementation.start();
2716
2802
  }
2717
2803
  async stop() {
2718
- if (!this.isRunning) {
2719
- return;
2720
- }
2721
- this.clear();
2722
- await this.implementation.stop();
2804
+ await this.implementation.stop({ beforeStop: () => this.clear() });
2723
2805
  }
2724
2806
  get = ((path) => {
2725
2807
  return this.implementation.get(path);
@@ -2757,24 +2839,24 @@ var RemoteHttpInterceptor = class {
2757
2839
  implementation;
2758
2840
  #auth;
2759
2841
  constructor(options) {
2760
- this.#auth = options.auth;
2761
2842
  const baseURL = new URL(options.baseURL);
2762
2843
  this.implementation = new HttpInterceptorImplementation_default({
2763
2844
  store: this.store,
2764
2845
  baseURL,
2765
2846
  createWorker: () => {
2766
2847
  return this.store.getOrCreateRemoteWorker({
2767
- serverURL: baseURL,
2848
+ serverURL: this.implementation.baseURL,
2768
2849
  auth: this.#auth
2769
2850
  });
2770
2851
  },
2771
2852
  deleteWorker: () => {
2772
- this.store.deleteRemoteWorker(baseURL, { auth: options.auth });
2853
+ this.store.deleteRemoteWorker(this.implementation.baseURL, { auth: this.#auth });
2773
2854
  },
2774
2855
  Handler: RemoteHttpRequestHandler_default,
2775
2856
  onUnhandledRequest: options.onUnhandledRequest,
2776
2857
  requestSaving: options.requestSaving
2777
2858
  });
2859
+ this.auth = options.auth;
2778
2860
  }
2779
2861
  get type() {
2780
2862
  return "remote";
@@ -2796,21 +2878,25 @@ var RemoteHttpInterceptor = class {
2796
2878
  }
2797
2879
  set auth(auth) {
2798
2880
  const cannotChangeAuthWhileRunningMessage = "Did you forget to call `await interceptor.stop()` before changing the authentication parameters?";
2799
- if (this.isRunning) {
2881
+ if (this.isRunning || this.implementation.isStarting) {
2800
2882
  throw new RunningHttpInterceptorError_default(cannotChangeAuthWhileRunningMessage);
2801
2883
  }
2802
2884
  if (!auth) {
2803
2885
  this.#auth = void 0;
2804
2886
  return;
2805
2887
  }
2806
- this.#auth = new Proxy(auth, {
2807
- set: (target, property, value) => {
2808
- if (this.isRunning) {
2809
- throw new RunningHttpInterceptorError_default(cannotChangeAuthWhileRunningMessage);
2888
+ this.#auth = new Proxy(
2889
+ { ...auth },
2890
+ // Copy object to ensure it's not mutated later without going though the proxy.
2891
+ {
2892
+ set: (target, property, value) => {
2893
+ if (this.isRunning || this.implementation.isStarting) {
2894
+ throw new RunningHttpInterceptorError_default(cannotChangeAuthWhileRunningMessage);
2895
+ }
2896
+ return Reflect.set(target, property, value);
2810
2897
  }
2811
- return Reflect.set(target, property, value);
2812
2898
  }
2813
- });
2899
+ );
2814
2900
  }
2815
2901
  get onUnhandledRequest() {
2816
2902
  return this.implementation.onUnhandledRequest;
@@ -2825,17 +2911,10 @@ var RemoteHttpInterceptor = class {
2825
2911
  return this.implementation.isRunning;
2826
2912
  }
2827
2913
  async start() {
2828
- if (this.isRunning) {
2829
- return;
2830
- }
2831
2914
  await this.implementation.start();
2832
2915
  }
2833
2916
  async stop() {
2834
- if (!this.isRunning) {
2835
- return;
2836
- }
2837
- await this.clear();
2838
- await this.implementation.stop();
2917
+ await this.implementation.stop({ beforeStop: () => this.clear() });
2839
2918
  }
2840
2919
  get = ((path) => {
2841
2920
  return this.implementation.get(path);
@@ -2906,19 +2985,12 @@ var InvalidJSONError = class extends http.InvalidJSONError {
2906
2985
  * This is just a type guard to ensure the value is valid. In practice, this condition should never be true. */
2907
2986
  /* istanbul ignore next -- @preserve
2908
2987
  * Ignoring because there will always be a handler for the given method and path at this point. */
2909
- /* istanbul ignore if -- @preserve
2910
- * Trying to access the internal worker when it does not exist should not happen. */
2911
- /* istanbul ignore else -- @preserve
2912
- * We still check if we actually imported the server module in case our `isServerSide()` check returns true, but
2913
- * the environment actually resolves the browser module. */
2914
2988
  /* istanbul ignore else -- @preserve */
2989
+ /* istanbul ignore next -- @preserve */
2915
2990
  /* istanbul ignore else -- @preserve
2916
- * We still check if we actually imported the browser module in case our `isClientSide()` check returns true, but
2917
- * the environment actually resolves the server module. */
2918
- /* istanbul ignore next -- @preserve
2919
- * Ignoring because checking unknown platforms is not configured in our test setup. */
2920
- /* istanbul ignore else -- @preserve
2921
- * Since we start the internal worker once and do not stop it, tests may not be able exercise this branch. */
2991
+ * Browser worker start errors other than unregistered service workers come from MSW internals. */
2992
+ /* istanbul ignore if -- @preserve
2993
+ * Trying to access the internal worker when it does not exist should not happen. */
2922
2994
  /* istanbul ignore else -- @preserve
2923
2995
  * An unauthorized close event is the only one we expect to happen here. */
2924
2996
  /* istanbul ignore else -- @preserve
@@ -2932,6 +3004,8 @@ var InvalidJSONError = class extends http.InvalidJSONError {
2932
3004
  * would reach a timeout and not be responded. The empty set serves as a fallback. */
2933
3005
  /* istanbul ignore if -- @preserve
2934
3006
  * Aborting requests is highly non-deterministic because it depends on specific timing of socket events. */
3007
+ /* istanbul ignore next -- @preserve
3008
+ * Ignoring because checking unknown platforms is not configured in our test setup. */
2935
3009
  /* istanbul ignore next -- @preserve
2936
3010
  *
2937
3011
  * If the socket is closed before receiving a response, the message is aborted with an error. This can happen if
@@ -2940,7 +3014,6 @@ var InvalidJSONError = class extends http.InvalidJSONError {
2940
3014
  * necessary.
2941
3015
  *
2942
3016
  * Due to the rare nature of this edge case, we can't reliably reproduce it in tests. */
2943
- /* istanbul ignore next -- @preserve */
2944
3017
 
2945
3018
  exports.DisabledRequestSavingError = DisabledRequestSavingError_default;
2946
3019
  exports.HttpTimesCheckError = HttpTimesCheckError_default;