msw 0.40.2 → 0.42.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/config/constants.js +1 -3
- package/config/scripts/postinstall.js +32 -25
- package/lib/glossary-58eca5a8.d.ts +332 -0
- package/lib/iife/index.js +10911 -21
- package/lib/iife/index.js.map +1 -0
- package/lib/index.d.ts +353 -0
- package/lib/index.js +1875 -0
- package/lib/index.js.map +1 -0
- package/lib/{esm/mockServiceWorker.js → mockServiceWorker.js} +1 -1
- package/lib/native/index.d.ts +9 -0
- package/lib/native/index.js +1304 -0
- package/lib/native/index.mjs +1291 -0
- package/lib/node/index.d.ts +15 -0
- package/lib/node/index.js +1312 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/index.mjs +1297 -0
- package/lib/node/index.mjs.map +1 -0
- package/native/package.json +3 -2
- package/node/package.json +3 -2
- package/package.json +14 -24
- package/lib/esm/errors-deps.js +0 -74
- package/lib/esm/fetch-deps.js +0 -1005
- package/lib/esm/graphql-deps.js +0 -3545
- package/lib/esm/graphql.js +0 -5
- package/lib/esm/index-deps.js +0 -21
- package/lib/esm/index.js +0 -1731
- package/lib/esm/index2.js +0 -3
- package/lib/esm/matchRequestUrl-deps.js +0 -992
- package/lib/esm/rest-deps.js +0 -103
- package/lib/esm/rest.js +0 -5
- package/lib/esm/xml-deps.js +0 -44
- package/lib/iife/mockServiceWorker.js +0 -338
- package/lib/types/context/body.d.ts +0 -9
- package/lib/types/context/cookie.d.ts +0 -7
- package/lib/types/context/data.d.ts +0 -8
- package/lib/types/context/delay.d.ts +0 -15
- package/lib/types/context/errors.d.ts +0 -8
- package/lib/types/context/extensions.d.ts +0 -8
- package/lib/types/context/fetch.d.ts +0 -9
- package/lib/types/context/index.d.ts +0 -12
- package/lib/types/context/json.d.ts +0 -12
- package/lib/types/context/set.d.ts +0 -18
- package/lib/types/context/status.d.ts +0 -9
- package/lib/types/context/text.d.ts +0 -8
- package/lib/types/context/xml.d.ts +0 -9
- package/lib/types/graphql.d.ts +0 -74
- package/lib/types/handlers/GraphQLHandler.d.ts +0 -39
- package/lib/types/handlers/RequestHandler.d.ts +0 -103
- package/lib/types/handlers/RestHandler.d.ts +0 -47
- package/lib/types/index.d.ts +0 -26
- package/lib/types/native/index.d.ts +0 -1
- package/lib/types/node/createSetupServer.d.ts +0 -8
- package/lib/types/node/glossary.d.ts +0 -38
- package/lib/types/node/index.d.ts +0 -2
- package/lib/types/node/setupServer.d.ts +0 -6
- package/lib/types/response.d.ts +0 -35
- package/lib/types/rest.d.ts +0 -13
- package/lib/types/setupWorker/glossary.d.ts +0 -161
- package/lib/types/setupWorker/setupWorker.d.ts +0 -9
- package/lib/types/setupWorker/start/createFallbackStart.d.ts +0 -2
- package/lib/types/setupWorker/start/createStartHandler.d.ts +0 -2
- package/lib/types/setupWorker/start/utils/enableMocking.d.ts +0 -5
- package/lib/types/setupWorker/start/utils/getWorkerByRegistration.d.ts +0 -6
- package/lib/types/setupWorker/start/utils/getWorkerInstance.d.ts +0 -6
- package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +0 -9
- package/lib/types/setupWorker/start/utils/printStartMessage.d.ts +0 -10
- package/lib/types/setupWorker/start/utils/validateWorkerScope.d.ts +0 -2
- package/lib/types/setupWorker/stop/createFallbackStop.d.ts +0 -2
- package/lib/types/setupWorker/stop/createStop.d.ts +0 -2
- package/lib/types/setupWorker/stop/utils/printStopMessage.d.ts +0 -3
- package/lib/types/sharedOptions.d.ts +0 -24
- package/lib/types/typeUtils.d.ts +0 -7
- package/lib/types/utils/NetworkError.d.ts +0 -3
- package/lib/types/utils/createBroadcastChannel.d.ts +0 -18
- package/lib/types/utils/deferNetworkRequestsUntil.d.ts +0 -6
- package/lib/types/utils/getResponse.d.ts +0 -15
- package/lib/types/utils/handleRequest.d.ts +0 -34
- package/lib/types/utils/internal/compose.d.ts +0 -14
- package/lib/types/utils/internal/devUtils.d.ts +0 -18
- package/lib/types/utils/internal/getCallFrame.d.ts +0 -4
- package/lib/types/utils/internal/isIterable.d.ts +0 -4
- package/lib/types/utils/internal/isObject.d.ts +0 -4
- package/lib/types/utils/internal/isStringEqual.d.ts +0 -4
- package/lib/types/utils/internal/jsonParse.d.ts +0 -5
- package/lib/types/utils/internal/mergeRight.d.ts +0 -5
- package/lib/types/utils/internal/parseGraphQLRequest.d.ts +0 -23
- package/lib/types/utils/internal/parseMultipartData.d.ts +0 -6
- package/lib/types/utils/internal/pipeEvents.d.ts +0 -6
- package/lib/types/utils/internal/requestHandlerUtils.d.ts +0 -4
- package/lib/types/utils/internal/requestIntegrityCheck.d.ts +0 -2
- package/lib/types/utils/internal/tryCatch.d.ts +0 -1
- package/lib/types/utils/internal/uuidv4.d.ts +0 -1
- package/lib/types/utils/logging/getStatusCodeColor.d.ts +0 -9
- package/lib/types/utils/logging/getTimestamp.d.ts +0 -4
- package/lib/types/utils/logging/prepareRequest.d.ts +0 -23
- package/lib/types/utils/logging/prepareResponse.d.ts +0 -10
- package/lib/types/utils/matching/matchRequestUrl.d.ts +0 -17
- package/lib/types/utils/matching/normalizePath.d.ts +0 -9
- package/lib/types/utils/request/getPublicUrlFromRequest.d.ts +0 -6
- package/lib/types/utils/request/getRequestCookies.d.ts +0 -7
- package/lib/types/utils/request/onUnhandledRequest.d.ts +0 -8
- package/lib/types/utils/request/parseBody.d.ts +0 -5
- package/lib/types/utils/request/parseIsomorphicRequest.d.ts +0 -6
- package/lib/types/utils/request/parseWorkerRequest.d.ts +0 -7
- package/lib/types/utils/request/pruneGetRequestBody.d.ts +0 -7
- package/lib/types/utils/request/readResponseCookies.d.ts +0 -3
- package/lib/types/utils/request/setRequestCookies.d.ts +0 -9
- package/lib/types/utils/url/cleanUrl.d.ts +0 -5
- package/lib/types/utils/url/getAbsoluteUrl.d.ts +0 -4
- package/lib/types/utils/url/getAbsoluteWorkerUrl.d.ts +0 -5
- package/lib/types/utils/url/isAbsoluteUrl.d.ts +0 -4
- package/lib/types/utils/worker/createFallbackRequestListener.d.ts +0 -4
- package/lib/types/utils/worker/createRequestListener.d.ts +0 -4
- package/lib/types/utils/worker/createResponseListener.d.ts +0 -3
- package/lib/umd/index.js +0 -31617
- package/lib/umd/mockServiceWorker.js +0 -338
- package/native/lib/index.js +0 -6384
- package/node/lib/index.js +0 -8276
package/lib/esm/rest-deps.js
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import { e as defaultContext, R as RequestHandler, h as cleanUrl, i as getSearchParams, d as devUtils, m as matchRequestUrl, g as getPublicUrlFromRequest, j as prepareRequest, k as prepareResponse, l as getStatusCodeColor, n as getTimestamp } from './matchRequestUrl-deps.js';
|
|
2
|
-
import { d as cookie, g as json } from './fetch-deps.js';
|
|
3
|
-
import { b as body, t as text, x as xml } from './xml-deps.js';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Performs a case-insensitive comparison of two given strings.
|
|
7
|
-
*/
|
|
8
|
-
function isStringEqual(actual, expected) {
|
|
9
|
-
return actual.toLowerCase() === expected.toLowerCase();
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
var RESTMethods;
|
|
13
|
-
(function (RESTMethods) {
|
|
14
|
-
RESTMethods["HEAD"] = "HEAD";
|
|
15
|
-
RESTMethods["GET"] = "GET";
|
|
16
|
-
RESTMethods["POST"] = "POST";
|
|
17
|
-
RESTMethods["PUT"] = "PUT";
|
|
18
|
-
RESTMethods["PATCH"] = "PATCH";
|
|
19
|
-
RESTMethods["OPTIONS"] = "OPTIONS";
|
|
20
|
-
RESTMethods["DELETE"] = "DELETE";
|
|
21
|
-
})(RESTMethods || (RESTMethods = {}));
|
|
22
|
-
const restContext = Object.assign(Object.assign({}, defaultContext), { cookie,
|
|
23
|
-
body,
|
|
24
|
-
text,
|
|
25
|
-
json,
|
|
26
|
-
xml });
|
|
27
|
-
/**
|
|
28
|
-
* Request handler for REST API requests.
|
|
29
|
-
* Provides request matching based on method and URL.
|
|
30
|
-
*/
|
|
31
|
-
class RestHandler extends RequestHandler {
|
|
32
|
-
constructor(method, path, resolver) {
|
|
33
|
-
super({
|
|
34
|
-
info: {
|
|
35
|
-
header: `${method} ${path}`,
|
|
36
|
-
path,
|
|
37
|
-
method,
|
|
38
|
-
},
|
|
39
|
-
ctx: restContext,
|
|
40
|
-
resolver,
|
|
41
|
-
});
|
|
42
|
-
this.checkRedundantQueryParameters();
|
|
43
|
-
}
|
|
44
|
-
checkRedundantQueryParameters() {
|
|
45
|
-
const { method, path } = this.info;
|
|
46
|
-
if (path instanceof RegExp) {
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
const url = cleanUrl(path);
|
|
50
|
-
// Bypass request handler URLs that have no redundant characters.
|
|
51
|
-
if (url === path) {
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
const searchParams = getSearchParams(path);
|
|
55
|
-
searchParams.forEach((_, paramName) => {
|
|
56
|
-
});
|
|
57
|
-
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".`);
|
|
58
|
-
}
|
|
59
|
-
parse(request, resolutionContext) {
|
|
60
|
-
return matchRequestUrl(request.url, this.info.path, resolutionContext === null || resolutionContext === void 0 ? void 0 : resolutionContext.baseUrl);
|
|
61
|
-
}
|
|
62
|
-
getPublicRequest(request, parsedResult) {
|
|
63
|
-
return Object.assign(Object.assign({}, request), { params: parsedResult.params || {} });
|
|
64
|
-
}
|
|
65
|
-
predicate(request, parsedResult) {
|
|
66
|
-
const matchesMethod = this.info.method instanceof RegExp
|
|
67
|
-
? this.info.method.test(request.method)
|
|
68
|
-
: isStringEqual(this.info.method, request.method);
|
|
69
|
-
return matchesMethod && parsedResult.matches;
|
|
70
|
-
}
|
|
71
|
-
log(request, response) {
|
|
72
|
-
const publicUrl = getPublicUrlFromRequest(request);
|
|
73
|
-
const loggedRequest = prepareRequest(request);
|
|
74
|
-
const loggedResponse = prepareResponse(response);
|
|
75
|
-
const statusColor = getStatusCodeColor(response.status);
|
|
76
|
-
console.groupCollapsed(devUtils.formatMessage('%s %s %s (%c%s%c)'), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit');
|
|
77
|
-
console.log('Request', loggedRequest);
|
|
78
|
-
console.log('Handler:', {
|
|
79
|
-
mask: this.info.path,
|
|
80
|
-
resolver: this.resolver,
|
|
81
|
-
});
|
|
82
|
-
console.log('Response', loggedResponse);
|
|
83
|
-
console.groupEnd();
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function createRestHandler(method) {
|
|
88
|
-
return (path, resolver) => {
|
|
89
|
-
return new RestHandler(method, path, resolver);
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
const rest = {
|
|
93
|
-
all: createRestHandler(/.+/),
|
|
94
|
-
head: createRestHandler(RESTMethods.HEAD),
|
|
95
|
-
get: createRestHandler(RESTMethods.GET),
|
|
96
|
-
post: createRestHandler(RESTMethods.POST),
|
|
97
|
-
put: createRestHandler(RESTMethods.PUT),
|
|
98
|
-
delete: createRestHandler(RESTMethods.DELETE),
|
|
99
|
-
patch: createRestHandler(RESTMethods.PATCH),
|
|
100
|
-
options: createRestHandler(RESTMethods.OPTIONS),
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
export { RestHandler as R, RESTMethods as a, restContext as b, isStringEqual as i, rest as r };
|
package/lib/esm/rest.js
DELETED
package/lib/esm/xml-deps.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sets a raw response body. Does not append any `Content-Type` headers.
|
|
3
|
-
* @example
|
|
4
|
-
* res(ctx.body('Successful response'))
|
|
5
|
-
* res(ctx.body(JSON.stringify({ key: 'value' })))
|
|
6
|
-
* @see {@link https://mswjs.io/docs/api/context/body `ctx.body()`}
|
|
7
|
-
*/
|
|
8
|
-
const body = (value) => {
|
|
9
|
-
return (res) => {
|
|
10
|
-
res.body = value;
|
|
11
|
-
return res;
|
|
12
|
-
};
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Sets a textual response body. Appends a `Content-Type: text/plain`
|
|
17
|
-
* header on the mocked response.
|
|
18
|
-
* @example res(ctx.text('Successful response'))
|
|
19
|
-
* @see {@link https://mswjs.io/docs/api/context/text `ctx.text()`}
|
|
20
|
-
*/
|
|
21
|
-
const text = (body) => {
|
|
22
|
-
return (res) => {
|
|
23
|
-
res.headers.set('Content-Type', 'text/plain');
|
|
24
|
-
res.body = body;
|
|
25
|
-
return res;
|
|
26
|
-
};
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Sets an XML response body. Appends a `Content-Type: text/xml` header
|
|
31
|
-
* on the mocked response.
|
|
32
|
-
* @example
|
|
33
|
-
* res(ctx.xml('<node key="value">Content</node>'))
|
|
34
|
-
* @see {@link https://mswjs.io/docs/api/context/xml `ctx.xml()`}
|
|
35
|
-
*/
|
|
36
|
-
const xml = (body) => {
|
|
37
|
-
return (res) => {
|
|
38
|
-
res.headers.set('Content-Type', 'text/xml');
|
|
39
|
-
res.body = body;
|
|
40
|
-
return res;
|
|
41
|
-
};
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
export { body as b, text as t, xml as x };
|
|
@@ -1,338 +0,0 @@
|
|
|
1
|
-
/* eslint-disable */
|
|
2
|
-
/* tslint:disable */
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Mock Service Worker (0.40.2).
|
|
6
|
-
* @see https://github.com/mswjs/msw
|
|
7
|
-
* - Please do NOT modify this file.
|
|
8
|
-
* - Please do NOT serve this file on production.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
const INTEGRITY_CHECKSUM = '02f4ad4a2797f85668baf196e553d929'
|
|
12
|
-
const bypassHeaderName = 'x-msw-bypass'
|
|
13
|
-
const activeClientIds = new Set()
|
|
14
|
-
|
|
15
|
-
self.addEventListener('install', function () {
|
|
16
|
-
return self.skipWaiting()
|
|
17
|
-
})
|
|
18
|
-
|
|
19
|
-
self.addEventListener('activate', async function (event) {
|
|
20
|
-
return self.clients.claim()
|
|
21
|
-
})
|
|
22
|
-
|
|
23
|
-
self.addEventListener('message', async function (event) {
|
|
24
|
-
const clientId = event.source.id
|
|
25
|
-
|
|
26
|
-
if (!clientId || !self.clients) {
|
|
27
|
-
return
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const client = await self.clients.get(clientId)
|
|
31
|
-
|
|
32
|
-
if (!client) {
|
|
33
|
-
return
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const allClients = await self.clients.matchAll()
|
|
37
|
-
|
|
38
|
-
switch (event.data) {
|
|
39
|
-
case 'KEEPALIVE_REQUEST': {
|
|
40
|
-
sendToClient(client, {
|
|
41
|
-
type: 'KEEPALIVE_RESPONSE',
|
|
42
|
-
})
|
|
43
|
-
break
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
case 'INTEGRITY_CHECK_REQUEST': {
|
|
47
|
-
sendToClient(client, {
|
|
48
|
-
type: 'INTEGRITY_CHECK_RESPONSE',
|
|
49
|
-
payload: INTEGRITY_CHECKSUM,
|
|
50
|
-
})
|
|
51
|
-
break
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
case 'MOCK_ACTIVATE': {
|
|
55
|
-
activeClientIds.add(clientId)
|
|
56
|
-
|
|
57
|
-
sendToClient(client, {
|
|
58
|
-
type: 'MOCKING_ENABLED',
|
|
59
|
-
payload: true,
|
|
60
|
-
})
|
|
61
|
-
break
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
case 'MOCK_DEACTIVATE': {
|
|
65
|
-
activeClientIds.delete(clientId)
|
|
66
|
-
break
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
case 'CLIENT_CLOSED': {
|
|
70
|
-
activeClientIds.delete(clientId)
|
|
71
|
-
|
|
72
|
-
const remainingClients = allClients.filter((client) => {
|
|
73
|
-
return client.id !== clientId
|
|
74
|
-
})
|
|
75
|
-
|
|
76
|
-
// Unregister itself when there are no more clients
|
|
77
|
-
if (remainingClients.length === 0) {
|
|
78
|
-
self.registration.unregister()
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
break
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
})
|
|
85
|
-
|
|
86
|
-
// Resolve the "main" client for the given event.
|
|
87
|
-
// Client that issues a request doesn't necessarily equal the client
|
|
88
|
-
// that registered the worker. It's with the latter the worker should
|
|
89
|
-
// communicate with during the response resolving phase.
|
|
90
|
-
async function resolveMainClient(event) {
|
|
91
|
-
const client = await self.clients.get(event.clientId)
|
|
92
|
-
|
|
93
|
-
if (client.frameType === 'top-level') {
|
|
94
|
-
return client
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const allClients = await self.clients.matchAll()
|
|
98
|
-
|
|
99
|
-
return allClients
|
|
100
|
-
.filter((client) => {
|
|
101
|
-
// Get only those clients that are currently visible.
|
|
102
|
-
return client.visibilityState === 'visible'
|
|
103
|
-
})
|
|
104
|
-
.find((client) => {
|
|
105
|
-
// Find the client ID that's recorded in the
|
|
106
|
-
// set of clients that have registered the worker.
|
|
107
|
-
return activeClientIds.has(client.id)
|
|
108
|
-
})
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
async function handleRequest(event, requestId) {
|
|
112
|
-
const client = await resolveMainClient(event)
|
|
113
|
-
const response = await getResponse(event, client, requestId)
|
|
114
|
-
|
|
115
|
-
// Send back the response clone for the "response:*" life-cycle events.
|
|
116
|
-
// Ensure MSW is active and ready to handle the message, otherwise
|
|
117
|
-
// this message will pend indefinitely.
|
|
118
|
-
if (client && activeClientIds.has(client.id)) {
|
|
119
|
-
;(async function () {
|
|
120
|
-
const clonedResponse = response.clone()
|
|
121
|
-
sendToClient(client, {
|
|
122
|
-
type: 'RESPONSE',
|
|
123
|
-
payload: {
|
|
124
|
-
requestId,
|
|
125
|
-
type: clonedResponse.type,
|
|
126
|
-
ok: clonedResponse.ok,
|
|
127
|
-
status: clonedResponse.status,
|
|
128
|
-
statusText: clonedResponse.statusText,
|
|
129
|
-
body:
|
|
130
|
-
clonedResponse.body === null ? null : await clonedResponse.text(),
|
|
131
|
-
headers: serializeHeaders(clonedResponse.headers),
|
|
132
|
-
redirected: clonedResponse.redirected,
|
|
133
|
-
},
|
|
134
|
-
})
|
|
135
|
-
})()
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
return response
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
async function getResponse(event, client, requestId) {
|
|
142
|
-
const { request } = event
|
|
143
|
-
const requestClone = request.clone()
|
|
144
|
-
const getOriginalResponse = () => fetch(requestClone)
|
|
145
|
-
|
|
146
|
-
// Bypass mocking when the request client is not active.
|
|
147
|
-
if (!client) {
|
|
148
|
-
return getOriginalResponse()
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// Bypass initial page load requests (i.e. static assets).
|
|
152
|
-
// The absence of the immediate/parent client in the map of the active clients
|
|
153
|
-
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
|
154
|
-
// and is not ready to handle requests.
|
|
155
|
-
if (!activeClientIds.has(client.id)) {
|
|
156
|
-
return await getOriginalResponse()
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// Bypass requests with the explicit bypass header
|
|
160
|
-
if (requestClone.headers.get(bypassHeaderName) === 'true') {
|
|
161
|
-
const cleanRequestHeaders = serializeHeaders(requestClone.headers)
|
|
162
|
-
|
|
163
|
-
// Remove the bypass header to comply with the CORS preflight check.
|
|
164
|
-
delete cleanRequestHeaders[bypassHeaderName]
|
|
165
|
-
|
|
166
|
-
const originalRequest = new Request(requestClone, {
|
|
167
|
-
headers: new Headers(cleanRequestHeaders),
|
|
168
|
-
})
|
|
169
|
-
|
|
170
|
-
return fetch(originalRequest)
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// Send the request to the client-side MSW.
|
|
174
|
-
const reqHeaders = serializeHeaders(request.headers)
|
|
175
|
-
const body = await request.text()
|
|
176
|
-
|
|
177
|
-
const clientMessage = await sendToClient(client, {
|
|
178
|
-
type: 'REQUEST',
|
|
179
|
-
payload: {
|
|
180
|
-
id: requestId,
|
|
181
|
-
url: request.url,
|
|
182
|
-
method: request.method,
|
|
183
|
-
headers: reqHeaders,
|
|
184
|
-
cache: request.cache,
|
|
185
|
-
mode: request.mode,
|
|
186
|
-
credentials: request.credentials,
|
|
187
|
-
destination: request.destination,
|
|
188
|
-
integrity: request.integrity,
|
|
189
|
-
redirect: request.redirect,
|
|
190
|
-
referrer: request.referrer,
|
|
191
|
-
referrerPolicy: request.referrerPolicy,
|
|
192
|
-
body,
|
|
193
|
-
bodyUsed: request.bodyUsed,
|
|
194
|
-
keepalive: request.keepalive,
|
|
195
|
-
},
|
|
196
|
-
})
|
|
197
|
-
|
|
198
|
-
switch (clientMessage.type) {
|
|
199
|
-
case 'MOCK_SUCCESS': {
|
|
200
|
-
return delayPromise(
|
|
201
|
-
() => respondWithMock(clientMessage),
|
|
202
|
-
clientMessage.payload.delay,
|
|
203
|
-
)
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
case 'MOCK_NOT_FOUND': {
|
|
207
|
-
return getOriginalResponse()
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
case 'NETWORK_ERROR': {
|
|
211
|
-
const { name, message } = clientMessage.payload
|
|
212
|
-
const networkError = new Error(message)
|
|
213
|
-
networkError.name = name
|
|
214
|
-
|
|
215
|
-
// Rejecting a request Promise emulates a network error.
|
|
216
|
-
throw networkError
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
case 'INTERNAL_ERROR': {
|
|
220
|
-
const parsedBody = JSON.parse(clientMessage.payload.body)
|
|
221
|
-
|
|
222
|
-
console.error(
|
|
223
|
-
`\
|
|
224
|
-
[MSW] Uncaught exception in the request handler for "%s %s":
|
|
225
|
-
|
|
226
|
-
${parsedBody.location}
|
|
227
|
-
|
|
228
|
-
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
|
|
229
|
-
`,
|
|
230
|
-
request.method,
|
|
231
|
-
request.url,
|
|
232
|
-
)
|
|
233
|
-
|
|
234
|
-
return respondWithMock(clientMessage)
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
return getOriginalResponse()
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
self.addEventListener('fetch', function (event) {
|
|
242
|
-
const { request } = event
|
|
243
|
-
const accept = request.headers.get('accept') || ''
|
|
244
|
-
|
|
245
|
-
// Bypass server-sent events.
|
|
246
|
-
if (accept.includes('text/event-stream')) {
|
|
247
|
-
return
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// Bypass navigation requests.
|
|
251
|
-
if (request.mode === 'navigate') {
|
|
252
|
-
return
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// Opening the DevTools triggers the "only-if-cached" request
|
|
256
|
-
// that cannot be handled by the worker. Bypass such requests.
|
|
257
|
-
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
|
|
258
|
-
return
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// Bypass all requests when there are no active clients.
|
|
262
|
-
// Prevents the self-unregistered worked from handling requests
|
|
263
|
-
// after it's been deleted (still remains active until the next reload).
|
|
264
|
-
if (activeClientIds.size === 0) {
|
|
265
|
-
return
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
const requestId = uuidv4()
|
|
269
|
-
|
|
270
|
-
return event.respondWith(
|
|
271
|
-
handleRequest(event, requestId).catch((error) => {
|
|
272
|
-
if (error.name === 'NetworkError') {
|
|
273
|
-
console.warn(
|
|
274
|
-
'[MSW] Successfully emulated a network error for the "%s %s" request.',
|
|
275
|
-
request.method,
|
|
276
|
-
request.url,
|
|
277
|
-
)
|
|
278
|
-
return
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
// At this point, any exception indicates an issue with the original request/response.
|
|
282
|
-
console.error(
|
|
283
|
-
`\
|
|
284
|
-
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
|
|
285
|
-
request.method,
|
|
286
|
-
request.url,
|
|
287
|
-
`${error.name}: ${error.message}`,
|
|
288
|
-
)
|
|
289
|
-
}),
|
|
290
|
-
)
|
|
291
|
-
})
|
|
292
|
-
|
|
293
|
-
function serializeHeaders(headers) {
|
|
294
|
-
const reqHeaders = {}
|
|
295
|
-
headers.forEach((value, name) => {
|
|
296
|
-
reqHeaders[name] = reqHeaders[name]
|
|
297
|
-
? [].concat(reqHeaders[name]).concat(value)
|
|
298
|
-
: value
|
|
299
|
-
})
|
|
300
|
-
return reqHeaders
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function sendToClient(client, message) {
|
|
304
|
-
return new Promise((resolve, reject) => {
|
|
305
|
-
const channel = new MessageChannel()
|
|
306
|
-
|
|
307
|
-
channel.port1.onmessage = (event) => {
|
|
308
|
-
if (event.data && event.data.error) {
|
|
309
|
-
return reject(event.data.error)
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
resolve(event.data)
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
client.postMessage(JSON.stringify(message), [channel.port2])
|
|
316
|
-
})
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
function delayPromise(cb, duration) {
|
|
320
|
-
return new Promise((resolve) => {
|
|
321
|
-
setTimeout(() => resolve(cb()), duration)
|
|
322
|
-
})
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
function respondWithMock(clientMessage) {
|
|
326
|
-
return new Response(clientMessage.payload.body, {
|
|
327
|
-
...clientMessage.payload,
|
|
328
|
-
headers: clientMessage.payload.headers,
|
|
329
|
-
})
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
function uuidv4() {
|
|
333
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
|
334
|
-
const r = (Math.random() * 16) | 0
|
|
335
|
-
const v = c == 'x' ? r : (r & 0x3) | 0x8
|
|
336
|
-
return v.toString(16)
|
|
337
|
-
})
|
|
338
|
-
}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
/**
|
|
3
|
-
* Sets a raw response body. Does not append any `Content-Type` headers.
|
|
4
|
-
* @example
|
|
5
|
-
* res(ctx.body('Successful response'))
|
|
6
|
-
* res(ctx.body(JSON.stringify({ key: 'value' })))
|
|
7
|
-
* @see {@link https://mswjs.io/docs/api/context/body `ctx.body()`}
|
|
8
|
-
*/
|
|
9
|
-
export declare const body: <BodyType extends string | Blob | BufferSource | ReadableStream<any> | FormData>(value: BodyType) => ResponseTransformer<BodyType, any>;
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import * as cookieUtils from 'cookie';
|
|
2
|
-
import { ResponseTransformer } from '../response';
|
|
3
|
-
/**
|
|
4
|
-
* Sets a given cookie on the mocked response.
|
|
5
|
-
* @example res(ctx.cookie('name', 'value'))
|
|
6
|
-
*/
|
|
7
|
-
export declare const cookie: (name: string, value: string, options?: cookieUtils.CookieSerializeOptions | undefined) => ResponseTransformer;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { GraphQLPayloadContext } from '../typeUtils';
|
|
2
|
-
/**
|
|
3
|
-
* Sets a given payload as a GraphQL response body.
|
|
4
|
-
* @example
|
|
5
|
-
* res(ctx.data({ user: { firstName: 'John' }}))
|
|
6
|
-
* @see {@link https://mswjs.io/docs/api/context/data `ctx.data()`}
|
|
7
|
-
*/
|
|
8
|
-
export declare const data: GraphQLPayloadContext<Record<string, unknown>>;
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
export declare const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
|
|
3
|
-
export declare const MIN_SERVER_RESPONSE_TIME = 100;
|
|
4
|
-
export declare const MAX_SERVER_RESPONSE_TIME = 400;
|
|
5
|
-
export declare const NODE_SERVER_RESPONSE_TIME = 5;
|
|
6
|
-
export declare type DelayMode = 'real' | 'infinite';
|
|
7
|
-
/**
|
|
8
|
-
* Delays the response by the given duration (ms).
|
|
9
|
-
* @example
|
|
10
|
-
* res(ctx.delay(1200)) // delay response by 1200ms
|
|
11
|
-
* res(ctx.delay()) // emulate realistic server response time
|
|
12
|
-
* res(ctx.delay('infinite')) // delay response infinitely
|
|
13
|
-
* @see {@link https://mswjs.io/docs/api/context/delay `ctx.delay()`}
|
|
14
|
-
*/
|
|
15
|
-
export declare const delay: (durationOrMode?: number | DelayMode | undefined) => ResponseTransformer;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { GraphQLError } from 'graphql';
|
|
2
|
-
import { ResponseTransformer } from '../response';
|
|
3
|
-
/**
|
|
4
|
-
* Sets a given list of GraphQL errors on the mocked response.
|
|
5
|
-
* @example res(ctx.errors([{ message: 'Unauthorized' }]))
|
|
6
|
-
* @see {@link https://mswjs.io/docs/api/context/errors}
|
|
7
|
-
*/
|
|
8
|
-
export declare const errors: <ErrorsType extends readonly Partial<GraphQLError>[] | null | undefined>(errorsList: ErrorsType) => ResponseTransformer<string>;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { GraphQLPayloadContext } from '../typeUtils';
|
|
2
|
-
/**
|
|
3
|
-
* Sets the GraphQL extensions on a given response.
|
|
4
|
-
* @example
|
|
5
|
-
* res(ctx.extensions({ tracing: { version: 1 }}))
|
|
6
|
-
* @see {@link https://mswjs.io/docs/api/context/extensions `ctx.extensions()`}
|
|
7
|
-
*/
|
|
8
|
-
export declare const extensions: GraphQLPayloadContext<Record<string, unknown>>;
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { MockedRequest } from '../handlers/RequestHandler';
|
|
2
|
-
export declare const augmentRequestInit: (requestInit: RequestInit) => RequestInit;
|
|
3
|
-
/**
|
|
4
|
-
* Performs a bypassed request inside a request handler.
|
|
5
|
-
* @example
|
|
6
|
-
* const originalResponse = await ctx.fetch(req)
|
|
7
|
-
* @see {@link https://mswjs.io/docs/api/context/fetch `ctx.fetch()`}
|
|
8
|
-
*/
|
|
9
|
-
export declare const fetch: (input: string | MockedRequest, requestInit?: RequestInit) => Promise<Response>;
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
export { status } from './status';
|
|
2
|
-
export { set } from './set';
|
|
3
|
-
export { cookie } from './cookie';
|
|
4
|
-
export { body } from './body';
|
|
5
|
-
export { data } from './data';
|
|
6
|
-
export { extensions } from './extensions';
|
|
7
|
-
export { delay } from './delay';
|
|
8
|
-
export { errors } from './errors';
|
|
9
|
-
export { fetch } from './fetch';
|
|
10
|
-
export { json } from './json';
|
|
11
|
-
export { text } from './text';
|
|
12
|
-
export { xml } from './xml';
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
/**
|
|
3
|
-
* Sets the given value as the JSON body of the response.
|
|
4
|
-
* Appends a `Content-Type: application/json` header on the
|
|
5
|
-
* mocked response.
|
|
6
|
-
* @example
|
|
7
|
-
* res(ctx.json('Some string'))
|
|
8
|
-
* res(ctx.json({ key: 'value' }))
|
|
9
|
-
* res(ctx.json([1, '2', false, { ok: true }]))
|
|
10
|
-
* @see {@link https://mswjs.io/docs/api/context/json `ctx.json()`}
|
|
11
|
-
*/
|
|
12
|
-
export declare const json: <BodyTypeJSON>(body: BodyTypeJSON) => ResponseTransformer<BodyTypeJSON, any>;
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
export declare type HeadersObject<KeyType extends string = string> = Record<KeyType, string | string[]>;
|
|
3
|
-
/**
|
|
4
|
-
* @see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
|
|
5
|
-
*/
|
|
6
|
-
export declare type ForbiddenHeaderNames = 'cookie' | 'cookie2' | 'set-cookie' | 'set-cookie2';
|
|
7
|
-
export declare type ForbiddenHeaderError<HeaderName extends string> = `SafeResponseHeader: the '${HeaderName}' header cannot be set on the response. Please use the 'ctx.cookie()' function instead.`;
|
|
8
|
-
/**
|
|
9
|
-
* Sets one or multiple response headers.
|
|
10
|
-
* @example
|
|
11
|
-
* ctx.set('Content-Type', 'text/plain')
|
|
12
|
-
* ctx.set({
|
|
13
|
-
* 'Accept': 'application/javascript',
|
|
14
|
-
* 'Content-Type': "text/plain"
|
|
15
|
-
* })
|
|
16
|
-
* @see {@link https://mswjs.io/docs/api/context/set `ctx.set()`}
|
|
17
|
-
*/
|
|
18
|
-
export declare function set<N extends string | HeadersObject>(...args: N extends string ? Lowercase<N> extends ForbiddenHeaderNames ? ForbiddenHeaderError<N> : [N, string] : N extends HeadersObject<infer CookieName> ? Lowercase<CookieName> extends ForbiddenHeaderNames ? ForbiddenHeaderError<CookieName> : [N] : [N]): ResponseTransformer;
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
/**
|
|
3
|
-
* Sets a response status code and text.
|
|
4
|
-
* @example
|
|
5
|
-
* res(ctx.status(301))
|
|
6
|
-
* res(ctx.status(400, 'Custom status text'))
|
|
7
|
-
* @see {@link https://mswjs.io/docs/api/context/status `ctx.status()`}
|
|
8
|
-
*/
|
|
9
|
-
export declare const status: (statusCode: number, statusText?: string | undefined) => ResponseTransformer;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
/**
|
|
3
|
-
* Sets a textual response body. Appends a `Content-Type: text/plain`
|
|
4
|
-
* header on the mocked response.
|
|
5
|
-
* @example res(ctx.text('Successful response'))
|
|
6
|
-
* @see {@link https://mswjs.io/docs/api/context/text `ctx.text()`}
|
|
7
|
-
*/
|
|
8
|
-
export declare const text: <BodyType extends string>(body: BodyType) => ResponseTransformer<BodyType, any>;
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { ResponseTransformer } from '../response';
|
|
2
|
-
/**
|
|
3
|
-
* Sets an XML response body. Appends a `Content-Type: text/xml` header
|
|
4
|
-
* on the mocked response.
|
|
5
|
-
* @example
|
|
6
|
-
* res(ctx.xml('<node key="value">Content</node>'))
|
|
7
|
-
* @see {@link https://mswjs.io/docs/api/context/xml `ctx.xml()`}
|
|
8
|
-
*/
|
|
9
|
-
export declare const xml: <BodyType extends string>(body: BodyType) => ResponseTransformer<BodyType, any>;
|