SPB Git

Repository Public

sw.ts 1.5 KB 20 lines typescript

1// App-shell service worker: makes the app installable and lets it open instantly. It never caches API answers or2// document content — files stay on the server and are fetched under the user's session every time.3const sw = self as unknown as ServiceWorkerGlobalScope; // typed by tsconfig.sw.json (WebWorker lib)4declare const __SW_VERSION__: string;5const CACHE = `spd-shell-${__SW_VERSION__}`;67sw.addEventListener('install', (e) => { e.waitUntil(caches.open(CACHE).then((c) => c.addAll(['/', '/manifest.webmanifest'])).then(() => sw.skipWaiting())); });8sw.addEventListener('activate', (e) => { e.waitUntil(caches.keys().then((ks) => Promise.all(ks.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => sw.clients.claim())); });9sw.addEventListener('fetch', (e) => {10  const req = e.request, url = new URL(req.url);11  if (req.method !== 'GET' || url.origin !== sw.location.origin || url.pathname.startsWith('/api/')) return; // network only12  if (url.pathname.startsWith('/assets/') || url.pathname.startsWith('/pwa/')) { // hashed, immutable13    e.respondWith(caches.open(CACHE).then(async (c) => (await c.match(req)) ?? fetch(req).then((res) => { if (res.ok) void c.put(req, res.clone()); return res; })));14    return;15  }16  if (req.mode === 'navigate') { // the shell: fresh when online, cached copy when offline17    e.respondWith(fetch(req).then((res) => { if (res.ok) void caches.open(CACHE).then((c) => c.put('/', res.clone())); return res; }).catch(async () => (await caches.match('/')) ?? Response.error()));18  }19});20
Files main
Menu

Theme