Coves frontend - a photon fork
at main 89 lines 2.4 kB view raw
1/// <reference types="@sveltejs/kit" /> 2/// <reference no-default-lib="true"/> 3/// <reference lib="esnext" /> 4/// <reference lib="webworker" /> 5 6import { build, files, version } from '$service-worker' 7 8// Create a unique cache name for this deployment 9const CACHE = `cache-${version}` 10 11const ASSETS = [ 12 ...build, // the app itself 13 ...files, // everything in `static` 14] 15 16self.addEventListener('install', (event) => { 17 console.info('[i] Installing service worker') 18 // Create a new cache and add all files to it 19 async function addFilesToCache() { 20 const cache = await caches.open(CACHE) 21 await cache.addAll(ASSETS) 22 } 23 24 event.waitUntil(addFilesToCache()) 25}) 26 27self.addEventListener('activate', (event) => { 28 console.info('[i] Activating service worker') 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 39self.addEventListener('fetch', (e) => { 40 const event = e as FetchEvent 41 // ignore POST requests etc 42 if (event.request.method !== 'GET') return 43 44 async function respond() { 45 const url = new URL(event.request.url) 46 const cache = await caches.open(CACHE) 47 48 // `build`/`files` can always be served from the cache 49 if (ASSETS.includes(url.pathname)) { 50 const response = await cache.match(url.pathname) 51 52 if (response) return response 53 } 54 55 if (url.pathname.includes('/api/')) { 56 return fetch(event.request) 57 } 58 59 // for everything else, try the network first, but 60 // fall back to the cache if we're offline 61 try { 62 const response = await fetch(event.request) 63 64 // if we're offline, fetch can return a value that is not a Response 65 // instead of throwing - and we can't pass this non-Response to respondWith 66 if (!(response instanceof Response)) { 67 throw new Error('invalid response from fetch') 68 } 69 70 if (response.ok) { 71 cache.put(event.request, response.clone()) 72 } 73 74 return response 75 } catch (err) { 76 const response = await cache.match(event.request) 77 78 if (response) { 79 return response 80 } 81 82 // if there's no cache, then just error out 83 // as there is nothing we can do to respond to this request 84 throw err 85 } 86 } 87 88 event.respondWith(respond()) 89})