// Offline support: the app shell and every built asset are cached on first use, // so lessons, quizzes, flashcards and mock exams work without a connection. // The AI tutor (/api/*) always goes to the network. const CACHE = 'kcna-v1'; self.addEventListener('install', (e) => { e.waitUntil(caches.open(CACHE).then((c) => c.addAll(['./', './index.html', './manifest.webmanifest', './theme-init.js', './favicon.svg']))); self.skipWaiting(); }); self.addEventListener('activate', (e) => { e.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim())); }); self.addEventListener('fetch', (e) => { const req = e.request; const url = new URL(req.url); if (req.method !== 'GET' || url.origin !== location.origin || url.pathname.includes('/api/')) return; if (req.mode === 'navigate') { // network first for the page itself so new deployments show up; cache when offline e.respondWith( fetch(req) .then((res) => { const copy = res.clone(); caches.open(CACHE).then((c) => c.put('./index.html', copy)); return res; }) .catch(() => caches.match('./index.html')), ); return; } // hashed assets never change: cache first e.respondWith( caches.match(req).then( (hit) => hit || fetch(req).then((res) => { if (res.ok) { const copy = res.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return res; }), ), ); });