winzik/engine/web/sw.js
David Nurdin 070aece6b4 PWA: offline bar and "new version" bar of the page, the cached build really starts offline
- jumphp-pwa.js (pwa on, not framed by a portal): a small bar while the network is gone (also when the
  worker had to answer from its cache while navigator.onLine says true; a probe takes it away when the
  network is back) and a "new version, reload" bar when a newer build waits (Pwa::applyUpdate()),
  14 languages
- sw.js: tells the page it was opened from the cache (to the new page of a navigation, and on request:
  {type: 'jumphp:offline?'}), an unversioned file falls back to the cached one, redirects never kept
- jumphp.js hears the worker from the start (window.JUMPHP_OFFLINE, event 'jumphp:offline')
- package-web.sh: jumphp.js was missing from version.json, so the worker never cached it and a
  normal build with pwa on did not start offline
- AGENTS.md: the bars, and the playground's games installed as apps of their own and played offline

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JkYTqsvYu6AYr9yQ3Q4Nt6
2026-11-15 20:34:33 +01:00

80 lines
3.9 KiB
JavaScript

// JumPHP service worker (game.yaml `pwa`): the game plays offline once loaded.
// Install: caches every file of this build (the list and hashes come from version.json, the URLs are exactly
// the ones the page asks for: file?v=<hash>). Requests: cache first for versioned files, network first for
// the page and version.json (an update is seen at once when online; offline, the cached build starts).
// A new build has a new BUILD below: it installs next to the old one and waits; the page shows "update ready"
// (JumPHP\Device\Pwa::updateReady()) and applyUpdate() switches to it.
const BUILD = '__JUMPHP_BUILD__';
const GAME = '__JUMPHP_GAME__';
const CACHE = `jumphp-pwa-${GAME}-${BUILD}`;
const STATIC = ['./', 'index.html', 'game.json', 'manifest.webmanifest', 'icon-192.png', 'icon-512.png'];
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE);
const version = await fetch('version.json', { cache: 'no-store' }).then((r) => r.json());
const files = Object.keys(version).filter((k) => k !== 'build').map((f) => `${f}?v=${version[f]}`);
await cache.add(new Request('version.json', { cache: 'no-store' }));
await cache.addAll([...STATIC, ...files].map((url) => new Request(url, { cache: 'reload' })));
})().catch((e) => { console.error('[sw] install failed', e); throw e; }));
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
for (const name of await caches.keys()) {
if (name.startsWith(`jumphp-pwa-${GAME}-`) && name !== CACHE) await caches.delete(name);
}
await self.clients.claim();
})());
});
self.addEventListener('message', (event) => {
if (event.data === 'skipWaiting') self.skipWaiting();
if (event.data?.type === 'jumphp:offline?' && event.source && shownOffline.has(event.source.id)) event.source.postMessage({ type: 'jumphp:offline' });
});
// a page being opened is not a client yet: asked again for a few seconds
const shownOffline = new Set(); // pages opened from the cache: they may ask ({type: 'jumphp:offline?'}) when their listener came late
async function tell(id) {
if (id) shownOffline.add(id);
for (let i = 0; id && i < 20; i++) {
const client = await self.clients.get(id).catch(() => null);
if (client) { client.postMessage({ type: 'jumphp:offline' }); return; }
await new Promise((r) => setTimeout(r, 250));
}
}
self.addEventListener('fetch', (event) => {
const request = event.request;
const url = new URL(request.url);
if (request.method !== 'GET' || url.origin !== location.origin) return;
const file = url.pathname.split('/').pop();
if (request.mode === 'navigate' || file === 'version.json' || file === '' || file === 'index.html') {
// network first: updates; offline: this build
event.respondWith(fetch(request).catch(async () => {
const cache = await caches.open(CACHE);
const hit = (await cache.match(request, { ignoreSearch: true })) || (await cache.match('./'));
// the page shows its offline bar (jumphp-pwa.js): navigator.onLine may still say true on a network that answers nothing
if (hit) event.waitUntil(tell(request.mode === 'navigate' ? event.resultingClientId : event.clientId)); // a navigation's clientId is the page it leaves
return hit || Response.error();
}));
return;
}
event.respondWith((async () => {
const cache = await caches.open(CACHE);
const hit = await cache.match(request);
if (hit) return hit;
let response;
try {
response = await fetch(request);
} catch (e) {
// offline: the same file of this build under another query (an unversioned address)
const other = await cache.match(request, { ignoreSearch: true });
if (other) return other;
throw e;
}
// same-origin files of a newer build (seen online before this worker was replaced): keep them too
if (response.ok && !response.redirected && url.search.startsWith('?v=')) cache.put(request, response.clone()).catch(() => {});
return response;
})());
});