@zimic/interceptor 0.16.0-canary.1 → 0.16.0-canary.11

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 (41) hide show
  1. package/README.md +4 -5
  2. package/dist/{chunk-6TSSHQW5.mjs → chunk-NTRC2S4I.mjs} +253 -312
  3. package/dist/chunk-NTRC2S4I.mjs.map +1 -0
  4. package/dist/{chunk-R2ROSKU4.js → chunk-O6ZIPCUJ.js} +254 -313
  5. package/dist/chunk-O6ZIPCUJ.js.map +1 -0
  6. package/dist/cli.js +9 -9
  7. package/dist/cli.js.map +1 -1
  8. package/dist/cli.mjs +5 -5
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/http.d.ts +156 -176
  11. package/dist/http.js +265 -324
  12. package/dist/http.js.map +1 -1
  13. package/dist/http.mjs +263 -323
  14. package/dist/http.mjs.map +1 -1
  15. package/dist/server.d.ts +20 -46
  16. package/dist/server.js +7 -7
  17. package/dist/server.mjs +1 -1
  18. package/package.json +8 -8
  19. package/src/cli/browser/init.ts +2 -2
  20. package/src/cli/server/start.ts +2 -2
  21. package/src/http/index.ts +6 -13
  22. package/src/http/interceptor/HttpInterceptorClient.ts +30 -15
  23. package/src/http/interceptor/LocalHttpInterceptor.ts +8 -8
  24. package/src/http/interceptor/RemoteHttpInterceptor.ts +8 -8
  25. package/src/http/interceptor/errors/RequestSavingSafeLimitExceededError.ts +22 -0
  26. package/src/http/interceptor/factory.ts +1 -1
  27. package/src/http/interceptor/types/options.ts +4 -11
  28. package/src/http/interceptor/types/public.ts +44 -12
  29. package/src/http/interceptor/types/schema.ts +2 -2
  30. package/src/http/interceptorWorker/HttpInterceptorWorker.ts +6 -31
  31. package/src/http/requestHandler/HttpRequestHandlerClient.ts +15 -5
  32. package/src/http/requestHandler/errors/DisabledRequestSavingError.ts +2 -2
  33. package/src/http/requestHandler/errors/TimesCheckError.ts +15 -14
  34. package/src/http/requestHandler/types/public.ts +16 -8
  35. package/src/server/index.ts +1 -11
  36. package/src/utils/console.ts +2 -2
  37. package/dist/chunk-6TSSHQW5.mjs.map +0 -1
  38. package/dist/chunk-R2ROSKU4.js.map +0 -1
  39. package/src/http/interceptorWorker/HttpInterceptorWorkerStore.ts +0 -34
  40. package/src/http/namespace/HttpInterceptorNamespace.ts +0 -81
  41. package/src/server/namespace/InterceptorServerNamespace.ts +0 -21
package/dist/http.mjs CHANGED
@@ -1,5 +1,5 @@
1
+ import color2 from 'picocolors';
1
2
  import { HttpHeaders, HttpSearchParams, HttpFormData, HTTP_METHODS, HTTP_METHODS_WITH_RESPONSE_BODY } from '@zimic/http';
2
- import chalk2 from 'chalk';
3
3
  import { http, passthrough } from 'msw';
4
4
  import * as mswBrowser from 'msw/browser';
5
5
  import * as mswNode from 'msw/node';
@@ -8,6 +8,44 @@ import ClientSocket from 'isomorphic-ws';
8
8
  var __defProp = Object.defineProperty;
9
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
10
 
11
+ // src/http/interceptor/errors/RunningHttpInterceptorError.ts
12
+ var RunningHttpInterceptorError = class extends Error {
13
+ static {
14
+ __name(this, "RunningHttpInterceptorError");
15
+ }
16
+ constructor(additionalMessage) {
17
+ super(`The interceptor is running.${additionalMessage}`);
18
+ this.name = "RunningHttpInterceptorError";
19
+ }
20
+ };
21
+ var RunningHttpInterceptorError_default = RunningHttpInterceptorError;
22
+
23
+ // src/http/interceptor/errors/NotRunningHttpInterceptorError.ts
24
+ var NotRunningHttpInterceptorError = class extends Error {
25
+ static {
26
+ __name(this, "NotRunningHttpInterceptorError");
27
+ }
28
+ constructor() {
29
+ super("Interceptor is not running. Did you forget to call `await interceptor.start()`?");
30
+ this.name = "NotRunningHttpInterceptorError";
31
+ }
32
+ };
33
+ var NotRunningHttpInterceptorError_default = NotRunningHttpInterceptorError;
34
+
35
+ // src/http/interceptor/errors/UnknownHttpInterceptorPlatformError.ts
36
+ var UnknownHttpInterceptorPlatformError = class extends Error {
37
+ static {
38
+ __name(this, "UnknownHttpInterceptorPlatformError");
39
+ }
40
+ /* istanbul ignore next -- @preserve
41
+ * Ignoring because checking unknown platforms is currently not possible in our Vitest setup. */
42
+ constructor() {
43
+ super("Unknown interceptor platform.");
44
+ this.name = "UnknownHttpInterceptorPlatform";
45
+ }
46
+ };
47
+ var UnknownHttpInterceptorPlatformError_default = UnknownHttpInterceptorPlatformError;
48
+
11
49
  // src/http/interceptor/errors/UnknownHttpInterceptorTypeError.ts
