msw 0.47.4 → 0.48.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.
@@ -1,7 +1,11 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
5
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
7
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
5
9
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
10
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -36,31 +40,315 @@ var __objRest = (source, exclude) => {
36
40
  }
37
41
  return target;
38
42
  };
43
+ var __copyProps = (to, from, except, desc) => {
44
+ if (from && typeof from === "object" || typeof from === "function") {
45
+ for (let key of __getOwnPropNames(from))
46
+ if (!__hasOwnProp.call(to, key) && key !== except)
47
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
48
+ }
49
+ return to;
50
+ };
51
+ 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));
39
52
 
40
53
  // src/native/index.ts
41
54
  import { XMLHttpRequestInterceptor } from "@mswjs/interceptors/lib/interceptors/XMLHttpRequest";
42
55
 
43
- // src/node/createSetupServer.ts
44
- import { bold } from "chalk";
45
- import { isNodeProcess as isNodeProcess3 } from "is-node-process";
46
- import { StrictEventEmitter } from "strict-event-emitter";
56
+ // src/node/SetupServerApi.ts
57
+ import chalk from "chalk";
58
+ import { invariant as invariant3 } from "outvariant";
47
59
  import {
48
- BatchInterceptor
60
+ BatchInterceptor,
61
+ InterceptorReadyState
49
62
  } from "@mswjs/interceptors";
50
63
 
