pkg/pwa/static/sw.js 4.1 K raw
1
// Shared andromeda service worker.
2
//
3
// Strategy:
4
//   - HTML navigations: network-first. Successful responses are cached, so
5
//     any page visited while online keeps working offline. Uncached pages
6
//     fall back to /offline.
7
//   - Static assets (css/js/fonts/images): stale-while-revalidate.
8
//   - Auth surfaces (/admin, /login, /logout), APIs, non-GET requests, and
9
//     cross-origin requests are never intercepted or cached.
10
//
11
// Bump CACHE_VERSION to invalidate all caches when this file changes.
12
13
const CACHE_VERSION = 'v1';
14
const SHELL_CACHE = 'andromeda-shell-' + CACHE_VERSION;
15
const PAGES_CACHE = 'andromeda-pages-' + CACHE_VERSION;
16
const ASSETS_CACHE = 'andromeda-assets-' + CACHE_VERSION;
17
const MAX_PAGE_ENTRIES = 60;
18
19
const OFFLINE_URL = '/offline';
20
21
// App-shell assets attempted at install. Entries missing in a given app are
22
// skipped, so the same worker works across apps with different layouts.
23
const SHELL_ASSETS = [
24
  OFFLINE_URL,
25
  '/static/site.webmanifest',
26
  '/static/styles.css',
27
  '/assets/darkmatter.css',
28
  '/assets/kepler.css',
29
];
30
31
// Requests the worker never touches.
32
const SKIP_PATTERNS = [
33
  /^\/admin(\/|$)/,
34
  /^\/login$/,
35
  /^\/logout$/,
36
  /^\/api\//,
37
];
38
39
self.addEventListener('install', (event) => {
40
  event.waitUntil(
41
    (async () => {
42
      const cache = await caches.open(SHELL_CACHE);
43
      await Promise.allSettled(
44
        SHELL_ASSETS.map(async (url) => {
45
          const res = await fetch(url, { cache: 'reload' });
46
          if (res.ok) await cache.put(url, res);
47
        })
48
      );
49
      await self.skipWaiting();
50
    })()
51
  );
52
});
53
54
self.addEventListener('activate', (event) => {
55
  event.waitUntil(
56
    (async () => {
57
      const keep = [SHELL_CACHE, PAGES_CACHE, ASSETS_CACHE];
58
      const names = await caches.keys();
59
      await Promise.all(
60
        names.filter((n) => !keep.includes(n)).map((n) => caches.delete(n))
61
      );
62
      await self.clients.claim();
63
    })()
64
  );
65
});
66
67
self.addEventListener('fetch', (event) => {
68
  if (!shouldHandle(event.request)) return;
69
  if (event.request.mode === 'navigate') {
70
    event.respondWith(handleNavigation(event.request));
71
  } else {
72
    event.respondWith(staleWhileRevalidate(event.request));
73
  }
74
});
75
76
function shouldHandle(request) {
77
  if (request.method !== 'GET') return false;
78
  const url = new URL(request.url);
79
  if (url.origin !== self.location.origin) return false;
80
  return !SKIP_PATTERNS.some((re) => re.test(url.pathname));
81
}
82
83
// Network-first for pages: fresh when online, cached copy when offline.
84
async function handleNavigation(request) {
85
  const cache = await caches.open(PAGES_CACHE);
86
  try {
87
    const response = await fetch(request);
88
    if (response.ok) {
89
      cache.put(request, response.clone());
90
      trimCache(cache, MAX_PAGE_ENTRIES);
91
    }
92
    return response;
93
  } catch (err) {
94
    const cached = await cache.match(request);
95
    if (cached) return cached;
96
    const shell = await caches.open(SHELL_CACHE);
97
    const offline = await shell.match(OFFLINE_URL);
98
    return offline || Response.error();
99
  }
100
}
101
102
// Stale-while-revalidate for static assets.
103
async function staleWhileRevalidate(request) {
104
  const cache = await caches.open(ASSETS_CACHE);
105
  const cached = await cache.match(request);
106
  const network = fetch(request)
107
    .then((response) => {
108
      if (response.ok && isCacheableAsset(response)) {
109
        cache.put(request, response.clone());
110
      }
111
      return response;
112
    })
113
    .catch(() => null);
114
  if (cached) return cached;
115
  const response = await network;
116
  return response || new Response('offline', { status: 503, statusText: 'Offline' });
117
}
118
119
function isCacheableAsset(response) {
120
  const type = (response.headers.get('content-type') || '').toLowerCase();
121
  return (
122
    type.startsWith('text/css') ||
123
    type.startsWith('image/') ||
124
    type.startsWith('font/') ||
125
    type.startsWith('application/javascript') ||
126
    type.startsWith('text/javascript')
127
  );
128
}
129
130
// Keep the pages cache bounded by evicting the oldest entries.
131
async function trimCache(cache, max) {
132
  const keys = await cache.keys();
133
  if (keys.length <= max) return;
134
  for (const key of keys.slice(0, keys.length - max)) {
135
    await cache.delete(key);
136
  }
137
}