const CACHE_NAME = @json($cacheName); const CACHE_PREFIX = @json($cachePrefix); const SHELL_URLS = @json($shellUrls); const PRIVATE_PATH_FRAGMENTS = @json($privatePathFragments); const FALLBACK_URL = @json($fallbackUrl); const CREATE_URL = @json($createUrl); const ASSET_PREFIXES = @json($assetPrefixes); const isPrivatePath = (pathname) => PRIVATE_PATH_FRAGMENTS.some(fragment => pathname.includes(fragment)); const isAsset = (url) => ASSET_PREFIXES.some(prefix => url.pathname.startsWith(prefix)); const publicShellUrl = (url) => SHELL_URLS.includes(url.pathname); // Only anonymous server responses may be retained as public navigation shells. // Never cache the HTML returned by a signed-in navigation. const cacheShellResource = async (cache, path) => { try { const response = await fetch(new Request(path, {cache: 'reload', credentials: 'omit'})); if (response.ok && response.type === 'basic' && !response.redirected && !/no-store/i.test(response.headers.get('Cache-Control') || '')) { await cache.put(path, response); } } catch { /* A partial cache is allowed, never a fake offline success. */ } }; self.addEventListener('install', event => event.waitUntil( caches.open(CACHE_NAME).then(cache => Promise.allSettled(SHELL_URLS.map(path => cacheShellResource(cache, path)))).then(() => self.skipWaiting()) )); self.addEventListener('activate', event => event.waitUntil( caches.keys().then(keys => Promise.all(keys.filter(key => key.startsWith(CACHE_PREFIX + '-') && key !== CACHE_NAME).map(key => caches.delete(key)))).then(() => self.clients.claim()) )); const navigate = async request => { try { return await fetch(request); } catch { const url = new URL(request.url); const cache = await caches.open(CACHE_NAME); if (!isPrivatePath(url.pathname) && publicShellUrl(url)) { const shell = await cache.match(url.pathname); if (shell) return shell; } return (await cache.match(FALLBACK_URL)) || Response.error(); } }; const cacheFirstAsset = async request => { const cache = await caches.open(CACHE_NAME); const cached = await cache.match(request); if (cached) return cached; const response = await fetch(request); if (response.ok && response.type === 'basic' && !response.redirected && !/private|no-store/i.test(response.headers.get('Cache-Control') || '')) { await cache.put(request, response.clone()); } return response; }; self.addEventListener('fetch', event => { const request = event.request; const url = new URL(request.url); if (request.method !== 'GET' || url.origin !== self.location.origin) return; if (request.mode === 'navigate') { event.respondWith(navigate(request)); return; } if (isPrivatePath(url.pathname) || !isAsset(url)) return; if (['style', 'script', 'image', 'font'].includes(request.destination)) event.respondWith(cacheFirstAsset(request)); });