msw 0.40.1 → 0.41.1

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 (119) hide show
  1. package/config/constants.js +1 -3
  2. package/config/scripts/postinstall.js +32 -25
  3. package/lib/esm/index.js +1967 -1587
  4. package/lib/esm/index.js.map +1 -0
  5. package/lib/glossary-eda04a15.d.ts +331 -0
  6. package/lib/iife/index.js +9773 -21
  7. package/lib/iife/index.js.map +1 -0
  8. package/lib/index.d.ts +353 -0
  9. package/lib/index.js +2125 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/{esm/mockServiceWorker.js → mockServiceWorker.js} +1 -1
  12. package/lib/native/index.d.ts +9 -0
  13. package/lib/native/index.js +1532 -0
  14. package/lib/native/index.mjs +1532 -0
  15. package/lib/node/index.d.ts +15 -0
  16. package/lib/node/index.js +1601 -0
  17. package/lib/node/index.js.map +1 -0
  18. package/lib/node/index.mjs +1601 -0
  19. package/lib/node/index.mjs.map +1 -0
  20. package/native/package.json +3 -2
  21. package/node/package.json +3 -2
  22. package/package.json +13 -22
  23. package/lib/esm/errors-deps.js +0 -74
  24. package/lib/esm/fetch-deps.js +0 -1005
  25. package/lib/esm/graphql-deps.js +0 -3545
  26. package/lib/esm/graphql.js +0 -5
  27. package/lib/esm/index-deps.js +0 -21
  28. package/lib/esm/index2.js +0 -3
  29. package/lib/esm/matchRequestUrl-deps.js +0 -992
  30. package/lib/esm/rest-deps.js +0 -103
  31. package/lib/esm/rest.js +0 -5
  32. package/lib/esm/xml-deps.js +0 -44
  33. package/lib/iife/mockServiceWorker.js +0 -338
  34. package/lib/types/context/body.d.ts +0 -9
  35. package/lib/types/context/cookie.d.ts +0 -7
  36. package/lib/types/context/data.d.ts +0 -8
  37. package/lib/types/context/delay.d.ts +0 -15
  38. package/lib/types/context/errors.d.ts +0 -8
  39. package/lib/types/context/extensions.d.ts +0 -8
  40. package/lib/types/context/fetch.d.ts +0 -9
  41. package/lib/types/context/index.d.ts +0 -12
  42. package/lib/types/context/json.d.ts +0 -12
  43. package/lib/types/context/set.d.ts +0 -18
  44. package/lib/types/context/status.d.ts +0 -9
  45. package/lib/types/context/text.d.ts +0 -8
  46. package/lib/types/context/xml.d.ts +0 -9
  47. package/lib/types/graphql.d.ts +0 -74
  48. package/lib/types/handlers/GraphQLHandler.d.ts +0 -39
  49. package/lib/types/handlers/RequestHandler.d.ts +0 -103
  50. package/lib/types/handlers/RestHandler.d.ts +0 -47
  51. package/lib/types/index.d.ts +0 -26
  52. package/lib/types/native/index.d.ts +0 -1
  53. package/lib/types/node/createSetupServer.d.ts +0 -8
  54. package/lib/types/node/glossary.d.ts +0 -38
  55. package/lib/types/node/index.d.ts +0 -2
  56. package/lib/types/node/setupServer.d.ts +0 -6
  57. package/lib/types/response.d.ts +0 -35
  58. package/lib/types/rest.d.ts +0 -13
  59. package/lib/types/setupWorker/glossary.d.ts +0 -161
  60. package/lib/types/setupWorker/setupWorker.d.ts +0 -9
  61. package/lib/types/setupWorker/start/createFallbackStart.d.ts +0 -2
  62. package/lib/types/setupWorker/start/createStartHandler.d.ts +0 -2
  63. package/lib/types/setupWorker/start/utils/enableMocking.d.ts +0 -5
  64. package/lib/types/setupWorker/start/utils/getWorkerByRegistration.d.ts +0 -6
  65. package/lib/types/setupWorker/start/utils/getWorkerInstance.d.ts +0 -6
  66. package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +0 -9
  67. package/lib/types/setupWorker/start/utils/printStartMessage.d.ts +0 -10
  68. package/lib/types/setupWorker/start/utils/validateWorkerScope.d.ts +0 -2
  69. package/lib/types/setupWorker/stop/createFallbackStop.d.ts +0 -2
  70. package/lib/types/setupWorker/stop/createStop.d.ts +0 -2
  71. package/lib/types/setupWorker/stop/utils/printStopMessage.d.ts +0 -3
  72. package/lib/types/sharedOptions.d.ts +0 -24
  73. package/lib/types/typeUtils.d.ts +0 -7
  74. package/lib/types/utils/NetworkError.d.ts +0 -3
  75. package/lib/types/utils/createBroadcastChannel.d.ts +0 -18
  76. package/lib/types/utils/deferNetworkRequestsUntil.d.ts +0 -6
  77. package/lib/types/utils/getResponse.d.ts +0 -15
  78. package/lib/types/utils/handleRequest.d.ts +0 -34
  79. package/lib/types/utils/internal/compose.d.ts +0 -14
  80. package/lib/types/utils/internal/devUtils.d.ts +0 -18
  81. package/lib/types/utils/internal/getCallFrame.d.ts +0 -4
  82. package/lib/types/utils/internal/isIterable.d.ts +0 -4
  83. package/lib/types/utils/internal/isObject.d.ts +0 -4
  84. package/lib/types/utils/internal/isStringEqual.d.ts +0 -4
  85. package/lib/types/utils/internal/jsonParse.d.ts +0 -5
  86. package/lib/types/utils/internal/mergeRight.d.ts +0 -5
  87. package/lib/types/utils/internal/parseGraphQLRequest.d.ts +0 -23
  88. package/lib/types/utils/internal/parseMultipartData.d.ts +0 -6
  89. package/lib/types/utils/internal/pipeEvents.d.ts +0 -6
  90. package/lib/types/utils/internal/requestHandlerUtils.d.ts +0 -4
  91. package/lib/types/utils/internal/requestIntegrityCheck.d.ts +0 -2
  92. package/lib/types/utils/internal/tryCatch.d.ts +0 -1
  93. package/lib/types/utils/internal/uuidv4.d.ts +0 -1
  94. package/lib/types/utils/logging/getStatusCodeColor.d.ts +0 -9
  95. package/lib/types/utils/logging/getTimestamp.d.ts +0 -4
  96. package/lib/types/utils/logging/prepareRequest.d.ts +0 -23
  97. package/lib/types/utils/logging/prepareResponse.d.ts +0 -10
  98. package/lib/types/utils/matching/matchRequestUrl.d.ts +0 -17
  99. package/lib/types/utils/matching/normalizePath.d.ts +0 -9
  100. package/lib/types/utils/request/getPublicUrlFromRequest.d.ts +0 -6
  101. package/lib/types/utils/request/getRequestCookies.d.ts +0 -7
  102. package/lib/types/utils/request/onUnhandledRequest.d.ts +0 -8
  103. package/lib/types/utils/request/parseBody.d.ts +0 -5
  104. package/lib/types/utils/request/parseIsomorphicRequest.d.ts +0 -6
  105. package/lib/types/utils/request/parseWorkerRequest.d.ts +0 -7
  106. package/lib/types/utils/request/pruneGetRequestBody.d.ts +0 -7
  107. package/lib/types/utils/request/readResponseCookies.d.ts +0 -3
  108. package/lib/types/utils/request/setRequestCookies.d.ts +0 -9
  109. package/lib/types/utils/url/cleanUrl.d.ts +0 -5
  110. package/lib/types/utils/url/getAbsoluteUrl.d.ts +0 -4
  111. package/lib/types/utils/url/getAbsoluteWorkerUrl.d.ts +0 -5
  112. package/lib/types/utils/url/isAbsoluteUrl.d.ts +0 -4
  113. package/lib/types/utils/worker/createFallbackRequestListener.d.ts +0 -4
  114. package/lib/types/utils/worker/createRequestListener.d.ts +0 -4
  115. package/lib/types/utils/worker/createResponseListener.d.ts +0 -3
  116. package/lib/umd/index.js +0 -31615
  117. package/lib/umd/mockServiceWorker.js +0 -338
  118. package/native/lib/index.js +0 -6384
  119. package/node/lib/index.js +0 -8276
