arthur/static/arthur/sw.js
Olive Vaughn f0af8d392a arthur installs as an app, and keeps what projects load
A manifest and icons make it installable. A service worker at /sw.js,
so its scope is every page, keeps by kind of URL: content-addressed
blobs and blocks for good, as projects load them; the versioned bundle
and styles until the next build; and the last copy of the page, the API
reads and other statics, for when there is no network. A project opened
once opens again offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011FLuCjp9kNH6ovwJVXSbq9
2026-10-11 00:42:53 -04:00

109 lines
4.2 KiB
JavaScript

// The service worker: what arthur keeps so it opens, and shows what it has
// already shown, without the network. Served from `/sw.js` by `clips.views`
// so its scope is the whole site; see `server/urls.py`.
//
// ONE RULE PER KIND OF URL, chosen by whether what is at it can change:
//
// - CONTENT-ADDRESSED — `/blob/<digest>`, `/api/blocks/<key>` — is named by its
// own hash, so a copy cannot be stale: cache first, keep for good. These are
// a project's frames, footage and drawings, cached as they load.
// - VERSIONED — the bundle and the stylesheet, `?v=<mtime>` — is a new URL
// for every build: cache first, and drop the versions it replaces.
// - EVERYTHING ELSE of ours — the page, `/api/` reads, unversioned statics —
// can change under the same URL: the network first, the last copy offline.
//
// A Range request is left to the browser: a `<video>` seeking a blob asks for
// slices, and the Cache API cannot store a 206.
const KEEP = 'arthur-keep-v1'; // content-addressed, never stale
const BUILD = 'arthur-build-v1'; // versioned bundle and styles
const LAST = 'arthur-last-v1'; // last good copy of everything else
// The page every address opens, kept at install, so the app opens offline
// even at an address it was never opened at.
self.addEventListener('install', event => {
event.waitUntil(caches.open(LAST).then(cache => cache.add('/')).catch(() => {}));
self.skipWaiting();
});
self.addEventListener('activate', event => {
const ours = new Set([KEEP, BUILD, LAST]);
event.waitUntil((async () => {
for (const name of await caches.keys()) {
if (!ours.has(name)) await caches.delete(name);
}
await self.clients.claim();
})());
});
const immutable = url =>
url.pathname.startsWith('/blob/') || url.pathname.startsWith('/api/blocks/');
const versioned = url =>
url.pathname.startsWith('/static/') && url.searchParams.has('v');
async function keep(cache, request) {
const hit = await cache.match(request);
if (hit) return hit;
const response = await fetch(request);
if (response.ok) await cache.put(request, response.clone());
return response;
}
async function build(request) {
const cache = await caches.open(BUILD);
const hit = await cache.match(request);
if (hit) return hit;
const response = await fetch(request);
if (response.ok) {
// A new build of this file replaces the old ones rather than piling up.
const path = new URL(request.url).pathname;
for (const old of await cache.keys()) {
if (new URL(old.url).pathname === path) await cache.delete(old);
}
await cache.put(request, response.clone());
}
return response;
}
async function last(request, fallback) {
const cache = await caches.open(LAST);
try {
const response = await fetch(request);
if (response.ok) await cache.put(request, response.clone());
return response;
} catch (offline) {
const hit = (await cache.match(request)) || (fallback && (await cache.match(fallback)));
if (hit) return hit;
throw offline;
}
}
// The rule for one request, or nil for the browser's own handling.
function handle(request) {
const url = new URL(request.url);
if (request.method !== 'GET' || url.origin !== self.location.origin) return null;
if (request.headers.has('range')) return null;
if (url.pathname === '/sw.js') return null;
if (immutable(url)) return caches.open(KEEP).then(cache => keep(cache, request));
if (versioned(url)) return build(request);
// Every page is the same shell, which opens whichever project the path
// names: offline, any copy of it will do.
if (request.mode === 'navigate') return last(request, '/');
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/static/')) return last(request);
return null;
}
self.addEventListener('fetch', event => {
const answer = handle(event.request);
if (answer) event.respondWith(answer);
});
// The first page a worker sees loaded its bundle and styles before the worker
// was there to keep them; it sends their URLs once the worker is ready.
self.addEventListener('message', event => {
const urls = (event.data && event.data.keep) || [];
event.waitUntil(Promise.all(urls.map(u => handle(new Request(u))).filter(Boolean))
.catch(() => {}));
});