This commit is contained in:
Nicolas Lepage 2021-01-21 23:59:35 +01:00
parent 272c6d8876
commit cf2a3ceefa
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F

22
sw.js
View File

@ -15,30 +15,26 @@ function registerWasmHTTPListener(wasm, base, args) {
let path = new URL(registration.scope).pathname
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
const wasmPromise = fetch(wasm)
addEventListener('fetch', e => {
const { pathname } = new URL(e.request.url)
if (!pathname.startsWith(path)) return
console.log(`FetchEvent ${pathname}`)
const handlerId = `${nextHandlerId++}`
const handlerPromise = new Promise(resolve => handlerResolvers[handlerId] = resolve)
const go = new Go()
go.env = { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path }
go.argv = [wasm, ...args]
const { instance } = await WebAssembly.instantiateStreaming(wasmPromise, go.importObject)
// FIXME await ? catch ?
startWasm(wasm, { env: { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path }, args })
go.run(instance)
e.respondWith(handlerPromise.then(handler => handler(e.request)))
})
}
async function startWasm(wasm, { env, args = [] }) {
const go = new Go()
go.env = env
go.argv = [wasm, ...args]
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
return go.run(instance)
}
function trimStart(s, c) {
let r = s
while (r.startsWith(c)) r = r.slice(c.length)