12
50
  var UnknownHttpInterceptorTypeError = class extends TypeError {
13
51
  static {
@@ -22,102 +60,73 @@ var UnknownHttpInterceptorTypeError = class extends TypeError {
22
60
  };
23
61
  var UnknownHttpInterceptorTypeError_default = UnknownHttpInterceptorTypeError;
24
62
 
25
- // ../zimic-utils/dist/chunk-PAWJFY3S.mjs
26
- var __defProp2 = Object.defineProperty;
27
- var __name2 = /* @__PURE__ */ __name((target, value) => __defProp2(target, "name", { value, configurable: true }), "__name");
63
+ // src/http/interceptor/errors/RequestSavingSafeLimitExceededError.ts
64
+ var RequestSavingSafeLimitExceededError = class extends TypeError {
65
+ static {
66
+ __name(this, "RequestSavingSafeLimitExceededError");
67
+ }
68
+ constructor(numberOfSavedRequests, safeLimit) {
69
+ super(
70
+ `The number of intercepted requests saved in memory (${numberOfSavedRequests}) exceeded the safe limit of ${safeLimit}. Did you forget to call \`interceptor.clear()\`?
28
71
 
29
- // ../zimic-utils/dist/data/blobContains.mjs
30
- async function blobContains(blob, otherBlob) {
31
- return blob.type === otherBlob.type && blob.size >= otherBlob.size && (await blob.text()).includes(await otherBlob.text());
32
- }
33
- __name(blobContains, "blobContains");
34
- __name2(blobContains, "blobContains");
35
- var blobContains_default = blobContains;
72
+ If you need to save requests, make sure to regularly call \`interceptor.clear()\`. Alternatively, you can hide this warning by increasing \`requestSaving.safeLimit\` in your interceptor. Note that saving too many requests in memory can lead to performance issues.
36
73
 
37
- // ../zimic-utils/dist/chunk-HVLEF6VF.mjs
38
- async function blobEquals(blob, otherBlob) {
39
- return blob.type === otherBlob.type && blob.size === otherBlob.size && await blob.text() === await otherBlob.text();
40
- }
41
- __name(blobEquals, "blobEquals");
42
- __name2(blobEquals, "blobEquals");
43
- var blobEquals_default = blobEquals;
74
+ If you do not need to save requests, consider setting \`requestSaving.enabled: false\` in your interceptor.
44
75
 
45
- // src/utils/json.ts
46
- function isPrimitiveJSONValue(value) {
47
- return typeof value !== "object" || value === null;
48
- }
49
- __name(isPrimitiveJSONValue, "isPrimitiveJSONValue");
50
- function jsonEquals(value, otherValue) {
51
- if (isPrimitiveJSONValue(value)) {
52
- return value === otherValue;
53
- }
54
- if (isPrimitiveJSONValue(otherValue)) {
55
- return false;
56
- }
57
- if (Array.isArray(value)) {
58
- if (!Array.isArray(otherValue)) {
59
- return false;
60
- }
61
- if (value.length !== otherValue.length) {
62
- return false;
63
- }
64
- return value.every((item, index) => jsonEquals(item, otherValue[index]));
76
+ Learn more: https://github.com/zimicjs/zimic/wiki/api\u2010zimic\u2010interceptor\u2010http#saving-requests`
77
+ );
78
+ this.name = "RequestSavingSafeLimitExceededError";
65
79
  }
66
- if (Array.isArray(otherValue)) {
67
- return false;
80
+ };
81
+ var RequestSavingSafeLimitExceededError_default = RequestSavingSafeLimitExceededError;
82
+
83
+ // src/http/interceptorWorker/errors/InvalidFormDataError.ts
84
+ var InvalidFormDataError = class extends SyntaxError {
85
+ static {
86
+ __name(this, "InvalidFormDataError");
68
87
  }
69
- const valueKeys = Object.keys(value);
70
- const otherValueKeys = Object.keys(otherValue);
71
- if (valueKeys.length !== otherValueKeys.length) {
72
- return false;
88
+ constructor(value) {
89
+ super(`Failed to parse value as form data: ${value}`);
90
+ this.name = "InvalidFormDataError";
73
91
  }
74
- return valueKeys.every((key) => {
75
- const subValue = value[key];
76
- const subOtherValue = otherValue[key];
77
- return jsonEquals(subValue, subOtherValue);
78
- });
79
- }
80
- __name(jsonEquals, "jsonEquals");
81
- function jsonContains(value, otherValue) {
82
- if (isPrimitiveJSONValue(value)) {
83
- return value === otherValue;
92
+ };
93
+ var InvalidFormDataError_default = InvalidFormDataError;
94
+
95
+ // src/http/interceptorWorker/errors/InvalidJSONError.ts
96
+ var InvalidJSONError = class extends SyntaxError {
97
+ static {
98
+ __name(this, "InvalidJSONError");
84
99
  }
85
- if (isPrimitiveJSONValue(otherValue)) {
86
- return false;
100
+ constructor(value) {
101
+ super(`Failed to parse value as JSON: ${value}`);
102
+ this.name = "InvalidJSONError";
87
103
  }
88
- if (Array.isArray(value)) {
89
- if (!Array.isArray(otherValue)) {
90
- return false;
91
- }
92
- if (value.length < otherValue.length) {
93
- return false;
94
- }
95
- let lastMatchedIndex = -1;
96
- return otherValue.every((otherItem) => {
97
- for (let index = lastMatchedIndex + 1; index < value.length; index++) {
98
- if (jsonContains(value[index], otherItem)) {
99
- lastMatchedIndex = index;
100
- return true;
101
- }
102
- }
103
- return false;
104
- });
104
+ };
105
+ var InvalidJSONError_default = InvalidJSONError;
106
+
107
+ // src/cli/browser/shared/constants.ts
108
+ var SERVICE_WORKER_FILE_NAME = "mockServiceWorker.js";
109
+
110
+ // src/http/interceptorWorker/errors/UnregisteredBrowserServiceWorkerError.ts
111
+ var UnregisteredBrowserServiceWorkerError = class extends Error {
112
+ static {
113
+ __name(this, "UnregisteredBrowserServiceWorkerError");
105
114
  }
106
- if (Array.isArray(otherValue)) {
107
- return false;
115
+ constructor() {
116
+ super(
117
+ `Failed to register the browser service worker: script '${window.location.origin}/${SERVICE_WORKER_FILE_NAME}' not found.
118
+
119
+ Did you forget to run \`zimic-interceptor browser init <publicDirectory>\`?
120
+
121
+ Learn more: https://github.com/zimicjs/zimic/wiki/getting\u2010started#client-side-post-install`
122
+ );
123
+ this.name = "UnregisteredBrowserServiceWorkerError";
108
124
  }
109
- const valueKeys = Object.keys(value);
110
- const otherValueKeys = Object.keys(otherValue);
111
- if (valueKeys.length < otherValueKeys.length) {
112
- return false;
125
+ static matchesRawError(error) {
126
+ return error instanceof Error && error.message.toLowerCase().includes("service worker script does not exist at the given path");
113
127
  }
114
- return otherValueKeys.every((key) => {
115
- const subValue = value[key];
116
- const subOtherValue = otherValue[key];
117
- return jsonContains(subValue, subOtherValue);
118
- });
119
- }
120
- __name(jsonContains, "jsonContains");
128
+ };
129
+ var UnregisteredBrowserServiceWorkerError_default = UnregisteredBrowserServiceWorkerError;
121
130
 
122
131
  // src/http/requestHandler/errors/DisabledRequestSavingError.ts
123
132
  var DisabledRequestSavingError = class extends TypeError {
@@ -126,24 +135,16 @@ var DisabledRequestSavingError = class extends TypeError {
126
135
  }
127
136
  constructor() {
128
137
  super(
129
- "Intercepted requests are not saved by default. Did you forget to use `saveRequests: true` when creating the interceptor?\n\nLearn more: https://github.com/zimicjs/zimic/wiki/api\u2010zimic\u2010interceptor\u2010http#saving-requests"
138
+ "Intercepted requests are not being saved. Did you forget to use `requestSaving.enabled: true` in your interceptor?\n\nLearn more: https://github.com/zimicjs/zimic/wiki/api\u2010zimic\u2010interceptor\u2010http#saving-requests"
130
139
  );
131
140
  this.name = "DisabledRequestSavingError";
132
141
  }
133
142
  };
134
143
  var DisabledRequestSavingError_default = DisabledRequestSavingError;
135
144
 
136
- // src/http/requestHandler/errors/NoResponseDefinitionError.ts
137
- var NoResponseDefinitionError = class extends TypeError {
138
- static {
139
- __name(this, "NoResponseDefinitionError");
140
- }
141
- constructor() {
142
- super("Cannot generate a response without a definition. Use .respond() to set a response.");
143
- this.name = "NoResponseDefinitionError";
144
- }
145
- };
146
- var NoResponseDefinitionError_default = NoResponseDefinitionError;
145
+ // ../zimic-utils/dist/chunk-PAWJFY3S.mjs
146
+ var __defProp2 = Object.defineProperty;
147
+ var __name2 = /* @__PURE__ */ __name((target, value) => __defProp2(target, "name", { value, configurable: true }), "__name");
147
148
 
148
149
  // ../zimic-utils/dist/chunk-3O5CS47X.mjs
149
150
  function isDefined(value) {
@@ -247,7 +248,7 @@ __name(formatValueToLog, "formatValueToLog");
247
248
  function logWithPrefix(messageOrMessages, options = {}) {
248
249
  const { method = "log" } = options;
249
250
  const messages = Array.isArray(messageOrMessages) ? messageOrMessages : [messageOrMessages];
250
- console[method](chalk2.cyan("[@zimic/interceptor]"), ...messages);
251
+ console[method](color2.cyan("[@zimic/interceptor]"), ...messages);
251
252
  }
252
253
  __name(logWithPrefix, "logWithPrefix");
253
254
 
@@ -273,14 +274,14 @@ function createMessageHeader({
273
274
 
274
275
  Requests evaluated by this handler:
275
276
 
276
- ${chalk2.green("- Expected")}
277
- ${chalk2.red("+ Received")}`
277
+ ${color2.green("- Expected")}
278
+ ${color2.red("+ Received")}`
278
279
  ].filter((part) => part !== false).join("");
279
280
  }
280
281
  __name(createMessageHeader, "createMessageHeader");
281
- function createMessageDiffs({ hasSavedRequests, unmatchedRequestGroups }) {
282
- if (!hasSavedRequests) {
283
- return "Tip: enable `saveRequests: true` in your interceptor for more details about the unmatched requests.";
282
+ function createMessageDiffs({ requestSaving, unmatchedRequestGroups }) {
283
+ if (!requestSaving.enabled) {
284
+ return "Tip: use `requestSaving.enabled: true` in your interceptor for more details about the unmatched requests.";
284
285
  }
285
286
  return unmatchedRequestGroups.map(({ request, diff }, index) => {
286
287
  const requestNumber = index + 1;
@@ -289,22 +290,22 @@ function createMessageDiffs({ hasSavedRequests, unmatchedRequestGroups }) {
289
290
  messageParts.push("Computed restriction:");
290
291
  const stringifiedExpected = stringifyValueToLog(diff.computed.expected);
291
292
  const stringifiedReceived = stringifyValueToLog(diff.computed.received);
292
- messageParts.push(` ${chalk2.green(`- return ${stringifiedExpected}`)}`);
293
- messageParts.push(` ${chalk2.red(`+ return ${stringifiedReceived}`)}`);
293
+ messageParts.push(` ${color2.green(`- return ${stringifiedExpected}`)}`);
294
+ messageParts.push(` ${color2.red(`+ return ${stringifiedReceived}`)}`);
294
295
  }
295
296
  if (diff.headers) {
296
297
  messageParts.push("Headers:");
297
298
  const stringifiedExpected = stringifyValueToLog(diff.headers.expected);
298
299
  const stringifiedReceived = stringifyValueToLog(diff.headers.received);
299
- messageParts.push(` ${chalk2.green(`- ${stringifiedExpected}`)}`);
300
- messageParts.push(` ${chalk2.red(`+ ${stringifiedReceived}`)}`);
300
+ messageParts.push(` ${color2.green(`- ${stringifiedExpected}`)}`);
301
+ messageParts.push(` ${color2.red(`+ ${stringifiedReceived}`)}`);
301
302
  }
302
303
  if (diff.searchParams) {
303
304
  messageParts.push("Search params:");
304
305
  const stringifiedExpected = stringifyValueToLog(diff.searchParams.expected);
305
306
  const stringifiedReceived = stringifyValueToLog(diff.searchParams.received);
306
- messageParts.push(` ${chalk2.green(`- ${stringifiedExpected}`)}`);
307
- messageParts.push(` ${chalk2.red(`+ ${stringifiedReceived}`)}`);
307
+ messageParts.push(` ${color2.green(`- ${stringifiedExpected}`)}`);
308
+ messageParts.push(` ${color2.red(`+ ${stringifiedReceived}`)}`);
308
309
  }
309
310
  if (diff.body) {
310
311
  messageParts.push("Body:");
@@ -314,8 +315,8 @@ function createMessageDiffs({ hasSavedRequests, unmatchedRequestGroups }) {
314
315
  const stringifiedReceived = stringifyValueToLog(diff.body.received, {
315
316
  includeClassName: { searchParams: true }
316
317
  });
317
- messageParts.push(` ${chalk2.green(`- ${stringifiedExpected}`)}`);
318
- messageParts.push(` ${chalk2.red(`+ ${stringifiedReceived}`)}`);
318
+ messageParts.push(` ${color2.green(`- ${stringifiedExpected}`)}`);
319
+ messageParts.push(` ${color2.red(`+ ${stringifiedReceived}`)}`);
319
320
  }
320
321
  return messageParts.join("\n ");
321
322
  }).join("\n\n");
@@ -345,6 +346,111 @@ var TimesCheckError = class extends TypeError {
345
346
  };
346
347
  var TimesCheckError_default = TimesCheckError;
347
348
 
349
+ // ../zimic-utils/dist/data/blobContains.mjs
350
+ async function blobContains(blob, otherBlob) {
351
+ return blob.type === otherBlob.type && blob.size >= otherBlob.size && (await blob.text()).includes(await otherBlob.text());
352
+ }
353
+ __name(blobContains, "blobContains");
354
+ __name2(blobContains, "blobContains");
355
+ var blobContains_default = blobContains;
356
+
357
+ // ../zimic-utils/dist/chunk-HVLEF6VF.mjs
358
+ async function blobEquals(blob, otherBlob) {
359
+ return blob.type === otherBlob.type && blob.size === otherBlob.size && await blob.text() === await otherBlob.text();
360
+ }
361
+ __name(blobEquals, "blobEquals");
362
+ __name2(blobEquals, "blobEquals");
363
+ var blobEquals_default = blobEquals;
364
+
365
+ // src/utils/json.ts
366
+ function isPrimitiveJSONValue(value) {
367
+ return typeof value !== "object" || value === null;
368
+ }
369
+ __name(isPrimitiveJSONValue, "isPrimitiveJSONValue");
370
+ function jsonEquals(value, otherValue) {
371
+ if (isPrimitiveJSONValue(value)) {
372
+ return value === otherValue;
373
+ }
374
+ if (isPrimitiveJSONValue(otherValue)) {
375
+ return false;
376
+ }
377
+ if (Array.isArray(value)) {
378
+ if (!Array.isArray(otherValue)) {
379
+ return false;
380
+ }
381
+ if (value.length !== otherValue.length) {
382
+ return false;
383
+ }
384
+ return value.every((item, index) => jsonEquals(item, otherValue[index]));
385
+ }
386
+ if (Array.isArray(otherValue)) {
387
+ return false;
388
+ }
389
+ const valueKeys = Object.keys(value);
390
+ const otherValueKeys = Object.keys(otherValue);
391
+ if (valueKeys.length !== otherValueKeys.length) {
392
+ return false;
393
+ }
394
+ return valueKeys.every((key) => {
395
+ const subValue = value[key];
396
+ const subOtherValue = otherValue[key];
397
+ return jsonEquals(subValue, subOtherValue);
398
+ });
399
+ }
400
+ __name(jsonEquals, "jsonEquals");
401
+ function jsonContains(value, otherValue) {
402
+ if (isPrimitiveJSONValue(value)) {
403
+ return value === otherValue;
404
+ }
405
+ if (isPrimitiveJSONValue(otherValue)) {
406
+ return false;
407
+ }
408
+ if (Array.isArray(value)) {
409
+ if (!Array.isArray(otherValue)) {
410
+ return false;
411
+ }
412
+ if (value.length < otherValue.length) {
413
+ return false;
414
+ }
415
+ let lastMatchedIndex = -1;
416
+ return otherValue.every((otherItem) => {
417
+ for (let index = lastMatchedIndex + 1; index < value.length; index++) {
418
+ if (jsonContains(value[index], otherItem)) {
419
+ lastMatchedIndex = index;
420
+ return true;
421
+ }
422
+ }
423
+ return false;
424
+ });
425
+ }
426
+ if (Array.isArray(otherValue)) {
427
+ return false;
428
+ }
429
+ const valueKeys = Object.keys(value);
430
+ const otherValueKeys = Object.keys(otherValue);
431
+ if (valueKeys.length < otherValueKeys.length) {
432
+ return false;
433
+ }
434
+ return otherValueKeys.every((key) => {
435
+ const subValue = value[key];
436
+ const subOtherValue = otherValue[key];
437
+ return jsonContains(subValue, subOtherValue);
438
+ });
439
+ }
440
+ __name(jsonContains, "jsonContains");
441
+
442
+ // src/http/requestHandler/errors/NoResponseDefinitionError.ts
443
+ var NoResponseDefinitionError = class extends TypeError {
444
+ static {
445
+ __name(this, "NoResponseDefinitionError");
446
+ }
447
+ constructor() {
448
+ super("Cannot generate a response without a definition. Use .respond() to set a response.");
449
+ this.name = "NoResponseDefinitionError";
450
+ }
451
+ };
452
+ var NoResponseDefinitionError_default = NoResponseDefinitionError;
453
+
348
454
  // src/http/requestHandler/errors/TimesDeclarationPointer.ts
349
455
  var TimesDeclarationPointer = class extends Error {
350
456
  static {
@@ -390,7 +496,7 @@ var HttpRequestHandlerClient = class {
390
496
  newThis.createResponseDeclaration = this.isResponseDeclarationFactory(declaration) ? declaration : () => declaration;
391
497
  newThis.numberOfMatchedRequests = 0;
392
498
  newThis.unmatchedRequestGroups.length = 0;
393
- newThis._requests.length = 0;
499
+ newThis.clearInterceptedRequests();
394
500
  this.interceptor.registerRequestHandler(this.handler);
395
501
  return newThis;
396
502
  }
@@ -414,7 +520,7 @@ var HttpRequestHandlerClient = class {
414
520
  declarationPointer: this.timesDeclarationPointer,
415
521
  unmatchedRequestGroups: this.unmatchedRequestGroups,
416
522
  hasRestrictions: this.restrictions.length > 0,
417
- hasSavedRequests: this.interceptor.saveRequests
523
+ requestSaving: this.interceptor.requestSaving
418
524
  });
419
525
  }
420
526
  }
@@ -426,7 +532,7 @@ var HttpRequestHandlerClient = class {
426
532
  this.timesDeclarationPointer = void 0;
427
533
  this.numberOfMatchedRequests = 0;
428
534
  this.unmatchedRequestGroups.length = 0;
429
- this._requests.length = 0;
535
+ this.clearInterceptedRequests();
430
536
  this.createResponseDeclaration = void 0;
431
537
  return this;
432
538
  }
@@ -439,7 +545,7 @@ var HttpRequestHandlerClient = class {
439
545
  if (restrictionsMatch.value) {
440
546
  this.numberOfMatchedRequests++;
441
547
  } else {
442
- const shouldSaveUnmatchedGroup = this.interceptor.saveRequests && this.restrictions.length > 0 && this.timesDeclarationPointer !== void 0;
548
+ const shouldSaveUnmatchedGroup = this.interceptor.requestSaving.enabled && this.restrictions.length > 0 && this.timesDeclarationPointer !== void 0;
443
549
  if (shouldSaveUnmatchedGroup) {
444
550
  this.unmatchedRequestGroups.push({ request, diff: restrictionsMatch.diff });
445
551
  }
@@ -573,6 +679,11 @@ var HttpRequestHandlerClient = class {
573
679
  saveInterceptedRequest(request, response) {
574
680
  const interceptedRequest = this.createInterceptedRequest(request, response);
575
681
  this._requests.push(interceptedRequest);
682
+ this.interceptor.incrementNumberOfSavedRequests(1);
683
+ }
684
+ clearInterceptedRequests() {
685
+ this.interceptor.incrementNumberOfSavedRequests(-this._requests.length);
686
+ this._requests.length = 0;
576
687
  }
577
688
  createInterceptedRequest(request, response) {
578
689
  const interceptedRequest = request;
@@ -585,7 +696,7 @@ var HttpRequestHandlerClient = class {
585
696
  return interceptedRequest;
586
697
  }
587
698
  get requests() {
588
- if (!this.interceptor.saveRequests) {
699
+ if (!this.interceptor.requestSaving.enabled) {
589
700
  throw new DisabledRequestSavingError_default();
590
701
  }
591
702
  return this._requests;
@@ -760,53 +871,6 @@ var DEFAULT_UNHANDLED_REQUEST_STRATEGY = Object.freeze({
760
871
  })
761
872
  });
762
873
 
763
- // src/http/interceptorWorker/errors/InvalidFormDataError.ts
764
- var InvalidFormDataError = class extends SyntaxError {
765
- static {
766
- __name(this, "InvalidFormDataError");
767
- }
768
- constructor(value) {
769
- super(`Failed to parse value as form data: ${value}`);
770
- this.name = "InvalidFormDataError";
771
- }
772
- };
773
- var InvalidFormDataError_default = InvalidFormDataError;
774
-
775
- // src/http/interceptorWorker/errors/InvalidJSONError.ts
776
- var InvalidJSONError = class extends SyntaxError {
777
- static {
778
- __name(this, "InvalidJSONError");
779
- }
780
- constructor(value) {
781
- super(`Failed to parse value as JSON: ${value}`);
782
- this.name = "InvalidJSONError";
783
- }
784
- };
785
- var InvalidJSONError_default = InvalidJSONError;
786
-
787
- // src/http/interceptorWorker/HttpInterceptorWorkerStore.ts
788
- var HttpInterceptorWorkerStore = class _HttpInterceptorWorkerStore {
789
- static {
790
- __name(this, "HttpInterceptorWorkerStore");
791
- }
792
- static _defaultOnUnhandledRequest = {
793
- local: { ...DEFAULT_UNHANDLED_REQUEST_STRATEGY.local },
794
- remote: { ...DEFAULT_UNHANDLED_REQUEST_STRATEGY.remote }
795
- };
796
- class = _HttpInterceptorWorkerStore;
797
- defaultOnUnhandledRequest(interceptorType) {
798
- return this.class._defaultOnUnhandledRequest[interceptorType];
799
- }
800
- setDefaultOnUnhandledRequest(interceptorType, strategy) {
801
- if (interceptorType === "local") {
802
- this.class._defaultOnUnhandledRequest[interceptorType] = strategy;
803
- } else {
804
- this.class._defaultOnUnhandledRequest[interceptorType] = strategy;
805
- }
806
- }
807
- };
808
- var HttpInterceptorWorkerStore_default = HttpInterceptorWorkerStore;
809
-
810
874
  // src/http/interceptorWorker/HttpInterceptorWorker.ts
811
875
  var HttpInterceptorWorker = class _HttpInterceptorWorker {
812
876
  static {
@@ -816,7 +880,6 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
816
880
  isRunning = false;
817
881
  startingPromise;
818
882
  stoppingPromise;
819
- store = new HttpInterceptorWorkerStore_default();
820
883
  runningInterceptors = [];
821
884
  async sharedStart(internalStart) {
822
885
  if (this.isRunning) {
@@ -875,24 +938,18 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
875
938
  );
876
939
  }
877
940
  async getUnhandledRequestStrategyCandidates(request, interceptorType) {
878
- const globalDefaultStrategy = this.getGlobalDefaultUnhandledRequestStrategy(interceptorType);
941
+ const globalDefaultStrategy = DEFAULT_UNHANDLED_REQUEST_STRATEGY[interceptorType];
879
942
  try {
880
943
  const interceptor = this.findInterceptorByRequestBaseURL(request);
881
944
  if (!interceptor) {
882
945
  return [];
883
946
  }
884
947
  const requestClone = request.clone();
885
- const [defaultStrategy, interceptorStrategy] = await Promise.all([
886
- this.getDefaultUnhandledRequestStrategy(request, interceptorType),
887
- this.getInterceptorUnhandledRequestStrategy(requestClone, interceptor)
888
- ]);
889
- const candidatesOrPromises = [interceptorStrategy, defaultStrategy, globalDefaultStrategy];
890
- const candidateStrategies = await Promise.all(candidatesOrPromises.filter(isDefined_default));
891
- return candidateStrategies;
948
+ const interceptorStrategy = await this.getInterceptorUnhandledRequestStrategy(requestClone, interceptor);
949
+ return [interceptorStrategy, globalDefaultStrategy].filter(isDefined_default);
892
950
  } catch (error) {
893
951
  console.error(error);
894
- const candidateStrategies = [globalDefaultStrategy];
895
- return candidateStrategies;
952
+ return [globalDefaultStrategy];
896
953
  }
897
954
  }
898
955
  registerRunningInterceptor(interceptor) {
@@ -907,17 +964,6 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
907
964
  });
908
965
  return interceptor;
909
966
  }
910
- getGlobalDefaultUnhandledRequestStrategy(interceptorType) {
911
- return DEFAULT_UNHANDLED_REQUEST_STRATEGY[interceptorType];
912
- }
913
- async getDefaultUnhandledRequestStrategy(request, interceptorType) {
914
- const defaultStrategyOrFactory = this.store.defaultOnUnhandledRequest(interceptorType);
915
- if (typeof defaultStrategyOrFactory === "function") {
916
- const parsedRequest = await _HttpInterceptorWorker.parseRawUnhandledRequest(request);
917
- return defaultStrategyOrFactory(parsedRequest);
918
- }
919
- return defaultStrategyOrFactory;
920
- }
921
967
  async getInterceptorUnhandledRequestStrategy(request, interceptor) {
922
968
  if (typeof interceptor.onUnhandledRequest === "function") {
923
969
  const parsedRequest = await _HttpInterceptorWorker.parseRawUnhandledRequest(request);
@@ -1131,7 +1177,7 @@ var HttpInterceptorWorker = class _HttpInterceptorWorker {
1131
1177
  ]);
1132
1178
  logWithPrefix(
1133
1179
  [
1134
- `${action === "bypass" ? "Warning:" : "Error:"} Request was not handled and was ${action === "bypass" ? chalk2.yellow("bypassed") : chalk2.red("rejected")}.
1180
+ `${action === "bypass" ? "Warning:" : "Error:"} Request was not handled and was ${action === "bypass" ? color2.yellow("bypassed") : color2.red("rejected")}.
1135
1181
 
1136
1182
  `,
1137
1183
  `${request.method} ${request.url}`,
@@ -1179,58 +1225,6 @@ function validateURLPathParams(url) {
1179
1225
  __name(validateURLPathParams, "validateURLPathParams");
1180
1226
  __name2(validateURLPathParams, "validateURLPathParams");
1181
1227
  var validateURLPathParams_default = validateURLPathParams;
1182
-
1183
- // src/http/interceptor/errors/NotRunningHttpInterceptorError.ts
1184
- var NotRunningHttpInterceptorError = class extends Error {
1185
- static {
1186
- __name(this, "NotRunningHttpInterceptorError");
1187
- }
1188
- constructor() {
1189
- super("Interceptor is not running. Did you forget to call `await interceptor.start()`?");
1190
- this.name = "NotRunningHttpInterceptorError";
1191
- }
1192
- };
1193
- var NotRunningHttpInterceptorError_default = NotRunningHttpInterceptorError;
1194
-
1195
- // src/http/interceptor/errors/UnknownHttpInterceptorPlatformError.ts
1196
- var UnknownHttpInterceptorPlatformError = class extends Error {
1197
- static {
1198
- __name(this, "UnknownHttpInterceptorPlatformError");
1199
- }
1200
- /* istanbul ignore next -- @preserve
1201
- * Ignoring because checking unknown platforms is currently not possible in our Vitest setup. */
1202
- constructor() {
1203
- super("Unknown interceptor platform.");
1204
- this.name = "UnknownHttpInterceptorPlatform";
1205
- }
1206
- };
1207
- var UnknownHttpInterceptorPlatformError_default = UnknownHttpInterceptorPlatformError;
1208
-
1209
- // src/cli/browser/shared/constants.ts
1210
- var SERVICE_WORKER_FILE_NAME = "mockServiceWorker.js";
1211
-
1212
- // src/http/interceptorWorker/errors/UnregisteredBrowserServiceWorkerError.ts
1213
- var UnregisteredBrowserServiceWorkerError = class extends Error {
1214
- static {
1215
- __name(this, "UnregisteredBrowserServiceWorkerError");
1216
- }
1217
- constructor() {
1218
- super(
1219
- `Failed to register the browser service worker: script '${window.location.origin}/${SERVICE_WORKER_FILE_NAME}' not found.
1220
-
1221
- Did you forget to run \`zimic-interceptor browser init <publicDirectory>\`?
1222
-
1223
- Learn more: https://github.com/zimicjs/zimic/wiki/getting\u2010started#client-side-post-install`
1224
- );
1225
- this.name = "UnregisteredBrowserServiceWorkerError";
1226
- }
1227
- static matchesRawError(error) {
1228
- return error instanceof Error && error.message.toLowerCase().includes("service worker script does not exist at the given path");
1229
- }
1230
- };
1231
- var UnregisteredBrowserServiceWorkerError_default = UnregisteredBrowserServiceWorkerError;
1232
-
1233
- // src/http/interceptorWorker/LocalHttpInterceptorWorker.ts
1234
1228
  var LocalHttpInterceptorWorker = class extends HttpInterceptorWorker_default {
1235
1229
  static {
1236
1230
  __name(this, "LocalHttpInterceptorWorker");
@@ -1488,20 +1482,9 @@ var RemoteHttpRequestHandler = class {
1488
1482
  };
1489
1483
  var RemoteHttpRequestHandler_default = RemoteHttpRequestHandler;
1490
1484
 
1491
- // src/http/interceptor/errors/RunningHttpInterceptorError.ts
1492
- var RunningHttpInterceptorError = class extends Error {
1493
- static {
1494
- __name(this, "RunningHttpInterceptorError");
1495
- }
1496
- constructor(additionalMessage) {
1497
- super(`The interceptor is running.${additionalMessage}`);
1498
- this.name = "RunningHttpInterceptorError";
1499
- }
1500
- };
1501
- var RunningHttpInterceptorError_default = RunningHttpInterceptorError;
1502
-
1503
1485
  // src/http/interceptor/HttpInterceptorClient.ts
1504
1486
  var SUPPORTED_BASE_URL_PROTOCOLS = Object.freeze(["http", "https"]);
1487
+ var DEFAULT_REQUEST_SAVING_SAFE_LIMIT = 1e3;
1505
1488
  var HttpInterceptorClient = class {
1506
1489
  static {
1507
1490
  __name(this, "HttpInterceptorClient");
@@ -1509,7 +1492,8 @@ var HttpInterceptorClient = class {
1509
1492
  worker;
1510
1493
  store;
1511
1494
  _baseURL;
1512
- _saveRequests;
1495
+ requestSaving;
1496
+ numberOfSavedRequests = 0;
1513
1497
  onUnhandledRequest;
1514
1498
  isRunning = false;
1515
1499
  Handler;
@@ -1526,10 +1510,16 @@ var HttpInterceptorClient = class {
1526
1510
  this.worker = options.worker;
1527
1511
  this.store = options.store;
1528
1512
  this.baseURL = options.baseURL;
1529
- this._saveRequests = options.saveRequests;
1513
+ this.requestSaving = {
1514
+ enabled: options.requestSaving?.enabled ?? this.getDefaultRequestSavingEnabled(),
1515
+ safeLimit: options.requestSaving?.safeLimit ?? DEFAULT_REQUEST_SAVING_SAFE_LIMIT
1516
+ };
1530
1517
  this.onUnhandledRequest = options.onUnhandledRequest;
1531
1518
  this.Handler = options.Handler;
1532
1519
  }
1520
+ getDefaultRequestSavingEnabled() {
1521
+ return isServerSide() ? process.env.NODE_ENV === "test" : false;
1522
+ }
1533
1523
  get baseURL() {
1534
1524
  return this._baseURL;
1535
1525
  }
@@ -1549,15 +1539,6 @@ var HttpInterceptorClient = class {
1549
1539
  }
1550
1540
  return this.baseURL.href;
1551
1541
  }
1552
- get saveRequests() {
1553
- if (this._saveRequests === void 0) {
1554
- return isServerSide() ? process.env.NODE_ENV === "test" : false;
1555
- }
1556
- return this._saveRequests;
1557
- }
1558
- set saveRequests(saveRequests) {
1559
- this._saveRequests = saveRequests;
1560
- }
1561
1542
  get platform() {
1562
1543
  return this.worker.platform;
1563
1544
  }
@@ -1655,13 +1636,21 @@ var HttpInterceptorClient = class {
1655
1636
  }
1656
1637
  const responseDeclaration = await matchedHandler.applyResponseDeclaration(parsedRequest);
1657
1638
  const response = HttpInterceptorWorker_default.createResponseFromDeclaration(request, responseDeclaration);
1658
- if (this.saveRequests) {
1639
+ if (this.requestSaving.enabled) {
1659
1640
  const responseClone = response.clone();
1660
1641
  const parsedResponse = await HttpInterceptorWorker_default.parseRawResponse(responseClone);
1661
1642
  matchedHandler.saveInterceptedRequest(parsedRequest, parsedResponse);
1662
1643
  }
1663
1644
  return response;
1664
1645
  }
1646
+ incrementNumberOfSavedRequests(increment) {
1647
+ this.numberOfSavedRequests = Math.max(this.numberOfSavedRequests + increment, 0);
1648
+ const exceedsSafeLimit = this.numberOfSavedRequests > this.requestSaving.safeLimit;
1649
+ if (increment > 0 && exceedsSafeLimit) {
1650
+ const error = new RequestSavingSafeLimitExceededError_default(this.numberOfSavedRequests, this.requestSaving.safeLimit);
1651
+ console.warn(error);
1652
+ }
1653
+ }
1665
1654
  async findMatchedHandler(method, path, parsedRequest) {
1666
1655
  const handlersByPath = this.handlerClientsByMethod[method].get(path) ?? [];
1667
1656
  for (let handlerIndex = handlersByPath.length - 1; handlerIndex >= 0; handlerIndex--) {
@@ -2410,7 +2399,7 @@ var LocalHttpInterceptor = class {
2410
2399
  baseURL,
2411
2400
  Handler: LocalHttpRequestHandler_default,
2412
2401
  onUnhandledRequest: options.onUnhandledRequest,
2413
- saveRequests: options.saveRequests
2402
+ requestSaving: options.requestSaving
2414
2403
  });
2415
2404
  }
2416
2405
  get type() {
@@ -2422,11 +2411,11 @@ var LocalHttpInterceptor = class {
2422
2411
  set baseURL(baseURL) {
2423
2412
  this.client.baseURL = new URL(baseURL);
2424
2413
  }
2425
- get saveRequests() {
2426
- return this.client.saveRequests;
2414
+ get requestSaving() {
2415
+ return this.client.requestSaving;
2427
2416
  }
2428
- set saveRequests(saveRequests) {
2429
- this.client.saveRequests = saveRequests;
2417
+ set requestSaving(requestSaving) {
2418
+ this.client.requestSaving = requestSaving;
2430
2419
  }
2431
2420
  get onUnhandledRequest() {
2432
2421
  return this.client.onUnhandledRequest;
@@ -2500,7 +2489,7 @@ var RemoteHttpInterceptor = class {
2500
2489
  baseURL,
2501
2490
  Handler: RemoteHttpRequestHandler_default,
2502
2491
  onUnhandledRequest: options.onUnhandledRequest,
2503
- saveRequests: options.saveRequests
2492
+ requestSaving: options.requestSaving
2504
2493
  });
2505
2494
  }
2506
2495
  get type() {
@@ -2512,11 +2501,11 @@ var RemoteHttpInterceptor = class {
2512
2501
  set baseURL(baseURL) {
2513
2502
  this.client.baseURL = new URL(baseURL);
2514
2503
  }
2515
- get saveRequests() {
2516
- return this.client.saveRequests;
2504
+ get requestSaving() {
2505
+ return this.client.requestSaving;
2517
2506
  }
2518
- set saveRequests(saveRequests) {
2519
- this.client.saveRequests = saveRequests;
2507
+ set requestSaving(requestSaving) {
2508
+ this.client.requestSaving = requestSaving;
2520
2509
  }
2521
2510
  get onUnhandledRequest() {
2522
2511
  return this.client.onUnhandledRequest;
@@ -2604,55 +2593,6 @@ function createHttpInterceptor(options) {
2604
2593
  throw new UnknownHttpInterceptorTypeError_default(type);
2605
2594
  }
2606
2595
  __name(createHttpInterceptor, "createHttpInterceptor");
2607
-
2608
- // src/http/namespace/HttpInterceptorNamespace.ts
2609
- var HttpInterceptorNamespaceDefault = class {
2610
- static {
2611
- __name(this, "HttpInterceptorNamespaceDefault");
2612
- }
2613
- local;
2614
- remote;
2615
- constructor() {
2616
- const workerStore = new HttpInterceptorWorkerStore_default();
2617
- this.local = {
2618
- get onUnhandledRequest() {
2619
- return workerStore.defaultOnUnhandledRequest("local");
2620
- },
2621
- set onUnhandledRequest(strategy) {
2622
- workerStore.setDefaultOnUnhandledRequest("local", strategy);
2623
- }
2624
- };
2625
- this.remote = {
2626
- get onUnhandledRequest() {
2627
- return workerStore.defaultOnUnhandledRequest("remote");
2628
- },
2629
- set onUnhandledRequest(strategy) {
2630
- workerStore.setDefaultOnUnhandledRequest("remote", strategy);
2631
- }
2632
- };
2633
- }
2634
- };
2635
- var HttpInterceptorNamespace = class {
2636
- static {
2637
- __name(this, "HttpInterceptorNamespace");
2638
- }
2639
- /**
2640
- * Creates an HTTP interceptor.
2641
- *
2642
- * @param options The options for the interceptor.
2643
- * @returns The created HTTP interceptor.
2644
- * @throws {InvalidURLError} If the base URL is invalid.
2645
- * @throws {UnsupportedURLProtocolError} If the base URL protocol is not either `http` or `https`.
2646
- * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐interceptor‐http#httpinterceptorcreateoptions `httpInterceptor.create(options)` API reference}
2647
- */
2648
- create = createHttpInterceptor;
2649
- /** Default HTTP interceptor settings. */
2650
- default = Object.freeze(new HttpInterceptorNamespaceDefault());
2651
- };
2652
- var HttpInterceptorNamespace_default = HttpInterceptorNamespace;
2653
-
2654
- // src/http/index.ts
2655
- var httpInterceptor = Object.freeze(new HttpInterceptorNamespace_default());
2656
2596
  /* istanbul ignore else -- @preserve */
2657
2597
  /* istanbul ignore next -- @preserve
2658
2598
  * Ignoring because checking unknown platforms is not configured in our test setup. */
@@ -2668,6 +2608,6 @@ var httpInterceptor = Object.freeze(new HttpInterceptorNamespace_default());
2668
2608
  * Reply listeners are always present when notified in normal conditions. If they were not present, the request
2669
2609
  * would reach a timeout and not be responded. The empty set serves as a fallback. */
2670
2610
 
2671
- export { DisabledRequestSavingError_default as DisabledRequestSavingError, InvalidFormDataError_default as InvalidFormDataError, InvalidJSONError_default as InvalidJSONError, NotRunningHttpInterceptorError_default as NotRunningHttpInterceptorError, RunningHttpInterceptorError_default as RunningHttpInterceptorError, TimesCheckError_default as TimesCheckError, UnknownHttpInterceptorPlatformError_default as UnknownHttpInterceptorPlatformError, UnknownHttpInterceptorTypeError_default as UnknownHttpInterceptorTypeError, UnregisteredBrowserServiceWorkerError_default as UnregisteredBrowserServiceWorkerError, httpInterceptor };
2611
+ export { DisabledRequestSavingError_default as DisabledRequestSavingError, InvalidFormDataError_default as InvalidFormDataError, InvalidJSONError_default as InvalidJSONError, NotRunningHttpInterceptorError_default as NotRunningHttpInterceptorError, RequestSavingSafeLimitExceededError_default as RequestSavingSafeLimitExceededError, RunningHttpInterceptorError_default as RunningHttpInterceptorError, TimesCheckError_default as TimesCheckError, UnknownHttpInterceptorPlatformError_default as UnknownHttpInterceptorPlatformError, UnknownHttpInterceptorTypeError_default as UnknownHttpInterceptorTypeError, UnregisteredBrowserServiceWorkerError_default as UnregisteredBrowserServiceWorkerError, createHttpInterceptor };
2672
2612
  //# sourceMappingURL=http.mjs.map
2673
2613
  //# sourceMappingURL=http.mjs.map