feat: Provide ability to passthrough and hit network

This commit is contained in:
Nicolas Lepage 2025-02-06 09:58:37 +01:00 committed by GitHub
commit 1f38d08145
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 8 additions and 1 deletions

View File

@ -182,7 +182,9 @@ URL string of the WebAssembly module, example: `"path/to/my-module.wasm"`.
An optional object containing:
- `base` (`string`): Base path of the server, relative to the ServiceWorker's scope.
- `cacheName` (`string`): Name of the [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to store the WebAssembly binary.
- `args` (`string[]`): Arguments for the WebAssembly module.
- `passthrough` (`(request: Request): boolean`): Optional callback to allow passing the request through to network.
## Contributors ✨

7
sw.js
View File

@ -1,4 +1,4 @@
function registerWasmHTTPListener(wasm, { base, cacheName, args = [] } = {}) {
function registerWasmHTTPListener(wasm, { base, cacheName, passthrough, args = [] } = {}) {
let path = new URL(registration.scope).pathname
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
@ -17,6 +17,11 @@ function registerWasmHTTPListener(wasm, { base, cacheName, args = [] } = {}) {
WebAssembly.instantiateStreaming(source, go.importObject).then(({ instance }) => go.run(instance))
addEventListener('fetch', e => {
if (passthrough?.(e.request)) {
e.respondWith(fetch(e.request))
return;
}
const { pathname } = new URL(e.request.url)
if (!pathname.startsWith(path)) return