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