(event, client, requestId)
| 185 | } |
| 186 | |
| 187 | async function getResponse(event, client, requestId) { |
| 188 | const { request } = event |
| 189 | |
| 190 | // Clone the request because it might've been already used |
| 191 | // (i.e. its body has been read and sent to the client). |
| 192 | const requestClone = request.clone() |
| 193 | |
| 194 | function passthrough() { |
| 195 | // Cast the request headers to a new Headers instance |
| 196 | // so the headers can be manipulated with. |
| 197 | const headers = new Headers(requestClone.headers) |
| 198 | |
| 199 | // Remove the "accept" header value that marked this request as passthrough. |
| 200 | // This prevents request alteration and also keeps it compliant with the |
| 201 | // user-defined CORS policies. |
| 202 | const acceptHeader = headers.get('accept') |
| 203 | if (acceptHeader) { |
| 204 | const values = acceptHeader.split(',').map((value) => value.trim()) |
| 205 | const filteredValues = values.filter( |
| 206 | (value) => value !== 'msw/passthrough', |
| 207 | ) |
| 208 | |
| 209 | if (filteredValues.length > 0) { |
| 210 | headers.set('accept', filteredValues.join(', ')) |
| 211 | } else { |
| 212 | headers.delete('accept') |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | return fetch(requestClone, { headers }) |
| 217 | } |
| 218 | |
| 219 | // Bypass mocking when the client is not active. |
| 220 | if (!client) { |
| 221 | return passthrough() |
| 222 | } |
| 223 | |
| 224 | // Bypass initial page load requests (i.e. static assets). |
| 225 | // The absence of the immediate/parent client in the map of the active clients |
| 226 | // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet |
| 227 | // and is not ready to handle requests. |
| 228 | if (!activeClientIds.has(client.id)) { |
| 229 | return passthrough() |
| 230 | } |
| 231 | |
| 232 | // Notify the client that a request has been intercepted. |
| 233 | const requestBuffer = await request.arrayBuffer() |
| 234 | const clientMessage = await sendToClient( |
| 235 | client, |
| 236 | { |
| 237 | type: 'REQUEST', |
| 238 | payload: { |
| 239 | id: requestId, |
| 240 | url: request.url, |
| 241 | mode: request.mode, |
| 242 | method: request.method, |
| 243 | headers: Object.fromEntries(request.headers.entries()), |
| 244 | cache: request.cache, |
no test coverage detected