mapcomplete/service-worker.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

73 lines
2.6 KiB
TypeScript
Raw Normal View History

const version = "0.0.8-GITHUB-COMMIT"
2022-06-02 02:59:34 +02:00
interface ServiceWorkerFetchEvent extends Event {
request: RequestInfo & { url: string }
respondWith: (response: any | PromiseLike<Response>) => Promise<void>
}
async function install() {
console.log("Installing service worker!")
}
addEventListener("install", (e) => (<any>e).waitUntil(install()))
addEventListener("activate", (e) => (<any>e).waitUntil(activate()))
async function activate() {
console.log("Activating service worker")
2022-09-08 21:40:48 +02:00
caches
.keys()
2022-06-02 02:59:34 +02:00
.then((keys) => {
2022-06-02 03:02:35 +02:00
// Remove all old caches
2022-06-02 02:59:34 +02:00
Promise.all(keys.map((key) => key !== version && caches.delete(key)))
2022-09-08 21:40:48 +02:00
})
2022-06-02 02:59:34 +02:00
.catch(console.error)
2022-09-08 21:40:48 +02:00
}
2022-06-02 02:59:34 +02:00
2023-02-24 17:47:30 +01:00
const cacheFirst = async (event) => {
await event.respondWith(
2022-06-02 02:59:34 +02:00
caches.match(event.request, { ignoreSearch: true }).then((cacheResponse) => {
if (cacheResponse !== undefined) {
console.log("Loaded from cache: ", event.request)
return cacheResponse
}
return fetch(event.request).then((networkResponse) => {
return caches.open(version).then((cache) => {
cache.put(event.request, networkResponse.clone())
console.log("Cached", event.request)
return networkResponse
})
})
})
)
}
2023-02-24 17:47:30 +01:00
self.addEventListener("fetch", async (e) => {
2022-06-02 02:59:34 +02:00
// Important: this lambda must run synchronously, as the browser will otherwise handle the request
const event = <ServiceWorkerFetchEvent>e
2022-09-08 21:40:48 +02:00
try {
2022-06-02 02:59:34 +02:00
const origin = new URL(self.origin)
const requestUrl = new URL(event.request.url)
if (requestUrl.pathname.endsWith("service-worker-version")) {
console.log("Sending version number...")
2023-02-24 17:47:30 +01:00
await event.respondWith(
new Response(JSON.stringify({ "service-worker-version": version }))
)
2022-09-08 21:40:48 +02:00
return
}
const shouldBeCached =
origin.host === requestUrl.host &&
origin.hostname !== "127.0.0.1" &&
origin.hostname !== "localhost" &&
2022-06-02 02:59:34 +02:00
!origin.host.endsWith(".gitpod.io")
if (!shouldBeCached) {
console.log("Not intercepting ", requestUrl.toString(), origin.host, requestUrl.host)
// We return _without_ calling event.respondWith, which signals the browser that it'll have to handle it himself
2022-09-08 21:40:48 +02:00
return
2022-06-02 02:59:34 +02:00
}
2023-02-24 17:47:30 +01:00
await cacheFirst(event)
2022-09-08 21:40:48 +02:00
} catch (e) {
2022-06-02 02:59:34 +02:00
console.error("CRASH IN SW:", e)
2023-02-24 17:47:30 +01:00
await event.respondWith(fetch(event.request.url))
2022-09-08 21:40:48 +02:00
}
2022-06-02 02:59:34 +02:00
})