62 lines
1.8 KiB
JavaScript
62 lines
1.8 KiB
JavaScript
// Basic service worker for PWA installability and future caching
|
|
// Generated by Copilot — you can extend with runtime caching if needed.
|
|
|
|
const CACHE_NAME = 'cvl-cache-v1';
|
|
const APP_SHELL = [
|
|
'/',
|
|
'/index.html',
|
|
'/icon.png',
|
|
// Vite will handle asset hashing; we keep shell minimal to avoid stale caches.
|
|
];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
// Skip waiting so updates activate faster.
|
|
self.skipWaiting();
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)).catch(() => void 0)
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) =>
|
|
Promise.all(
|
|
keys.map((k) => (k === CACHE_NAME ? undefined : caches.delete(k)))
|
|
)
|
|
)
|
|
);
|
|
// Take control of uncontrolled clients as soon as possible.
|
|
self.clients.claim();
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
// Only handle GET requests and same-origin.
|
|
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) {
|
|
return;
|
|
}
|
|
// Network-first for HTML navigations; cache-first for others.
|
|
if (request.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((resp) => {
|
|
const copy = resp.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put('/', copy)).catch(() => void 0);
|
|
return resp;
|
|
})
|
|
.catch(() => caches.match('/') || caches.match('/index.html'))
|
|
);
|
|
} else {
|
|
event.respondWith(
|
|
caches.match(request).then((cached) =>
|
|
cached ||
|
|
fetch(request).then((resp) => {
|
|
const copy = resp.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)).catch(() => void 0);
|
|
return resp;
|
|
}).catch(() => cached)
|
|
)
|
|
);
|
|
}
|
|
});
|