// 정적 자원 캐시 전략: // - index.html: stale-while-revalidate. 캐시 즉시 반환 → 부팅 0초 시작. // 백그라운드로 새 HTML fetch 후 응답이 캐시와 다르면 클라이언트에 sw-updated 알림 → 자동 reload. // - 그 외 정적(favicon, manifest, sw.js 자체 제외): cache-first. // - API / cdn / 외부 호스트: 항상 네트워크 (캐시 우회). const CACHE = 'tvchak-v8'; self.addEventListener('install', (e) => { // 새 SW는 즉시 활성화 (옛 SW 대기 안 함) self.skipWaiting(); }); self.addEventListener('activate', (e) => { e.waitUntil((async () => { // 옛 캐시 모두 폐기 const keys = await caches.keys(); await Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k))); // 즉시 모든 클라이언트 take over await self.clients.claim(); // 열려있는 탭들에게 새 SW 활성화 알림 → 자동 reload 가능하도록 const clients = await self.clients.matchAll({ type: 'window' }); for (const c of clients) c.postMessage({ type: 'sw-updated' }); })()); }); // 본문 변경 감지용 — Cache API의 ResponseBody는 한 번만 읽으므로 미리 hash 계산해 저장. // 가벼운 FNV-1a 32bit (HTML 50KB 대상이라 충분). async function hashOfResponse(resp) { try { const text = await resp.clone().text(); let h = 0x811c9dc5; for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0; } return h.toString(16); } catch { return null; } } // 캐시 항목에 우리만 쓰는 해시 헤더를 붙여 저장. 다음 비교 때 이 헤더를 키로. async function storeWithHash(cache, request, resp) { const hash = await hashOfResponse(resp); if (hash == null) { await cache.put(request, resp); return; } const text = await resp.clone().text(); const newHeaders = new Headers(resp.headers); newHeaders.set('X-Tvchak-Body-Hash', hash); await cache.put(request, new Response(text, { status: resp.status, statusText: resp.statusText, headers: newHeaders, })); } self.addEventListener('fetch', (e) => { const url = new URL(e.request.url); if (e.request.method !== 'GET') return; // API / cdn / 외부 호스트는 캐시 우회 (항상 네트워크) if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/cdn') || url.origin !== self.location.origin) return; // HTML(/, /index.html) — stale-while-revalidate if (url.pathname === '/' || url.pathname === '/index.html') { e.respondWith((async () => { const cache = await caches.open(CACHE); const cached = await cache.match(e.request); // 백그라운드로 네트워크 갱신 (await 안 함 — 캐시는 바로 반환) const networkPromise = fetch(e.request).then(async (resp) => { if (!resp || resp.status !== 200) return; const oldHash = cached?.headers.get('X-Tvchak-Body-Hash'); const newHash = await hashOfResponse(resp); await storeWithHash(cache, e.request, resp); // 본문이 달라졌으면 클라이언트에 알림 — 자동 reload 트리거 if (cached && oldHash && newHash && oldHash !== newHash) { const clients = await self.clients.matchAll({ type: 'window' }); for (const c of clients) c.postMessage({ type: 'sw-updated' }); } }).catch(() => {}); if (cached) { // 캐시 있으면 즉시 반환, 네트워크는 백그라운드 e.waitUntil(networkPromise); return cached; } // 캐시 없으면(첫 방문) 네트워크 결과 기다림 try { const resp = await fetch(e.request); if (resp && resp.status === 200) { await storeWithHash(cache, e.request, resp.clone()); } return resp; } catch { // 오프라인 + 캐시 없음 — 최후 폴백 return cache.match('/index.html') || new Response('offline', { status: 503 }); } })()); return; } // 그 외 정적(favicon, manifest 등)은 cache-first e.respondWith( caches.match(e.request).then(hit => hit || fetch(e.request).then(resp => { if (resp && resp.status === 200 && resp.type === 'basic') { const clone = resp.clone(); caches.open(CACHE).then(c => c.put(e.request, clone)).catch(() => {}); } return resp; })) ); });