diff --git a/src/service-worker.ts b/src/service-worker.ts new file mode 100644 index 0000000..23f9f81 --- /dev/null +++ b/src/service-worker.ts @@ -0,0 +1,55 @@ +// https://svelte.dev/docs/kit/service-workers +// Disables access to DOM typings like `HTMLElement` which are not available +// inside a service worker and instantiates the correct globals +/// +/// +/// +// Ensures that the `$service-worker` import has proper type definitions +/// + +import { build, files, version } from "$service-worker"; + +const self = globalThis.self as unknown as ServiceWorkerGlobalScope; + +const CACHE = `cache-${version}`; + +// const ASSETS = [...files, ...build]; +const ASSETS = [...build]; + +self.addEventListener("install", (event) => { + self.skipWaiting(); + const openCache = async () => { + const cache = await caches.open(CACHE); + await cache.addAll(ASSETS); + }; + event.waitUntil(openCache()); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil(self.clients.claim()); + const clearCaches = async () => { + for (const key of await caches.keys()) { + if (key !== CACHE) { + await caches.delete(key); + } + } + }; + event.waitUntil(clearCaches()); +}); + +self.addEventListener("fetch", (event) => { + const { method } = event.request; + if (method !== "GET") return; + + const respond = async () => { + const url = new URL(event.request.url); + const cache = await caches.open(CACHE); + if (ASSETS.includes(url.pathname)) { + const response = await cache.match(url.pathname); + if (response) return response; + } + return fetch(event.request); + }; + + event.respondWith(respond()); +});