'use strict'; // v2: card faces are now precached so they never flash or refetch mid-game const CACHE_NAME = 'hearts-v2'; // ── All 52 card faces ─────────────────────────────────────────── const SUITS = ['CLUB', 'DIAMOND', 'HEART', 'SPADE']; const CARD_PATHS = SUITS.flatMap(s => [ `/cards/${s}-1.svg`, `/cards/${s}-2.svg`, `/cards/${s}-3.svg`, `/cards/${s}-4.svg`, `/cards/${s}-5.svg`, `/cards/${s}-6.svg`, `/cards/${s}-7.svg`, `/cards/${s}-8.svg`, `/cards/${s}-9.svg`, `/cards/${s}-10.svg`, `/cards/${s}-11-JACK.svg`, `/cards/${s}-12-QUEEN.svg`, `/cards/${s}-13-KING.svg`, ]); const SHELL = [ '/', '/index.html', '/style.css', '/app.js', '/manifest.json', '/icons/icon-192.png', '/icons/icon-512.png', '/icons/icon.svg', ]; self.addEventListener('install', event => { event.waitUntil((async () => { const cache = await caches.open(CACHE_NAME); // The shell must land; a missing card shouldn't abort the whole install await cache.addAll(SHELL); await Promise.all(CARD_PATHS.map(p => cache.add(p).catch(() => {}))); })()); self.skipWaiting(); }); self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(keys => Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k))) ) ); self.clients.claim(); }); self.addEventListener('fetch', event => { const url = event.request.url; if (event.request.method !== 'GET') return; if (url.includes('/socket.io/')) return; // Cards never change — always cache-first, and never go to the network again // once we hold a copy. if (url.includes('/cards/')) { event.respondWith( caches.match(event.request).then(cached => cached || fetch(event.request).then(res => { const copy = res.clone(); caches.open(CACHE_NAME).then(c => c.put(event.request, copy)); return res; })) ); return; } // Everything else: network-first, cache as the offline fallback event.respondWith( fetch(event.request) .then(res => { const copy = res.clone(); caches.open(CACHE_NAME).then(c => c.put(event.request, copy)); return res; }) .catch(() => caches.match(event.request)) ); });