Service worker: the shell and the built assets are precached at install and the copy for the cache is cloned before the page reads the response (it was cloned too late and never stored, so an offline reload of the home-screen app failed); the cache is named after the build; starting the app offline raises the offline line at once

This commit is contained in:
Duarte Santos committed 2026-09-12 22:20:48 +02:00
1 parent 14c454f5c1
commit b1d79d54c7
4 files changed
+76 -36

No files matched your search

+44 -33
View File
@@ -1,16 +1,36 @@
/* openGym service worker — runtime caching (works with Vite's hashed asset names).
Media (img/gif) cache-first; everything else network-first with offline fallback. */
const CACHE = 'opengym-rt-v1'
/* openGym service worker — the app shell and its hashed assets are cached at install and kept
fresh network-first, media (img/gif) cache-first. A home-screen app reopened without a network
comes back from here with the same bundle it last ran; the state itself lives in localStorage.
`CACHE` carries the build hash (vite.config.js rewrites it), so every deploy is a new worker
with its own cache and the previous build's files are dropped on activate. */
const CACHE = 'opengym-rt-__BUILD__'
self.addEventListener('install', () => self.skipWaiting())
// What the shell needs to boot without a network: index.html plus every script/style/icon it
// references. Read from the served index.html so the list follows the build, not a hand-kept
// manifest that would go stale the first time a chunk is renamed.
async function precache() {
const c = await caches.open(CACHE)
const res = await fetch('index.html', { cache: 'no-cache' })
if (!res.ok) return
const html = await res.text()
await c.put('index.html', new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } }))
const refs = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map(m => m[1])
.filter(u => /\.(?:js|css|png|svg|webmanifest|json)(?:\?|$)/.test(u) && !/^(?:https?:)?\/\//.test(u))
await Promise.all([...new Set(refs)].map(u => c.add(u).catch(() => {})))
}
self.addEventListener('install', e => {
e.waitUntil(precache().catch(() => {}).then(() => self.skipWaiting()))
})
self.addEventListener('activate', e => {
e.waitUntil(caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
).then(() => self.clients.claim()))
})
// Every push shows a notification, whatever the payload: a push that shows nothing counts
// against the site (Chrome revokes the subscription after a few), and a payload that fails to
// parse used to throw before waitUntil was ever reached — exactly such a silent push.
// The payload is parsed inside waitUntil: a push whose handler throws before showing anything is
// a "silent push", which Chrome counts against the site and eventually revokes. A body that is
// not JSON still shows a notification.
self.addEventListener('push', e => {
e.waitUntil((async () => {
let data = {}
@@ -36,30 +56,16 @@ self.addEventListener('notificationclick', e => {
return c ? c.focus() : self.clients.openWindow('./')
}))
})
// The push service rotated the subscription (it does, unannounced, every few months on some
// platforms). Without this the server keeps sending to the old endpoint until it 410s, and the
// browser holds a new one nobody registered — "notifications just stopped". Re-subscribe with
// the same application server key and hand the new endpoint to the API; the session cookie
// travels with the same-origin fetch. Signed out, the API answers 401 and the next signed-in
// boot (lib/push.js syncPushSubscription) registers it instead.
const b64ToBytes = b64 => {
const padded = (b64 + '='.repeat((4 - b64.length % 4) % 4)).replace(/-/g, '+').replace(/_/g, '/')
return Uint8Array.from(atob(padded), c => c.charCodeAt(0))
}
// The push service rotated the subscription (key change, expiry): subscribe again with the same
// server key and tell the server, so the row it holds keeps pointing at this browser.
self.addEventListener('pushsubscriptionchange', e => {
e.waitUntil((async () => {
let key = e.oldSubscription?.options?.applicationServerKey
if (!key) {
const r = await fetch(new URL('api/push/public-key', self.registration.scope))
key = b64ToBytes((await r.json()).key)
}
const old = e.oldSubscription || (await self.registration.pushManager.getSubscription())
const key = e.newSubscription?.options?.applicationServerKey || old?.options?.applicationServerKey
if (!key) return
const sub = e.newSubscription || await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key })
await fetch(new URL('api/push/subscribe', self.registration.scope), {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ subscription: sub.toJSON() })
})
})().catch(() => {}))
await fetch('api/push/subscribe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ subscription: sub.toJSON() }) }).catch(() => {})
})())
})
self.addEventListener('fetch', e => {
@@ -72,10 +78,15 @@ self.addEventListener('fetch', e => {
e.respondWith(caches.open(CACHE).then(c => c.match(e.request).then(hit =>
hit || fetch(e.request).then(res => { if (res.ok) c.put(e.request, res.clone()); return res })
)))
} else {
e.respondWith(fetch(e.request).then(res => {
if (res.ok) caches.open(CACHE).then(c => c.put(e.request, res.clone()))
return res
}).catch(() => caches.match(e.request).then(hit => hit || caches.match('index.html'))))
return
}
// Network first; the copy for the cache is cloned before the response is handed to the page —
// cloning later, once the page has started reading the body, throws and caches nothing, which
// is why the shell never used to survive an offline reload.
e.respondWith(fetch(e.request).then(res => {
if (res.ok) { const copy = res.clone(); caches.open(CACHE).then(c => c.put(e.request, copy)).catch(() => {}) }
return res
}).catch(() => caches.match(e.request, { ignoreSearch: true }).then(hit =>
hit || (e.request.mode === 'navigate' ? caches.match('index.html') : undefined)
)))
})
+4 -1
View File
@@ -550,7 +550,7 @@ export const useStore = create((set, get) => {
await get().pullState()
} catch (e) {
if (e.status === 401) { await forgetRemote(); get().setGuest(true) }
else get().setUser(remote.user) // offline — keep going from the last-synced local copy
else { get().setUser(remote.user); setSync({ offline: true }) } // offline — keep going from the last-synced local copy
}
syncReminder(get().S)
finishBoot()
@@ -599,6 +599,9 @@ export const useStore = create((set, get) => {
}
} catch (e) {
if (e.status === 401) get().setUser(null)
// Started without a network (a home-screen app reopened in the gym's basement): keep the
// signed-in copy and say so from the first screen, not only after the first failed push.
else if (isNetworkError(e) && get().user) setSync({ offline: true })
}
finishBoot()
}
+19 -2
View File
@@ -1,4 +1,5 @@
import { readFileSync } from 'node:fs'
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
@@ -29,6 +30,22 @@ const umami = {
}
}
// The service worker's cache is named after the build (public/sw.js carries a `__BUILD__`
// placeholder): a deploy is then a new worker with its own cache, and the previous build's
// shell and chunks are dropped on activate instead of piling up under one fixed name. The
// stamp is a hash of the built index.html — it changes exactly when the bundle does.
const swStamp = {
name: 'opengym-sw-stamp',
apply: 'build',
closeBundle() {
const dir = new URL('./dist/', import.meta.url)
const html = new URL('index.html', dir), sw = new URL('sw.js', dir)
if (!existsSync(html) || !existsSync(sw)) return
const stamp = createHash('sha256').update(readFileSync(html)).digest('hex').slice(0, 10)
writeFileSync(sw, readFileSync(sw, 'utf8').replace('__BUILD__', stamp))
}
}
// The version people are asked for in #install-help and on every bug report. Read from
// package.json so it cannot drift from the release it was built in, and inlined at build
// time so no runtime fetch is involved.
@@ -36,7 +53,7 @@ const pkgVersion = JSON.parse(readFileSync(new URL('./package.json', import.meta
export default defineConfig({
define: { __APP_VERSION__: JSON.stringify(pkgVersion) },
plugins: [react(), umami],
plugins: [react(), umami, swStamp],
base: './',
server: {
// The Coach's core (payload, validator, prompts, HTTP adapters) lives in ../api/coach/core