|
| 1 | +/// <reference types="@sveltejs/kit" /> |
| 2 | +/// <reference no-default-lib="true"/> |
| 3 | +/// <reference lib="esnext" /> |
| 4 | +/// <reference lib="webworker" /> |
| 5 | + |
| 6 | +import { build, files, version } from '$service-worker'; |
| 7 | + |
| 8 | +// Create a unique cache name for this deployment |
| 9 | +const CACHE = `cache-${version}`; |
| 10 | + |
| 11 | +const ASSETS = [ |
| 12 | + ...build, // the app itself |
| 13 | + ...files // everything in `static` |
| 14 | +]; |
| 15 | + |
| 16 | +const sw = self as unknown as ServiceWorkerGlobalScope; |
| 17 | + |
| 18 | +sw.addEventListener('install', (event) => { |
| 19 | + // Create a new cache and add all files to it |
| 20 | + async function addFilesToCache() { |
| 21 | + const cache = await caches.open(CACHE); |
| 22 | + await cache.addAll(ASSETS); |
| 23 | + } |
| 24 | + |
| 25 | + event.waitUntil(addFilesToCache()); |
| 26 | +}); |
| 27 | + |
| 28 | +sw.addEventListener('activate', (event) => { |
| 29 | + // Remove previous cached data from disk |
| 30 | + async function deleteOldCaches() { |
| 31 | + for (const key of await caches.keys()) { |
| 32 | + if (key !== CACHE) await caches.delete(key); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + event.waitUntil(deleteOldCaches()); |
| 37 | +}); |
| 38 | + |
| 39 | +sw.addEventListener('fetch', async (event) => { |
| 40 | + // ignore POST requests etc |
| 41 | + if (event.request.method !== 'GET') return; |
| 42 | + |
| 43 | + const url = new URL(event.request.url); |
| 44 | + // ignore requests from protocols like chrome-extension |
| 45 | + if (!url.protocol.startsWith('http')) return; |
| 46 | + |
| 47 | + async function respond(url: URL): Promise<Response> { |
| 48 | + const cache = await caches.open(CACHE); |
| 49 | + |
| 50 | + if (url.protocol) |
| 51 | + if (ASSETS.includes(url.pathname)) { |
| 52 | + // `build`/`files` can always be served from the cache |
| 53 | + return cache.match(url.pathname) as Promise<Response>; |
| 54 | + } |
| 55 | + |
| 56 | + // for everything else, try the network first, but |
| 57 | + // fall back to the cache if we're offline |
| 58 | + try { |
| 59 | + const response = await fetch(event.request); |
| 60 | + |
| 61 | + if (response.status === 200) { |
| 62 | + cache.put(event.request, response.clone()); |
| 63 | + } |
| 64 | + |
| 65 | + return response; |
| 66 | + } catch (error) { |
| 67 | + const match = await cache.match(event.request); |
| 68 | + |
| 69 | + if (!match) throw error; |
| 70 | + |
| 71 | + return match; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + event.respondWith(respond(url)); |
| 76 | +}); |
0 commit comments