@@ -0,0 +1,1532 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
25
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
26
+ }) : x)(function(x) {
27
+ if (typeof require !== "undefined")
28
+ return require.apply(this, arguments);
29
+ throw new Error('Dynamic require of "' + x + '" is not supported');
30
+ });
31
+ var __objRest = (source, exclude) => {
32
+ var target = {};
33
+ for (var prop in source)
34
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
35
+ target[prop] = source[prop];
36
+ if (source != null && __getOwnPropSymbols)
37
+ for (var prop of __getOwnPropSymbols(source)) {
38
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
39
+ target[prop] = source[prop];
40
+ }
41
+ return target;
42
+ };
43
+ var __esm = (fn, res) => function __init() {
44
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
45
+ };
46
+ var __commonJS = (cb, mod) => function __require2() {
47
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
48
+ };
49
+ var __copyProps = (to, from, except, desc) => {
50
+ if (from && typeof from === "object" || typeof from === "function") {
51
+ for (let key of __getOwnPropNames(from))
52
+ if (!__hasOwnProp.call(to, key) && key !== except)
53
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
54
+ }
55
+ return to;
56
+ };
57
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
58
+
59
+ // node_modules/tsup/assets/esm_shims.js
60
+ var init_esm_shims = __esm({
61
+ "node_modules/tsup/assets/esm_shims.js"() {
62
+ }
63
+ });
64
+
65
+ // node_modules/outvariant/lib/format.js
66
+ var require_format = __commonJS({
67
+ "node_modules/outvariant/lib/format.js"(exports) {
68
+ "use strict";
69
+ init_esm_shims();
70
+ Object.defineProperty(exports, "__esModule", { value: true });
71
+ exports.format = void 0;
72
+ var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
73
+ function serializePositional(positional, flag) {
74
+ switch (flag) {
75
+ case "s":
76
+ return positional;
77
+ case "d":
78
+ case "i":
79
+ return Number(positional);
80
+ case "j":
81
+ return JSON.stringify(positional);
82
+ case "o": {
83
+ if (typeof positional === "string") {
84
+ return positional;
85
+ }
86
+ var json2 = JSON.stringify(positional);
87
+ if (json2 === "{}" || json2 === "[]" || /^\[object .+?\]$/.test(json2)) {
88
+ return positional;
89
+ }
90
+ return json2;
91
+ }
92
+ }
93
+ }
94
+ function format2(message) {
95
+ var positionals = [];
96
+ for (var _i = 1; _i < arguments.length; _i++) {
97
+ positionals[_i - 1] = arguments[_i];
98
+ }
99
+ if (positionals.length === 0) {
100
+ return message;
101
+ }
102
+ var positionalIndex = 0;
103
+ var formattedMessage = message.replace(POSITIONALS_EXP, function(match2, isEscaped, _, flag) {
104
+ var positional = positionals[positionalIndex];
105
+ var value = serializePositional(positional, flag);
106
+ if (!isEscaped) {
107
+ positionalIndex++;
108
+ return value;
109
+ }
110
+ return match2;
111
+ });
112
+ if (positionalIndex < positionals.length) {
113
+ formattedMessage += " " + positionals.slice(positionalIndex).join(" ");
114
+ }
115
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
116
+ return formattedMessage;
117
+ }
118
+ exports.format = format2;
119
+ }
120
+ });
121
+
122
+ // node_modules/outvariant/lib/invariant.js
123
+ var require_invariant = __commonJS({
124
+ "node_modules/outvariant/lib/invariant.js"(exports) {
125
+ "use strict";
126
+ init_esm_shims();
127
+ var __extends = exports && exports.__extends || function() {
128
+ var extendStatics = function(d, b) {
129
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
130
+ d2.__proto__ = b2;
131
+ } || function(d2, b2) {
132
+ for (var p in b2)
133
+ if (Object.prototype.hasOwnProperty.call(b2, p))
134
+ d2[p] = b2[p];
135
+ };
136
+ return extendStatics(d, b);
137
+ };
138
+ return function(d, b) {
139
+ if (typeof b !== "function" && b !== null)
140
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
141
+ extendStatics(d, b);
142
+ function __() {
143
+ this.constructor = d;
144
+ }
145
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
146
+ };
147
+ }();
148
+ var __spreadArray = exports && exports.__spreadArray || function(to, from) {
149
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
150
+ to[j] = from[i];
151
+ return to;
152
+ };
153
+ Object.defineProperty(exports, "__esModule", { value: true });
154
+ exports.invariant = exports.InvariantError = void 0;
155
+ var format_1 = require_format();
156
+ var STACK_FRAMES_TO_IGNORE = 2;
157
+ var InvariantError = function(_super) {
158
+ __extends(InvariantError2, _super);
159
+ function InvariantError2(message) {
160
+ var positionals = [];
161
+ for (var _i = 1; _i < arguments.length; _i++) {
162
+ positionals[_i - 1] = arguments[_i];
163
+ }
164
+ var _this = _super.call(this, message) || this;
165
+ _this.name = "Invariant Violation";
166
+ _this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
167
+ if (_this.stack) {
168
+ var nextStack = _this.stack.split("\n");
169
+ nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
170
+ _this.stack = nextStack.join("\n");
171
+ }
172
+ return _this;
173
+ }
174
+ return InvariantError2;
175
+ }(Error);
176
+ exports.InvariantError = InvariantError;
177
+ function invariant(predicate, message) {
178
+ var positionals = [];
179
+ for (var _i = 2; _i < arguments.length; _i++) {
180
+ positionals[_i - 2] = arguments[_i];
181
+ }
182
+ if (!predicate) {
183
+ throw new (InvariantError.bind.apply(InvariantError, __spreadArray([void 0, message], positionals)))();
184
+ }
185
+ }
186
+ exports.invariant = invariant;
187
+ }
188
+ });
189
+
190
+ // node_modules/outvariant/lib/index.js
191
+ var require_lib = __commonJS({
192
+ "node_modules/outvariant/lib/index.js"(exports) {
193
+ "use strict";
194
+ init_esm_shims();
195
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
196
+ if (k2 === void 0)
197
+ k2 = k;
198
+ Object.defineProperty(o, k2, { enumerable: true, get: function() {
199
+ return m[k];
200
+ } });
201
+ } : function(o, m, k, k2) {
202
+ if (k2 === void 0)
203
+ k2 = k;
204
+ o[k2] = m[k];
205
+ });
206
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
207
+ for (var p in m)
208
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
209
+ __createBinding(exports2, m, p);
210
+ };
211
+ Object.defineProperty(exports, "__esModule", { value: true });
212
+ __exportStar(require_invariant(), exports);
213
+ __exportStar(require_format(), exports);
214
+ }
215
+ });
216
+
217
+ // src/native/index.ts
218
+ init_esm_shims();
219
+ import { interceptXMLHttpRequest } from "@mswjs/interceptors/lib/interceptors/XMLHttpRequest";
220
+
221
+ // src/node/createSetupServer.ts
222
+ init_esm_shims();
223
+ import { bold } from "chalk";
224
+ import { isNodeProcess as isNodeProcess3 } from "is-node-process";
225
+ import { StrictEventEmitter } from "strict-event-emitter";
226
+ import {
227
+ createInterceptor
228
+ } from "@mswjs/interceptors";
229
+
230
+ // src/utils/internal/requestHandlerUtils.ts
231
+ init_esm_shims();
232
+ function use(currentHandlers, ...handlers) {
233
+ currentHandlers.unshift(...handlers);
234
+ }
235
+ function restoreHandlers(handlers) {
236
+ handlers.forEach((handler) => {
237
+ handler.markAsSkipped(false);
238
+ });
239
+ }
240
+ function resetHandlers(initialHandlers, ...nextHandlers) {
241
+ return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
242
+ }
243
+
244
+ // src/utils/request/parseIsomorphicRequest.ts
245
+ init_esm_shims();
246
+
247
+ // src/handlers/RequestHandler.ts
248
+ init_esm_shims();
249
+ import { Headers as Headers3 } from "headers-polyfill";
250
+
251
+ // src/response.ts
252
+ init_esm_shims();
253
+ import { Headers } from "headers-polyfill";
254
+
255
+ // src/utils/internal/compose.ts
256
+ init_esm_shims();
257
+ function compose(...fns) {
258
+ return (...args) => {
259
+ return fns.reduceRight((leftFn, rightFn) => {
260
+ return leftFn instanceof Promise ? Promise.resolve(leftFn).then(rightFn) : rightFn(leftFn);
261
+ }, args[0]);
262
+ };
263
+ }
264
+
265
+ // src/utils/NetworkError.ts
266
+ init_esm_shims();
267
+ var NetworkError = class extends Error {
268
+ constructor(message) {
269
+ super(message);
270
+ this.name = "NetworkError";
271
+ }
272
+ };
273
+
274
+ // src/response.ts
275
+ var defaultResponse = {
276
+ status: 200,
277
+ statusText: "OK",
278
+ body: null,
279
+ delay: 0,
280
+ once: false,
281
+ passthrough: false
282
+ };
283
+ var defaultResponseTransformers = [];
284
+ function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {
285
+ return async (...transformers) => {
286
+ const initialResponse = Object.assign({}, defaultResponse, {
287
+ headers: new Headers({
288
+ "x-powered-by": "msw"
289
+ })
290
+ }, responseOverrides);
291
+ const resolvedTransformers = [
292
+ ...defaultTransformers,
293
+ ...transformers
294
+ ].filter(Boolean);
295
+ const resolvedResponse = resolvedTransformers.length > 0 ? compose(...resolvedTransformers)(initialResponse) : initialResponse;
296
+ return resolvedResponse;
297
+ };
298
+ }
299
+ var response = Object.assign(createResponseComposition(), {
300
+ once: createResponseComposition({ once: true }),
301
+ networkError(message) {
302
+ throw new NetworkError(message);
303
+ }
304
+ });
305
+
306
+ // src/utils/internal/getCallFrame.ts
307
+ init_esm_shims();
308
+ var SOURCE_FRAME = /\/msw\/src\/(.+)/;
309
+ var BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](umd|esm|iief|cjs)[\/\\]|^[^\/\\]*$/;
310
+ function getCallFrame(error2) {
311
+ const stack = error2.stack;
312
+ if (!stack) {
313
+ return;
314
+ }
315
+ const frames = stack.split("\n").slice(1);
316
+ const declarationFrame = frames.find((frame) => {
317
+ return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame));
318
+ });
319
+ if (!declarationFrame) {
320
+ return;
321
+ }
322
+ const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, "");
323
+ return declarationPath;
324
+ }
325
+
326
+ // src/utils/internal/isIterable.ts
327
+ init_esm_shims();
328
+ function isIterable(fn) {
329
+ if (!fn) {
330
+ return false;
331
+ }
332
+ return typeof fn[Symbol.iterator] == "function";
333
+ }
334
+
335
+ // src/context/status.ts
336
+ init_esm_shims();
337
+ import statuses from "statuses/codes.json";
338
+ var status = (statusCode, statusText) => {
339
+ return (res) => {
340
+ res.status = statusCode;
341
+ res.statusText = statusText || statuses[String(statusCode)];
342
+ return res;
343
+ };
344
+ };
345
+
346
+ // src/context/set.ts
347
+ init_esm_shims();
348
+ import { objectToHeaders } from "headers-polyfill";
349
+ function set(...args) {
350
+ return (res) => {
351
+ const [name, value] = args;
352
+ if (typeof name === "string") {
353
+ res.headers.append(name, value);
354
+ } else {
355
+ const headers = objectToHeaders(name);
356
+ headers.forEach((value2, name2) => {
357
+ res.headers.append(name2, value2);
358
+ });
359
+ }
360
+ return res;
361
+ };
362
+ }
363
+
364
+ // src/context/delay.ts
365
+ init_esm_shims();
366
+ import { isNodeProcess } from "is-node-process";
367
+ var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
368
+ var MIN_SERVER_RESPONSE_TIME = 100;
369
+ var MAX_SERVER_RESPONSE_TIME = 400;
370
+ var NODE_SERVER_RESPONSE_TIME = 5;
371
+ var getRandomServerResponseTime = () => {
372
+ if (isNodeProcess()) {
373
+ return NODE_SERVER_RESPONSE_TIME;
374
+ }
375
+ return Math.floor(Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME);
376
+ };
377
+ var delay = (durationOrMode) => {
378
+ return (res) => {
379
+ let delayTime;
380
+ if (typeof durationOrMode === "string") {
381
+ switch (durationOrMode) {
382
+ case "infinite": {
383
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
384
+ break;
385
+ }
386
+ case "real": {
387
+ delayTime = getRandomServerResponseTime();
388
+ break;
389
+ }
390
+ default: {
391
+ throw new Error(`Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number to "ctx.delay".`);
392
+ }
393
+ }
394
+ } else if (typeof durationOrMode === "undefined") {
395
+ delayTime = getRandomServerResponseTime();
396
+ } else {
397
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
398
+ throw new Error(`Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`);
399
+ }
400
+ delayTime = durationOrMode;
401
+ }
402
+ res.delay = delayTime;
403
+ return res;
404
+ };
405
+ };
406
+
407
+ // src/context/fetch.ts
408
+ init_esm_shims();
409
+ import { isNodeProcess as isNodeProcess2 } from "is-node-process";
410
+ import { Headers as Headers2 } from "headers-polyfill";
411
+ var useFetch = isNodeProcess2() ? __require("node-fetch") : window.fetch;
412
+ var augmentRequestInit = (requestInit) => {
413
+ const headers = new Headers2(requestInit.headers);
414
+ headers.set("x-msw-bypass", "true");
415
+ return __spreadProps(__spreadValues({}, requestInit), {
416
+ headers: headers.all()
417
+ });
418
+ };
419
+ var createFetchRequestParameters = (input) => {
420
+ const { body: body2, method } = input;
421
+ const requestParameters = __spreadProps(__spreadValues({}, input), {
422
+ body: void 0
423
+ });
424
+ if (["GET", "HEAD"].includes(method)) {
425
+ return requestParameters;
426
+ }
427
+ if (typeof body2 === "object" || typeof body2 === "number" || typeof body2 === "boolean") {
428
+ requestParameters.body = JSON.stringify(body2);
429
+ } else {
430
+ requestParameters.body = body2;
431
+ }
432
+ return requestParameters;
433
+ };
434
+ var fetch = (input, requestInit = {}) => {
435
+ if (typeof input === "string") {
436
+ return useFetch(input, augmentRequestInit(requestInit));
437
+ }
438
+ const requestParameters = createFetchRequestParameters(input);
439
+ const derivedRequestInit = augmentRequestInit(requestParameters);
440
+ return useFetch(input.url.href, derivedRequestInit);
441
+ };
442
+
443
+ // src/handlers/RequestHandler.ts
444
+ var defaultContext = {
445
+ status,
446
+ set,
447
+ delay,
448
+ fetch
449
+ };
450
+ var RequestHandler = class {
451
+ constructor(options) {
452
+ this.shouldSkip = false;
453
+ this.ctx = options.ctx || defaultContext;
454
+ this.resolver = options.resolver;
455
+ const callFrame = getCallFrame(new Error());
456
+ this.info = __spreadProps(__spreadValues({}, options.info), {
457
+ callFrame
458
+ });
459
+ }
460
+ parse(_request, _resolutionContext) {
461
+ return null;
462
+ }
463
+ test(request, resolutionContext) {
464
+ return this.predicate(request, this.parse(request, resolutionContext), resolutionContext);
465
+ }
466
+ getPublicRequest(request, _parsedResult) {
467
+ return request;
468
+ }
469
+ markAsSkipped(shouldSkip = true) {
470
+ this.shouldSkip = shouldSkip;
471
+ }
472
+ async run(request, resolutionContext) {
473
+ if (this.shouldSkip) {
474
+ return null;
475
+ }
476
+ const parsedResult = this.parse(request, resolutionContext);
477
+ const shouldIntercept = this.predicate(request, parsedResult, resolutionContext);
478
+ if (!shouldIntercept) {
479
+ return null;
480
+ }
481
+ const publicRequest = this.getPublicRequest(request, parsedResult);
482
+ const executeResolver = this.wrapResolver(this.resolver);
483
+ const mockedResponse = await executeResolver(publicRequest, response, this.ctx);
484
+ return this.createExecutionResult(parsedResult, publicRequest, mockedResponse);
485
+ }
486
+ wrapResolver(resolver) {
487
+ return async (req, res, ctx) => {
488
+ const result = this.resolverGenerator || await resolver(req, res, ctx);
489
+ if (isIterable(result)) {
490
+ const { value, done } = result[Symbol.iterator]().next();
491
+ const nextResponse = await value;
492
+ if (!nextResponse && done) {
493
+ return this.resolverGeneratorResult;
494
+ }
495
+ if (!this.resolverGenerator) {
496
+ this.resolverGenerator = result;
497
+ }
498
+ this.resolverGeneratorResult = nextResponse;
499
+ return nextResponse;
500
+ }
501
+ return result;
502
+ };
503
+ }
504
+ createExecutionResult(parsedResult, request, response2) {
505
+ return {
506
+ handler: this,
507
+ parsedResult: parsedResult || null,
508
+ request,
509
+ response: response2 || null
510
+ };
511
+ }
512
+ };
513
+ function passthrough() {
514
+ return {
515
+ status: 101,
516
+ statusText: "Continue",
517
+ headers: new Headers3(),
518
+ body: null,
519
+ passthrough: true,
520
+ once: false
521
+ };
522
+ }
523
+
524
+ // src/utils/request/parseBody.ts
525
+ init_esm_shims();
526
+
527
+ // src/utils/internal/jsonParse.ts
528
+ init_esm_shims();
529
+ function jsonParse(value) {
530
+ try {
531
+ return JSON.parse(value);
532
+ } catch (error2) {
533
+ return void 0;
534
+ }
535
+ }
536
+
537
+ // src/utils/internal/parseMultipartData.ts
538
+ init_esm_shims();
539
+ import { stringToHeaders } from "headers-polyfill";
540
+ function parseContentHeaders(headersString) {
541
+ var _a, _b;
542
+ const headers = stringToHeaders(headersString);
543
+ const contentType = headers.get("content-type") || "text/plain";
544
+ const disposition = headers.get("content-disposition");
545
+ if (!disposition) {
546
+ throw new Error('"Content-Disposition" header is required.');
547
+ }
548
+ const directives = disposition.split(";").reduce((acc, chunk) => {
549
+ const [name2, ...rest] = chunk.trim().split("=");
550
+ acc[name2] = rest.join("=");
551
+ return acc;
552
+ }, {});
553
+ const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
554
+ const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
555
+ return {
556
+ name,
557
+ filename,
558
+ contentType
559
+ };
560
+ }
561
+ function parseMultipartData(data2, headers) {
562
+ const contentType = headers == null ? void 0 : headers.get("content-type");
563
+ if (!contentType) {
564
+ return void 0;
565
+ }
566
+ const [, ...directives] = contentType.split(/; */);
567
+ const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
568
+ if (!boundary) {
569
+ return void 0;
570
+ }
571
+ const boundaryRegExp = new RegExp(`--+${boundary}`);
572
+ const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
573
+ if (!fields.length) {
574
+ return void 0;
575
+ }
576
+ const parsedBody = {};
577
+ try {
578
+ for (const field of fields) {
579
+ const [contentHeaders, ...rest] = field.split("\r\n\r\n");
580
+ const contentBody = rest.join("\r\n\r\n");
581
+ const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
582
+ const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
583
+ const parsedValue = parsedBody[name];
584
+ if (parsedValue === void 0) {
585
+ parsedBody[name] = value;
586
+ } else if (Array.isArray(parsedValue)) {
587
+ parsedBody[name] = [...parsedValue, value];
588
+ } else {
589
+ parsedBody[name] = [parsedValue, value];
590
+ }
591
+ }
592
+ return parsedBody;
593
+ } catch (error2) {
594
+ return void 0;
595
+ }
596
+ }
597
+
598
+ // src/utils/request/parseBody.ts
599
+ function parseBody(body2, headers) {
600
+ var _a;
601
+ if (!body2) {
602
+ return body2;
603
+ }
604
+ const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
605
+ const hasMultipartContent = contentType.startsWith("multipart/form-data");
606
+ if (hasMultipartContent && typeof body2 !== "object") {
607
+ return parseMultipartData(body2.toString(), headers) || body2;
608
+ }
609
+ const hasJsonContent = contentType.includes("json");
610
+ if (hasJsonContent && typeof body2 !== "object") {
611
+ return jsonParse(body2.toString()) || body2;
612
+ }
613
+ return body2;
614
+ }
615
+
616
+ // src/utils/request/setRequestCookies.ts
617
+ init_esm_shims();
618
+ import * as cookieUtils2 from "cookie";
619
+ import { store } from "@mswjs/cookies";
620
+
621
+ // src/utils/request/getRequestCookies.ts
622
+ init_esm_shims();
623
+ import * as cookieUtils from "cookie";
624
+ function getAllCookies() {
625
+ return cookieUtils.parse(document.cookie);
626
+ }
627
+ function getRequestCookies(request) {
628
+ if (typeof document === "undefined" || typeof location === "undefined") {
629
+ return {};
630
+ }
631
+ switch (request.credentials) {
632
+ case "same-origin": {
633
+ return location.origin === request.url.origin ? getAllCookies() : {};
634
+ }
635
+ case "include": {
636
+ return getAllCookies();
637
+ }
638
+ default: {
639
+ return {};
640
+ }
641
+ }
642
+ }
643
+
644
+ // src/utils/request/setRequestCookies.ts
645
+ function setRequestCookies(request) {
646
+ var _a;
647
+ const requestCookiesString = request.headers.get("cookie");
648
+ store.hydrate();
649
+ const cookiesFromStore = Array.from((_a = store.get(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
650
+ return Object.assign(cookies, { [name.trim()]: value });
651
+ }, {});
652
+ const cookiesFromDocument = getRequestCookies(request);
653
+ const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
654
+ for (const [name, value] of Object.entries(forwardedCookies)) {
655
+ request.headers.append("cookie", `${name}=${value}`);
656
+ }
657
+ const ownCookies = requestCookiesString ? cookieUtils2.parse(requestCookiesString) : {};
658
+ request.cookies = __spreadValues(__spreadValues(__spreadValues({}, request.cookies), forwardedCookies), ownCookies);
659
+ }
660
+
661
+ // src/utils/request/parseIsomorphicRequest.ts
662
+ function parseIsomorphicRequest(request) {
663
+ const mockedRequest = {
664
+ id: request.id,
665
+ url: request.url,
666
+ method: request.method,
667
+ body: parseBody(request.body, request.headers),
668
+ credentials: request.credentials || "same-origin",
669
+ headers: request.headers,
670
+ cookies: {},
671
+ redirect: "manual",
672
+ referrer: "",
673
+ keepalive: false,
674
+ cache: "default",
675
+ mode: "cors",
676
+ referrerPolicy: "no-referrer",
677
+ integrity: "",
678
+ destination: "document",
679
+ bodyUsed: false,
680
+ passthrough
681
+ };
682
+ setRequestCookies(mockedRequest);
683
+ return mockedRequest;
684
+ }
685
+
686
+ // src/utils/handleRequest.ts
687
+ init_esm_shims();
688
+ import { until } from "@open-draft/until";
689
+
690
+ // src/utils/getResponse.ts
691
+ init_esm_shims();
692
+ var getResponse = async (request, handlers, resolutionContext) => {
693
+ const relevantHandlers = handlers.filter((handler) => {
694
+ return handler.test(request, resolutionContext);
695
+ });
696
+ if (relevantHandlers.length === 0) {
697
+ return {
698
+ handler: void 0,
699
+ response: void 0
700
+ };
701
+ }
702
+ const result = await relevantHandlers.reduce(async (executionResult, handler) => {
703
+ const previousResults = await executionResult;
704
+ if (!!(previousResults == null ? void 0 : previousResults.response)) {
705
+ return executionResult;
706
+ }
707
+ const result2 = await handler.run(request, resolutionContext);
708
+ if (result2 === null || result2.handler.shouldSkip) {
709
+ return null;
710
+ }
711
+ if (!result2.response) {
712
+ return {
713
+ request: result2.request,
714
+ handler: result2.handler,
715
+ response: void 0,
716
+ parsedResult: result2.parsedResult
717
+ };
718
+ }
719
+ if (result2.response.once) {
720
+ handler.markAsSkipped(true);
721
+ }
722
+ return result2;
723
+ }, Promise.resolve(null));
724
+ if (!result) {
725
+ return {
726
+ handler: void 0,
727
+ response: void 0
728
+ };
729
+ }
730
+ return {
731
+ handler: result.handler,
732
+ publicRequest: result.request,
733
+ parsedRequest: result.parsedResult,
734
+ response: result.response
735
+ };
736
+ };
737
+
738
+ // src/utils/internal/devUtils.ts
739
+ init_esm_shims();
740
+ var import_outvariant = __toESM(require_lib());
741
+ var LIBRARY_PREFIX = "[MSW]";
742
+ function formatMessage(message, ...positionals) {
743
+ const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
744
+ return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
745
+ }
746
+ function warn(message, ...positionals) {
747
+ console.warn(formatMessage(message, ...positionals));
748
+ }
749
+ function error(message, ...positionals) {
750
+ console.error(formatMessage(message, ...positionals));
751
+ }
752
+ var devUtils = {
753
+ formatMessage,
754
+ warn,
755
+ error
756
+ };
757
+
758
+ // src/utils/request/onUnhandledRequest.ts
759
+ init_esm_shims();
760
+ import getStringMatchScore from "js-levenshtein";
761
+
762
+ // src/utils/internal/parseGraphQLRequest.ts
763
+ init_esm_shims();
764
+ import {
765
+ parse as parse3
766
+ } from "graphql";
767
+
768
+ // src/utils/request/getPublicUrlFromRequest.ts
769
+ init_esm_shims();
770
+ var getPublicUrlFromRequest = (request) => {
771
+ return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
772
+ };
773
+
774
+ // src/utils/internal/parseGraphQLRequest.ts
775
+ function parseDocumentNode(node) {
776
+ var _a;
777
+ const operationDef = node.definitions.find((def) => {
778
+ return def.kind === "OperationDefinition";
779
+ });
780
+ return {
781
+ operationType: operationDef == null ? void 0 : operationDef.operation,
782
+ operationName: (_a = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a.value
783
+ };
784
+ }
785
+ function parseQuery(query) {
786
+ try {
787
+ const ast = parse3(query);
788
+ return parseDocumentNode(ast);
789
+ } catch (error2) {
790
+ return error2;
791
+ }
792
+ }
793
+ function extractMultipartVariables(variables, map, files) {
794
+ const operations = { variables };
795
+ for (const [key, pathArray] of Object.entries(map)) {
796
+ if (!(key in files)) {
797
+ throw new Error(`Given files do not have a key '${key}' .`);
798
+ }
799
+ for (const dotPath of pathArray) {
800
+ const [lastPath, ...reversedPaths] = dotPath.split(".").reverse();
801
+ const paths = reversedPaths.reverse();
802
+ let target = operations;
803
+ for (const path of paths) {
804
+ if (!(path in target)) {
805
+ throw new Error(`Property '${paths}' is not in operations.`);
806
+ }
807
+ target = target[path];
808
+ }
809
+ target[lastPath] = files[key];
810
+ }
811
+ }
812
+ return operations.variables;
813
+ }
814
+ function getGraphQLInput(request) {
815
+ var _a, _b;
816
+ switch (request.method) {
817
+ case "GET": {
818
+ const query = request.url.searchParams.get("query");
819
+ const variables = request.url.searchParams.get("variables") || "";
820
+ return {
821
+ query,
822
+ variables: jsonParse(variables)
823
+ };
824
+ }
825
+ case "POST": {
826
+ if ((_a = request.body) == null ? void 0 : _a.query) {
827
+ const { query, variables } = request.body;
828
+ return {
829
+ query,
830
+ variables
831
+ };
832
+ }
833
+ if ((_b = request.body) == null ? void 0 : _b.operations) {
834
+ const _c = request.body, { operations, map } = _c, files = __objRest(_c, ["operations", "map"]);
835
+ const parsedOperations = jsonParse(operations) || {};
836
+ if (!parsedOperations.query) {
837
+ return null;
838
+ }
839
+ const parsedMap = jsonParse(map || "") || {};
840
+ const variables = parsedOperations.variables ? extractMultipartVariables(parsedOperations.variables, parsedMap, files) : {};
841
+ return {
842
+ query: parsedOperations.query,
843
+ variables
844
+ };
845
+ }
846
+ }
847
+ default:
848
+ return null;
849
+ }
850
+ }
851
+ function parseGraphQLRequest(request) {
852
+ const input = getGraphQLInput(request);
853
+ if (!input || !input.query) {
854
+ return void 0;
855
+ }
856
+ const { query, variables } = input;
857
+ const parsedResult = parseQuery(query);
858
+ if (parsedResult instanceof Error) {
859
+ const requestPublicUrl = getPublicUrlFromRequest(request);
860
+ throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s', request.method, requestPublicUrl, parsedResult.message));
861
+ }
862
+ return {
863
+ operationType: parsedResult.operationType,
864
+ operationName: parsedResult.operationName,
865
+ variables
866
+ };
867
+ }
868
+
869
+ // src/utils/internal/isStringEqual.ts
870
+ init_esm_shims();
871
+ function isStringEqual(actual, expected) {
872
+ return actual.toLowerCase() === expected.toLowerCase();
873
+ }
874
+
875
+ // src/handlers/RestHandler.ts
876
+ init_esm_shims();
877
+
878
+ // src/context/index.ts
879
+ init_esm_shims();
880
+
881
+ // src/context/cookie.ts
882
+ init_esm_shims();
883
+ import * as cookieUtils3 from "cookie";
884
+ var cookie = (name, value, options) => {
885
+ return (res) => {
886
+ const serializedCookie = cookieUtils3.serialize(name, value, options);
887
+ res.headers.set("Set-Cookie", serializedCookie);
888
+ if (typeof document !== "undefined") {
889
+ document.cookie = serializedCookie;
890
+ }
891
+ return res;
892
+ };
893
+ };
894
+
895
+ // src/context/body.ts
896
+ init_esm_shims();
897
+ var body = (value) => {
898
+ return (res) => {
899
+ res.body = value;
900
+ return res;
901
+ };
902
+ };
903
+
904
+ // src/context/data.ts
905
+ init_esm_shims();
906
+
907
+ // src/utils/internal/mergeRight.ts
908
+ init_esm_shims();
909
+
910
+ // src/utils/internal/isObject.ts
911
+ init_esm_shims();
912
+ function isObject(value) {
913
+ return value != null && typeof value === "object" && !Array.isArray(value);
914
+ }
915
+
916
+ // src/utils/internal/mergeRight.ts
917
+ function mergeRight(left, right) {
918
+ return Object.entries(right).reduce((result, [key, rightValue]) => {
919
+ const leftValue = result[key];
920
+ if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
921
+ result[key] = leftValue.concat(rightValue);
922
+ return result;
923
+ }
924
+ if (isObject(leftValue) && isObject(rightValue)) {
925
+ result[key] = mergeRight(leftValue, rightValue);
926
+ return result;
927
+ }
928
+ result[key] = rightValue;
929
+ return result;
930
+ }, Object.assign({}, left));
931
+ }
932
+
933
+ // src/context/json.ts
934
+ init_esm_shims();
935
+ var json = (body2) => {
936
+ return (res) => {
937
+ res.headers.set("Content-Type", "application/json");
938
+ res.body = JSON.stringify(body2);
939
+ return res;
940
+ };
941
+ };
942
+
943
+ // src/context/data.ts
944
+ var data = (payload) => {
945
+ return (res) => {
946
+ const prevBody = jsonParse(res.body) || {};
947
+ const nextBody = mergeRight(prevBody, { data: payload });
948
+ return json(nextBody)(res);
949
+ };
950
+ };
951
+
952
+ // src/context/extensions.ts
953
+ init_esm_shims();
954
+ var extensions = (payload) => {
955
+ return (res) => {
956
+ const prevBody = jsonParse(res.body) || {};
957
+ const nextBody = mergeRight(prevBody, { extensions: payload });
958
+ return json(nextBody)(res);
959
+ };
960
+ };
961
+
962
+ // src/context/errors.ts
963
+ init_esm_shims();
964
+ var errors = (errorsList) => {
965
+ return (res) => {
966
+ if (errorsList == null) {
967
+ return res;
968
+ }
969
+ const prevBody = jsonParse(res.body) || {};
970
+ const nextBody = mergeRight(prevBody, { errors: errorsList });
971
+ return json(nextBody)(res);
972
+ };
973
+ };
974
+
975
+ // src/context/text.ts
976
+ init_esm_shims();
977
+ var text = (body2) => {
978
+ return (res) => {
979
+ res.headers.set("Content-Type", "text/plain");
980
+ res.body = body2;
981
+ return res;
982
+ };
983
+ };
984
+
985
+ // src/context/xml.ts
986
+ init_esm_shims();
987
+ var xml = (body2) => {
988
+ return (res) => {
989
+ res.headers.set("Content-Type", "text/xml");
990
+ res.body = body2;
991
+ return res;
992
+ };
993
+ };
994
+
995
+ // src/utils/logging/getStatusCodeColor.ts
996
+ init_esm_shims();
997
+ function getStatusCodeColor(status2) {
998
+ if (status2 < 300) {
999
+ return "#69AB32" /* Success */;
1000
+ }
1001
+ if (status2 < 400) {
1002
+ return "#F0BB4B" /* Warning */;
1003
+ }
1004
+ return "#E95F5D" /* Danger */;
1005
+ }
1006
+
1007
+ // src/utils/logging/getTimestamp.ts
1008
+ init_esm_shims();
1009
+ function getTimestamp() {
1010
+ const now = new Date();
1011
+ return [now.getHours(), now.getMinutes(), now.getSeconds()].map(String).map((chunk) => chunk.slice(0, 2)).map((chunk) => chunk.padStart(2, "0")).join(":");
1012
+ }
1013
+
1014
+ // src/utils/logging/prepareRequest.ts
1015
+ init_esm_shims();
1016
+ function prepareRequest(request) {
1017
+ return __spreadProps(__spreadValues({}, request), {
1018
+ headers: request.headers.all()
1019
+ });
1020
+ }
1021
+
1022
+ // src/utils/logging/prepareResponse.ts
1023
+ init_esm_shims();
1024
+ import { objectToHeaders as objectToHeaders2 } from "headers-polyfill";
1025
+ function prepareResponse(res) {
1026
+ const responseHeaders = objectToHeaders2(res.headers);
1027
+ return __spreadProps(__spreadValues({}, res), {
1028
+ body: parseBody(res.body, responseHeaders)
1029
+ });
1030
+ }
1031
+
1032
+ // src/utils/matching/matchRequestUrl.ts
1033
+ init_esm_shims();
1034
+ import { match } from "path-to-regexp";
1035
+ import { getCleanUrl } from "@mswjs/interceptors/lib/utils/getCleanUrl";
1036
+
1037
+ // src/utils/matching/normalizePath.ts
1038
+ init_esm_shims();
1039
+
1040
+ // src/utils/url/cleanUrl.ts
1041
+ init_esm_shims();
1042
+ var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
1043
+ function getSearchParams(path) {
1044
+ return new URL(`/${path}`, "http://localhost").searchParams;
1045
+ }
1046
+ function cleanUrl(path) {
1047
+ return path.replace(REDUNDANT_CHARACTERS_EXP, "");
1048
+ }
1049
+
1050
+ // src/utils/url/getAbsoluteUrl.ts
1051
+ init_esm_shims();
1052
+
1053
+ // src/utils/url/isAbsoluteUrl.ts
1054
+ init_esm_shims();
1055
+ function isAbsoluteUrl(url) {
1056
+ return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
1057
+ }
1058
+
1059
+ // src/utils/url/getAbsoluteUrl.ts
1060
+ function getAbsoluteUrl(path, baseUrl) {
1061
+ if (isAbsoluteUrl(path)) {
1062
+ return path;
1063
+ }
1064
+ if (path.startsWith("*")) {
1065
+ return path;
1066
+ }
1067
+ const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
1068
+ return origin ? decodeURI(new URL(encodeURI(path), origin).href) : path;
1069
+ }
1070
+
1071
+ // src/utils/matching/normalizePath.ts
1072
+ function normalizePath(path, baseUrl) {
1073
+ if (path instanceof RegExp) {
1074
+ return path;
1075
+ }
1076
+ const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
1077
+ return cleanUrl(maybeAbsoluteUrl);
1078
+ }
1079
+
1080
+ // src/utils/matching/matchRequestUrl.ts
1081
+ function coercePath(path) {
1082
+ return path.replace(/([:a-zA-Z_-]*)(\*{1,2})+/g, (_, parameterName, wildcard) => {
1083
+ const expression = "(.*)";
1084
+ if (!parameterName) {
1085
+ return expression;
1086
+ }
1087
+ return parameterName.startsWith(":") ? `${parameterName}${wildcard}` : `${parameterName}${expression}`;
1088
+ }).replace(/([^\/])(:)(?=\d+)/, "$1\\$2").replace(/^([^\/]+)(:)(?=\/\/)/, "$1\\$2");
1089
+ }
1090
+ function matchRequestUrl(url, path, baseUrl) {
1091
+ const normalizedPath = normalizePath(path, baseUrl);
1092
+ const cleanPath = typeof normalizedPath === "string" ? coercePath(normalizedPath) : normalizedPath;
1093
+ const cleanUrl2 = getCleanUrl(url);
1094
+ const result = match(cleanPath, { decode: decodeURIComponent })(cleanUrl2);
1095
+ const params = result && result.params || {};
1096
+ return {
1097
+ matches: result !== false,
1098
+ params
1099
+ };
1100
+ }
1101
+
1102
+ // src/handlers/RestHandler.ts
1103
+ var restContext = __spreadProps(__spreadValues({}, defaultContext), {
1104
+ cookie,
1105
+ body,
1106
+ text,
1107
+ json,
1108
+ xml
1109
+ });
1110
+ var RestHandler = class extends RequestHandler {
1111
+ constructor(method, path, resolver) {
1112
+ super({
1113
+ info: {
1114
+ header: `${method} ${path}`,
1115
+ path,
1116
+ method
1117
+ },
1118
+ ctx: restContext,
1119
+ resolver
1120
+ });
1121
+ this.checkRedundantQueryParameters();
1122
+ }
1123
+ checkRedundantQueryParameters() {
1124
+ const { method, path } = this.info;
1125
+ if (path instanceof RegExp) {
1126
+ return;
1127
+ }
1128
+ const url = cleanUrl(path);
1129
+ if (url === path) {
1130
+ return;
1131
+ }
1132
+ const searchParams = getSearchParams(path);
1133
+ const queryParams = [];
1134
+ searchParams.forEach((_, paramName) => {
1135
+ queryParams.push(paramName);
1136
+ });
1137
+ devUtils.warn(`Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`);
1138
+ }
1139
+ parse(request, resolutionContext) {
1140
+ return matchRequestUrl(request.url, this.info.path, resolutionContext == null ? void 0 : resolutionContext.baseUrl);
1141
+ }
1142
+ getPublicRequest(request, parsedResult) {
1143
+ return __spreadProps(__spreadValues({}, request), {
1144
+ params: parsedResult.params || {}
1145
+ });
1146
+ }
1147
+ predicate(request, parsedResult) {
1148
+ const matchesMethod = this.info.method instanceof RegExp ? this.info.method.test(request.method) : isStringEqual(this.info.method, request.method);
1149
+ return matchesMethod && parsedResult.matches;
1150
+ }
1151
+ log(request, response2) {
1152
+ const publicUrl = getPublicUrlFromRequest(request);
1153
+ const loggedRequest = prepareRequest(request);
1154
+ const loggedResponse = prepareResponse(response2);
1155
+ const statusColor = getStatusCodeColor(response2.status);
1156
+ console.groupCollapsed(devUtils.formatMessage("%s %s %s (%c%s%c)"), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response2.status} ${response2.statusText}`, "color:inherit");
1157
+ console.log("Request", loggedRequest);
1158
+ console.log("Handler:", {
1159
+ mask: this.info.path,
1160
+ resolver: this.resolver
1161
+ });
1162
+ console.log("Response", loggedResponse);
1163
+ console.groupEnd();
1164
+ }
1165
+ };
1166
+
1167
+ // src/handlers/GraphQLHandler.ts
1168
+ init_esm_shims();
1169
+
1170
+ // src/utils/internal/tryCatch.ts
1171
+ init_esm_shims();
1172
+ function tryCatch(fn, onException) {
1173
+ try {
1174
+ const result = fn();
1175
+ return result;
1176
+ } catch (error2) {
1177
+ onException == null ? void 0 : onException(error2);
1178
+ }
1179
+ }
1180
+
1181
+ // src/handlers/GraphQLHandler.ts
1182
+ var graphqlContext = __spreadProps(__spreadValues({}, defaultContext), {
1183
+ data,
1184
+ extensions,
1185
+ errors,
1186
+ cookie
1187
+ });
1188
+ function isDocumentNode(value) {
1189
+ if (value == null) {
1190
+ return false;
1191
+ }
1192
+ return typeof value === "object" && "kind" in value && "definitions" in value;
1193
+ }
1194
+ var GraphQLHandler = class extends RequestHandler {
1195
+ constructor(operationType, operationName, endpoint, resolver) {
1196
+ let resolvedOperationName = operationName;
1197
+ if (isDocumentNode(operationName)) {
1198
+ const parsedNode = parseDocumentNode(operationName);
1199
+ if (parsedNode.operationType !== operationType) {
1200
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
1201
+ }
1202
+ if (!parsedNode.operationName) {
1203
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
1204
+ }
1205
+ resolvedOperationName = parsedNode.operationName;
1206
+ }
1207
+ const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
1208
+ super({
1209
+ info: {
1210
+ header,
1211
+ operationType,
1212
+ operationName: resolvedOperationName
1213
+ },
1214
+ ctx: graphqlContext,
1215
+ resolver
1216
+ });
1217
+ this.endpoint = endpoint;
1218
+ }
1219
+ parse(request) {
1220
+ return tryCatch(() => parseGraphQLRequest(request), (error2) => console.error(error2.message));
1221
+ }
1222
+ getPublicRequest(request, parsedResult) {
1223
+ return __spreadProps(__spreadValues({}, request), {
1224
+ variables: (parsedResult == null ? void 0 : parsedResult.variables) || {}
1225
+ });
1226
+ }
1227
+ predicate(request, parsedResult) {
1228
+ if (!parsedResult) {
1229
+ return false;
1230
+ }
1231
+ if (!parsedResult.operationName && this.info.operationType !== "all") {
1232
+ const publicUrl = getPublicUrlFromRequest(request);
1233
+ devUtils.warn(`Failed to intercept a GraphQL request at "${request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
1234
+
1235
+ Consider naming this operation or using "graphql.operation" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation `);
1236
+ return false;
1237
+ }
1238
+ const hasMatchingUrl = matchRequestUrl(request.url, this.endpoint);
1239
+ const hasMatchingOperationType = this.info.operationType === "all" || parsedResult.operationType === this.info.operationType;
1240
+ const hasMatchingOperationName = this.info.operationName instanceof RegExp ? this.info.operationName.test(parsedResult.operationName || "") : parsedResult.operationName === this.info.operationName;
1241
+ return hasMatchingUrl.matches && hasMatchingOperationType && hasMatchingOperationName;
1242
+ }
1243
+ log(request, response2, handler, parsedRequest) {
1244
+ const loggedRequest = prepareRequest(request);
1245
+ const loggedResponse = prepareResponse(response2);
1246
+ const statusColor = getStatusCodeColor(response2.status);
1247
+ const requestInfo = (parsedRequest == null ? void 0 : parsedRequest.operationName) ? `${parsedRequest == null ? void 0 : parsedRequest.operationType} ${parsedRequest == null ? void 0 : parsedRequest.operationName}` : `anonymous ${parsedRequest == null ? void 0 : parsedRequest.operationType}`;
1248
+ console.groupCollapsed(devUtils.formatMessage("%s %s (%c%s%c)"), getTimestamp(), `${requestInfo}`, `color:${statusColor}`, `${response2.status} ${response2.statusText}`, "color:inherit");
1249
+ console.log("Request:", loggedRequest);
1250
+ console.log("Handler:", this);
1251
+ console.log("Response:", loggedResponse);
1252
+ console.groupEnd();
1253
+ }
1254
+ };
1255
+
1256
+ // src/utils/request/onUnhandledRequest.ts
1257
+ var MAX_MATCH_SCORE = 3;
1258
+ var MAX_SUGGESTION_COUNT = 4;
1259
+ var TYPE_MATCH_DELTA = 0.5;
1260
+ function groupHandlersByType(handlers) {
1261
+ return handlers.reduce((groups, handler) => {
1262
+ if (handler instanceof RestHandler) {
1263
+ groups.rest.push(handler);
1264
+ }
1265
+ if (handler instanceof GraphQLHandler) {
1266
+ groups.graphql.push(handler);
1267
+ }
1268
+ return groups;
1269
+ }, {
1270
+ rest: [],
1271
+ graphql: []
1272
+ });
1273
+ }
1274
+ function getRestHandlerScore() {
1275
+ return (request, handler) => {
1276
+ const { path, method } = handler.info;
1277
+ if (path instanceof RegExp || method instanceof RegExp) {
1278
+ return Infinity;
1279
+ }
1280
+ const hasSameMethod = isStringEqual(request.method, method);
1281
+ const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
1282
+ const requestPublicUrl = getPublicUrlFromRequest(request);
1283
+ const score = getStringMatchScore(requestPublicUrl, path);
1284
+ return score - methodScoreDelta;
1285
+ };
1286
+ }
1287
+ function getGraphQLHandlerScore(parsedQuery) {
1288
+ return (_, handler) => {
1289
+ if (typeof parsedQuery.operationName === "undefined") {
1290
+ return Infinity;
1291
+ }
1292
+ const { operationType, operationName } = handler.info;
1293
+ if (typeof operationName !== "string") {
1294
+ return Infinity;
1295
+ }
1296
+ const hasSameOperationType = parsedQuery.operationType === operationType;
1297
+ const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
1298
+ const score = getStringMatchScore(parsedQuery.operationName, operationName);
1299
+ return score - operationTypeScoreDelta;
1300
+ };
1301
+ }
1302
+ function getSuggestedHandler(request, handlers, getScore) {
1303
+ const suggestedHandlers = handlers.reduce((suggestions, handler) => {
1304
+ const score = getScore(request, handler);
1305
+ return suggestions.concat([[score, handler]]);
1306
+ }, []).sort(([leftScore], [rightScore]) => leftScore - rightScore).filter(([score]) => score <= MAX_MATCH_SCORE).slice(0, MAX_SUGGESTION_COUNT).map(([, handler]) => handler);
1307
+ return suggestedHandlers;
1308
+ }
1309
+ function getSuggestedHandlersMessage(handlers) {
1310
+ if (handlers.length > 1) {
1311
+ return `Did you mean to request one of the following resources instead?
1312
+
1313
+ ${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
1314
+ }
1315
+ return `Did you mean to request "${handlers[0].info.header}" instead?`;
1316
+ }
1317
+ function onUnhandledRequest(request, handlers, strategy = "warn") {
1318
+ const parsedGraphQLQuery = tryCatch(() => parseGraphQLRequest(request));
1319
+ function generateHandlerSuggestion() {
1320
+ const handlerGroups = groupHandlersByType(handlers);
1321
+ const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.rest;
1322
+ const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getRestHandlerScore());
1323
+ return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
1324
+ }
1325
+ function generateUnhandledRequestMessage() {
1326
+ const publicUrl = getPublicUrlFromRequest(request);
1327
+ const requestHeader = parsedGraphQLQuery ? `${parsedGraphQLQuery.operationType} ${parsedGraphQLQuery.operationName} (${request.method} ${publicUrl})` : `${request.method} ${publicUrl}`;
1328
+ const handlerSuggestion = generateHandlerSuggestion();
1329
+ const messageTemplate = [
1330
+ `captured a request without a matching request handler:`,
1331
+ ` \u2022 ${requestHeader}`,
1332
+ handlerSuggestion,
1333
+ `If you still wish to intercept this unhandled request, please create a request handler for it.
1334
+ Read more: https://mswjs.io/docs/getting-started/mocks`
1335
+ ].filter(Boolean);
1336
+ return messageTemplate.join("\n\n");
1337
+ }
1338
+ function applyStrategy(strategy2) {
1339
+ const message = generateUnhandledRequestMessage();
1340
+ switch (strategy2) {
1341
+ case "error": {
1342
+ devUtils.error("Error: %s", message);
1343
+ throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
1344
+ }
1345
+ case "warn": {
1346
+ devUtils.warn("Warning: %s", message);
1347
+ break;
1348
+ }
1349
+ case "bypass":
1350
+ break;
1351
+ default:
1352
+ throw new Error(devUtils.formatMessage('Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', strategy2));
1353
+ }
1354
+ }
1355
+ if (typeof strategy === "function") {
1356
+ strategy(request, {
1357
+ warning: applyStrategy.bind(null, "warn"),
1358
+ error: applyStrategy.bind(null, "error")
1359
+ });
1360
+ return;
1361
+ }
1362
+ applyStrategy(strategy);
1363
+ }
1364
+
1365
+ // src/utils/request/readResponseCookies.ts
1366
+ init_esm_shims();
1367
+ import { store as store2 } from "@mswjs/cookies";
1368
+ function readResponseCookies(request, response2) {
1369
+ store2.add(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }), response2);
1370
+ store2.persist();
1371
+ }
1372
+
1373
+ // src/utils/handleRequest.ts
1374
+ async function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
1375
+ var _a, _b, _c, _d;
1376
+ emitter.emit("request:start", request);
1377
+ if (request.headers.get("x-msw-bypass") === "true") {
1378
+ emitter.emit("request:end", request);
1379
+ (_a = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _a.call(handleRequestOptions, request);
1380
+ return;
1381
+ }
1382
+ const [lookupError, lookupResult] = await until(() => {
1383
+ return getResponse(request, handlers, handleRequestOptions == null ? void 0 : handleRequestOptions.resolutionContext);
1384
+ });
1385
+ if (lookupError) {
1386
+ emitter.emit("unhandledException", lookupError, request);
1387
+ throw lookupError;
1388
+ }
1389
+ const { handler, response: response2 } = lookupResult;
1390
+ if (!handler) {
1391
+ onUnhandledRequest(request, handlers, options.onUnhandledRequest);
1392
+ emitter.emit("request:unhandled", request);
1393
+ emitter.emit("request:end", request);
1394
+ (_b = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _b.call(handleRequestOptions, request);
1395
+ return;
1396
+ }
1397
+ if (!response2) {
1398
+ devUtils.warn(`Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.
1399
+
1400
+ \u2022 %s
1401
+ %s`, response2, handler.info.header, handler.info.callFrame);
1402
+ emitter.emit("request:end", request);
1403
+ (_c = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _c.call(handleRequestOptions, request);
1404
+ return;
1405
+ }
1406
+ if (response2.passthrough) {
1407
+ emitter.emit("request:end", request);
1408
+ (_d = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _d.call(handleRequestOptions, request);
1409
+ return;
1410
+ }
1411
+ readResponseCookies(request, response2);
1412
+ emitter.emit("request:match", request);
1413
+ return new Promise((resolve) => {
1414
+ var _a2, _b2, _c2;
1415
+ const requiredLookupResult = lookupResult;
1416
+ const transformedResponse = ((_a2 = handleRequestOptions == null ? void 0 : handleRequestOptions.transformResponse) == null ? void 0 : _a2.call(handleRequestOptions, response2)) || response2;
1417
+ (_b2 = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponse) == null ? void 0 : _b2.call(handleRequestOptions, transformedResponse, requiredLookupResult);
1418
+ setTimeout(() => {
1419
+ var _a3;
1420
+ (_a3 = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponseSent) == null ? void 0 : _a3.call(handleRequestOptions, transformedResponse, requiredLookupResult);
1421
+ emitter.emit("request:end", request);
1422
+ resolve(transformedResponse);
1423
+ }, (_c2 = response2.delay) != null ? _c2 : 0);
1424
+ });
1425
+ }
1426
+
1427
+ // src/utils/internal/pipeEvents.ts
1428
+ init_esm_shims();
1429
+ function pipeEvents(source, destination) {
1430
+ const rawEmit = source.emit;
1431
+ if (rawEmit._isPiped) {
1432
+ return;
1433
+ }
1434
+ source.emit = function(event, ...data2) {
1435
+ destination.emit(event, ...data2);
1436
+ return rawEmit.call(this, event, ...data2);
1437
+ };
1438
+ source.emit._isPiped = true;
1439
+ }
1440
+
1441
+ // src/node/createSetupServer.ts
1442
+ var DEFAULT_LISTEN_OPTIONS = {
1443
+ onUnhandledRequest: "warn"
1444
+ };
1445
+ function createSetupServer(...interceptors) {
1446
+ const emitter = new StrictEventEmitter();
1447
+ const publicEmitter = new StrictEventEmitter();
1448
+ pipeEvents(emitter, publicEmitter);
1449
+ return function setupServer2(...requestHandlers) {
1450
+ requestHandlers.forEach((handler) => {
1451
+ if (Array.isArray(handler))
1452
+ throw new Error(devUtils.formatMessage('Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expected to receive each handler individually: setupServer(a, b).'));
1453
+ });
1454
+ let currentHandlers = [...requestHandlers];
1455
+ if (!isNodeProcess3()) {
1456
+ throw new Error(devUtils.formatMessage("Failed to execute `setupServer` in the environment that is not Node.js (i.e. a browser). Consider using `setupWorker` instead."));
1457
+ }
1458
+ let resolvedOptions = {};
1459
+ const interceptor = createInterceptor({
1460
+ modules: interceptors,
1461
+ async resolver(request) {
1462
+ const mockedRequest = parseIsomorphicRequest(request);
1463
+ return handleRequest(mockedRequest, currentHandlers, resolvedOptions, emitter, {
1464
+ transformResponse(response2) {
1465
+ return {
1466
+ status: response2.status,
1467
+ statusText: response2.statusText,
1468
+ headers: response2.headers.all(),
1469
+ body: response2.body
1470
+ };
1471
+ }
1472
+ });
1473
+ }
1474
+ });
1475
+ interceptor.on("response", (request, response2) => {
1476
+ if (!request.id) {
1477
+ return;
1478
+ }
1479
+ if (response2.headers.get("x-powered-by") === "msw") {
1480
+ emitter.emit("response:mocked", response2, request.id);
1481
+ } else {
1482
+ emitter.emit("response:bypass", response2, request.id);
1483
+ }
1484
+ });
1485
+ return {
1486
+ listen(options) {
1487
+ resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options || {});
1488
+ interceptor.apply();
1489
+ },
1490
+ use(...handlers) {
1491
+ use(currentHandlers, ...handlers);
1492
+ },
1493
+ restoreHandlers() {
1494
+ restoreHandlers(currentHandlers);
1495
+ },
1496
+ resetHandlers(...nextHandlers) {
1497
+ currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
1498
+ },
1499
+ printHandlers() {
1500
+ currentHandlers.forEach((handler) => {
1501
+ const { header, callFrame } = handler.info;
1502
+ const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1503
+ console.log(`${bold(`${pragma} ${header}`)}
1504
+ Declaration: ${callFrame}
1505
+ `);
1506
+ });
1507
+ },
1508
+ events: {
1509
+ on(...args) {
1510
+ return publicEmitter.on(...args);
1511
+ },
1512
+ removeListener(...args) {
1513
+ return publicEmitter.removeListener(...args);
1514
+ },
1515
+ removeAllListeners(...args) {
1516
+ return publicEmitter.removeAllListeners(...args);
1517
+ }
1518
+ },
1519
+ close() {
1520
+ emitter.removeAllListeners();
1521
+ publicEmitter.removeAllListeners();
1522
+ interceptor.restore();
1523
+ }
1524
+ };
1525
+ };
1526
+ }
1527
+
1528
+ // src/native/index.ts
1529
+ var setupServer = createSetupServer(interceptXMLHttpRequest);
1530
+ export {
1531
+ setupServer
1532
+ };