62 lines
1.6 KiB
JavaScript
62 lines
1.6 KiB
JavaScript
const CACHE_NAME = "auratrade-v1.0.0";
|
|
const STATIC_ASSETS = [
|
|
"/",
|
|
"/manifest.json",
|
|
"/icons/icon-192x192.png",
|
|
"/icons/icon-512x512.png",
|
|
"/icons/apple-touch-icon.png",
|
|
"/favicon.ico"
|
|
];
|
|
|
|
// Install: Cache static app shell
|
|
self.addEventListener("install", (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
return cache.addAll(STATIC_ASSETS);
|
|
})
|
|
);
|
|
self.skipWaiting();
|
|
});
|
|
|
|
// Activate: Clean up old caches
|
|
self.addEventListener("activate", (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) => {
|
|
return Promise.all(
|
|
keys.map((key) => {
|
|
if (key !== CACHE_NAME) {
|
|
return caches.delete(key);
|
|
}
|
|
})
|
|
);
|
|
})
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
// Fetch: Bypass live API & WebSocket, Stale-while-revalidate for static assets
|
|
self.addEventListener("fetch", (event) => {
|
|
const url = new URL(event.request.url);
|
|
|
|
// Always bypass cache for live APIs and WebSockets
|
|
if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/ws")) {
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
caches.match(event.request).then((cachedResponse) => {
|
|
const fetchPromise = fetch(event.request).then((networkResponse) => {
|
|
if (networkResponse && networkResponse.status === 200 && event.request.method === "GET") {
|
|
const responseToCache = networkResponse.clone();
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(event.request, responseToCache);
|
|
});
|
|
}
|
|
return networkResponse;
|
|
}).catch(() => cachedResponse);
|
|
|
|
return cachedResponse || fetchPromise;
|
|
})
|
|
);
|
|
});
|