-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
69 lines (61 loc) · 2.48 KB
/
Copy pathsw.js
File metadata and controls
69 lines (61 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Beachwave service worker.
//
// Goals: make the app installable and resilient offline, WITHOUT ever
// interfering with authentication or media. Therefore it:
// * only touches same-origin GET requests;
// * never caches /api/* (token, grant-speak, client-metadata) — always network;
// * never caches OAuth callbacks (requests carrying ?code/?state) — always network;
// * serves navigations network-first (fresh app after every deploy), falling
// back to the cached shell only when offline;
// * serves other same-origin assets stale-while-revalidate.
//
// Bump CACHE_VERSION to invalidate old caches on the next activation.
const CACHE_VERSION = 'beachwave-v1';
const SHELL = ['/', '/index.html', '/src/client/styles.css', '/beachwave.svg', '/manifest.webmanifest', '/icon-192.png', '/icon-512.png'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_VERSION).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key))))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return; // let cross-origin (esm.sh, bsky, livekit, fonts) pass through
if (url.pathname.startsWith('/api/')) return; // never cache server functions
if (url.search.includes('code=') || url.search.includes('state=')) return; // never cache OAuth callbacks
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((response) => {
cachePut(request, response.clone());
return response;
})
.catch(() => caches.match(request).then((cached) => cached || caches.match('/')))
);
return;
}
// Static assets: stale-while-revalidate.
event.respondWith(
caches.match(request).then((cached) => {
const network = fetch(request)
.then((response) => {
cachePut(request, response.clone());
return response;
})
.catch(() => cached);
return cached || network;
})
);
});
function cachePut(request, response) {
if (!response || !response.ok || response.type === 'opaque') return;
caches.open(CACHE_VERSION).then((cache) => cache.put(request, response));
}