const CACHE_NAME = "termix-v1"; const STATIC_ASSETS = [ "/", "/index.html", "/manifest.json", "/favicon.ico", "/icons/48x48.png", "/icons/128x128.png", "/icons/256x256.png", "/icons/512x512.png", ]; self.addEventListener("install", (event) => { event.waitUntil( caches .open(CACHE_NAME) .then((cache) => { return cache.addAll(STATIC_ASSETS); }) .then(() => { return self.skipWaiting(); }), ); }); self.addEventListener("activate", (event) => { event.waitUntil( caches .keys() .then((cacheNames) => { return Promise.all( cacheNames .filter((name) => name !== CACHE_NAME) .map((name) => { return caches.delete(name); }), ); }) .then(() => { return self.clients.claim(); }), ); }); self.addEventListener("fetch", (event) => { const { request } = event; const url = new URL(request.url); if (request.method !== "GET") { return; } if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/ws")) { return; } if (url.origin !== self.location.origin) { return; } if (request.mode === "navigate") { event.respondWith( fetch(request).catch(() => { return caches.match("/index.html"); }), ); return; } const isStaticAsset = STATIC_ASSETS.some((asset) => { if (asset === "/") return url.pathname === "/"; return url.pathname === asset || url.pathname.startsWith("/assets/"); }); if (!isStaticAsset) { return; } event.respondWith( caches.match(request).then((cachedResponse) => { if (cachedResponse) { return cachedResponse; } return fetch(request).then((response) => { if (!response || response.status !== 200 || response.type !== "basic") { return response; } const responseClone = response.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(request, responseClone); }); return response; }); }), ); });