Open History to see the last commit
1/* eslint-disable */
2/* tslint:disable */
3
4/**
5 * Mock Service Worker.
6 * @see https://github.com/mswjs/msw
7 * - Please do NOT modify this file.
8 */
9
10const PACKAGE_VERSION = "2.12.10";
11const INTEGRITY_CHECKSUM = "4db4a41e972cec1b64cc569c66952d82";
12const IS_MOCKED_RESPONSE = Symbol("isMockedResponse");
13const activeClientIds = new Set();
14
15addEventListener("install", function () {
16 self.skipWaiting();
17});
18
19addEventListener("activate", function (event) {
20 event.waitUntil(self.clients.claim());
21});
22
23addEventListener("message", async function (event) {
24 const clientId = Reflect.get(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 type: "window",
38 });
39
40 switch (event.data) {
41 case "KEEPALIVE_REQUEST": {
42 sendToClient(client, {
43 type: "KEEPALIVE_RESPONSE",
44 });
45 break;
46 }
47
48 case "INTEGRITY_CHECK_REQUEST": {
49 sendToClient(client, {
50 type: "INTEGRITY_CHECK_RESPONSE",
51 payload: {
52 packageVersion: PACKAGE_VERSION,
53 checksum: INTEGRITY_CHECKSUM,
54 },
55 });
56 break;
57 }
58
59 case "MOCK_ACTIVATE": {
60 activeClientIds.add(clientId);
61
62 sendToClient(client, {
63 type: "MOCKING_ENABLED",
64 payload: {
65 client: {
66 id: client.id,
67 frameType: client.frameType,
68 },
69 },
70 });
71 break;
72 }
73
74 case "CLIENT_CLOSED": {
75 activeClientIds.delete(clientId);
76
77 const remainingClients = allClients.filter((client) => {
78 return client.id !== clientId;
79 });
80
81 // Unregister itself when there are no more clients
82 if (remainingClients.length === 0) {
83 self.registration.unregister();
84 }
85
86 break;
87 }
88 }
89});
90
91addEventListener("fetch", function (event) {
92 const requestInterceptedAt = Date.now();
93
94 // Bypass navigation requests.
95 if (event.request.mode === "navigate") {
96 return;
97 }
98
99 // Opening the DevTools triggers the "only-if-cached" request
100 // that cannot be handled by the worker. Bypass such requests.
101 if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {
102 return;
103 }
104
105 // Bypass all requests when there are no active clients.
106 // Prevents the self-unregistered worked from handling requests
107 // after it's been terminated (still remains active until the next reload).
108 if (activeClientIds.size === 0) {
109 return;
110 }
111
112 const requestId = crypto.randomUUID();
113 event.respondWith(handleRequest(event, requestId, requestInterceptedAt));
114});
115
116/**
117 * @param {FetchEvent} event
118 * @param {string} requestId
119 * @param {number} requestInterceptedAt
120 */
121async function handleRequest(event, requestId, requestInterceptedAt) {
122 const client = await resolveMainClient(event);
123 const requestCloneForEvents = event.request.clone();
124 const response = await getResponse(event, client, requestId, requestInterceptedAt);
125
126 // Send back the response clone for the "response:*" life-cycle events.
127 // Ensure MSW is active and ready to handle the message, otherwise
128 // this message will pend indefinitely.
129 if (client && activeClientIds.has(client.id)) {
130 const serializedRequest = await serializeRequest(requestCloneForEvents);
131
132 // Clone the response so both the client and the library could consume it.
133 const responseClone = response.clone();
134
135 sendToClient(
136 client,
137 {
138 type: "RESPONSE",
139 payload: {
140 isMockedResponse: IS_MOCKED_RESPONSE in response,
141 request: {
142 id: requestId,
143 ...serializedRequest,
144 },
145 response: {
146 type: responseClone.type,
147 status: responseClone.status,
148 statusText: responseClone.statusText,
149 headers: Object.fromEntries(responseClone.headers.entries()),
150 body: responseClone.body,
151 },
152 },
153 },
154 responseClone.body ? [serializedRequest.body, responseClone.body] : [],
155 );
156 }
157
158 return response;
159}
160
161/**
162 * Resolve the main client for the given event.
163 * Client that issues a request doesn't necessarily equal the client
164 * that registered the worker. It's with the latter the worker should
165 * communicate with during the response resolving phase.
166 * @param {FetchEvent} event
167 * @returns {Promise<Client | undefined>}
168 */
169async function resolveMainClient(event) {
170 const client = await self.clients.get(event.clientId);
171
172 if (activeClientIds.has(event.clientId)) {
173 return client;
174 }
175
176 if (client?.frameType === "top-level") {
177 return client;
178 }
179
180 const allClients = await self.clients.matchAll({
181 type: "window",
182 });
183
184 return allClients
185 .filter((client) => {
186 // Get only those clients that are currently visible.
187 return client.visibilityState === "visible";
188 })
189 .find((client) => {
190 // Find the client ID that's recorded in the
191 // set of clients that have registered the worker.
192 return activeClientIds.has(client.id);
193 });
194}
195
196/**
197 * @param {FetchEvent} event
198 * @param {Client | undefined} client
199 * @param {string} requestId
200 * @param {number} requestInterceptedAt
201 * @returns {Promise<Response>}
202 */
203async function getResponse(event, client, requestId, requestInterceptedAt) {
204 // Clone the request because it might've been already used
205 // (i.e. its body has been read and sent to the client).
206 const requestClone = event.request.clone();
207
208 function passthrough() {
209 // Cast the request headers to a new Headers instance
210 // so the headers can be manipulated with.
211 const headers = new Headers(requestClone.headers);
212
213 // Remove the "accept" header value that marked this request as passthrough.
214 // This prevents request alteration and also keeps it compliant with the
215 // user-defined CORS policies.
216 const acceptHeader = headers.get("accept");
217 if (acceptHeader) {
218 const values = acceptHeader.split(",").map((value) => value.trim());
219 const filteredValues = values.filter((value) => value !== "msw/passthrough");
220
221 if (filteredValues.length > 0) {
222 headers.set("accept", filteredValues.join(", "));
223 } else {
224 headers.delete("accept");
225 }
226 }
227
228 return fetch(requestClone, { headers });
229 }
230
231 // Bypass mocking when the client is not active.
232 if (!client) {
233 return passthrough();
234 }
235
236 // Bypass initial page load requests (i.e. static assets).
237 // The absence of the immediate/parent client in the map of the active clients
238 // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
239 // and is not ready to handle requests.
240 if (!activeClientIds.has(client.id)) {
241 return passthrough();
242 }
243
244 // Notify the client that a request has been intercepted.
245 const serializedRequest = await serializeRequest(event.request);
246 const clientMessage = await sendToClient(
247 client,
248 {
249 type: "REQUEST",
250 payload: {
251 id: requestId,
252 interceptedAt: requestInterceptedAt,
253 ...serializedRequest,
254 },
255 },
256 [serializedRequest.body],
257 );
258
259 switch (clientMessage.type) {
260 case "MOCK_RESPONSE": {
261 return respondWithMock(clientMessage.data);
262 }
263
264 case "PASSTHROUGH": {
265 return passthrough();
266 }
267 }
268
269 return passthrough();
270}
271
272/**
273 * @param {Client} client
274 * @param {any} message
275 * @param {Array<Transferable>} transferrables
276 * @returns {Promise<any>}
277 */
278function sendToClient(client, message, transferrables = []) {
279 return new Promise((resolve, reject) => {
280 const channel = new MessageChannel();
281
282 channel.port1.onmessage = (event) => {
283 if (event.data && event.data.error) {
284 return reject(event.data.error);
285 }
286
287 resolve(event.data);
288 };
289
290 client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)]);
291 });
292}
293
294/**
295 * @param {Response} response
296 * @returns {Response}
297 */
298function respondWithMock(response) {
299 // Setting response status code to 0 is a no-op.
300 // However, when responding with a "Response.error()", the produced Response
301 // instance will have status code set to 0. Since it's not possible to create
302 // a Response instance with status code 0, handle that use-case separately.
303 if (response.status === 0) {
304 return Response.error();
305 }
306
307 const mockedResponse = new Response(response.body, response);
308
309 Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
310 value: true,
311 enumerable: true,
312 });
313
314 return mockedResponse;
315}
316
317/**
318 * @param {Request} request
319 */
320async function serializeRequest(request) {
321 return {
322 url: request.url,
323 mode: request.mode,
324 method: request.method,
325 headers: Object.fromEntries(request.headers.entries()),
326 cache: request.cache,
327 credentials: request.credentials,
328 destination: request.destination,
329 integrity: request.integrity,
330 redirect: request.redirect,
331 referrer: request.referrer,
332 referrerPolicy: request.referrerPolicy,
333 body: await request.arrayBuffer(),
334 keepalive: request.keepalive,
335 };
336}