Files
image-prompt-studio/public/sw.js
2026-04-25 11:26:33 +08:00

101 lines
2.4 KiB
JavaScript

const STATIC_CACHE_PREFIX = "image-prompt-studio-static";
const STATIC_CACHE_NAME = `${STATIC_CACHE_PREFIX}-v1`;
function shouldCache(requestUrl) {
if (requestUrl.origin !== self.location.origin) {
return false;
}
return (
requestUrl.pathname.startsWith("/_next/static/") ||
requestUrl.pathname === "/manifest.webmanifest" ||
requestUrl.pathname === "/pwa-icon.svg" ||
requestUrl.pathname === "/pwa-icon-maskable.svg" ||
requestUrl.pathname === "/pwa-badge.svg"
);
}
self.addEventListener("install", () => {
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
Promise.all([
self.clients.claim(),
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames
.filter(
(cacheName) =>
cacheName.startsWith(STATIC_CACHE_PREFIX) &&
cacheName !== STATIC_CACHE_NAME,
)
.map((cacheName) => caches.delete(cacheName)),
),
),
]),
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") {
return;
}
const requestUrl = new URL(event.request.url);
if (!shouldCache(requestUrl)) {
return;
}
event.respondWith(
caches.open(STATIC_CACHE_NAME).then(async (cache) => {
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
return cachedResponse;
}
const networkResponse = await fetch(event.request);
if (networkResponse.ok) {
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
}),
);
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const destinationUrl =
typeof event.notification.data?.url === "string"
? new URL(event.notification.data.url, self.location.origin).href
: `${self.location.origin}/studio`;
event.waitUntil(
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(
async (windowClients) => {
for (const client of windowClients) {
if ("focus" in client) {
await client.focus();
if ("navigate" in client) {
await client.navigate(destinationUrl);
}
return;
}
}
if (self.clients.openWindow) {
await self.clients.openWindow(destinationUrl);
}
},
),
);
});