98 lines
2.4 KiB
JavaScript
98 lines
2.4 KiB
JavaScript
const cacheName = "xiteng-portal-v8";
|
|
const appShell = [
|
|
"/",
|
|
"/styles.css",
|
|
"/app.js?v=7",
|
|
"/manifest.webmanifest",
|
|
"/favicon.svg",
|
|
"/favicon.ico",
|
|
"/icons/favicon-32.png",
|
|
"/icons/apple-touch-icon.png",
|
|
"/icons/icon-192.png",
|
|
"/icons/icon-512.png",
|
|
"/icons/icon-maskable-512.png"
|
|
];
|
|
|
|
self.addEventListener("install", (event) => {
|
|
event.waitUntil(
|
|
caches.open(cacheName)
|
|
.then((cache) => cache.addAll(appShell))
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
self.addEventListener("activate", (event) => {
|
|
event.waitUntil(
|
|
caches.keys()
|
|
.then((keys) => Promise.all(keys.filter((key) => key !== cacheName).map((key) => caches.delete(key))))
|
|
.then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
self.addEventListener("fetch", (event) => {
|
|
const request = event.request;
|
|
const url = new URL(request.url);
|
|
|
|
if (request.method !== "GET" || url.origin !== self.location.origin) {
|
|
return;
|
|
}
|
|
|
|
if (url.pathname.startsWith("/api/")) {
|
|
event.respondWith(
|
|
fetch(request).catch(() => new Response(
|
|
JSON.stringify({error: "Network unavailable"}),
|
|
{
|
|
status: 503,
|
|
headers: {
|
|
"Cache-Control": "no-store",
|
|
"Content-Type": "application/json; charset=utf-8"
|
|
}
|
|
}
|
|
))
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (url.pathname.startsWith("/admin")
|
|
|| url.pathname.startsWith("/account")
|
|
|| url.pathname === "/admin.js"
|
|
|| url.pathname === "/account.js"
|
|
|| url.pathname.startsWith("/oauth2/")
|
|
|| url.pathname.startsWith("/outpost.goauthentik.io/")) {
|
|
event.respondWith(fetch(request));
|
|
return;
|
|
}
|
|
|
|
if (request.mode === "navigate") {
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
if (response.ok && ["/", "/index.html"].includes(url.pathname)) {
|
|
const copy = response.clone();
|
|
caches.open(cacheName).then((cache) => cache.put("/", copy));
|
|
}
|
|
return response;
|
|
})
|
|
.catch(() => caches.match("/"))
|
|
);
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
caches.match(request).then((cached) => {
|
|
const network = fetch(request).then((response) => {
|
|
if (response.ok) {
|
|
const copy = response.clone();
|
|
caches.open(cacheName).then((cache) => cache.put(request, copy));
|
|
}
|
|
return response;
|
|
});
|
|
if (cached) {
|
|
network.catch(() => undefined);
|
|
return cached;
|
|
}
|
|
return network;
|
|
})
|
|
);
|
|
});
|