51
- // src/utils/internal/requestHandlerUtils.ts
52
- function use(currentHandlers, ...handlers) {
53
- currentHandlers.unshift(...handlers);
64
+ // src/SetupApi.ts
65
+ import { invariant } from "outvariant";
66
+ import { StrictEventEmitter } from "strict-event-emitter";
67
+
68
+ // src/utils/internal/devUtils.ts
69
+ import { format } from "outvariant";
70
+ var LIBRARY_PREFIX = "[MSW]";
71
+ function formatMessage(message, ...positionals) {
72
+ const interpolatedMessage = format(message, ...positionals);
73
+ return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
54
74
  }
55
- function restoreHandlers(handlers) {
56
- handlers.forEach((handler) => {
57
- handler.markAsSkipped(false);
58
- });
75
+ function warn(message, ...positionals) {
76
+ console.warn(formatMessage(message, ...positionals));
77
+ }
78
+ function error(message, ...positionals) {
79
+ console.error(formatMessage(message, ...positionals));
80
+ }
81
+ var devUtils = {
82
+ formatMessage,
83
+ warn,
84
+ error
85
+ };
86
+
87
+ // src/utils/internal/pipeEvents.ts
88
+ function pipeEvents(source, destination) {
89
+ const rawEmit = source.emit;
90
+ if (rawEmit._isPiped) {
91
+ return;
92
+ }
93
+ source.emit = function(event, ...data2) {
94
+ destination.emit(event, ...data2);
95
+ return rawEmit.call(this, event, ...data2);
96
+ };
97
+ source.emit._isPiped = true;
98
+ }
99
+
100
+ // src/utils/internal/toReadonlyArray.ts
101
+ function toReadonlyArray(source) {
102
+ const clone = [...source];
103
+ Object.freeze(clone);
104
+ return clone;
105
+ }
106
+
107
+ // src/SetupApi.ts
108
+ var SetupApi = class {
109
+ constructor(initialHandlers) {
110
+ this.validateHandlers(initialHandlers);
111
+ this.initialHandlers = toReadonlyArray(initialHandlers);
112
+ this.currentHandlers = [...initialHandlers];
113
+ this.emitter = new StrictEventEmitter();
114
+ this.publicEmitter = new StrictEventEmitter();
115
+ pipeEvents(this.emitter, this.publicEmitter);
116
+ this.events = this.createLifeCycleEvents();
117
+ }
118
+ validateHandlers(handlers) {
119
+ for (const handler of handlers) {
120
+ 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);
121
+ }
122
+ }
123
+ dispose() {
124
+ this.emitter.removeAllListeners();
125
+ this.publicEmitter.removeAllListeners();
126
+ }
127
+ use(...runtimeHandlers) {
128
+ this.currentHandlers.unshift(...runtimeHandlers);
129
+ }
130
+ restoreHandlers() {
131
+ this.currentHandlers.forEach((handler) => {
132
+ handler.markAsSkipped(false);
133
+ });
134
+ }
135
+ resetHandlers(...nextHandlers) {
136
+ this.currentHandlers = nextHandlers.length > 0 ? [...nextHandlers] : [...this.initialHandlers];
137
+ }
138
+ listHandlers() {
139
+ return toReadonlyArray(this.currentHandlers);
140
+ }
141
+ createLifeCycleEvents() {
142
+ return {
143
+ on: (...args) => {
144
+ return this.publicEmitter.on(...args);
145
+ },
146
+ removeListener: (...args) => {
147
+ return this.publicEmitter.removeListener(...args);
148
+ },
149
+ removeAllListeners: (...args) => {
150
+ return this.publicEmitter.removeAllListeners(...args);
151
+ }
152
+ };
153
+ }
154
+ };
155
+
156
+ // src/utils/internal/isObject.ts
157
+ function isObject(value) {
158
+ return value != null && typeof value === "object" && !Array.isArray(value);
59
159
  }
60
- function resetHandlers(initialHandlers, ...nextHandlers) {
61
- return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
160
+
161
+ // src/utils/internal/mergeRight.ts
162
+ function mergeRight(left, right) {
163
+ return Object.entries(right).reduce((result, [key, rightValue]) => {
164
+ const leftValue = result[key];
165
+ if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
166
+ result[key] = leftValue.concat(rightValue);
167
+ return result;
168
+ }
169
+ if (isObject(leftValue) && isObject(rightValue)) {
170
+ result[key] = mergeRight(leftValue, rightValue);
171
+ return result;
172
+ }
173
+ result[key] = rightValue;
174
+ return result;
175
+ }, Object.assign({}, left));
176
+ }
177
+
178
+ // src/utils/request/MockedRequest.ts
179
+ import * as cookieUtils2 from "cookie";
180
+ import { store } from "@mswjs/cookies";
181
+ import { IsomorphicRequest } from "@mswjs/interceptors";
182
+ import { decodeBuffer } from "@mswjs/interceptors/lib/utils/bufferUtils.js";
183
+ import { Headers } from "headers-polyfill";
184
+
185
+ // src/utils/request/getRequestCookies.ts
186
+ import * as cookieUtils from "cookie";
187
+ function getAllCookies() {
188
+ return cookieUtils.parse(document.cookie);
189
+ }
190
+ function getRequestCookies(request) {
191
+ if (typeof document === "undefined" || typeof location === "undefined") {
192
+ return {};
193
+ }
194
+ switch (request.credentials) {
195
+ case "same-origin": {
196
+ return location.origin === request.url.origin ? getAllCookies() : {};
197
+ }
198
+ case "include": {
199
+ return getAllCookies();
200
+ }
201
+ default: {
202
+ return {};
203
+ }
204
+ }
205
+ }
206
+
207
+ // src/utils/internal/jsonParse.ts
208
+ function jsonParse(value) {
209
+ try {
210
+ return JSON.parse(value);
211
+ } catch (error2) {
212
+ return void 0;
213
+ }
62
214
  }
63
215
 
216
+ // src/utils/internal/parseMultipartData.ts
217
+ import { stringToHeaders } from "headers-polyfill";
218
+ function parseContentHeaders(headersString) {
219
+ var _a, _b;
220
+ const headers = stringToHeaders(headersString);
221
+ const contentType = headers.get("content-type") || "text/plain";
222
+ const disposition = headers.get("content-disposition");
223
+ if (!disposition) {
224
+ throw new Error('"Content-Disposition" header is required.');
225
+ }
226
+ const directives = disposition.split(";").reduce((acc, chunk) => {
227
+ const [name2, ...rest] = chunk.trim().split("=");
228
+ acc[name2] = rest.join("=");
229
+ return acc;
230
+ }, {});
231
+ const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
232
+ const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
233
+ return {
234
+ name,
235
+ filename,
236
+ contentType
237
+ };
238
+ }
239
+ function parseMultipartData(data2, headers) {
240
+ const contentType = headers == null ? void 0 : headers.get("content-type");
241
+ if (!contentType) {
242
+ return void 0;
243
+ }
244
+ const [, ...directives] = contentType.split(/; */);
245
+ const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
246
+ if (!boundary) {
247
+ return void 0;
248
+ }
249
+ const boundaryRegExp = new RegExp(`--+${boundary}`);
250
+ const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
251
+ if (!fields.length) {
252
+ return void 0;
253
+ }
254
+ const parsedBody = {};
255
+ try {
256
+ for (const field2 of fields) {
257
+ const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
258
+ const contentBody = rest.join("\r\n\r\n");
259
+ const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
260
+ const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
261
+ const parsedValue = parsedBody[name];
262
+ if (parsedValue === void 0) {
263
+ parsedBody[name] = value;
264
+ } else if (Array.isArray(parsedValue)) {
265
+ parsedBody[name] = [...parsedValue, value];
266
+ } else {
267
+ parsedBody[name] = [parsedValue, value];
268
+ }
269
+ }
270
+ return parsedBody;
271
+ } catch (error2) {
272
+ return void 0;
273
+ }
274
+ }
275
+
276
+ // src/utils/request/parseBody.ts
277
+ function parseBody(body2, headers) {
278
+ var _a;
279
+ if (!body2) {
280
+ return body2;
281
+ }
282
+ const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
283
+ const hasMultipartContent = contentType.startsWith("multipart/form-data");
284
+ if (hasMultipartContent && typeof body2 !== "object") {
285
+ return parseMultipartData(body2.toString(), headers) || body2;
286
+ }
287
+ const hasJsonContent = contentType.includes("json");
288
+ if (hasJsonContent && typeof body2 !== "object") {
289
+ return jsonParse(body2.toString()) || body2;
290
+ }
291
+ return body2;
292
+ }
293
+
294
+ // src/utils/internal/isStringEqual.ts
295
+ function isStringEqual(actual, expected) {
296
+ return actual.toLowerCase() === expected.toLowerCase();
297
+ }
298
+
299
+ // src/utils/request/MockedRequest.ts
300
+ var MockedRequest = class extends IsomorphicRequest {
301
+ constructor(url, init = {}) {
302
+ super(url, init);
303
+ if (init.id) {
304
+ this.id = init.id;
305
+ }
306
+ this.cache = init.cache || "default";
307
+ this.destination = init.destination || "";
308
+ this.integrity = init.integrity || "";
309
+ this.keepalive = init.keepalive || false;
310
+ this.mode = init.mode || "cors";
311
+ this.priority = init.priority || "auto";
312
+ this.redirect = init.redirect || "follow";
313
+ this.referrer = init.referrer || "";
314
+ this.referrerPolicy = init.referrerPolicy || "no-referrer";
315
+ this.cookies = init.cookies || this.getCookies();
316
+ }
317
+ get body() {
318
+ const text2 = decodeBuffer(this["_body"]);
319
+ const body2 = parseBody(text2, this.headers);
320
+ if (isStringEqual(this.method, "GET") && body2 === "") {
321
+ return void 0;
322
+ }
323
+ return body2;
324
+ }
325
+ passthrough() {
326
+ return {
327
+ status: 101,
328
+ statusText: "Continue",
329
+ headers: new Headers(),
330
+ body: null,
331
+ passthrough: true,
332
+ once: false
333
+ };
334
+ }
335
+ getCookies() {
336
+ var _a;
337
+ const requestCookiesString = this.headers.get("cookie");
338
+ const ownCookies = requestCookiesString ? cookieUtils2.parse(requestCookiesString) : {};
339
+ store.hydrate();
340
+ const cookiesFromStore = Array.from((_a = store.get(__spreadProps(__spreadValues({}, this), { url: this.url.href }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
341
+ return Object.assign(cookies, { [name.trim()]: value });
342
+ }, {});
343
+ const cookiesFromDocument = getRequestCookies(this);
344
+ const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
345
+ for (const [name, value] of Object.entries(forwardedCookies)) {
346
+ this.headers.append("cookie", `${name}=${value}`);
347
+ }
348
+ return __spreadValues(__spreadValues({}, forwardedCookies), ownCookies);
349
+ }
350
+ };
351
+
64
352
  // src/utils/handleRequest.ts
65
353
  import { until } from "@open-draft/until";
66
354
 
@@ -111,45 +399,17 @@ var getResponse = async (request, handlers, resolutionContext) => {
111
399
  };
112
400
  };
113
401
 
114
- // src/utils/internal/devUtils.ts
115
- import { format } from "outvariant";
116
- var LIBRARY_PREFIX = "[MSW]";
117
- function formatMessage(message, ...positionals) {
118
- const interpolatedMessage = format(message, ...positionals);
119
- return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
120
- }
121
- function warn(message, ...positionals) {
122
- console.warn(formatMessage(message, ...positionals));
123
- }
124
- function error(message, ...positionals) {
125
- console.error(formatMessage(message, ...positionals));
126
- }
127
- var devUtils = {
128
- formatMessage,
129
- warn,
130
- error
131
- };
132
-
133
402
  // src/utils/request/onUnhandledRequest.ts
134
403
  import getStringMatchScore from "js-levenshtein";
135
404
 
136
405
  // src/utils/internal/parseGraphQLRequest.ts
137
- import { parse } from "graphql";
406
+ import { parse as parse3 } from "graphql";
138
407
 
139
408
  // src/utils/request/getPublicUrlFromRequest.ts
140
409
  var getPublicUrlFromRequest = (request) => {
141
410
  return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
142
411
  };
143
412
 
144
- // src/utils/internal/jsonParse.ts
145
- function jsonParse(value) {
146
- try {
147
- return JSON.parse(value);
148
- } catch (error2) {
149
- return void 0;
150
- }
151
- }
152
-
153
413
  // src/utils/internal/parseGraphQLRequest.ts
154
414
  function parseDocumentNode(node) {
155
415
  var _a;
@@ -163,7 +423,7 @@ function parseDocumentNode(node) {
163
423
  }
164
424
  function parseQuery(query) {
165
425
  try {
166
- const ast = parse(query);
426
+ const ast = parse3(query);
167
427
  return parseDocumentNode(ast);
168
428
  } catch (error2) {
169
429
  return error2;
@@ -245,11 +505,6 @@ function parseGraphQLRequest(request) {
245
505
  };
246
506
  }
247
507
 
248
- // src/utils/internal/isStringEqual.ts
249
- function isStringEqual(actual, expected) {
250
- return actual.toLowerCase() === expected.toLowerCase();
251
- }
252
-
253
508
  // src/context/status.ts
254
509
  import statuses from "statuses/codes.json";
255
510
  var status = (statusCode, statusText) => {
@@ -278,10 +533,10 @@ function set(...args) {
278
533
  }
279
534
 
280
535
  // src/context/cookie.ts
281
- import * as cookieUtils from "cookie";
536
+ import * as cookieUtils3 from "cookie";
282
537
  var cookie = (name, value, options) => {
283
538
  return (res) => {
284
- const serializedCookie = cookieUtils.serialize(name, value, options);
539
+ const serializedCookie = cookieUtils3.serialize(name, value, options);
285
540
  res.headers.append("Set-Cookie", serializedCookie);
286
541
  if (typeof document !== "undefined") {
287
542
  document.cookie = serializedCookie;
@@ -298,28 +553,6 @@ var body = (value) => {
298
553
  };
299
554
  };
300
555
 
301
- // src/utils/internal/isObject.ts
302
- function isObject(value) {
303
- return value != null && typeof value === "object" && !Array.isArray(value);
304
- }
305
-
306
- // src/utils/internal/mergeRight.ts
307
- function mergeRight(left, right) {
308
- return Object.entries(right).reduce((result, [key, rightValue]) => {
309
- const leftValue = result[key];
310
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
311
- result[key] = leftValue.concat(rightValue);
312
- return result;
313
- }
314
- if (isObject(leftValue) && isObject(rightValue)) {
315
- result[key] = mergeRight(leftValue, rightValue);
316
- return result;
317
- }
318
- result[key] = rightValue;
319
- return result;
320
- }, Object.assign({}, left));
321
- }
322
-
323
556
  // src/context/json.ts
324
557
  var json = (body2) => {
325
558
  return (res) => {
@@ -403,10 +636,10 @@ var errors = (errorsList) => {
403
636
 
404
637
  // src/context/fetch.ts
405
638
  import { isNodeProcess as isNodeProcess2 } from "is-node-process";
406
- import { Headers } from "headers-polyfill";
407
- var useFetch = isNodeProcess2() ? __require("node-fetch") : window.fetch;
639
+ import { Headers as Headers2 } from "headers-polyfill";
640
+ var useFetch = isNodeProcess2() ? (input, init) => Promise.resolve().then(() => __toESM(__require("node-fetch"))).then(({ default: nodeFetch }) => nodeFetch(input, init)) : window.fetch;
408
641
  var augmentRequestInit = (requestInit) => {
409
- const headers = new Headers(requestInit.headers);
642
+ const headers = new Headers2(requestInit.headers);
410
643
  headers.set("x-msw-bypass", "true");
411
644
  return __spreadProps(__spreadValues({}, requestInit), {
412
645
  headers: headers.all()
@@ -481,86 +714,6 @@ function prepareRequest(request) {
481
714
 
482
715
  // src/utils/logging/prepareResponse.ts
483
716
  import { objectToHeaders as objectToHeaders2 } from "headers-polyfill";
484
-
485
- // src/utils/internal/parseMultipartData.ts
486
- import { stringToHeaders } from "headers-polyfill";
487
- function parseContentHeaders(headersString) {
488
- var _a, _b;
489
- const headers = stringToHeaders(headersString);
490
- const contentType = headers.get("content-type") || "text/plain";
491
- const disposition = headers.get("content-disposition");
492
- if (!disposition) {
493
- throw new Error('"Content-Disposition" header is required.');
494
- }
495
- const directives = disposition.split(";").reduce((acc, chunk) => {
496
- const [name2, ...rest] = chunk.trim().split("=");
497
- acc[name2] = rest.join("=");
498
- return acc;
499
- }, {});
500
- const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
501
- const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
502
- return {
503
- name,
504
- filename,
505
- contentType
506
- };
507
- }
508
- function parseMultipartData(data2, headers) {
509
- const contentType = headers == null ? void 0 : headers.get("content-type");
510
- if (!contentType) {
511
- return void 0;
512
- }
513
- const [, ...directives] = contentType.split(/; */);
514
- const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
515
- if (!boundary) {
516
- return void 0;
517
- }
518
- const boundaryRegExp = new RegExp(`--+${boundary}`);
519
- const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
520
- if (!fields.length) {
521
- return void 0;
522
- }
523
- const parsedBody = {};
524
- try {
525
- for (const field2 of fields) {
526
- const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
527
- const contentBody = rest.join("\r\n\r\n");
528
- const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
529
- const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
530
- const parsedValue = parsedBody[name];
531
- if (parsedValue === void 0) {
532
- parsedBody[name] = value;
533
- } else if (Array.isArray(parsedValue)) {
534
- parsedBody[name] = [...parsedValue, value];
535
- } else {
536
- parsedBody[name] = [parsedValue, value];
537
- }
538
- }
539
- return parsedBody;
540
- } catch (error2) {
541
- return void 0;
542
- }
543
- }
544
-
545
- // src/utils/request/parseBody.ts
546
- function parseBody(body2, headers) {
547
- var _a;
548
- if (!body2) {
549
- return body2;
550
- }
551
- const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
552
- const hasMultipartContent = contentType.startsWith("multipart/form-data");
553
- if (hasMultipartContent && typeof body2 !== "object") {
554
- return parseMultipartData(body2.toString(), headers) || body2;
555
- }
556
- const hasJsonContent = contentType.includes("json");
557
- if (hasJsonContent && typeof body2 !== "object") {
558
- return jsonParse(body2.toString()) || body2;
559
- }
560
- return body2;
561
- }
562
-
563
- // src/utils/logging/prepareResponse.ts
564
717
  function prepareResponse(res) {
565
718
  const responseHeaders = objectToHeaders2(res.headers);
566
719
  return __spreadProps(__spreadValues({}, res), {
@@ -570,7 +723,7 @@ function prepareResponse(res) {
570
723
 
571
724
  // src/utils/matching/matchRequestUrl.ts
572
725
  import { match } from "path-to-regexp";
573
- import { getCleanUrl } from "@mswjs/interceptors/lib/utils/getCleanUrl";
726
+ import { getCleanUrl } from "@mswjs/interceptors/lib/utils/getCleanUrl.js";
574
727
 
575
728
  // src/utils/url/cleanUrl.ts
576
729
  var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
@@ -629,88 +782,6 @@ function matchRequestUrl(url, path, baseUrl) {
629
782
  };
630
783
  }
631
784
 
632
- // src/utils/request/MockedRequest.ts
633
- import * as cookieUtils3 from "cookie";
634
- import { store } from "@mswjs/cookies";
635
- import { IsomorphicRequest } from "@mswjs/interceptors";
636
- import { decodeBuffer } from "@mswjs/interceptors/lib/utils/bufferUtils";
637
- import { Headers as Headers2 } from "headers-polyfill";
638
-
639
- // src/utils/request/getRequestCookies.ts
640
- import * as cookieUtils2 from "cookie";
641
- function getAllCookies() {
642
- return cookieUtils2.parse(document.cookie);
643
- }
644
- function getRequestCookies(request) {
645
- if (typeof document === "undefined" || typeof location === "undefined") {
646
- return {};
647
- }
648
- switch (request.credentials) {
649
- case "same-origin": {
650
- return location.origin === request.url.origin ? getAllCookies() : {};
651
- }
652
- case "include": {
653
- return getAllCookies();
654
- }
655
- default: {
656
- return {};
657
- }
658
- }
659
- }
660
-
661
- // src/utils/request/MockedRequest.ts
662
- var MockedRequest = class extends IsomorphicRequest {
663
- constructor(url, init = {}) {
664
- super(url, init);
665
- if (init.id) {
666
- this.id = init.id;
667
- }
668
- this.cache = init.cache || "default";
669
- this.destination = init.destination || "";
670
- this.integrity = init.integrity || "";
671
- this.keepalive = init.keepalive || false;
672
- this.mode = init.mode || "cors";
673
- this.priority = init.priority || "auto";
674
- this.redirect = init.redirect || "follow";
675
- this.referrer = init.referrer || "";
676
- this.referrerPolicy = init.referrerPolicy || "no-referrer";
677
- this.cookies = init.cookies || this.getCookies();
678
- }
679
- get body() {
680
- const text2 = decodeBuffer(this["_body"]);
681
- const body2 = parseBody(text2, this.headers);
682
- if (isStringEqual(this.method, "GET") && body2 === "") {
683
- return void 0;
684
- }
685
- return body2;
686
- }
687
- passthrough() {
688
- return {
689
- status: 101,
690
- statusText: "Continue",
691
- headers: new Headers2(),
692
- body: null,
693
- passthrough: true,
694
- once: false
695
- };
696
- }
697
- getCookies() {
698
- var _a;
699
- const requestCookiesString = this.headers.get("cookie");
700
- const ownCookies = requestCookiesString ? cookieUtils3.parse(requestCookiesString) : {};
701
- store.hydrate();
702
- const cookiesFromStore = Array.from((_a = store.get(__spreadProps(__spreadValues({}, this), { url: this.url.href }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
703
- return Object.assign(cookies, { [name.trim()]: value });
704
- }, {});
705
- const cookiesFromDocument = getRequestCookies(this);
706
- const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
707
- for (const [name, value] of Object.entries(forwardedCookies)) {
708
- this.headers.append("cookie", `${name}=${value}`);
709
- }
710
- return __spreadValues(__spreadValues({}, forwardedCookies), ownCookies);
711
- }
712
- };
713
-
714
785
  // src/handlers/RequestHandler.ts
715
786
  import { Headers as Headers4 } from "headers-polyfill";
716
787
 
@@ -934,7 +1005,7 @@ var RestHandler = class extends RequestHandler {
934
1005
  };
935
1006
 
936
1007
  // src/context/field.ts
937
- import { invariant } from "outvariant";
1008
+ import { invariant as invariant2 } from "outvariant";
938
1009
  var field = (fieldName, fieldValue) => {
939
1010
  return (res) => {
940
1011
  validateFieldName(fieldName);
@@ -944,10 +1015,10 @@ var field = (fieldName, fieldValue) => {
944
1015
  };
945
1016
  };
946
1017
  function validateFieldName(fieldName) {
947
- invariant(fieldName.trim() !== "", devUtils.formatMessage("Failed to set a custom field on a GraphQL response: field name cannot be empty."));
948
- 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));
949
- 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));
950
- 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));
1018
+ invariant2(fieldName.trim() !== "", devUtils.formatMessage("Failed to set a custom field on a GraphQL response: field name cannot be empty."));
1019
+ invariant2(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));
1020
+ invariant2(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));
1021
+ invariant2(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));
951
1022
  }
952
1023
 
953
1024
  // src/utils/internal/tryCatch.ts
@@ -1205,53 +1276,27 @@ async function handleRequest(request, handlers, options, emitter, handleRequestO
1205
1276
  return transformedResponse;
1206
1277
  }
1207
1278
 
1208
- // src/utils/internal/pipeEvents.ts
1209
- function pipeEvents(source, destination) {
1210
- const rawEmit = source.emit;
1211
- if (rawEmit._isPiped) {
1212
- return;
1213
- }
1214
- source.emit = function(event, ...data2) {
1215
- destination.emit(event, ...data2);
1216
- return rawEmit.call(this, event, ...data2);
1217
- };
1218
- source.emit._isPiped = true;
1219
- }
1220
-
1221
- // src/utils/internal/toReadonlyArray.ts
1222
- function toReadonlyArray(source) {
1223
- const clone = [...source];
1224
- Object.freeze(clone);
1225
- return clone;
1226
- }
1227
-
1228
- // src/node/createSetupServer.ts
1279
+ // src/node/SetupServerApi.ts
1280
+ var { bold } = chalk;
1229
1281
  var DEFAULT_LISTEN_OPTIONS = {
1230
1282
  onUnhandledRequest: "warn"
1231
1283
  };
1232
- function createSetupServer(...interceptors) {
1233
- const emitter = new StrictEventEmitter();
1234
- const publicEmitter = new StrictEventEmitter();
1235
- pipeEvents(emitter, publicEmitter);
1236
- return function setupServer2(...requestHandlers) {
1237
- requestHandlers.forEach((handler) => {
1238
- if (Array.isArray(handler))
1239
- 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).'));
1240
- });
1241
- let currentHandlers = [...requestHandlers];
1242
- if (!isNodeProcess3()) {
1243
- 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."));
1244
- }
1245
- let resolvedOptions = {};
1246
- const interceptor = new BatchInterceptor({
1284
+ var SetupServerApi = class extends SetupApi {
1285
+ constructor(interceptors, handlers) {
1286
+ super(handlers);
1287
+ this.interceptor = new BatchInterceptor({
1247
1288
  name: "setup-server",
1248
1289
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
1249
1290
  });
1250
- interceptor.on("request", async function setupServerListener(request) {
1291
+ this.resolvedOptions = {};
1292
+ this.init();
1293
+ }
1294
+ init() {
1295
+ this.interceptor.on("request", async (request) => {
1251
1296
  const mockedRequest = new MockedRequest(request.url, __spreadProps(__spreadValues({}, request), {
1252
1297
  body: await request.arrayBuffer()
1253
1298
  }));
1254
- const response2 = await handleRequest(mockedRequest, currentHandlers, resolvedOptions, emitter, {
1299
+ const response2 = await handleRequest(mockedRequest, this.currentHandlers, this.resolvedOptions, this.emitter, {
1255
1300
  transformResponse(response3) {
1256
1301
  return {
1257
1302
  status: response3.status,
@@ -1272,65 +1317,42 @@ function createSetupServer(...interceptors) {
1272
1317
  }
1273
1318
  return;
1274
1319
  });
1275
- interceptor.on("response", (request, response2) => {
1320
+ this.interceptor.on("response", (request, response2) => {
1276
1321
  if (!request.id) {
1277
1322
  return;
1278
1323
  }
1279
1324
  if (response2.headers.get("x-powered-by") === "msw") {
1280
- emitter.emit("response:mocked", response2, request.id);
1325
+ this.emitter.emit("response:mocked", response2, request.id);
1281
1326
  } else {
1282
- emitter.emit("response:bypass", response2, request.id);
1327
+ this.emitter.emit("response:bypass", response2, request.id);
1283
1328
  }
1284
1329
  });
1285
- return {
1286
- listen(options) {
1287
- resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options || {});
1288
- interceptor.apply();
1289
- },
1290
- use(...handlers) {
1291
- use(currentHandlers, ...handlers);
1292
- },
1293
- restoreHandlers() {
1294
- restoreHandlers(currentHandlers);
1295
- },
1296
- resetHandlers(...nextHandlers) {
1297
- currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
1298
- },
1299
- listHandlers() {
1300
- return toReadonlyArray(currentHandlers);
1301
- },
1302
- printHandlers() {
1303
- const handlers = this.listHandlers();
1304
- handlers.forEach((handler) => {
1305
- const { header, callFrame } = handler.info;
1306
- const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1307
- console.log(`${bold(`${pragma} ${header}`)}
1330
+ }
1331
+ listen(options = {}) {
1332
+ this.resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options);
1333
+ this.interceptor.apply();
1334
+ invariant3([InterceptorReadyState.APPLYING, 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");
1335
+ }
1336
+ printHandlers() {
1337
+ const handlers = this.listHandlers();
1338
+ handlers.forEach((handler) => {
1339
+ const { header, callFrame } = handler.info;
1340
+ const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1341
+ console.log(`${bold(`${pragma} ${header}`)}
1308
1342
  Declaration: ${callFrame}
1309
1343
  `);
1310
- });
1311
- },
1312
- events: {
1313
- on(...args) {
1314
- return publicEmitter.on(...args);
1315
- },
1316
- removeListener(...args) {
1317
- return publicEmitter.removeListener(...args);
1318
- },
1319
- removeAllListeners(...args) {
1320
- return publicEmitter.removeAllListeners(...args);
1321
- }
1322
- },
1323
- close() {
1324
- emitter.removeAllListeners();
1325
- publicEmitter.removeAllListeners();
1326
- interceptor.dispose();
1327
- }
1328
- };
1329
- };
1330
- }
1344
+ });
1345
+ }
1346
+ close() {
1347
+ super.dispose();
1348
+ this.interceptor.dispose();
1349
+ }
1350
+ };
1331
1351
 
1332
1352
  // src/native/index.ts
1333
- var setupServer = createSetupServer(XMLHttpRequestInterceptor);
1353
+ function setupServer(...handlers) {
1354
+ return new SetupServerApi([XMLHttpRequestInterceptor], handlers);
1355
+ }
1334
1356
  export {
1335
1357
  setupServer
1336
1358
  };