const CACHE_NAME = 'inknote-v2'; // Install — cache app shell on first load self.addEventListener('install', (e) => { e.waitUntil( caches.open(CACHE_NAME).then(async (cache) => { // Cache the main page and manifest const urls = ['/', '/manifest.json', '/icon-192.png', '/icon-512.png']; for (const url of urls) { try { await cache.add(url); } catch (err) { console.warn('[SW] Failed to cache:', url); } } }) ); self.skipWaiting(); }); // Activate — clean old caches self.addEventListener('activate', (e) => { e.waitUntil( caches.keys().then(keys => Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))) ); self.clients.claim(); }); // Fetch handler self.addEventListener('fetch', (e) => { const url = new URL(e.request.url); // Skip API/WebSocket requests entirely — handled by app + IndexedDB if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/ws')) return; // Skip non-GET requests if (e.request.method !== 'GET') return; // Navigation (HTML pages) — network-first, fallback to cache if (e.request.mode === 'navigate') { e.respondWith( fetch(e.request) .then(r => { const c = r.clone(); caches.open(CACHE_NAME).then(cache => cache.put('/', c)); return r; }) .catch(() => caches.match('/')) ); return; } // JS/CSS/images — stale-while-revalidate e.respondWith( caches.match(e.request).then(cached => { const fetchP = fetch(e.request).then(r => { if (r.ok && r.type === 'basic') { caches.open(CACHE_NAME).then(cache => cache.put(e.request, r.clone())); } return r; }).catch(() => cached); return cached || fetchP; }) ); }); // Background sync self.addEventListener('sync', (e) => { if (e.tag === 'sync-changes') { e.waitUntil(self.clients.matchAll().then(clients => { clients.forEach(c => c.postMessage({ type: 'FLUSH_QUEUE' })); })); } });