const CACHE_VERSION = "simple-llm-chat-ui-v2" const APP_SHELL_URLS = [ "/", "/manifest.webmanifest", "/icons/icon-192.png", "/icons/icon-512.png", "/icons/maskable-512.png", "/icons/apple-touch-icon.png", ] const CACHEABLE_DESTINATIONS = new Set(["font", "image", "script", "style"]) self.addEventListener("install", (event) => { event.waitUntil( caches .open(CACHE_VERSION) .then((cache) => cache.addAll(APP_SHELL_URLS)) .then(() => self.skipWaiting()) ) }) self.addEventListener("activate", (event) => { event.waitUntil( caches .keys() .then((keys) => Promise.all( keys .filter((key) => key !== CACHE_VERSION) .map((key) => caches.delete(key)) ) ) .then(() => self.clients.claim()) ) }) self.addEventListener("fetch", (event) => { const { request } = event const url = new URL(request.url) if (request.method !== "GET" || url.origin !== self.location.origin) { return } if (request.mode === "navigate") { event.respondWith(networkFirst(request)) return } if (CACHEABLE_DESTINATIONS.has(request.destination)) { event.respondWith(cacheFirst(request)) } }) async function networkFirst(request) { const cache = await caches.open(CACHE_VERSION) try { const response = await fetch(request) if (response.ok) { await cache.put(request, response.clone()) } return response } catch { return (await cache.match(request)) ?? (await cache.match("/")) } } async function cacheFirst(request) { const cache = await caches.open(CACHE_VERSION) const cached = await cache.match(request) if (cached) { return cached } const response = await fetch(request) if (response.ok) { await cache.put(request, response.clone()) } return response }