|
| 1 | +/** |
| 2 | + * Mock Service Worker. |
| 3 | + * @see https://github.com/mswjs/msw |
| 4 | + * - Please do NOT modify this file. |
| 5 | + * - Please do NOT serve this file on production. |
| 6 | + */ |
| 7 | +/* eslint-disable */ |
| 8 | +/* tslint:disable */ |
| 9 | + |
| 10 | +const INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187' |
| 11 | +const bypassHeaderName = 'x-msw-bypass' |
| 12 | +const activeClientIds = new Set() |
| 13 | + |
| 14 | +self.addEventListener('install', function () { |
| 15 | + return self.skipWaiting() |
| 16 | +}) |
| 17 | + |
| 18 | +self.addEventListener('activate', async function (event) { |
| 19 | + return self.clients.claim() |
| 20 | +}) |
| 21 | + |
| 22 | +self.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 | + |
| 37 | + switch (event.data) { |
| 38 | + case 'KEEPALIVE_REQUEST': { |
| 39 | + sendToClient(client, { |
| 40 | + type: 'KEEPALIVE_RESPONSE', |
| 41 | + }) |
| 42 | + break |
| 43 | + } |
| 44 | + |
| 45 | + case 'INTEGRITY_CHECK_REQUEST': { |
| 46 | + sendToClient(client, { |
| 47 | + type: 'INTEGRITY_CHECK_RESPONSE', |
| 48 | + payload: INTEGRITY_CHECKSUM, |
| 49 | + }) |
| 50 | + break |
| 51 | + } |
| 52 | + |
| 53 | + case 'MOCK_ACTIVATE': { |
| 54 | + activeClientIds.add(clientId) |
| 55 | + |
| 56 | + sendToClient(client, { |
| 57 | + type: 'MOCKING_ENABLED', |
| 58 | + payload: true, |
| 59 | + }) |
| 60 | + break |
| 61 | + } |
| 62 | + |
| 63 | + case 'MOCK_DEACTIVATE': { |
| 64 | + activeClientIds.delete(clientId) |
| 65 | + break |
| 66 | + } |
| 67 | + |
| 68 | + case 'CLIENT_CLOSED': { |
| 69 | + activeClientIds.delete(clientId) |
| 70 | + |
| 71 | + const remainingClients = allClients.filter((client) => { |
| 72 | + return client.id !== clientId |
| 73 | + }) |
| 74 | + |
| 75 | + // Unregister itself when there are no more clients |
| 76 | + if (remainingClients.length === 0) { |
| 77 | + self.registration.unregister() |
| 78 | + } |
| 79 | + |
| 80 | + break |
| 81 | + } |
| 82 | + } |
| 83 | +}) |
| 84 | + |
| 85 | +// Resolve the "master" client for the given event. |
| 86 | +// Client that issues a request doesn't necessarily equal the client |
| 87 | +// that registered the worker. It's with the latter the worker should |
| 88 | +// communicate with during the response resolving phase. |
| 89 | +async function resolveMasterClient(event) { |
| 90 | + const client = await self.clients.get(event.clientId) |
| 91 | + |
| 92 | + if (client.frameType === 'top-level') { |
| 93 | + return client |
| 94 | + } |
| 95 | + |
| 96 | + const allClients = await self.clients.matchAll() |
| 97 | + |
| 98 | + return allClients |
| 99 | + .filter((client) => { |
| 100 | + // Get only those clients that are currently visible. |
| 101 | + return client.visibilityState === 'visible' |
| 102 | + }) |
| 103 | + .find((client) => { |
| 104 | + // Find the client ID that's recorded in the |
| 105 | + // set of clients that have registered the worker. |
| 106 | + return activeClientIds.has(client.id) |
| 107 | + }) |
| 108 | +} |
| 109 | + |
| 110 | +async function handleRequest(event, requestId) { |
| 111 | + const client = await resolveMasterClient(event) |
| 112 | + const response = await getResponse(event, client, requestId) |
| 113 | + |
| 114 | + // Send back the response clone for the "response:*" life-cycle events. |
| 115 | + // Ensure MSW is active and ready to handle the message, otherwise |
| 116 | + // this message will pend indefinitely. |
| 117 | + if (client && activeClientIds.has(client.id)) { |
| 118 | + ;(async function () { |
| 119 | + const clonedResponse = response.clone() |
| 120 | + sendToClient(client, { |
| 121 | + type: 'RESPONSE', |
| 122 | + payload: { |
| 123 | + requestId, |
| 124 | + type: clonedResponse.type, |
| 125 | + ok: clonedResponse.ok, |
| 126 | + status: clonedResponse.status, |
| 127 | + statusText: clonedResponse.statusText, |
| 128 | + body: |
| 129 | + clonedResponse.body === null ? null : await clonedResponse.text(), |
| 130 | + headers: serializeHeaders(clonedResponse.headers), |
| 131 | + redirected: clonedResponse.redirected, |
| 132 | + }, |
| 133 | + }) |
| 134 | + })() |
| 135 | + } |
| 136 | + |
| 137 | + return response |
| 138 | +} |
| 139 | + |
| 140 | +async function getResponse(event, client, requestId) { |
| 141 | + const { request } = event |
| 142 | + const requestClone = request.clone() |
| 143 | + const getOriginalResponse = () => fetch(requestClone) |
| 144 | + |
| 145 | + // Bypass mocking when the request client is not active. |
| 146 | + if (!client) { |
| 147 | + return getOriginalResponse() |
| 148 | + } |
| 149 | + |
| 150 | + // Bypass initial page load requests (i.e. static assets). |
| 151 | + // The absence of the immediate/parent client in the map of the active clients |
| 152 | + // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet |
| 153 | + // and is not ready to handle requests. |
| 154 | + if (!activeClientIds.has(client.id)) { |
| 155 | + return await getOriginalResponse() |
| 156 | + } |
| 157 | + |
| 158 | + // Bypass requests with the explicit bypass header |
| 159 | + if (requestClone.headers.get(bypassHeaderName) === 'true') { |
| 160 | + const cleanRequestHeaders = serializeHeaders(requestClone.headers) |
| 161 | + |
| 162 | + // Remove the bypass header to comply with the CORS preflight check. |
| 163 | + delete cleanRequestHeaders[bypassHeaderName] |
| 164 | + |
| 165 | + const originalRequest = new Request(requestClone, { |
| 166 | + headers: new Headers(cleanRequestHeaders), |
| 167 | + }) |
| 168 | + |
| 169 | + return fetch(originalRequest) |
| 170 | + } |
| 171 | + |
| 172 | + // Send the request to the client-side MSW. |
| 173 | + const reqHeaders = serializeHeaders(request.headers) |
| 174 | + const body = await request.text() |
| 175 | + |
| 176 | + const clientMessage = await sendToClient(client, { |
| 177 | + type: 'REQUEST', |
| 178 | + payload: { |
| 179 | + id: requestId, |
| 180 | + url: request.url, |
| 181 | + method: request.method, |
| 182 | + headers: reqHeaders, |
| 183 | + cache: request.cache, |
| 184 | + mode: request.mode, |
| 185 | + credentials: request.credentials, |
| 186 | + destination: request.destination, |
| 187 | + integrity: request.integrity, |
| 188 | + redirect: request.redirect, |
| 189 | + referrer: request.referrer, |
| 190 | + referrerPolicy: request.referrerPolicy, |
| 191 | + body, |
| 192 | + bodyUsed: request.bodyUsed, |
| 193 | + keepalive: request.keepalive, |
| 194 | + }, |
| 195 | + }) |
| 196 | + |
| 197 | + switch (clientMessage.type) { |
| 198 | + case 'MOCK_SUCCESS': { |
| 199 | + return delayPromise( |
| 200 | + () => respondWithMock(clientMessage), |
| 201 | + clientMessage.payload.delay, |
| 202 | + ) |
| 203 | + } |
| 204 | + |
| 205 | + case 'MOCK_NOT_FOUND': { |
| 206 | + return getOriginalResponse() |
| 207 | + } |
| 208 | + |
| 209 | + case 'NETWORK_ERROR': { |
| 210 | + const { name, message } = clientMessage.payload |
| 211 | + const networkError = new Error(message) |
| 212 | + networkError.name = name |
| 213 | + |
| 214 | + // Rejecting a request Promise emulates a network error. |
| 215 | + throw networkError |
| 216 | + } |
| 217 | + |
| 218 | + case 'INTERNAL_ERROR': { |
| 219 | + const parsedBody = JSON.parse(clientMessage.payload.body) |
| 220 | + |
| 221 | + console.error( |
| 222 | + `\ |
| 223 | +[MSW] Request handler function for "%s %s" has thrown the following exception: |
| 224 | +
|
| 225 | +${parsedBody.errorType}: ${parsedBody.message} |
| 226 | +(see more detailed error stack trace in the mocked response body) |
| 227 | +
|
| 228 | +This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error. |
| 229 | +If you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\ |
| 230 | +`, |
| 231 | + request.method, |
| 232 | + request.url, |
| 233 | + ) |
| 234 | + |
| 235 | + return respondWithMock(clientMessage) |
| 236 | + } |
| 237 | + } |
| 238 | + |
| 239 | + return getOriginalResponse() |
| 240 | +} |
| 241 | + |
| 242 | +self.addEventListener('fetch', function (event) { |
| 243 | + const { request } = event |
| 244 | + |
| 245 | + // Bypass navigation requests. |
| 246 | + if (request.mode === 'navigate') { |
| 247 | + return |
| 248 | + } |
| 249 | + |
| 250 | + // Opening the DevTools triggers the "only-if-cached" request |
| 251 | + // that cannot be handled by the worker. Bypass such requests. |
| 252 | + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { |
| 253 | + return |
| 254 | + } |
| 255 | + |
| 256 | + // Bypass all requests when there are no active clients. |
| 257 | + // Prevents the self-unregistered worked from handling requests |
| 258 | + // after it's been deleted (still remains active until the next reload). |
| 259 | + if (activeClientIds.size === 0) { |
| 260 | + return |
| 261 | + } |
| 262 | + |
| 263 | + const requestId = uuidv4() |
| 264 | + |
| 265 | + return event.respondWith( |
| 266 | + handleRequest(event, requestId).catch((error) => { |
| 267 | + console.error( |
| 268 | + '[MSW] Failed to mock a "%s" request to "%s": %s', |
| 269 | + request.method, |
| 270 | + request.url, |
| 271 | + error, |
| 272 | + ) |
| 273 | + }), |
| 274 | + ) |
| 275 | +}) |
| 276 | + |
| 277 | +function serializeHeaders(headers) { |
| 278 | + const reqHeaders = {} |
| 279 | + headers.forEach((value, name) => { |
| 280 | + reqHeaders[name] = reqHeaders[name] |
| 281 | + ? [].concat(reqHeaders[name]).concat(value) |
| 282 | + : value |
| 283 | + }) |
| 284 | + return reqHeaders |
| 285 | +} |
| 286 | + |
| 287 | +function sendToClient(client, message) { |
| 288 | + return new Promise((resolve, reject) => { |
| 289 | + const channel = new MessageChannel() |
| 290 | + |
| 291 | + channel.port1.onmessage = (event) => { |
| 292 | + if (event.data && event.data.error) { |
| 293 | + return reject(event.data.error) |
| 294 | + } |
| 295 | + |
| 296 | + resolve(event.data) |
| 297 | + } |
| 298 | + |
| 299 | + client.postMessage(JSON.stringify(message), [channel.port2]) |
| 300 | + }) |
| 301 | +} |
| 302 | + |
| 303 | +function delayPromise(cb, duration) { |
| 304 | + return new Promise((resolve) => { |
| 305 | + setTimeout(() => resolve(cb()), duration) |
| 306 | + }) |
| 307 | +} |
| 308 | + |
| 309 | +function respondWithMock(clientMessage) { |
| 310 | + return new Response(clientMessage.payload.body, { |
| 311 | + ...clientMessage.payload, |
| 312 | + headers: clientMessage.payload.headers, |
| 313 | + }) |
| 314 | +} |
| 315 | + |
| 316 | +function uuidv4() { |
| 317 | + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { |
| 318 | + const r = (Math.random() * 16) | 0 |
| 319 | + const v = c == 'x' ? r : (r & 0x3) | 0x8 |
| 320 | + return v.toString(16) |
| 321 | + }) |
| 322 | +} |
0 commit comments