/* ========================================================================== CHASSIS OCR PWA - SERVICE WORKER ========================================================================== */ const CACHE_NAME = 'chassis-ocr-pwa-v1'; const ASSETS_TO_CACHE = [ '/', '/index.html', '/app.css', '/app.js', '/manifest.json', '/icons/icon-192.png', '/icons/icon-512.png' ]; // Install Service Worker and Cache Assets self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then((cache) => { console.log('[Service Worker] Caching App Shell...'); return cache.addAll(ASSETS_TO_CACHE); }) .then(() => self.skipWaiting()) ); }); // Activate event (clean up old caches) self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keyList) => { return Promise.all(keyList.map((key) => { if (key !== CACHE_NAME) { console.log('[Service Worker] Removing old cache:', key); return caches.delete(key); } })); }).then(() => self.clients.claim()) ); }); // Fetch events (Network-first with Cache Fallback for API / Cache-first for Assets) self.addEventListener('fetch', (event) => { const requestUrl = new URL(event.request.url); // Bypass caching for backend API requests and other HTTP methods (POST, PUT, DELETE) if (event.request.method !== 'GET' || requestUrl.pathname.startsWith('/api/')) { return; } event.respondWith( caches.match(event.request) .then((cachedResponse) => { if (cachedResponse) { // Serve cached asset immediately, but fetch fresh version in the background fetch(event.request).then((networkResponse) => { if (networkResponse && networkResponse.status === 200) { caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, networkResponse); }); } }).catch(() => {/* Ignore network failures in background */}); return cachedResponse; } // If not cached, fetch from network return fetch(event.request).then((networkResponse) => { if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') { return networkResponse; } // Cache the newly fetched asset const responseToCache = networkResponse.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, responseToCache); }); return networkResponse; }); }) ); });