const CACHE_NAME = 'darahub-cache-v1'; const PRECACHE_URLS = ['/', '/collections/all', '/cart']; self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return cache.addAll(PRECACHE_URLS); }).then(function() { return self.skipWaiting(); }) ); }); self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.filter(function(name) { return name.startsWith('darahub-cache-') && name !== CACHE_NAME; }).map(function(name) { return caches.delete(name); }) ); }).then(function() { return self.clients.claim(); }) ); }); self.addEventListener('fetch', function(event) { var request = event.request; var url = new URL(request.url); // Cache First: static assets if (request.destination === 'style' || request.destination === 'script' || request.destination === 'image' || request.destination === 'font') { event.respondWith( caches.match(request).then(function(cached) { return cached || fetch(request).then(function(response) { return caches.open(CACHE_NAME).then(function(cache) { cache.put(request, response.clone()); return response; }); }); }) ); return; } // Network First: HTML pages and API event.respondWith( fetch(request).then(function(response) { return caches.open(CACHE_NAME).then(function(cache) { cache.put(request, response.clone()); return response; }); }).catch(function() { return caches.match(request).then(function(cached) { return cached || caches.match('/'); }); }) ); }); self.addEventListener('sync', function(event) { if (event.tag === 'cart-sync') { event.waitUntil(syncCart()); } }); function syncCart() { return fetch('/cart.js').then(function(res) { return res.json(); }).then(function(cart) { return self.clients.matchAll().then(function(clients) { clients.forEach(function(client) { client.postMessage({ type: 'CART_SYNC', cart: cart }); }); }); }); } self.addEventListener('push', function(event) { var data = event.data ? event.data.json() : {}; event.waitUntil( self.registration.showNotification(data.title || 'DARAHUB', { body: data.body || 'New update available.', icon: '/path/to/icon-192.png', badge: '/path/to/badge.png', data: { url: data.url || '/' } }) ); }); self.addEventListener('notificationclick', function(event) { event.notification.close(); event.waitUntil( clients.openWindow(event.notification.data.url) ); });