Files
sudoku-tools/public/sw.js
T

120 lines
3.7 KiB
JavaScript

/* Sudoku Tools offline worker. This file intentionally has no dependencies. */
const CACHE_PREFIX = "sudoku-tools-shell-";
const CACHE_VERSION = "v1";
const CACHE_NAME = `${CACHE_PREFIX}${CACHE_VERSION}`;
const CORE_ASSETS = ["./", "./manifest.webmanifest", "./favicon.svg"];
const BUILD_ASSET_PATTERN =
/(?:(?:\.\/)?assets\/)?[A-Za-z0-9][A-Za-z0-9._-]*-[A-Za-z0-9_-]{6,}\.(?:css|js|json|png|svg|wasm)/gu;
async function cacheAssetTree(cache, assetUrl, discovered, depth = 0) {
const url = new URL(assetUrl, self.registration.scope).href;
if (discovered.has(url)) return;
discovered.add(url);
const response = await fetch(url, { cache: "no-cache" });
if (!response.ok) return;
await cache.put(url, response.clone());
const contentType = response.headers.get("content-type") ?? "";
if (depth >= 3 || !/(?:javascript|text\/css)/iu.test(contentType)) return;
const source = await response.text();
await Promise.all(
[...source.matchAll(BUILD_ASSET_PATTERN)].map((match) => {
const reference = match[0];
const base = reference.includes("assets/")
? self.registration.scope
: url;
return cacheAssetTree(
cache,
new URL(reference, base).href,
discovered,
depth + 1,
);
}),
);
}
async function cacheDocumentAssets(cache) {
const response = await fetch("./", { cache: "no-cache" });
if (!response.ok) throw new Error("Could not cache the application shell.");
await cache.put("./", response.clone());
const html = await response.text();
const urls = new Set(CORE_ASSETS.slice(1));
for (const match of html.matchAll(/(?:src|href)=["']([^"'#]+)["']/giu)) {
const raw = match[1];
if (raw === undefined) continue;
const resolved = new URL(raw, self.registration.scope);
if (resolved.origin === self.location.origin) urls.add(resolved.href);
}
const canonicalUrls = new Set([new URL("./", self.registration.scope).href]);
await Promise.all(
[...urls].map((url) => cacheAssetTree(cache, url, canonicalUrls)),
);
await Promise.all(
(await cache.keys())
.filter((request) => !canonicalUrls.has(request.url))
.map((request) => cache.delete(request)),
);
}
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then(cacheDocumentAssets)
.then(() => self.skipWaiting()),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
.map((key) => caches.delete(key)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const request = event.request;
if (request.method !== "GET") return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (request.mode === "navigate") {
event.respondWith(
fetch(request)
.then(async (response) => {
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
await cache.put("./", response.clone());
}
return response;
})
.catch(async () => {
const cached = await caches.match("./");
return cached ?? Response.error();
}),
);
return;
}
event.respondWith(
caches.match(request).then(
(cached) =>
cached ??
fetch(request).then(async (response) => {
if (response.ok && response.type === "basic") {
const cache = await caches.open(CACHE_NAME);
await cache.put(request, response.clone());
}
return response;
}),
),
);
});