msw 0.47.3 → 0.48.0

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.
package/lib/node/index.js CHANGED
@@ -59,29 +59,299 @@ module.exports = __toCommonJS(node_exports);
59
59
  var import_timers = require("timers");
60
60
  var setTimeout = import_timers.setTimeout;
61
61
 
62
- // src/node/setupServer.ts
63
- var import_ClientRequest = require("@mswjs/interceptors/lib/interceptors/ClientRequest");
64
- var import_XMLHttpRequest = require("@mswjs/interceptors/lib/interceptors/XMLHttpRequest");
62
+ // src/node/SetupServerApi.ts
63
+ var import_chalk = __toESM(require("chalk"));
64
+ var import_outvariant4 = require("outvariant");
65
+ var import_interceptors2 = require("@mswjs/interceptors");
65
66
 
66
- // src/node/createSetupServer.ts
67
- var import_chalk = require("chalk");
68
- var import_is_node_process3 = require("is-node-process");
67
+ // src/SetupApi.ts
68
+ var import_outvariant2 = require("outvariant");
69
69
  var import_strict_event_emitter = require("strict-event-emitter");
70
- var import_interceptors2 = require("@mswjs/interceptors");
71
70
 
72
- // src/utils/internal/requestHandlerUtils.ts
73
- function use(currentHandlers, ...handlers) {
74
- currentHandlers.unshift(...handlers);
71
+ // src/utils/internal/devUtils.ts
72
+ var import_outvariant = require("outvariant");
73
+ var LIBRARY_PREFIX = "[MSW]";
74
+ function formatMessage(message, ...positionals) {
75
+ const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
76
+ return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
75
77
  }
76
- function restoreHandlers(handlers) {
77
- handlers.forEach((handler) => {
78
- handler.markAsSkipped(false);
79
- });
78
+ function warn(message, ...positionals) {
79
+ console.warn(formatMessage(message, ...positionals));
80
+ }
81
+ function error(message, ...positionals) {
82
+ console.error(formatMessage(message, ...positionals));
83
+ }
84
+ var devUtils = {
85
+ formatMessage,
86
+ warn,
87
+ error
88
+ };
89
+
90
+ // src/utils/internal/pipeEvents.ts
91
+ function pipeEvents(source, destination) {
92
+ const rawEmit = source.emit;
93
+ if (rawEmit._isPiped) {
94
+ return;
95
+ }
96
+ source.emit = function(event, ...data2) {
97
+ destination.emit(event, ...data2);
98
+ return rawEmit.call(this, event, ...data2);
99
+ };
100
+ source.emit._isPiped = true;
101
+ }
102
+
103
+ // src/utils/internal/toReadonlyArray.ts
104
+ function toReadonlyArray(source) {
105
+ const clone = [...source];
106
+ Object.freeze(clone);
107
+ return clone;
108
+ }
109
+
110
+ // src/SetupApi.ts
111
+ var SetupApi = class {
112
+ constructor(initialHandlers) {
113
+ this.validateHandlers(initialHandlers);
114
+ this.initialHandlers = toReadonlyArray(initialHandlers);
115
+ this.currentHandlers = [...initialHandlers];
116
+ this.emitter = new import_strict_event_emitter.StrictEventEmitter();
117
+ this.publicEmitter = new import_strict_event_emitter.StrictEventEmitter();
118
+ pipeEvents(this.emitter, this.publicEmitter);
119
+ this.events = this.createLifeCycleEvents();
120
+ }
121
+ validateHandlers(handlers) {
122
+ for (const handler of handlers) {
123
+ (0, import_outvariant2.invariant)(!Array.isArray(handler), devUtils.formatMessage('Failed to construct "%s" given an Array of request handlers. Make sure you spread the request handlers when calling the respective setup function.'), this.constructor.name);
124
+ }
125
+ }
126
+ dispose() {
127
+ this.emitter.removeAllListeners();
128
+ this.publicEmitter.removeAllListeners();
129
+ }
130
+ use(...runtimeHandlers) {
131
+ this.currentHandlers.unshift(...runtimeHandlers);
132
+ }
133
+ restoreHandlers() {
134
+ this.currentHandlers.forEach((handler) => {
135
+ handler.markAsSkipped(false);
136
+ });
137
+ }
138
+ resetHandlers(...nextHandlers) {
139
+ this.currentHandlers = nextHandlers.length > 0 ? [...nextHandlers] : [...this.initialHandlers];
140
+ }
141
+ listHandlers() {
142
+ return toReadonlyArray(this.currentHandlers);
143
+ }
144
+ createLifeCycleEvents() {
145
+ return {
146
+ on: (...args) => {
147
+ return this.publicEmitter.on(...args);
148
+ },
149
+ removeListener: (...args) => {
150
+ return this.publicEmitter.removeListener(...args);
151
+ },
152
+ removeAllListeners: (...args) => {
153
+ return this.publicEmitter.removeAllListeners(...args);
154
+ }
155
+ };
156
+ }
157
+ };
158
+
159
+ // src/utils/internal/isObject.ts
160
+ function isObject(value) {
161
+ return value != null && typeof value === "object" && !Array.isArray(value);
162
+ }
163
+
164
+ // src/utils/internal/mergeRight.ts
165
+ function mergeRight(left, right) {
166
+ return Object.entries(right).reduce((result, [key, rightValue]) => {
167
+ const leftValue = result[key];
168
+ if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
169
+ result[key] = leftValue.concat(rightValue);
170
+ return result;
171
+ }
172
+ if (isObject(leftValue) && isObject(rightValue)) {
173
+ result[key] = mergeRight(leftValue, rightValue);
174
+ return result;
175
+ }
176
+ result[key] = rightValue;
177
+ return result;
178
+ }, Object.assign({}, left));
179
+ }
180
+
181
+ // src/utils/request/MockedRequest.ts
182
+ var cookieUtils2 = __toESM(require("cookie"));
183
+ var import_cookies = require("@mswjs/cookies");
184
+ var import_interceptors = require("@mswjs/interceptors");
185
+ var import_bufferUtils = require("@mswjs/interceptors/lib/utils/bufferUtils");
186
+ var import_headers_polyfill2 = require("headers-polyfill");
187
+
188
+ // src/utils/request/getRequestCookies.ts
189
+ var cookieUtils = __toESM(require("cookie"));
190
+ function getAllCookies() {
191
+ return cookieUtils.parse(document.cookie);
192
+ }
193
+ function getRequestCookies(request) {
194
+ if (typeof document === "undefined" || typeof location === "undefined") {
195
+ return {};
196
+ }
197
+ switch (request.credentials) {
198
+ case "same-origin": {
199
+ return location.origin === request.url.origin ? getAllCookies() : {};
200
+ }
201
+ case "include": {
202
+ return getAllCookies();
203
+ }
204
+ default: {
205
+ return {};
206
+ }
207
+ }
208
+ }
209
+
210
+ // src/utils/internal/jsonParse.ts
211
+ function jsonParse(value) {
212
+ try {
213
+ return JSON.parse(value);
214
+ } catch (error2) {
215
+ return void 0;
216
+ }
217
+ }
218
+
219
+ // src/utils/internal/parseMultipartData.ts
220
+ var import_headers_polyfill = require("headers-polyfill");
221
+ function parseContentHeaders(headersString) {
222
+ var _a, _b;
223
+ const headers = (0, import_headers_polyfill.stringToHeaders)(headersString);
224
+ const contentType = headers.get("content-type") || "text/plain";
225
+ const disposition = headers.get("content-disposition");
226
+ if (!disposition) {
227
+ throw new Error('"Content-Disposition" header is required.');
228
+ }
229
+ const directives = disposition.split(";").reduce((acc, chunk) => {
230
+ const [name2, ...rest] = chunk.trim().split("=");
231
+ acc[name2] = rest.join("=");
232
+ return acc;
233
+ }, {});
234
+ const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
235
+ const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
236
+ return {
237
+ name,
238
+ filename,
239
+ contentType
240
+ };
241
+ }
242
+ function parseMultipartData(data2, headers) {
243
+ const contentType = headers == null ? void 0 : headers.get("content-type");
244
+ if (!contentType) {
245
+ return void 0;
246
+ }
247
+ const [, ...directives] = contentType.split(/; */);
248
+ const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
249
+ if (!boundary) {
250
+ return void 0;
251
+ }
252
+ const boundaryRegExp = new RegExp(`--+${boundary}`);
253
+ const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
254
+ if (!fields.length) {
255
+ return void 0;
256
+ }
257
+ const parsedBody = {};
258
+ try {
259
+ for (const field2 of fields) {
260
+ const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
261
+ const contentBody = rest.join("\r\n\r\n");
262
+ const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
263
+ const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
264
+ const parsedValue = parsedBody[name];
265
+ if (parsedValue === void 0) {
266
+ parsedBody[name] = value;
267
+ } else if (Array.isArray(parsedValue)) {
268
+ parsedBody[name] = [...parsedValue, value];
269
+ } else {
270
+ parsedBody[name] = [parsedValue, value];
271
+ }
272
+ }
273
+ return parsedBody;
274
+ } catch (error2) {
275
+ return void 0;
276
+ }
277
+ }
278
+
279
+ // src/utils/request/parseBody.ts
280
+ function parseBody(body2, headers) {
281
+ var _a;
282
+ if (!body2) {
283
+ return body2;
284
+ }
285
+ const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
286
+ const hasMultipartContent = contentType.startsWith("multipart/form-data");
287
+ if (hasMultipartContent && typeof body2 !== "object") {
288
+ return parseMultipartData(body2.toString(), headers) || body2;
289
+ }
290
+ const hasJsonContent = contentType.includes("json");
291
+ if (hasJsonContent && typeof body2 !== "object") {
292
+ return jsonParse(body2.toString()) || body2;
293
+ }
294
+ return body2;
80
295
  }
81
- function resetHandlers(initialHandlers, ...nextHandlers) {
82
- return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
296
+
297
+ // src/utils/internal/isStringEqual.ts
298
+ function isStringEqual(actual, expected) {
299
+ return actual.toLowerCase() === expected.toLowerCase();
83
300
  }
84
301
 
302
+ // src/utils/request/MockedRequest.ts
303
+ var MockedRequest = class extends import_interceptors.IsomorphicRequest {
304
+ constructor(url, init = {}) {
305
+ super(url, init);
306
+ if (init.id) {
307
+ this.id = init.id;
308
+ }
309
+ this.cache = init.cache || "default";
310
+ this.destination = init.destination || "";
311
+ this.integrity = init.integrity || "";
312
+ this.keepalive = init.keepalive || false;
313
+ this.mode = init.mode || "cors";
314
+ this.priority = init.priority || "auto";
315
+ this.redirect = init.redirect || "follow";
316
+ this.referrer = init.referrer || "";
317
+ this.referrerPolicy = init.referrerPolicy || "no-referrer";
318
+ this.cookies = init.cookies || this.getCookies();
319
+ }
320
+ get body() {
321
+ const text2 = (0, import_bufferUtils.decodeBuffer)(this["_body"]);
322
+ const body2 = parseBody(text2, this.headers);
323
+ if (isStringEqual(this.method, "GET") && body2 === "") {
324
+ return void 0;
325
+ }
326
+ return body2;
327
+ }
328
+ passthrough() {
329
+ return {
330
+ status: 101,
331
+ statusText: "Continue",
332
+ headers: new import_headers_polyfill2.Headers(),
333
+ body: null,
334
+ passthrough: true,
335
+ once: false
336
+ };
337
+ }
338
+ getCookies() {
339
+ var _a;
340
+ const requestCookiesString = this.headers.get("cookie");
341
+ const ownCookies = requestCookiesString ? cookieUtils2.parse(requestCookiesString) : {};
342
+ import_cookies.store.hydrate();
343
+ const cookiesFromStore = Array.from((_a = import_cookies.store.get(__spreadProps(__spreadValues({}, this), { url: this.url.href }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
344
+ return Object.assign(cookies, { [name.trim()]: value });
345
+ }, {});
346
+ const cookiesFromDocument = getRequestCookies(this);
347
+ const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
348
+ for (const [name, value] of Object.entries(forwardedCookies)) {
349
+ this.headers.append("cookie", `${name}=${value}`);
350
+ }
351
+ return __spreadValues(__spreadValues({}, forwardedCookies), ownCookies);
352
+ }
353
+ };
354
+
85
355
  // src/utils/handleRequest.ts
86
356
  var import_until = require("@open-draft/until");
87
357
 
@@ -132,25 +402,6 @@ var getResponse = async (request, handlers, resolutionContext) => {
132
402
  };
133
403
  };
134
404
 
135
- // src/utils/internal/devUtils.ts
136
- var import_outvariant = require("outvariant");
137
- var LIBRARY_PREFIX = "[MSW]";
138
- function formatMessage(message, ...positionals) {
139
- const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
140
- return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
141
- }
142
- function warn(message, ...positionals) {
143
- console.warn(formatMessage(message, ...positionals));
144
- }
145
- function error(message, ...positionals) {
146
- console.error(formatMessage(message, ...positionals));
147
- }
148
- var devUtils = {
149
- formatMessage,
150
- warn,
151
- error
152
- };
153
-
154
405
  // src/utils/request/onUnhandledRequest.ts
155
406
  var import_js_levenshtein = __toESM(require("js-levenshtein"));
156
407
 
@@ -162,15 +413,6 @@ var getPublicUrlFromRequest = (request) => {
162
413
  return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
163
414
  };
164
415
 
165
- // src/utils/internal/jsonParse.ts
166
- function jsonParse(value) {
167
- try {
168
- return JSON.parse(value);
169
- } catch (error2) {
170
- return void 0;
171
- }
172
- }
173
-
174
416
  // src/utils/internal/parseGraphQLRequest.ts
175
417
  function parseDocumentNode(node) {
176
418
  var _a;
@@ -266,11 +508,6 @@ function parseGraphQLRequest(request) {
266
508
  };
267
509
  }
268
510
 
269
- // src/utils/internal/isStringEqual.ts
270
- function isStringEqual(actual, expected) {
271
- return actual.toLowerCase() === expected.toLowerCase();
272
- }
273
-
274
511
  // src/context/status.ts
275
512
  var import_codes = __toESM(require("statuses/codes.json"));
276
513
  var status = (statusCode, statusText) => {
@@ -282,14 +519,14 @@ var status = (statusCode, statusText) => {
282
519
  };
283
520
 
284
521
  // src/context/set.ts
285
- var import_headers_polyfill = require("headers-polyfill");
522
+ var import_headers_polyfill3 = require("headers-polyfill");
286
523
  function set(...args) {
287
524
  return (res) => {
288
525
  const [name, value] = args;
289
526
  if (typeof name === "string") {
290
527
  res.headers.append(name, value);
291
528
  } else {
292
- const headers = (0, import_headers_polyfill.objectToHeaders)(name);
529
+ const headers = (0, import_headers_polyfill3.objectToHeaders)(name);
293
530
  headers.forEach((value2, name2) => {
294
531
  res.headers.append(name2, value2);
295
532
  });
@@ -299,10 +536,10 @@ function set(...args) {
299
536
  }
300
537
 
301
538
  // src/context/cookie.ts
302
- var cookieUtils = __toESM(require("cookie"));
539
+ var cookieUtils3 = __toESM(require("cookie"));
303
540
  var cookie = (name, value, options) => {
304
541
  return (res) => {
305
- const serializedCookie = cookieUtils.serialize(name, value, options);
542
+ const serializedCookie = cookieUtils3.serialize(name, value, options);
306
543
  res.headers.append("Set-Cookie", serializedCookie);
307
544
  if (typeof document !== "undefined") {
308
545
  document.cookie = serializedCookie;
@@ -319,28 +556,6 @@ var body = (value) => {
319
556
  };
320
557
  };
321
558
 
322
- // src/utils/internal/isObject.ts
323
- function isObject(value) {
324
- return value != null && typeof value === "object" && !Array.isArray(value);
325
- }
326
-
327
- // src/utils/internal/mergeRight.ts
328
- function mergeRight(left, right) {
329
- return Object.entries(right).reduce((result, [key, rightValue]) => {
330
- const leftValue = result[key];
331
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
332
- result[key] = leftValue.concat(rightValue);
333
- return result;
334
- }
335
- if (isObject(leftValue) && isObject(rightValue)) {
336
- result[key] = mergeRight(leftValue, rightValue);
337
- return result;
338
- }
339
- result[key] = rightValue;
340
- return result;
341
- }, Object.assign({}, left));
342
- }
343
-
344
559
  // src/context/json.ts
345
560
  var json = (body2) => {
346
561
  return (res) => {
@@ -424,10 +639,10 @@ var errors = (errorsList) => {
424
639
 
425
640
  // src/context/fetch.ts
426
641
  var import_is_node_process2 = require("is-node-process");
427
- var import_headers_polyfill2 = require("headers-polyfill");
428
- var useFetch = (0, import_is_node_process2.isNodeProcess)() ? require("node-fetch") : window.fetch;
642
+ var import_headers_polyfill4 = require("headers-polyfill");
643
+ var useFetch = (0, import_is_node_process2.isNodeProcess)() ? (input, init) => Promise.resolve().then(() => __toESM(require("node-fetch"))).then(({ default: nodeFetch }) => nodeFetch(input, init)) : window.fetch;
429
644
  var augmentRequestInit = (requestInit) => {
430
- const headers = new import_headers_polyfill2.Headers(requestInit.headers);
645
+ const headers = new import_headers_polyfill4.Headers(requestInit.headers);
431
646
  headers.set("x-msw-bypass", "true");
432
647
  return __spreadProps(__spreadValues({}, requestInit), {
433
648
  headers: headers.all()
@@ -501,89 +716,9 @@ function prepareRequest(request) {
501
716
  }
502
717
 
503
718
  // src/utils/logging/prepareResponse.ts
504
- var import_headers_polyfill4 = require("headers-polyfill");
505
-
506
- // src/utils/internal/parseMultipartData.ts
507
- var import_headers_polyfill3 = require("headers-polyfill");
508
- function parseContentHeaders(headersString) {
509
- var _a, _b;
510
- const headers = (0, import_headers_polyfill3.stringToHeaders)(headersString);
511
- const contentType = headers.get("content-type") || "text/plain";
512
- const disposition = headers.get("content-disposition");
513
- if (!disposition) {
514
- throw new Error('"Content-Disposition" header is required.');
515
- }
516
- const directives = disposition.split(";").reduce((acc, chunk) => {
517
- const [name2, ...rest] = chunk.trim().split("=");
518
- acc[name2] = rest.join("=");
519
- return acc;
520
- }, {});
521
- const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
522
- const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
523
- return {
524
- name,
525
- filename,
526
- contentType
527
- };
528
- }
529
- function parseMultipartData(data2, headers) {
530
- const contentType = headers == null ? void 0 : headers.get("content-type");
531
- if (!contentType) {
532
- return void 0;
533
- }
534
- const [, ...directives] = contentType.split(/; */);
535
- const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
536
- if (!boundary) {
537
- return void 0;
538
- }
539
- const boundaryRegExp = new RegExp(`--+${boundary}`);
540
- const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
541
- if (!fields.length) {
542
- return void 0;
543
- }
544
- const parsedBody = {};
545
- try {
546
- for (const field2 of fields) {
547
- const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
548
- const contentBody = rest.join("\r\n\r\n");
549
- const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
550
- const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
551
- const parsedValue = parsedBody[name];
552
- if (parsedValue === void 0) {
553
- parsedBody[name] = value;
554
- } else if (Array.isArray(parsedValue)) {
555
- parsedBody[name] = [...parsedValue, value];
556
- } else {
557
- parsedBody[name] = [parsedValue, value];
558
- }
559
- }
560
- return parsedBody;
561
- } catch (error2) {
562
- return void 0;
563
- }
564
- }
565
-
566
- // src/utils/request/parseBody.ts
567
- function parseBody(body2, headers) {
568
- var _a;
569
- if (!body2) {
570
- return body2;
571
- }
572
- const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
573
- const hasMultipartContent = contentType.startsWith("multipart/form-data");
574
- if (hasMultipartContent && typeof body2 !== "object") {
575
- return parseMultipartData(body2.toString(), headers) || body2;
576
- }
577
- const hasJsonContent = contentType.includes("json");
578
- if (hasJsonContent && typeof body2 !== "object") {
579
- return jsonParse(body2.toString()) || body2;
580
- }
581
- return body2;
582
- }
583
-
584
- // src/utils/logging/prepareResponse.ts
719
+ var import_headers_polyfill5 = require("headers-polyfill");
585
720
  function prepareResponse(res) {
586
- const responseHeaders = (0, import_headers_polyfill4.objectToHeaders)(res.headers);
721
+ const responseHeaders = (0, import_headers_polyfill5.objectToHeaders)(res.headers);
587
722
  return __spreadProps(__spreadValues({}, res), {
588
723
  body: parseBody(res.body, responseHeaders)
589
724
  });
@@ -591,7 +726,7 @@ function prepareResponse(res) {
591
726
 
592
727
  // src/utils/matching/matchRequestUrl.ts
593
728
  var import_path_to_regexp = require("path-to-regexp");
594
- var import_getCleanUrl = require("@mswjs/interceptors/lib/utils/getCleanUrl");
729
+ var import_getCleanUrl = require("@mswjs/interceptors/lib/utils/getCleanUrl.js");
595
730
 
596
731
  // src/utils/url/cleanUrl.ts
597
732
  var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
@@ -650,88 +785,6 @@ function matchRequestUrl(url, path, baseUrl) {
650
785
  };
651
786
  }
652
787
 
653
- // src/utils/request/MockedRequest.ts
654
- var cookieUtils3 = __toESM(require("cookie"));
655
- var import_cookies = require("@mswjs/cookies");
656
- var import_interceptors = require("@mswjs/interceptors");
657
- var import_bufferUtils = require("@mswjs/interceptors/lib/utils/bufferUtils");
658
- var import_headers_polyfill5 = require("headers-polyfill");
659
-
660
- // src/utils/request/getRequestCookies.ts
661
- var cookieUtils2 = __toESM(require("cookie"));
662
- function getAllCookies() {
663
- return cookieUtils2.parse(document.cookie);
664
- }
665
- function getRequestCookies(request) {
666
- if (typeof document === "undefined" || typeof location === "undefined") {
667
- return {};
668
- }
669
- switch (request.credentials) {
670
- case "same-origin": {
671
- return location.origin === request.url.origin ? getAllCookies() : {};
672
- }
673
- case "include": {
674
- return getAllCookies();
675
- }
676
- default: {
677
- return {};
678
- }
679
- }
680
- }
681
-
682
- // src/utils/request/MockedRequest.ts
683
- var MockedRequest = class extends import_interceptors.IsomorphicRequest {
684
- constructor(url, init = {}) {
685
- super(url, init);
686
- if (init.id) {
687
- this.id = init.id;
688
- }
689
- this.cache = init.cache || "default";
690
- this.destination = init.destination || "";
691
- this.integrity = init.integrity || "";
692
- this.keepalive = init.keepalive || false;
693
- this.mode = init.mode || "cors";
694
- this.priority = init.priority || "auto";
695
- this.redirect = init.redirect || "follow";
696
- this.referrer = init.referrer || "";
697
- this.referrerPolicy = init.referrerPolicy || "no-referrer";
698
- this.cookies = init.cookies || this.getCookies();
699
- }
700
- get body() {
701
- const text2 = (0, import_bufferUtils.decodeBuffer)(this["_body"]);
702
- const body2 = parseBody(text2, this.headers);
703
- if (isStringEqual(this.method, "GET") && body2 === "") {
704
- return void 0;
705
- }
706
- return body2;
707
- }
708
- passthrough() {
709
- return {
710
- status: 101,
711
- statusText: "Continue",
712
- headers: new import_headers_polyfill5.Headers(),
713
- body: null,
714
- passthrough: true,
715
- once: false
716
- };
717
- }
718
- getCookies() {
719
- var _a;
720
- const requestCookiesString = this.headers.get("cookie");
721
- const ownCookies = requestCookiesString ? cookieUtils3.parse(requestCookiesString) : {};
722
- import_cookies.store.hydrate();
723
- const cookiesFromStore = Array.from((_a = import_cookies.store.get(__spreadProps(__spreadValues({}, this), { url: this.url.href }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
724
- return Object.assign(cookies, { [name.trim()]: value });
725
- }, {});
726
- const cookiesFromDocument = getRequestCookies(this);
727
- const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
728
- for (const [name, value] of Object.entries(forwardedCookies)) {
729
- this.headers.append("cookie", `${name}=${value}`);
730
- }
731
- return __spreadValues(__spreadValues({}, forwardedCookies), ownCookies);
732
- }
733
- };
734
-
735
788
  // src/handlers/RequestHandler.ts
736
789
  var import_headers_polyfill7 = require("headers-polyfill");
737
790
 
@@ -788,7 +841,7 @@ var response = Object.assign(createResponseComposition(), {
788
841
  });
789
842
 
790
843
  // src/utils/internal/getCallFrame.ts
791
- var SOURCE_FRAME = /\/msw\/src\/(.+)/;
844
+ var SOURCE_FRAME = /[\/\\]msw[\/\\]src[\/\\](.+)/;
792
845
  var BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](umd|esm|iief|cjs)[\/\\]|^[^\/\\]*$/;
793
846
  function getCallFrame(error2) {
794
847
  const stack = error2.stack;
@@ -955,7 +1008,7 @@ var RestHandler = class extends RequestHandler {
955
1008
  };
956
1009
 
957
1010
  // src/context/field.ts
958
- var import_outvariant2 = require("outvariant");
1011
+ var import_outvariant3 = require("outvariant");
959
1012
  var field = (fieldName, fieldValue) => {
960
1013
  return (res) => {
961
1014
  validateFieldName(fieldName);
@@ -965,10 +1018,10 @@ var field = (fieldName, fieldValue) => {
965
1018
  };
966
1019
  };
967
1020
  function validateFieldName(fieldName) {
968
- (0, import_outvariant2.invariant)(fieldName.trim() !== "", devUtils.formatMessage("Failed to set a custom field on a GraphQL response: field name cannot be empty."));
969
- (0, import_outvariant2.invariant)(fieldName !== "data", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.data()" instead?', fieldName));
970
- (0, import_outvariant2.invariant)(fieldName !== "errors", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.errors()" instead?', fieldName));
971
- (0, import_outvariant2.invariant)(fieldName !== "extensions", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.extensions()" instead?', fieldName));
1021
+ (0, import_outvariant3.invariant)(fieldName.trim() !== "", devUtils.formatMessage("Failed to set a custom field on a GraphQL response: field name cannot be empty."));
1022
+ (0, import_outvariant3.invariant)(fieldName !== "data", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.data()" instead?', fieldName));
1023
+ (0, import_outvariant3.invariant)(fieldName !== "errors", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.errors()" instead?', fieldName));
1024
+ (0, import_outvariant3.invariant)(fieldName !== "extensions", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.extensions()" instead?', fieldName));
972
1025
  }
973
1026
 
974
1027
  // src/utils/internal/tryCatch.ts
@@ -1226,53 +1279,27 @@ async function handleRequest(request, handlers, options, emitter, handleRequestO
1226
1279
  return transformedResponse;
1227
1280
  }
1228
1281
 
1229
- // src/utils/internal/pipeEvents.ts
1230
- function pipeEvents(source, destination) {
1231
- const rawEmit = source.emit;
1232
- if (rawEmit._isPiped) {
1233
- return;
1234
- }
1235
- source.emit = function(event, ...data2) {
1236
- destination.emit(event, ...data2);
1237
- return rawEmit.call(this, event, ...data2);
1238
- };
1239
- source.emit._isPiped = true;
1240
- }
1241
-
1242
- // src/utils/internal/toReadonlyArray.ts
1243
- function toReadonlyArray(source) {
1244
- const clone = [...source];
1245
- Object.freeze(clone);
1246
- return clone;
1247
- }
1248
-
1249
- // src/node/createSetupServer.ts
1282
+ // src/node/SetupServerApi.ts
1283
+ var { bold } = import_chalk.default;
1250
1284
  var DEFAULT_LISTEN_OPTIONS = {
1251
1285
  onUnhandledRequest: "warn"
1252
1286
  };
1253
- function createSetupServer(...interceptors) {
1254
- const emitter = new import_strict_event_emitter.StrictEventEmitter();
1255
- const publicEmitter = new import_strict_event_emitter.StrictEventEmitter();
1256
- pipeEvents(emitter, publicEmitter);
1257
- return function setupServer2(...requestHandlers) {
1258
- requestHandlers.forEach((handler) => {
1259
- if (Array.isArray(handler))
1260
- 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).'));
1261
- });
1262
- let currentHandlers = [...requestHandlers];
1263
- if (!(0, import_is_node_process3.isNodeProcess)()) {
1264
- 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."));
1265
- }
1266
- let resolvedOptions = {};
1267
- const interceptor = new import_interceptors2.BatchInterceptor({
1287
+ var SetupServerApi = class extends SetupApi {
1288
+ constructor(interceptors, handlers) {
1289
+ super(handlers);
1290
+ this.interceptor = new import_interceptors2.BatchInterceptor({
1268
1291
  name: "setup-server",
1269
1292
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
1270
1293
  });
1271
- interceptor.on("request", async function setupServerListener(request) {
1294
+ this.resolvedOptions = {};
1295
+ this.init();
1296
+ }
1297
+ init() {
1298
+ this.interceptor.on("request", async (request) => {
1272
1299
  const mockedRequest = new MockedRequest(request.url, __spreadProps(__spreadValues({}, request), {
1273
1300
  body: await request.arrayBuffer()
1274
1301
  }));
1275
- const response2 = await handleRequest(mockedRequest, currentHandlers, resolvedOptions, emitter, {
1302
+ const response2 = await handleRequest(mockedRequest, this.currentHandlers, this.resolvedOptions, this.emitter, {
1276
1303
  transformResponse(response3) {
1277
1304
  return {
1278
1305
  status: response3.status,
@@ -1293,65 +1320,44 @@ function createSetupServer(...interceptors) {
1293
1320
  }
1294
1321
  return;
1295
1322
  });
1296
- interceptor.on("response", (request, response2) => {
1323
+ this.interceptor.on("response", (request, response2) => {
1297
1324
  if (!request.id) {
1298
1325
  return;
1299
1326
  }
1300
1327
  if (response2.headers.get("x-powered-by") === "msw") {
1301
- emitter.emit("response:mocked", response2, request.id);
1328
+ this.emitter.emit("response:mocked", response2, request.id);
1302
1329
  } else {
1303
- emitter.emit("response:bypass", response2, request.id);
1330
+ this.emitter.emit("response:bypass", response2, request.id);
1304
1331
  }
1305
1332
  });
1306
- return {
1307
- listen(options) {
1308
- resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options || {});
1309
- interceptor.apply();
1310
- },
1311
- use(...handlers) {
1312
- use(currentHandlers, ...handlers);
1313
- },
1314
- restoreHandlers() {
1315
- restoreHandlers(currentHandlers);
1316
- },
1317
- resetHandlers(...nextHandlers) {
1318
- currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
1319
- },
1320
- listHandlers() {
1321
- return toReadonlyArray(currentHandlers);
1322
- },
1323
- printHandlers() {
1324
- const handlers = this.listHandlers();
1325
- handlers.forEach((handler) => {
1326
- const { header, callFrame } = handler.info;
1327
- const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1328
- console.log(`${(0, import_chalk.bold)(`${pragma} ${header}`)}
1333
+ }
1334
+ listen(options = {}) {
1335
+ this.resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options);
1336
+ this.interceptor.apply();
1337
+ (0, import_outvariant4.invariant)([import_interceptors2.InterceptorReadyState.APPLYING, import_interceptors2.InterceptorReadyState.APPLIED].includes(this.interceptor.readyState), devUtils.formatMessage('Failed to start "setupServer": the interceptor failed to apply. This is likely an issue with the library and you should report it at "%s".'), "https://github.com/mswjs/msw/issues/new/choose");
1338
+ }
1339
+ printHandlers() {
1340
+ const handlers = this.listHandlers();
1341
+ handlers.forEach((handler) => {
1342
+ const { header, callFrame } = handler.info;
1343
+ const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1344
+ console.log(`${bold(`${pragma} ${header}`)}
1329
1345
  Declaration: ${callFrame}
1330
1346
  `);
1331
- });
1332
- },
1333
- events: {
1334
- on(...args) {
1335
- return publicEmitter.on(...args);
1336
- },
1337
- removeListener(...args) {
1338
- return publicEmitter.removeListener(...args);
1339
- },
1340
- removeAllListeners(...args) {
1341
- return publicEmitter.removeAllListeners(...args);
1342
- }
1343
- },
1344
- close() {
1345
- emitter.removeAllListeners();
1346
- publicEmitter.removeAllListeners();
1347
- interceptor.dispose();
1348
- }
1349
- };
1350
- };
1351
- }
1347
+ });
1348
+ }
1349
+ close() {
1350
+ super.dispose();
1351
+ this.interceptor.dispose();
1352
+ }
1353
+ };
1352
1354
 
1353
1355
  // src/node/setupServer.ts
1354
- var setupServer = createSetupServer(import_ClientRequest.ClientRequestInterceptor, import_XMLHttpRequest.XMLHttpRequestInterceptor);
1356
+ var import_ClientRequest = require("@mswjs/interceptors/lib/interceptors/ClientRequest/index.js");
1357
+ var import_XMLHttpRequest = require("@mswjs/interceptors/lib/interceptors/XMLHttpRequest/index.js");
1358
+ var setupServer = (...handlers) => {
1359
+ return new SetupServerApi([import_ClientRequest.ClientRequestInterceptor, import_XMLHttpRequest.XMLHttpRequestInterceptor], handlers);
1360
+ };
1355
1361
  // Annotate the CommonJS export names for ESM import in node:
1356
1362
  0 && (module.exports = {
1357
1363
  setupServer