/* * The Church App's service worker (APP-1.0-PLAN ยง2, P2). No push and no notification permission * (decision 13): it only keeps the App usable offline. * * - Next's built files and the icons: from the cache, refreshed in the background. * - Pages: from the network; a copy is kept for offline. Offline, the last copy of that page shows * (the page says "You're offline"), else the offline page. * - A page rendered for a signed-in member (the proxy marks it `x-cca-signed-in: 1`) is kept apart, * and that cache is emptied as soon as a page comes back signed out or the member signs out, so * nothing personal stays on the phone for someone signed out. * - The API, the admin and signing in are never cached. */ const VERSION = "cca-v1"; const SHELL = `${VERSION}-shell`; const PAGES = `${VERSION}-pages`; const PERSONAL = `${VERSION}-personal`; const OFFLINE = "/offline"; self.addEventListener("install", (event) => { event.waitUntil(caches.open(SHELL).then((c) => c.addAll([OFFLINE, "/manifest.webmanifest"])).then(() => self.skipWaiting())); }); self.addEventListener("activate", (event) => { event.waitUntil( caches.keys() .then((keys) => Promise.all(keys.filter((k) => !k.startsWith(`${VERSION}-`)).map((k) => caches.delete(k)))) .then(() => self.clients.claim()), ); }); const neverCached = (path) => path.startsWith("/api/") || path.startsWith("/admin") || path.startsWith("/auth/"); async function fromCacheThenRefresh(request) { const cache = await caches.open(SHELL); const hit = await cache.match(request); const refresh = fetch(request).then((res) => { if (res.ok) cache.put(request, res.clone()); return res; }); return hit ?? refresh; } async function page(request) { const url = new URL(request.url); try { const res = await fetch(request); const signedIn = res.headers.get("x-cca-signed-in") === "1"; if (!signedIn) await caches.delete(PERSONAL); if (res.ok && !neverCached(url.pathname)) { const cache = await caches.open(signedIn ? PERSONAL : PAGES); await cache.put(url.pathname, res.clone()); } return res; } catch { const personal = await caches.open(PERSONAL).then((c) => c.match(url.pathname)); const saved = personal ?? (await caches.open(PAGES).then((c) => c.match(url.pathname))); return saved ?? (await caches.open(SHELL).then((c) => c.match(OFFLINE))) ?? Response.error(); } } self.addEventListener("fetch", (event) => { const { request } = event; if (request.method !== "GET") { // Signing out: forget the member's pages at once. if (new URL(request.url).pathname === "/api/auth/signout") event.waitUntil(caches.delete(PERSONAL)); return; } const url = new URL(request.url); if (url.origin !== self.location.origin) return; if (url.pathname.startsWith("/_next/static/") || url.pathname.startsWith("/app-icon/")) { event.respondWith(fromCacheThenRefresh(request)); return; } if (request.mode === "navigate" && !neverCached(url.pathname)) event.respondWith(page(request)); });