Study/web/public/sw.js
Elijah 74a98ac1f1 Add the V2 web app: design system, shell, study flows, AI, settings, sharing
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 08:53:01 -07:00

50 lines
1.7 KiB
JavaScript

/* Study Desk service worker: makes the app installable and keeps the shell available offline.
* API calls are never cached, so study data is always live. */
const CACHE = 'studydesk-shell-v1';
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(['/', '/icon.svg', '/manifest.webmanifest'])).then(() => self.skipWaiting()));
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim()),
);
});
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (url.origin !== self.location.origin || url.pathname.startsWith('/api/') || url.pathname.startsWith('/media/')) return;
// Hashed build assets never change: serve from cache, fill on first use.
if (url.pathname.startsWith('/assets/')) {
event.respondWith(
caches.match(req).then(
(hit) =>
hit ||
fetch(req).then((res) => {
if (res.ok) caches.open(CACHE).then((c) => c.put(req, res.clone()));
return res.clone();
}),
),
);
return;
}
// Pages: always try the network so updates arrive, fall back to the cached shell offline.
if (req.mode === 'navigate') {
event.respondWith(
fetch(req)
.then((res) => {
if (res.ok) caches.open(CACHE).then((c) => c.put('/', res.clone()));
return res.clone();
})
.catch(() => caches.match('/').then((hit) => hit || new Response('Study Desk is offline.', { status: 503, headers: { 'Content-Type': 'text/plain' } }))),
);
}
});