Files
Heimdall/src/Heimdall.Web/wwwroot/service-worker.js
T
Arnaud Dartois eb49f8e925
Heimdall Gitea / Build and tests (pull_request) Successful in 15m45s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 5m34s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 11m43s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
fix(pwa): match excluded routes case insensitively
2026-10-24 20:44:51 +02:00

65 lines
1.8 KiB
JavaScript

const CACHE_NAME = "heimdall-public-shell-v1";
const OFFLINE_PAGE = "/offline.html";
const PUBLIC_SHELL = [
OFFLINE_PAGE,
"/manifest.webmanifest",
"/pwa-icon.svg"
];
const NO_OFFLINE_FALLBACK_PATHS = [
"/api",
"/_auth",
"/_blazor",
"/hubs",
"/hangfire",
"/metrics",
"/health",
"/healthz",
"/swagger",
"/docs",
"/scalar",
"/openapi"
];
function hasPathPrefix(pathname, prefix) {
let decodedPath;
try {
decodedPath = decodeURIComponent(pathname).toLowerCase();
} catch {
return true;
}
return decodedPath === prefix || decodedPath.startsWith(`${prefix}/`);
}
self.addEventListener("install", event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(PUBLIC_SHELL))
.then(() => self.skipWaiting())
);
});
self.addEventListener("activate", event => {
event.waitUntil((async () => {
const names = await caches.keys();
await Promise.all(names
.filter(name => name.startsWith("heimdall-public-shell-") && name !== CACHE_NAME)
.map(name => caches.delete(name)));
await self.clients.claim();
})());
});
self.addEventListener("fetch", event => {
const request = event.request;
if (request.method !== "GET" || request.mode !== "navigate") return;
const requestUrl = new URL(request.url);
if (requestUrl.origin !== self.location.origin) return;
if (NO_OFFLINE_FALLBACK_PATHS.some(prefix => hasPathPrefix(requestUrl.pathname, prefix))) return;
// Navigation responses may contain authenticated, user-specific data. Always
// fetch them from the server and use only the public offline page on failure.
// Operational, API and technical routes retain their normal network behavior.
event.respondWith(fetch(request).catch(async () =>
(await caches.match(OFFLINE_PAGE)) ?? Response.error()));
});