1
0
silverbullet/packages/web/service_worker.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

import { manifest, version } from "@parcel/service-worker";
async function install() {
const cache = await caches.open(version);
2022-05-04 14:09:39 +00:00
// console.log("Installing", manifest, "version", version);
await cache.addAll([...manifest, "/global.plug.json"]);
2022-04-25 17:46:08 +00:00
// @ts-ignore
self.skipWaiting(); // This automatically enables the service worker, preventing from caching stuff forever if there's a page open
2022-05-04 14:09:39 +00:00
// console.log("Installed");
}
2022-04-25 17:46:08 +00:00
//@ts-ignore
self.addEventListener("install", (e) => e.waitUntil(install()));
async function activate() {
const keys = await caches.keys();
2022-04-25 17:46:08 +00:00
// console.log("Activating for ", keys, "new version", version);
await Promise.all(keys.map((key) => key !== version && caches.delete(key)));
2022-04-07 13:21:30 +00:00
// console.log("DOne activating");
}
2022-04-25 17:46:08 +00:00
//@ts-ignore
self.addEventListener("activate", (e) => e.waitUntil(activate()));
2022-04-07 13:21:30 +00:00
self.addEventListener("fetch", (event: any) => {
event.respondWith(
caches.open(version).then(async (cache) => {
let parsedUrl = new URL(event.request.url);
// console.log("Got fetch request", parsedUrl.pathname);
let response = await cache.match(event.request, {
ignoreSearch: true,
});
// console.log("Got cache result", response);
if (response) {
return response;
} else {
if (
2022-09-12 12:50:37 +00:00
parsedUrl.pathname !== "/fs" &&
!parsedUrl.pathname.startsWith("/page/") &&
2022-04-07 13:21:30 +00:00
!parsedUrl.pathname.startsWith("/plug/")
) {
return cache.match("/index.html");
}
return fetch(event.request);
}
})
);
});