MCPcopy
hub / github.com/leaningtech/webvm / handleFetch

Function handleFetch

serviceWorker.js:1–34  ·  view source on GitHub ↗
(request)

Source from the content-addressed store, hash-verified

1async function handleFetch(request) {
2 // Perform the original fetch request and store the result in order to modify the response.
3 try {
4 var r = await fetch(request);
5 }
6 catch (e) {
7 console.error(e)
8 }
9 if (r.status === 0) {
10 return r;
11 }
12 // We add headers to the original response its headers, in order to enable cross-origin-isolation. And make it independent of the server config.
13 const newHeaders = new Headers(r.headers);
14 // COEP & COOP for cross-origin-isolation.
15 newHeaders.set("Cross-Origin-Embedder-Policy", "require-corp");
16 newHeaders.set("Cross-Origin-Opener-Policy", "same-origin");
17 newHeaders.set("Cross-Origin-Resource-Policy", "cross-origin");
18 /**
19 * This workaround is necessary due to a limitation of CheerpOS, which relies on the response URL being set to the resolved URL.
20 * When constructing a new response object, the URL is not set by the Response() constructor and the serviceworker respondwith() method will set the url to event.request.url in case of an empty string.
21 * To address this, we set the location URL to the resolved response URL and set the status code to 301 in the new Response object.
22 * This causes the request to bounce back to the serviceworker from Cheerpos, with the event.request.url now set to the resolved URL, which allows the respondWith method to properly set the response URL in our new response.
23 * https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith.
24 */
25 if (r.redirected === true)
26 newHeaders.set("location", r.url);
27 // In case of a redirection, we set the status to 301, and body to null, in order to not transfer too much data needlessly
28 const moddedResponse = new Response(r.redirected === true ? null : r.body, {
29 headers: newHeaders,
30 status: r.redirected === true ? 301 : r.status,
31 statusText: r.statusText,
32 });
33 return moddedResponse;
34}
35
36function serviceWorkerInit() {
37 // Init the service worker.

Callers 1

serviceWorkerInitFunction · 0.85

Calls 2

errorMethod · 0.80
setMethod · 0.45

Tested by

no test coverage detected