// Find a Dispensary PWA Service Worker const CACHE_NAME = 'findadispo-v1'; const STATIC_ASSETS = [ '/', '/index.html', '/manifest.json', '/favicon.ico', ]; // Install event - cache static assets self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { console.log('Service Worker: Caching static assets'); return cache.addAll(STATIC_ASSETS); }) ); // Activate immediately self.skipWaiting(); }); // Activate event - clean up old caches self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames .filter((name) => name !== CACHE_NAME) .map((name) => { console.log('Service Worker: Clearing old cache', name); return caches.delete(name); }) ); }) ); // Take control immediately self.clients.claim(); }); // Fetch event - network first, fallback to cache self.addEventListener('fetch', (event) => { // Skip non-GET requests if (event.request.method !== 'GET') return; // Skip API requests if (event.request.url.includes('/api/')) return; event.respondWith( fetch(event.request) .then((response) => { // Clone response for caching const responseClone = response.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, responseClone); }); return response; }) .catch(() => { // Return cached version if offline return caches.match(event.request).then((cachedResponse) => { if (cachedResponse) { return cachedResponse; } // Return offline page for navigation requests if (event.request.mode === 'navigate') { return caches.match('/index.html'); } }); }) ); }); // Background sync for saved searches self.addEventListener('sync', (event) => { if (event.tag === 'sync-searches') { console.log('Service Worker: Syncing saved searches'); } }); // Push notifications self.addEventListener('push', (event) => { const options = { body: event.data?.text() || 'New update from Find a Dispensary', icon: '/logo192.png', badge: '/logo192.png', vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: 1 }, actions: [ { action: 'explore', title: 'View Details' }, { action: 'close', title: 'Close' } ] }; event.waitUntil( self.registration.showNotification('Find a Dispensary', options) ); }); // Handle notification click self.addEventListener('notificationclick', (event) => { event.notification.close(); if (event.action === 'explore') { event.waitUntil( clients.openWindow('/dashboard/alerts') ); } });