const CACHE_NAME = 'alchemy-gardens-v1'; const PRECACHE_ASSETS = [ '/', '/collections/all' ]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(PRECACHE_ASSETS); }) ); self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames .filter((name) => name !== CACHE_NAME) .map((name) => caches.delete(name)) ); }) ); 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('/checkout') || url.pathname.startsWith('/admin') || url.pathname.startsWith('/cart') || url.pathname.includes('/account')) { return; } if (request.destination === 'image' || request.destination === 'style' || request.destination === 'script' || request.destination === 'font' || url.hostname.includes('cdn.shopify.com')) { event.respondWith( caches.match(request).then((cached) => { if (cached) return cached; return fetch(request).then((response) => { if (response && response.status === 200) { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)); } return response; }); }) ); return; } if (request.destination === 'document' || request.headers.get('accept')?.includes('text/html')) { event.respondWith( fetch(request) .then((response) => { if (response && response.status === 200) { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)); } return response; }) .catch(() => { return caches.match(request).then((cached) => { return cached || caches.match('/'); }); }) ); return; } event.respondWith( caches.match(request).then((cached) => { const fetchPromise = fetch(request).then((response) => { if (response && response.status === 200) { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)); } return response; }); return cached || fetchPromise; }) ); });