'use strict'; const CACHE_NAME = 'aamos-admin-v1'; const OFFLINE_URL = '/admin/'; const SHELL = [ '/admin/', '/admin/index.html', '/admin/dashboard.html', '/admin/modules.html', '/admin/assets/admin.js', '/admin/assets/api.js', ]; // ── Install: precache shell ─────────────────────────────────────────── self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then((cache) => cache.addAll(SHELL)) .then(() => self.skipWaiting()) ); }); // ── Activate: purge stale caches ───────────────────────────────────── self.addEventListener('activate', (event) => { event.waitUntil( caches.keys() .then((keys) => Promise.all( keys .filter((key) => key !== CACHE_NAME) .map((key) => caches.delete(key)) )) .then(() => self.clients.claim()) ); }); // ── Fetch ───────────────────────────────────────────────────────────── self.addEventListener('fetch', (event) => { const { request } = event; if (request.method !== 'GET') return; if (!request.url.startsWith('http')) return; const { pathname } = new URL(request.url); // API + auth: network-only, never cache tokens/responses if (pathname.startsWith('/api/') || pathname.startsWith('/auth/')) return; // Navigation: network-first → cached shell on offline if (request.mode === 'navigate') { event.respondWith( fetch(request) .catch(() => caches.match(request) .then((cached) => cached || caches.match(OFFLINE_URL)) .then((r) => r || offlineResponse()) ) ); return; } // Static assets: cache-first → fetch + update cache on miss event.respondWith( caches.match(request).then((cached) => { if (cached) return cached; return fetch(request).then((response) => { if (!response || response.status !== 200 || response.type === 'opaque') { return response; } const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)); return response; }).catch(() => caches.match(OFFLINE_URL).then((r) => r || offlineResponse())); }) ); }); function offlineResponse() { return new Response( 'Offline' + '' + '' + '

Ingen anslutning

' + '

Kontrollera nätverket och försök igen.

' + '
', { status: 503, headers: { 'Content-Type': 'text/html;charset=UTF-8' } } ); }