msw 0.27.2 → 0.29.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.
Files changed (37) hide show
  1. package/cli/init.js +14 -6
  2. package/lib/esm/RequestHandler-deps.js +128 -136
  3. package/lib/esm/fetch-deps.js +405 -118
  4. package/lib/esm/graphql-deps.js +11 -11
  5. package/lib/esm/index.js +4123 -660
  6. package/lib/esm/mockServiceWorker.js +5 -4
  7. package/lib/esm/rest-deps.js +2 -2
  8. package/lib/iife/index.js +4 -4
  9. package/lib/iife/mockServiceWorker.js +5 -4
  10. package/lib/types/handlers/GraphQLHandler.d.ts +2 -2
  11. package/lib/types/handlers/RequestHandler.d.ts +1 -1
  12. package/lib/types/handlers/RestHandler.d.ts +2 -2
  13. package/lib/types/node/createSetupServer.d.ts +1 -1
  14. package/lib/types/node/glossary.d.ts +5 -4
  15. package/lib/types/setupWorker/glossary.d.ts +21 -16
  16. package/lib/types/setupWorker/start/createFallbackStart.d.ts +2 -0
  17. package/lib/types/setupWorker/start/createStartHandler.d.ts +2 -0
  18. package/lib/types/setupWorker/start/utils/enableMocking.d.ts +5 -0
  19. package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +9 -0
  20. package/lib/types/setupWorker/start/utils/printStartMessage.d.ts +7 -0
  21. package/lib/types/setupWorker/stop/createFallbackStop.d.ts +2 -0
  22. package/lib/types/setupWorker/stop/createStop.d.ts +2 -2
  23. package/lib/types/setupWorker/stop/utils/printStopMessage.d.ts +3 -0
  24. package/lib/types/sharedOptions.d.ts +3 -2
  25. package/lib/types/utils/getResponse.d.ts +2 -3
  26. package/lib/types/utils/handleRequest.d.ts +27 -0
  27. package/lib/types/utils/logging/prepareResponse.d.ts +3 -3
  28. package/lib/types/utils/request/parseIsomorphicRequest.d.ts +6 -0
  29. package/lib/types/utils/request/parseWorkerRequest.d.ts +4 -0
  30. package/lib/types/utils/worker/createFallbackRequestListener.d.ts +3 -0
  31. package/lib/umd/index.js +26209 -5348
  32. package/lib/umd/mockServiceWorker.js +5 -4
  33. package/native/lib/index.js +2456 -2108
  34. package/node/lib/index.js +2461 -2110
  35. package/package.json +34 -37
  36. package/lib/types/setupWorker/start/createStart.d.ts +0 -2
  37. package/lib/types/setupWorker/start/utils/activateMocking.d.ts +0 -2
package/cli/init.js CHANGED
@@ -1,13 +1,14 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
3
  const chalk = require('chalk')
4
+ const { until } = require('@open-draft/until')
4
5
  const inquirer = require('inquirer')
5
6
  const invariant = require('./invariant')
6
7
  const { SERVICE_WORKER_BUILD_PATH } = require('../config/constants')
7
8
 
8
9
  const CWD = process.cwd()
9
10
 
