Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow js modules in the sandbox #347

Merged
merged 1 commit into from
Sep 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions public/sandbox/worker.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
const cache = {}
const referrers = {}

async function fetchUrl(url, file) {
// Let the service worker decide on secure response
// headers, but set its body to the file blob.
const record = await fetch(url)
const options = /\.m?js([#?].*)?$/.test(file) ? {headers: {'content-type': 'text/javascript'}} : undefined
return new Response(record.body, options);
}

self.addEventListener("fetch", async (event) => {
// get an ID from the request referrer url
Expand All @@ -18,11 +25,17 @@ self.addEventListener("fetch", async (event) => {
// only fetch if there is a match in the cache
if (!cache[id][path]) return null;

// Let the service worker decide on secure response
// headers, but set its body to the file blob.

const record = await fetch(cache[id][path].url);
return new Response(await record.body);
return await fetchUrl(cache[id][path].url, event.request.url)
}())
}
} else {
// check for js modules being requested because the referrer will differ
const cacheId = Object.keys(cache).pop()
const moduleName = event.request.url.split('/').pop()
// only fetch when module is part of cache
if(cacheId && moduleName && cache[cacheId][moduleName]) {
event.respondWith(async function() {
return await fetchUrl(cache[cacheId][moduleName].url, event.request.url)
}())
}
}
Expand Down Expand Up @@ -50,4 +63,4 @@ self.addEventListener("message", async (event) => {
})
}
}
})
})