// cdrop service worker — makes the web app installable and caches the static // shell for instant launch. // // HARD RULE: it MUST NOT intercept /api/* . The SSE stream (/api/hub/events), // clipboard, WebRTC signaling and relay all need a live, unbuffered network // connection — those requests are passed straight through to the network. Same // goes for cross-origin requests (fonts / CDN): the browser handles them. // // cdrop is useless offline (everything needs the backend), so this is a shell // cache for fast loads + installability, not a real offline app. const CACHE = "cdrop-shell-v1"; const SHELL = [ "/", "/site.webmanifest", "/favicon-96.png", "/icon-192.png", "/apple-touch-icon-180.png", "/logo-mark.png", ]; self.addEventListener("install", (event) => { event.waitUntil( caches.open(CACHE) .then((cache) => cache.addAll(SHELL)) .then(() => self.skipWaiting()) .catch(() => self.skipWaiting()), ); }); self.addEventListener("activate", (event) => { event.waitUntil( caches.keys() .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) .then(() => self.clients.claim()), ); }); self.addEventListener("fetch", (event) => { const req = event.request; if (req.method !== "GET") { return; } const url = new URL(req.url); if (url.origin !== self.location.origin) { return; } // cross-origin (fonts/CDN) → browser default if (url.pathname.startsWith("/api/")) { return; } // live backend → never intercept // SPA navigations: network-first so a new deploy serves fresh HTML (which // points at the new hashed assets); fall back to the cached shell offline. if (req.mode === "navigate") { event.respondWith( fetch(req) .then((resp) => { const copy = resp.clone(); caches.open(CACHE).then((c) => c.put("/", copy)).catch(() => {}); return resp; }) .catch(() => caches.match("/").then((r) => r || Response.error())), ); return; } // Static assets (hashed JS/CSS/images are immutable): stale-while-revalidate. event.respondWith( caches.match(req).then((cached) => { const network = fetch(req) .then((resp) => { if (resp && resp.status === 200 && resp.type === "basic") { const copy = resp.clone(); caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {}); } return resp; }) .catch(() => cached); return cached || network; }), ); });