10
- module.exports = function init(args) {
11
+ module.exports = async function init(args) {
11
12
  const { publicDir, save } = args
12
13
 
13
14
  // When running as a part of "postinstall" script, "cwd" equals the library's directory.
@@ -18,11 +19,18 @@ module.exports = function init(args) {
18
19
  const relativePublicDir = path.relative(CWD, absolutePublicDir)
19
20
  const dirExists = fs.existsSync(absolutePublicDir)
20
21
 
21
- invariant(
22
- dirExists,
23
- 'Failed to create a Service Worker at "%s": directory does not exist.\nMake sure to include a relative path to the root directory of your server.',
24
- absolutePublicDir,
25
- )
22
+ if (!dirExists) {
23
+ // Try to create the directory if it doesn't exist
24
+ const [createDirectoryError] = await until(() =>
25
+ fs.promises.mkdir(absolutePublicDir, { recursive: true }),
26
+ )
27
+ invariant(
28
+ createDirectoryError == null,
29
+ 'Failed to create a Service Worker at "%s": directory does not exist and could not be created.\nMake sure to include a relative path to the root directory of your server.\n\nSee the original error below:\n%s',
30
+ absolutePublicDir,
31
+ createDirectoryError,
32
+ )
33
+ }
26
34
 
27
35
  console.log(
28
36
  'Initializing the Mock Service Worker at "%s"...',
@@ -1,11 +1,4 @@
1
- import { c as stringToHeaders, j as jsonParse, l as listToHeaders, H as Headers, s as status, a as set, d as delay, f as fetch } from './fetch-deps.js';
2
-
3
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4
-
5
- function createCommonjsModule(fn) {
6
- var module = { exports: {} };
7
- return fn(module, module.exports), module.exports;
8
- }
1
+ import { l as lib, j as jsonParse, c as commonjsGlobal, s as status, a as set, d as delay, f as fetch } from './fetch-deps.js';
9
2
 
10
3
  /*! *****************************************************************************
11
4
  Copyright (c) Microsoft Corporation.
@@ -44,9 +37,115 @@ function __awaiter(thisArg, _arguments, P, generator) {
44
37
  });
45
38
  }
46
39
 
40
+ class NetworkError extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = 'NetworkError';
44
+ }
45
+ }
46
+
47
+ function parseContentHeaders(headersString) {
48
+ var _a, _b;
49
+ const headers = lib.stringToHeaders(headersString);
50
+ const contentType = headers.get('content-type') || 'text/plain';
51
+ const disposition = headers.get('content-disposition');
52
+ if (!disposition) {
53
+ throw new Error('"Content-Disposition" header is required.');
54
+ }
55
+ const directives = disposition.split(';').reduce((acc, chunk) => {
56
+ const [name, ...rest] = chunk.trim().split('=');
57
+ acc[name] = rest.join('=');
58
+ return acc;
59
+ }, {});
60
+ const name = (_a = directives.name) === null || _a === void 0 ? void 0 : _a.slice(1, -1);
61
+ const filename = (_b = directives.filename) === null || _b === void 0 ? void 0 : _b.slice(1, -1);
62
+ return {
63
+ name,
64
+ filename,
65
+ contentType,
66
+ };
67
+ }
68
+ /**
69
+ * Parses a given string as a multipart/form-data.
70
+ * Does not throw an exception on an invalid multipart string.
71
+ */
72
+ function parseMultipartData(data, headers) {
73
+ const contentType = headers === null || headers === void 0 ? void 0 : headers.get('content-type');
74
+ if (!contentType) {
75
+ return undefined;
76
+ }
77
+ const [, ...directives] = contentType.split(/; */);
78
+ const boundary = directives
79
+ .filter((d) => d.startsWith('boundary='))
80
+ .map((s) => s.replace(/^boundary=/, ''))[0];
81
+ if (!boundary) {
82
+ return undefined;
83
+ }
84
+ const boundaryRegExp = new RegExp(`--+${boundary}`);
85
+ const fields = data
86
+ .split(boundaryRegExp)
87
+ .filter((chunk) => chunk.startsWith('\r\n') && chunk.endsWith('\r\n'))
88
+ .map((chunk) => chunk.trimStart().replace(/\r\n$/, ''));
89
+ if (!fields.length) {
90
+ return undefined;
91
+ }
92
+ const parsedBody = {};
93
+ try {
94
+ for (const field of fields) {
95
+ const [contentHeaders, ...rest] = field.split('\r\n\r\n');
96
+ const contentBody = rest.join('\r\n\r\n');
97
+ const { contentType, filename, name } = parseContentHeaders(contentHeaders);
98
+ const value = filename === undefined
99
+ ? contentBody
100
+ : new File([contentBody], filename, { type: contentType });
101
+ const parsedValue = parsedBody[name];
102
+ if (parsedValue === undefined) {
103
+ parsedBody[name] = value;
104
+ }
105
+ else if (Array.isArray(parsedValue)) {
106
+ parsedBody[name] = [...parsedValue, value];
107
+ }
108
+ else {
109
+ parsedBody[name] = [parsedValue, value];
110
+ }
111
+ }
112
+ return parsedBody;
113
+ }
114
+ catch (error) {
115
+ return undefined;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Parses a given request/response body based on the `Content-Type` header.
121
+ */
122
+ function parseBody(body, headers) {
123
+ // Return whatever falsey body value is given.
124
+ if (!body) {
125
+ return body;
126
+ }
127
+ const contentType = headers === null || headers === void 0 ? void 0 : headers.get('content-type');
128
+ // If the body has a Multipart Content-Type
129
+ // parse it into an object.
130
+ const hasMultipartContent = contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('multipart/form-data');
131
+ if (hasMultipartContent && typeof body !== 'object') {
132
+ return parseMultipartData(body, headers) || body;
133
+ }
134
+ // If the intercepted request's body has a JSON Content-Type
135
+ // parse it into an object.
136
+ const hasJsonContent = contentType === null || contentType === void 0 ? void 0 : contentType.includes('json');
137
+ if (hasJsonContent && typeof body !== 'object') {
138
+ return jsonParse(body) || body;
139
+ }
140
+ // Otherwise leave as-is.
141
+ return body;
142
+ }
143
+
144
+ var punycode$1 = {exports: {}};
145
+
47
146
  /*! https://mths.be/punycode v1.3.2 by @mathias */
48
147
 
49
- var punycode = createCommonjsModule(function (module, exports) {
148
+ (function (module, exports) {
50
149
  (function(root) {
51
150
 
52
151
  /** Detect free variables */
@@ -568,9 +667,9 @@ var punycode = createCommonjsModule(function (module, exports) {
568
667
  }
569
668
 
570
669
  }(commonjsGlobal));
571
- });
670
+ }(punycode$1, punycode$1.exports));
572
671
 
573
- var util = {
672
+ var util$1 = {
574
673
  isString: function(arg) {
575
674
  return typeof(arg) === 'string';
576
675
  },
@@ -585,7 +684,7 @@ var util = {
585
684
  }
586
685
  };
587
686
 
588
- // Copyright Joyent, Inc. and other Node contributors.
687
+ var querystring$1 = {};
589
688
 
590
689
  // If obj.hasOwnProperty has been overridden, then calling
591
690
  // obj.hasOwnProperty(prop) will break.
@@ -645,8 +744,6 @@ var decode = function(qs, sep, eq, options) {
645
744
  return obj;
646
745
  };
647
746
 
648
- // Copyright Joyent, Inc. and other Node contributors.
649
-
650
747
  var stringifyPrimitive = function(v) {
651
748
  switch (typeof v) {
652
749
  case 'string':
@@ -689,12 +786,11 @@ var encode = function(obj, sep, eq, name) {
689
786
  encodeURIComponent(stringifyPrimitive(obj));
690
787
  };
691
788
 
692
- var querystring = createCommonjsModule(function (module, exports) {
693
-
694
- exports.decode = exports.parse = decode;
695
- exports.encode = exports.stringify = encode;
696
- });
789
+ querystring$1.decode = querystring$1.parse = decode;
790
+ querystring$1.encode = querystring$1.stringify = encode;
697
791
 
792
+ var punycode = punycode$1.exports;
793
+ var util = util$1;
698
794
  var format = urlFormat;
699
795
 
700
796
  function Url() {
@@ -762,7 +858,8 @@ var protocolPattern = /^([a-z0-9.+-]+:)/i,
762
858
  'ftp:': true,
763
859
  'gopher:': true,
764
860
  'file:': true
765
- };
861
+ },
862
+ querystring = querystring$1;
766
863
 
767
864
  function urlParse(url, parseQueryString, slashesDenoteHost) {
768
865
  if (url && util.isObject(url) && url instanceof Url) return url;
@@ -1427,111 +1524,14 @@ function getTimestamp() {
1427
1524
  * Formats a mocked request for introspection in browser's console.
1428
1525
  */
1429
1526
  function prepareRequest(request) {
1430
- return Object.assign(Object.assign({}, request), { headers: request.headers.getAllHeaders() });
1431
- }
1432
-
1433
- function parseContentHeaders(headersString) {
1434
- var _a, _b;
1435
- const headers = stringToHeaders(headersString);
1436
- const contentType = headers.get('content-type') || 'text/plain';
1437
- const disposition = headers.get('content-disposition');
1438
- if (!disposition) {
1439
- throw new Error('"Content-Disposition" header is required.');
1440
- }
1441
- const directives = disposition.split(';').reduce((acc, chunk) => {
1442
- const [name, ...rest] = chunk.trim().split('=');
1443
- acc[name] = rest.join('=');
1444
- return acc;
1445
- }, {});
1446
- const name = (_a = directives.name) === null || _a === void 0 ? void 0 : _a.slice(1, -1);
1447
- const filename = (_b = directives.filename) === null || _b === void 0 ? void 0 : _b.slice(1, -1);
1448
- return {
1449
- name,
1450
- filename,
1451
- contentType,
1452
- };
1453
- }
1454
- /**
1455
- * Parses a given string as a multipart/form-data.
1456
- * Does not throw an exception on an invalid multipart string.
1457
- */
1458
- function parseMultipartData(data, headers) {
1459
- const contentType = headers === null || headers === void 0 ? void 0 : headers.get('content-type');
1460
- if (!contentType) {
1461
- return undefined;
1462
- }
1463
- const [, ...directives] = contentType.split('; ');
1464
- const boundary = directives
1465
- .filter((d) => d.startsWith('boundary='))
1466
- .map((s) => s.replace(/^boundary=/, ''))[0];
1467
- if (!boundary) {
1468
- return undefined;
1469
- }
1470
- const boundaryRegExp = new RegExp(`--+${boundary}`);
1471
- const fields = data
1472
- .split(boundaryRegExp)
1473
- .filter((chunk) => chunk.startsWith('\r\n') && chunk.endsWith('\r\n'))
1474
- .map((chunk) => chunk.trimStart().replace(/\r\n$/, ''));
1475
- if (!fields.length) {
1476
- return undefined;
1477
- }
1478
- const parsedBody = {};
1479
- try {
1480
- for (const field of fields) {
1481
- const [contentHeaders, ...rest] = field.split('\r\n\r\n');
1482
- const contentBody = rest.join('\r\n\r\n');
1483
- const { contentType, filename, name } = parseContentHeaders(contentHeaders);
1484
- const value = filename === undefined
1485
- ? contentBody
1486
- : new File([contentBody], filename, { type: contentType });
1487
- const parsedValue = parsedBody[name];
1488
- if (parsedValue === undefined) {
1489
- parsedBody[name] = value;
1490
- }
1491
- else if (Array.isArray(parsedValue)) {
1492
- parsedBody[name] = [...parsedValue, value];
1493
- }
1494
- else {
1495
- parsedBody[name] = [parsedValue, value];
1496
- }
1497
- }
1498
- return parsedBody;
1499
- }
1500
- catch (error) {
1501
- return undefined;
1502
- }
1503
- }
1504
-
1505
- /**
1506
- * Parses a given request/response body based on the `Content-Type` header.
1507
- */
1508
- function parseBody(body, headers) {
1509
- if (body) {
1510
- const contentType = headers === null || headers === void 0 ? void 0 : headers.get('content-type');
1511
- // If the body has a Multipart Content-Type
1512
- // parse it into an object.
1513
- const hasMultipartContent = contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('multipart/form-data');
1514
- if (hasMultipartContent && typeof body !== 'object') {
1515
- return parseMultipartData(body, headers) || body;
1516
- }
1517
- // If the intercepted request's body has a JSON Content-Type
1518
- // parse it into an object.
1519
- const hasJsonContent = contentType === null || contentType === void 0 ? void 0 : contentType.includes('json');
1520
- if (hasJsonContent && typeof body !== 'object') {
1521
- return jsonParse(body) || body;
1522
- }
1523
- // Otherwise leave as-is.
1524
- return body;
1525
- }
1526
- // Return whatever falsey body value is given.
1527
- return body;
1527
+ return Object.assign(Object.assign({}, request), { headers: request.headers.all() });
1528
1528
  }
1529
1529
 
1530
1530
  /**
1531
1531
  * Formats a mocked response for introspection in browser's console.
1532
1532
  */
1533
1533
  function prepareResponse(res) {
1534
- const responseHeaders = listToHeaders(res.headers);
1534
+ const responseHeaders = lib.objectToHeaders(res.headers);
1535
1535
  return Object.assign(Object.assign({}, res), {
1536
1536
  // Parse a response JSON body for preview in the logs
1537
1537
  body: parseBody(res.body, responseHeaders) });
@@ -1576,9 +1576,10 @@ const match = (path, url) => {
1576
1576
  };
1577
1577
  };
1578
1578
 
1579
- var getCleanUrl_1 = createCommonjsModule(function (module, exports) {
1580
- Object.defineProperty(exports, "__esModule", { value: true });
1581
- exports.getCleanUrl = void 0;
1579
+ var getCleanUrl$1 = {};
1580
+
1581
+ Object.defineProperty(getCleanUrl$1, "__esModule", { value: true });
1582
+ var getCleanUrl_2 = getCleanUrl$1.getCleanUrl = void 0;
1582
1583
  /**
1583
1584
  * Removes query parameters and hashes from a given URL.
1584
1585
  */
@@ -1586,9 +1587,7 @@ function getCleanUrl(url, isAbsolute) {
1586
1587
  if (isAbsolute === void 0) { isAbsolute = true; }
1587
1588
  return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('');
1588
1589
  }
1589
- exports.getCleanUrl = getCleanUrl;
1590
-
1591
- });
1590
+ getCleanUrl_2 = getCleanUrl$1.getCleanUrl = getCleanUrl;
1592
1591
 
1593
1592
  /**
1594
1593
  * Returns an absolute URL based on the given relative URL, if possible.
@@ -1629,7 +1628,7 @@ function getUrlByMask(mask) {
1629
1628
 
1630
1629
  function getCleanMask(resolvedMask) {
1631
1630
  return resolvedMask instanceof URL
1632
- ? getCleanUrl_1.getCleanUrl(resolvedMask)
1631
+ ? getCleanUrl_2(resolvedMask)
1633
1632
  : resolvedMask instanceof RegExp
1634
1633
  ? resolvedMask
1635
1634
  : getAbsoluteUrl(resolvedMask);
@@ -1642,7 +1641,7 @@ function getCleanMask(resolvedMask) {
1642
1641
  function matchRequestUrl(url, mask) {
1643
1642
  const resolvedMask = getUrlByMask(mask);
1644
1643
  const cleanMask = getCleanMask(resolvedMask);
1645
- const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);
1644
+ const cleanRequestUrl = getCleanUrl_2(url);
1646
1645
  return match(cleanMask, cleanRequestUrl);
1647
1646
  }
1648
1647
 
@@ -1660,13 +1659,6 @@ function compose(...fns) {
1660
1659
  };
1661
1660
  }
1662
1661
 
1663
- class NetworkError extends Error {
1664
- constructor(message) {
1665
- super(message);
1666
- this.name = 'NetworkError';
1667
- }
1668
- }
1669
-
1670
1662
  const defaultResponse = {
1671
1663
  status: 200,
1672
1664
  statusText: 'OK',
@@ -1678,7 +1670,7 @@ const defaultResponseTransformers = [];
1678
1670
  function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {
1679
1671
  return (...transformers) => __awaiter(this, void 0, void 0, function* () {
1680
1672
  const initialResponse = Object.assign({}, defaultResponse, {
1681
- headers: new Headers({
1673
+ headers: new lib.Headers({
1682
1674
  'x-powered-by': 'msw',
1683
1675
  }),
1684
1676
  }, responseOverrides);
@@ -1788,4 +1780,4 @@ class RequestHandler {
1788
1780
  }
1789
1781
  }
1790
1782
 
1791
- export { NetworkError as N, RequestHandler as R, __awaiter as _, commonjsGlobal as a, createResponseComposition as b, createCommonjsModule as c, defaultResponse as d, defaultContext as e, compose as f, getPublicUrlFromRequest as g, getUrlByMask as h, prepareRequest as i, prepareResponse as j, getTimestamp as k, getStatusCodeColor as l, matchRequestUrl as m, __rest as n, parseBody as p, response as r };
1783
+ export { NetworkError as N, RequestHandler as R, __awaiter as _, getCleanUrl$1 as a, defaultContext as b, createResponseComposition as c, defaultResponse as d, compose as e, getUrlByMask as f, getPublicUrlFromRequest as g, prepareRequest as h, prepareResponse as i, getTimestamp as j, getStatusCodeColor as k, __rest as l, matchRequestUrl as m, parseBody as p, response as r };