1 // sw-register.js — register the bundle's service worker, from its own directory.
2 //
3 // The worker script is staged in $sw/ and its scope is the bundle's directory,
4 // which is wider than the script's own path: the browser allows that only when
5 // the server answers the script with `Service-Worker-Allowed: <scope>` (or
6 // wider). A deployment that omits the header gets a SecurityError here rather
7 // than a worker that silently controls nothing but $sw/.
8 //
9 // Emitted beside the module by `moxie build -target wasm`, and written against
10 // document.currentScript so it needs no knowledge of where the bundle was
11 // deployed: a site at the root and a bundle under /sub/dir/ both register the
12 // worker next to themselves and give it the same subtree as its scope. An
13 // absolute /$sw/ path (which is what apps wrote by hand) only works at a root.
14 (function () {
15 if (!("serviceWorker" in navigator)) return;
16 var here = new URL(".", document.currentScript.src);
17 navigator.serviceWorker
18 .register(new URL("$sw/wasm-host-sw.mjs", here).href, {
19 type: "module",
20 scope: here.pathname,
21 updateViaCache: "none",
22 })
23 .then(function (reg) {
24 // An installed update waits until every client of the old worker is gone
25 // unless it is told to take over now; the module asks for that itself, so
26 // only the first install is forced here.
27 reg.addEventListener("updatefound", function () {
28 var installing = reg.installing;
29 if (!installing) return;
30 installing.addEventListener("statechange", function () {
31 if (installing.state === "installed" && navigator.serviceWorker.controller) {
32 installing.postMessage("SKIP_WAITING");
33 }
34 });
35 });
36 })
37 .catch(function (err) {
38 console.error("[sw-register] failed: " + String(err));
39 });
40 })();
41