← back to Charge And Explore
public/sw.js
37 lines
// Charge & Explore service worker — offline app shell.
// Network-first for navigations/API (fresh data when online), cache fallback
// when offline. Never caches auth or the Tesla/Google flows.
const CACHE = "ce-v1";
const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/icon.svg"];
self.addEventListener("install", (e) => {
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
});
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (e) => {
const { request } = e;
const url = new URL(request.url);
if (request.method !== "GET") return;
// Never intercept auth/session flows.
if (url.pathname.startsWith("/auth/") || url.pathname.startsWith("/api/me") || url.pathname === "/admin") return;
// Network-first, fall back to cache (so offline shows the last-known shell/data).
e.respondWith(
fetch(request)
.then((res) => {
if (res.ok && url.origin === self.location.origin) {
const copy = res.clone();
caches.open(CACHE).then((c) => c.put(request, copy));
}
return res;
})
.catch(() => caches.match(request).then((r) => r || caches.match("/"))),
);
});