// SoftwareCannery loader service worker. // - Pre-caches the loader shell so it opens offline. // - Cache-first for boot payloads (/img/*, *.wasm, guiinit, the worker bundles) // so a station boots instantly and offline once cached. Cached Responses keep // their original COOP/COEP headers, so crossOriginIsolated still holds. const SHELL = 'sc-loader-shell-v3'; const IMG = 'sc-loader-img-v2'; // v2: evicts boot code cached before GLR1 const SHELL_FILES = ['/loader.html', '/manifest.webmanifest', '/icon.svg', '/stations.json']; self.addEventListener('install', (e) => { e.waitUntil(caches.open(SHELL).then(c => c.addAll(SHELL_FILES)).then(() => self.skipWaiting())); }); self.addEventListener('activate', (e) => { e.waitUntil(caches.keys().then(keys => Promise.all( keys.filter(k => ![SHELL, IMG].includes(k)).map(k => caches.delete(k)) )).then(() => self.clients.claim())); }); // Content-addressed files (sha256 in the name) never change: cache-first forever. const isHashed = (u) => /\/lib\/.+\.[0-9a-f]{64}$|\/kernel\/vmlinux-[0-9a-f]{64}\.wasm$/.test(u); // Everything else that boots a station (worker code, app images) CAN change in place: // network-first so a rebuild reaches the browser, cache only as the offline fallback. const isBoot = (u) => /\/img\/|\.wasm$|\/guiinit$|worker-browser\.js$|boot-worker\.js$|kernelWorker-browser\.js$|\/main\.js$/.test(u); self.addEventListener('fetch', (e) => { const u = new URL(e.request.url); if (u.origin !== location.origin) return; if (u.pathname.startsWith('/loader/')) return; // never cache the control channel if (isHashed(u.pathname)) { // immutable: cache-first e.respondWith(caches.open(IMG).then(async c => { const hit = await c.match(e.request); if (hit) return hit; const net = await fetch(e.request, { credentials: 'include' }); if (net.ok) c.put(e.request, net.clone()); return net; })); return; } if (isBoot(u.pathname)) { // mutable: network-first e.respondWith(caches.open(IMG).then(async c => { try { const net = await fetch(e.request, { credentials: 'include', cache: 'no-store' }); if (net.ok) c.put(e.request, net.clone()); return net; } catch (err) { const hit = await c.match(e.request); if (hit) return hit; throw err; } })); return; } if (SHELL_FILES.includes(u.pathname)) { // shell: cache, fall back to net e.respondWith(caches.match(e.request).then(h => h || fetch(e.request, { credentials: 'include' }))); } }); // Dashboard/loader can ask us to pre-warm a station's payload. self.addEventListener('message', async (e) => { if (e.data?.type === 'precache' && Array.isArray(e.data.urls)) { const c = await caches.open(IMG); for (const url of e.data.urls) { try { const r = await fetch(url, { credentials:'include' }); if (r.ok) await c.put(url, r.clone()); } catch {} } e.source?.postMessage({ type: 'precache-done', station: e.data.station }); } });