const CACHE_NAME = 'whisky-vault-v3'; // Increment version to apply new strategy const ASSETS_TO_CACHE = [ '/manifest.json', '/icon-192.png', '/icon-512.png', '/favicon.ico', ]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(ASSETS_TO_CACHE); }) ); }); self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.map((cacheName) => { if (cacheName !== CACHE_NAME) { return caches.delete(cacheName); } }) ); }) ); self.clients.claim(); }); // Helper for Network-First with Timeout function fetchWithTimeout(request, timeoutMs = 3000) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { reject(new Error('Network timeout')); }, timeoutMs); fetch(request).then( (response) => { clearTimeout(timeoutId); resolve(response); }, (err) => { clearTimeout(timeoutId); reject(err); } ); }); } self.addEventListener('fetch', (event) => { const url = new URL(event.request.url); // CRITICAL: Always bypass cache for auth, api, and supabase requests const isAuthRequest = url.pathname.includes('/auth/') || url.pathname.includes('/v1/auth/') || url.pathname.includes('/v1/token'); const isApiRequest = url.pathname.includes('/api/'); const isSupabaseRequest = url.hostname.includes('supabase.co'); if (isAuthRequest || isApiRequest || isSupabaseRequest) { return; } // 1. ASSETS & APP SHELL: Stale-While-Revalidate const isAsset = event.request.destination === 'style' || event.request.destination === 'script' || event.request.destination === 'worker' || event.request.destination === 'font' || event.request.destination === 'image' || url.pathname.startsWith('/_next/static'); if (isAsset) { event.respondWith( caches.match(event.request).then((cachedResponse) => { const fetchPromise = fetch(event.request).then((networkResponse) => { if (networkResponse && networkResponse.status === 200) { const responseClone = networkResponse.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, responseClone); }); } return networkResponse; }); return cachedResponse || fetchPromise; }) ); return; } // 2. NAVIGATION: Network-First with 3s Timeout if (event.request.mode === 'navigate') { event.respondWith( fetchWithTimeout(event.request, 3000) .catch(() => { console.log('[SW] Navigation network failure or timeout, falling back to cache'); return caches.match(event.request); }) ); return; } // Default: Network-Only or default fetch return; });