Open History to see the last commit
1/* eslint-disable */
2β
3/**
4 * Mock Service Worker (2.1.7).
5 * @see https://github.com/mswjs/msw
6 * - Please do NOT modify this file.
7 * - Please do NOT serve this file on production.
8 */
9β
10const INTEGRITY_CHECKSUM = '223d191a56023cd36aa88c802961b911'
11const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
12const activeClientIds = new Set()
13β
14self.addEventListener('install', function () {
15 self.skipWaiting()
16})
17β
18self.addEventListener('activate', function (event) {
19 event.waitUntil(self.clients.claim())
20})
21β
22self.addEventListener('message', async function (event) {
23 const clientId = event.source.id
24β
25 if (!clientId || !self.clients) {
26 return
27 }
28β
29 const client = await self.clients.get(clientId)
30β
31 if (!client) {
32 return
33 }
34β
35 const allClients = await self.clients.matchAll({
36 type: 'window',
37 })
38β
39 switch (event.data) {
40 case 'KEEPALIVE_REQUEST': {
41 sendToClient(client, {
42 type: 'KEEPALIVE_RESPONSE',
43 })
44 break
45 }
46β
47 case 'INTEGRITY_CHECK_REQUEST': {
48 sendToClient(client, {
49 type: 'INTEGRITY_CHECK_RESPONSE',
50 payload: INTEGRITY_CHECKSUM,
51 })
52 break
53 }
54β
55 case 'MOCK_ACTIVATE': {
56 activeClientIds.add(clientId)
57β
58 sendToClient(client, {
59 type: 'MOCKING_ENABLED',
60 payload: true,
61 })
62 break
63 }
64β
65 case 'MOCK_DEACTIVATE': {
66 activeClientIds.delete(clientId)
67 break
68 }
69β
70 case 'CLIENT_CLOSED': {
71 activeClientIds.delete(clientId)
72β
73 const remainingClients = allClients.filter((client) => {
74 return client.id !== clientId
75 })
76β
77 // Unregister itself when there are no more clients
78 if (remainingClients.length === 0) {
79 self.registration.unregister()
80 }
81β
82 break
83 }
84 }
85})
86β
87self.addEventListener('fetch', function (event) {
88 const { request } = event
89β
90 // Bypass navigation requests.
91 if (request.mode === 'navigate') {
92 return
93 }
94β
95 // Opening the DevTools triggers the "only-if-cached" request
96 // that cannot be handled by the worker. Bypass such requests.
97 if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
98 return
99 }
100β
101 // Bypass all requests when there are no active clients.
102 // Prevents the self-unregistered worked from handling requests
103 // after it's been deleted (still remains active until the next reload).
104 if (activeClientIds.size === 0) {
105 return
106 }
107β
108 // Generate unique request ID.
109 const requestId = crypto.randomUUID()
110 event.respondWith(handleRequest(event, requestId))
111})
112β
113async function handleRequest(event, requestId) {
114 const client = await resolveMainClient(event)
115 const response = await getResponse(event, client, requestId)
116β
117 // Send back the response clone for the "response:*" life-cycle events.
118 // Ensure MSW is active and ready to handle the message, otherwise
119 // this message will pend indefinitely.
120 if (client && activeClientIds.has(client.id)) {
121 ;(async function () {
122 const responseClone = response.clone()
123β
124 sendToClient(
125 client,
126 {
127 type: 'RESPONSE',
128 payload: {
129 requestId,
130 isMockedResponse: IS_MOCKED_RESPONSE in response,
131 type: responseClone.type,
132 status: responseClone.status,
133 statusText: responseClone.statusText,
134 body: responseClone.body,
135 headers: Object.fromEntries(responseClone.headers.entries()),
136 },
137 },
138 [responseClone.body],
139 )
140 })()
141 }
142β
143 return response
144}
145β
146// Resolve the main client for the given event.
147// Client that issues a request doesn't necessarily equal the client
148// that registered the worker. It's with the latter the worker should
149// communicate with during the response resolving phase.
150async function resolveMainClient(event) {
151 const client = await self.clients.get(event.clientId)
152β
153 if (client?.frameType === 'top-level') {
154 return client
155 }
156β
157 const allClients = await self.clients.matchAll({
158 type: 'window',
159 })
160β
161 return allClients
162 .filter((client) => {
163 // Get only those clients that are currently visible.
164 return client.visibilityState === 'visible'
165 })
166 .find((client) => {
167 // Find the client ID that's recorded in the
168 // set of clients that have registered the worker.
169 return activeClientIds.has(client.id)
170 })
171}
172β
173async function getResponse(event, client, requestId) {
174 const { request } = event
175β
176 // Clone the request because it might've been already used
177 // (i.e. its body has been read and sent to the client).
178 const requestClone = request.clone()
179β
180 function passthrough() {
181 const headers = Object.fromEntries(requestClone.headers.entries())
182β
183 // Remove internal MSW request header so the passthrough request
184 // complies with any potential CORS preflight checks on the server.
185 // Some servers forbid unknown request headers.
186 delete headers['x-msw-intention']
187β
188 return fetch(requestClone, { headers })
189 }
190β
191 // Bypass mocking when the client is not active.
192 if (!client) {
193 return passthrough()
194 }
195β
196 // Bypass initial page load requests (i.e. static assets).
197 // The absence of the immediate/parent client in the map of the active clients
198 // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
199 // and is not ready to handle requests.
200 if (!activeClientIds.has(client.id)) {
201 return passthrough()
202 }
203β
204 // Bypass requests with the explicit bypass header.
205 // Such requests can be issued by "ctx.fetch()".
206 const mswIntention = request.headers.get('x-msw-intention')
207 if (['bypass', 'passthrough'].includes(mswIntention)) {
208 return passthrough()
209 }
210β
211 // Notify the client that a request has been intercepted.
212 const requestBuffer = await request.arrayBuffer()
213 const clientMessage = await sendToClient(
214 client,
215 {
216 type: 'REQUEST',
217 payload: {
218 id: requestId,
219 url: request.url,
220 mode: request.mode,
221 method: request.method,
222 headers: Object.fromEntries(request.headers.entries()),
223 cache: request.cache,
224 credentials: request.credentials,
225 destination: request.destination,
226 integrity: request.integrity,
227 redirect: request.redirect,
228 referrer: request.referrer,
229 referrerPolicy: request.referrerPolicy,
230 body: requestBuffer,
231 keepalive: request.keepalive,
232 },
233 },
234 [requestBuffer],
235 )
236β
237 switch (clientMessage.type) {
238 case 'MOCK_RESPONSE': {
239 return respondWithMock(clientMessage.data)
240 }
241β
242 case 'MOCK_NOT_FOUND': {
243 return passthrough()
244 }
245 }
246β
247 return passthrough()
248}
249β
250function sendToClient(client, message, transferrables = []) {
251 return new Promise((resolve, reject) => {
252 const channel = new MessageChannel()
253β
254 channel.port1.onmessage = (event) => {
255 if (event.data && event.data.error) {
256 return reject(event.data.error)
257 }
258β
259 resolve(event.data)
260 }
261β
262 client.postMessage(
263 message,
264 [channel.port2].concat(transferrables.filter(Boolean)),
265 )
266 })
267}
268β
269async function respondWithMock(response) {
270 // Setting response status code to 0 is a no-op.
271 // However, when responding with a "Response.error()", the produced Response
272 // instance will have status code set to 0. Since it's not possible to create
273 // a Response instance with status code 0, handle that use-case separately.
274 if (response.status === 0) {
275 return Response.error()
276 }
277β
278 const mockedResponse = new Response(response.body, response)
279β
280 Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
281 value: true,
282 enumerable: true,
283 })
284β
285 return mockedResponse
286}