61 lines
1.7 KiB
JavaScript
61 lines
1.7 KiB
JavaScript
const CACHE = "tsumugu-shell-v1";
|
|
|
|
self.addEventListener("install", (event) => {
|
|
event.waitUntil(
|
|
caches
|
|
.open(CACHE)
|
|
.then((cache) => cache.add("/"))
|
|
.then(() => self.skipWaiting()),
|
|
);
|
|
});
|
|
|
|
self.addEventListener("activate", (event) => {
|
|
event.waitUntil(
|
|
caches
|
|
.keys()
|
|
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key))))
|
|
.then(() => self.clients.claim()),
|
|
);
|
|
});
|
|
|
|
self.addEventListener("fetch", (event) => {
|
|
const request = event.request;
|
|
if (request.method !== "GET" || request.headers.has("range")) return;
|
|
|
|
const url = new URL(request.url);
|
|
if (url.origin !== self.location.origin) return;
|
|
if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/health")) return;
|
|
if (url.pathname === "/sw.js" || url.pathname === "/manifest.webmanifest") return;
|
|
|
|
if (request.mode === "navigate") {
|
|
event.respondWith(networkFirstNavigation(request));
|
|
return;
|
|
}
|
|
|
|
if (url.pathname.startsWith("/assets/")) {
|
|
event.respondWith(cacheFirst(request));
|
|
}
|
|
});
|
|
|
|
async function networkFirstNavigation(request) {
|
|
const cache = await caches.open(CACHE);
|
|
try {
|
|
const response = await fetch(request);
|
|
if (response.ok && response.type === "basic") await cache.put("/", response.clone());
|
|
return response;
|
|
} catch (error) {
|
|
const cached = await cache.match("/");
|
|
if (cached) return cached;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function cacheFirst(request) {
|
|
const cache = await caches.open(CACHE);
|
|
const cached = await cache.match(request);
|
|
if (cached) return cached;
|
|
const response = await fetch(request);
|
|
if (response.ok && response.type === "basic") await cache.put(request, response.clone());
|
|
return response;
|
|
}
|