diff --git a/e2e/pwa.spec.ts b/e2e/pwa.spec.ts new file mode 100644 index 0000000..1bbe1a9 --- /dev/null +++ b/e2e/pwa.spec.ts @@ -0,0 +1,120 @@ +import { test, expect } from './fixtures/test'; +import { setupApiMocks } from './fixtures/api-mocks'; +import type { Page } from '@playwright/test'; + +/** + * Wait for the service worker to take control of the page. + */ +async function waitForSwControl(page: Page) { + await page.waitForFunction(() => navigator.serviceWorker.controller !== null, undefined, { + timeout: 15_000, + }); +} + +/** + * Wait until at least one hashed JS bundle is cached. Scans every cache rather + * than the SW's version-specific name, so a VERSION bump can't silently break it. + */ +async function waitForCachedBundle(page: Page) { + await page.waitForFunction( + async () => { + for (const name of await caches.keys()) { + const cache = await caches.open(name); + const keys = await cache.keys(); + if (keys.some((req) => req.url.includes('/assets/') && req.url.endsWith('.js'))) { + return true; + } + } + return false; + }, + undefined, + { timeout: 10_000 }, + ); +} + +/** + * PWA offline app shell. + * + * The rest of the suite blocks service workers (playwright.config.ts) to exercise + * the live network; this spec opts back in. It proves the SW lets the app cold-boot + * OFFLINE after the very FIRST visit — install precaches the shell AND this build's + * hashed bundles, so a fully offline reload still renders the shell from cache + * rather than a browser error page. + * + * Chromium only: SW + offline emulation is most reliable there, and the SW is + * identical across browsers. + */ +test.describe('PWA offline app shell', () => { + test.use({ serviceWorkers: 'allow' }); + + test.beforeEach(({ browserName }) => { + test.skip(browserName !== 'chromium', 'SW offline behavior validated in Chromium'); + }); + + test('cold-boots offline after a single online visit', async ({ page, context }) => { + await setupApiMocks(page); + + // 1. One online visit registers + activates the SW (skipWaiting + + // clients.claim), so it takes control of this page. + await page.goto('/'); + await waitForSwControl(page); + + // 2. Assert a JS bundle is in the SW cache after this FIRST visit — no reload. + // This is the cold-boot guarantee: it would fail if bundles were only cached + // lazily on a later load, and unlike the offline render it's independent of + // the HTTP cache. + await waitForCachedBundle(page); + + // 3. Go fully offline and reload — only the SW can satisfy the navigation + // + same-origin bundles now. + await context.setOffline(true); + await page.reload(); + + // 4. The shell still renders, and the SW is still in control. + await expect(page.locator('header').first()).toBeVisible(); + const controlled = await page.evaluate(() => navigator.serviceWorker.controller !== null); + expect(controlled).toBe(true); + }); + + test('shows the offline bar on a cold reload when navigator.onLine wrongly reports online, then clears it on reconnect', async ({ page, context }) => { + await setupApiMocks(page); + + // Reproduce real Chrome DevTools device-mode "Offline" / captive portals / + // lie-fi, where navigator.onLine stays `true` despite no connectivity AND no + // online/offline transition events ever fire — so the active connectivity probe + // is the ONLY thing that can move the state in either direction. Playwright's + // setOffline would otherwise both flip navigator.onLine to false and dispatch + // online/offline events, masking whether the probe itself works; pin onLine to + // `true` and swallow the events for the page's entire lifetime. + await page.addInitScript(() => { + Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => true }); + for (const type of ['online', 'offline']) { + window.addEventListener(type, (e) => e.stopImmediatePropagation()); + } + }); + + // 1. One online visit registers + activates the SW so it controls the reload. + await page.goto('/'); + await waitForSwControl(page); + + // 2. Wait until a hashed bundle is cached so the offline reload can boot. + await waitForCachedBundle(page); + + // 3. Cold offline reload: the SW serves the shell, navigator.onLine still lies + // "online", and no offline transition event fires — the active connectivity + // probe is the only thing that can reveal we're offline. + await context.setOffline(true); + await page.reload(); + + // 4. The shell renders AND the offline bar appears (regression: it used to stay + // hidden because the app trusted navigator.onLine alone on a fresh load). + await expect(page.locator('header').first()).toBeVisible(); + await expect(page.getByText('No internet connection')).toBeVisible({ timeout: 10_000 }); + + // 5. Reconnect. navigator.onLine is still pinned to `true`, so no `online` event + // fires — only the periodic connectivity re-probe can notice the link is back + // and clear the bar. (Without recovery the bar would stay stuck forever.) + await context.setOffline(false); + await expect(page.getByText('No internet connection')).toBeHidden({ timeout: 12_000 }); + }); +}); diff --git a/playwright.config.ts b/playwright.config.ts index 49c735a..31ad1b1 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -31,6 +31,11 @@ export default defineConfig({ the same pair is also added inside each per-project block below. */ locale: 'en-US', timezoneId: 'UTC', + + /* The prod build registers an offline service worker. Block it by default so + existing specs hit the network exactly as before; the PWA spec re-enables + it with test.use(). */ + serviceWorkers: 'block', }, projects: [ { diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..4e48f64 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,185 @@ +/* + * HackerTok service worker — minimal, dependency-free offline app shell. + * + * Goal: an installed PWA cold-boots OFFLINE, serving the HTML shell + the current + * build's hashed JS/CSS from cache. Third-party content (Algolia, Firebase RTDB + * over wss://) is cross-origin and skipped entirely, so the feed/comments stay + * live and Playwright's network mocks keep working. + * + * Hand-rolled rather than vite-plugin-pwa / Workbox: Vite already content-hashes + * assets (new build = new URL = cache miss = fresh fetch), making Workbox's + * revisioned precache manifest redundant, and nothing cross-origin is cached, so + * its runtime strategies are non-goals. What remains is ~100 auditable, + * zero-dependency lines. Registration is a bundled import (main.tsx), so the + * hash-based CSP stays clean; `worker-src 'self'` (vite.config.js) authorizes it. + * + * Two caches: an install-time SHELL precache and a bounded RUNTIME cache for + * hashed assets, FIFO-trimmed to MAX_RUNTIME_ENTRIES so stale chunks from prior + * deploys can't accumulate between VERSION bumps. + */ + +// Cache-schema version, NOT the app/GitHub release. Bump only when the caching +// contract changes (PRECACHE_URLS, cache layout, or a precached file like the +// manifest/icon); app-code releases self-bust via content-hashing + network-first +// navigation. A bump renames the caches, so `activate` wipes the old ones. +const VERSION = 'v1'; +const SHELL_CACHE = `hackertok-shell-${VERSION}`; +const RUNTIME_CACHE = `hackertok-runtime-${VERSION}`; +const CURRENT_CACHES = new Set([SHELL_CACHE, RUNTIME_CACHE]); +const OFFLINE_SHELL = '/index.html'; + +// Cap on cached same-origin assets. One build ships well under this, so the +// current shell always fits while stale entries from older deploys evict first. +const MAX_RUNTIME_ENTRIES = 64; + +// How long a navigation waits on the network before falling back to the cached +// shell. Bounds "lie-fi" launches (connected but stalled) that would otherwise +// hang on the browser's own ~30–60s timeout. The request is NOT abandoned at the +// cutoff — it keeps running to refresh the shell for the next launch. +const NETWORK_TIMEOUT_MS = 3000; + +// Static shell precached up-front. The build's hashed JS/CSS can't be listed here +// (names are unknown at author time) — `install` parses them from the cached shell +// HTML instead, so the first visit alone is enough to boot offline. +const PRECACHE_URLS = ['/', OFFLINE_SHELL, '/manifest.webmanifest', '/icons/icon.svg']; + +self.addEventListener('install', (event) => { + event.waitUntil( + (async () => { + const shell = await caches.open(SHELL_CACHE); + await shell.addAll(PRECACHE_URLS); + + // Precache this build's hashed bundles by parsing their /assets/* refs out of + // the shell HTML cached above. The SW doesn't control the first navigation, so + // those requests never reach the fetch handler — without this they'd be cached + // only on a later controlled load, defeating first-visit offline boot. + // Best-effort: any failure just defers to runtime caching. + try { + const shellResponse = await shell.match(OFFLINE_SHELL); + const html = shellResponse ? await shellResponse.text() : ''; + const assets = [...new Set(Array.from(html.matchAll(/["'](\/assets\/[^"']+)["']/g), (m) => m[1]))]; + if (assets.length) { + const runtime = await caches.open(RUNTIME_CACHE); + await runtime.addAll(assets); + } + } catch { + /* defer to runtime caching on the next controlled load */ + } + + await self.skipWaiting(); + })(), + ); +}); + +self.addEventListener('activate', (event) => { + // Drop caches from older versions, then take control of open clients. + event.waitUntil( + caches + .keys() + .then((keys) => Promise.all(keys.filter((key) => !CURRENT_CACHES.has(key)).map((key) => caches.delete(key)))) + .then(() => self.clients.claim()), + ); +}); + +// FIFO-trim the runtime cache. Cache.keys() returns entries in insertion order, +// so deleting from the front evicts the oldest (least-recently-written) assets. +async function trimCache(cache, maxEntries) { + const keys = await cache.keys(); + for (let i = 0; i < keys.length - maxEntries; i++) { + await cache.delete(keys[i]); + } +} + +// Network-first navigation, bounded by NETWORK_TIMEOUT_MS, falling back to the +// cached shell. Online users get the freshest index.html (and its newest hashed +// bundles); offline / lie-fi users get the cached shell promptly. +async function navigate(event) { + const { request } = event; + const network = fetch(request); + + // Refresh the offline shell only from a genuine root navigation. GitHub Pages + // serves unknown paths (e.g. a shared /item/123 deep link) as 404.html with a + // 200, so caching a non-root document here would poison the shell. Only `/` is + // guaranteed to be the real index.html. + const refreshShell = (response) => { + if (new URL(request.url).pathname !== '/' || !response.ok) return undefined; + // Clone synchronously. On the success path refreshShell runs before + // `return response`, so the copy is taken before the body is handed to the page. + // Deferring the clone into the caches.open().then() would instead read it after + // the body is already disturbed — clone() throws, the .catch() swallows it, and + // the shell silently never refreshes (it would then stay pinned to an old build + // across app-only deploys until its hashed bundles get evicted). + const copy = response.clone(); + return caches.open(SHELL_CACHE).then((cache) => cache.put(OFFLINE_SHELL, copy)); + }; + + try { + const response = await Promise.race([ + network, + new Promise((_, reject) => setTimeout(() => reject(new Error('nav-timeout')), NETWORK_TIMEOUT_MS)), + ]); + event.waitUntil(Promise.resolve(refreshShell(response)).catch(() => {})); + return response; + } catch { + // Timed out or the network failed. Serve the cached shell if we have one; on a + // brand-new install whose precache hasn't landed yet, fall through to the + // still-running network request. + const cached = + (await caches.match(OFFLINE_SHELL, { ignoreVary: true })) || (await caches.match('/', { ignoreVary: true })); + if (!cached) return network; + // Keep the slow request alive: a late success still refreshes the shell for the + // next launch. Swallow its rejection (offline) to avoid an unhandled rejection. + event.waitUntil( + network + .then((response) => refreshShell(response)) + .catch(() => {}), + ); + return cached; + } +} + +self.addEventListener('fetch', (event) => { + const { request } = event; + + // Never touch non-GET or cross-origin (Algolia / Firebase / external links): + // let them hit the network (and any Playwright route mocks) untouched. + if (request.method !== 'GET') return; + if (new URL(request.url).origin !== self.location.origin) return; + + // Navigations: see navigate() (network-first + cached-shell fallback). + if (request.mode === 'navigate') { + event.respondWith(navigate(event)); + return; + } + + // Same-origin static assets (hashed JS/CSS, icons, manifest): cache-first. + // Content-hashing keeps a cached copy permanently fresh (a changed file ships a + // new URL), and it skips GitHub Pages' max-age=600 revalidation every 10 min. + // The read checks every cache, so precached shell assets stay pinned in + // SHELL_CACHE until a VERSION bump. `ignoreVary` bridges a real mismatch: the + // install precache stores plain SW Requests, but the browser's module requests + // are `crossorigin`, and the asset's `Vary` differs by host (`vite preview` sends + // `Vary: Origin`, GitHub Pages `Vary: Accept-Encoding`) — a strict match could + // miss the precached bundle and fail offline. Hashed URLs are single-variant, so + // ignoring Vary is safe. + event.respondWith( + caches.match(request, { ignoreVary: true }).then((cached) => { + if (cached) return cached; + return fetch(request).then((response) => { + if (response && response.status === 200 && response.type === 'basic') { + const copy = response.clone(); + // Swallow write failures (e.g. QuotaExceededError under storage + // pressure): the response is already returned, so the cache write must + // not surface as an unhandled extend-lifetime rejection. + event.waitUntil( + caches + .open(RUNTIME_CACHE) + .then((cache) => cache.put(request, copy).then(() => trimCache(cache, MAX_RUNTIME_ENTRIES))) + .catch(() => {}), + ); + } + return response; + }); + }), + ); +}); diff --git a/src/context/NetworkStatusContext.tsx b/src/context/NetworkStatusContext.tsx index 2c06a74..9a0bd07 100644 --- a/src/context/NetworkStatusContext.tsx +++ b/src/context/NetworkStatusContext.tsx @@ -2,6 +2,16 @@ import { useState, useEffect, useCallback } from 'react'; import type { ReactNode } from 'react'; import { NetworkStatusContext } from './networkStatusDef'; +// Upper bound for a single connectivity probe below. A genuine offline read fails +// near-instantly; this only caps a slow-but-live ("lie-fi") link, which we treat as +// inconclusive rather than offline. +const CONNECTIVITY_PROBE_TIMEOUT_MS = 4000; + +// While we believe we're offline, re-probe on this cadence so the bar also clears +// once the connection returns: behind a SW-served page `navigator.onLine` can stay +// stuck at `true`, so no `online` event would ever fire to recover. +const CONNECTIVITY_RECHECK_INTERVAL_MS = 3000; + export function NetworkStatusProvider({ children }: { children: ReactNode }) { const [isOnline, setIsOnline] = useState(() => typeof navigator !== 'undefined' ? navigator.onLine : true, @@ -19,6 +29,97 @@ export function NetworkStatusProvider({ children }: { children: ReactNode }) { }; }, [goOnline, goOffline]); + // Active connectivity verification for offline-capable (service-worker) builds. + // + // `navigator.onLine` is unreliable once a SW can serve every request from cache: + // after a reload while offline, behind a captive portal, or in Chrome DevTools + // device-mode "Offline" it frequently still reads `true`, and since the page never + // made an online->offline *transition* no `offline` event fires either. The value + // latched at mount is then the only signal, so the offline bar stays hidden even + // though all content came from cache. + // + // Verify against the network directly instead: a cache-busted HEAD can't be + // answered from any HTTP cache (unique URL) and is skipped by the SW fetch handler + // (GET only), so it truly reaches the network and fails when offline. Keep + // re-checking while offline, because that same stuck `navigator.onLine` means no + // `online` event would fire to clear the bar once the link returns. + useEffect(() => { + if (!('serviceWorker' in navigator)) return; + + let disposed = false; + let recheck: ReturnType | null = null; + let inFlight: AbortController | null = null; + + const clearRecheck = () => { + if (recheck) { + clearTimeout(recheck); + recheck = null; + } + }; + + // true = reachable, false = genuinely offline, null = inconclusive (our own + // timeout fired on a slow-but-live link, so leave the state unchanged). + const probe = async (): Promise => { + inFlight?.abort(); + const ac = new AbortController(); + inFlight = ac; + const timeout = setTimeout(() => ac.abort(), CONNECTIVITY_PROBE_TIMEOUT_MS); + try { + await fetch(`${import.meta.env.BASE_URL}manifest.webmanifest?_probe=${Date.now()}`, { + method: 'HEAD', + cache: 'no-store', + signal: ac.signal, + }); + return true; + } catch (err) { + return (err as Error).name === 'AbortError' ? null : false; + } finally { + clearTimeout(timeout); + if (inFlight === ac) inFlight = null; + } + }; + + // Our current belief, tracked locally so a recovery poll keeps running until a + // probe positively confirms we're back online. An inconclusive probe (null — + // our own timeout firing on a slow-but-live link) must not silently end the + // poll and leave the bar stuck offline forever. + let offline = false; + + const check = async () => { + // Only a SW-controlled page can make `navigator.onLine` lie; an uncontrolled + // load came from the network, where it's already trustworthy. + if (!navigator.serviceWorker.controller) return; + const reachable = await probe(); + if (disposed) return; + // null = inconclusive: leave both the React state and our belief untouched. + if (reachable !== null) { + offline = !reachable; + setIsOnline(reachable); + } + // Re-arm the poll whenever we still believe we're offline — including after an + // inconclusive probe — so the bar clears once the link returns (no `online` + // event fires when `navigator.onLine` is stuck `true`). + clearRecheck(); + if (offline) { + recheck = setTimeout(() => void check(), CONNECTIVITY_RECHECK_INTERVAL_MS); + } + }; + + void check(); + + // A first visit isn't controlled until the SW claims it; probe as soon as + // control arrives so the first offline-capable session is covered too. + const onControllerChange = () => void check(); + navigator.serviceWorker.addEventListener('controllerchange', onControllerChange); + + return () => { + disposed = true; + clearRecheck(); + inFlight?.abort(); + navigator.serviceWorker.removeEventListener('controllerchange', onControllerChange); + }; + }, []); + return ( {children} diff --git a/src/main.tsx b/src/main.tsx index a6469c6..2851b4b 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -12,3 +12,15 @@ createRoot(document.getElementById('root')!).render( , ) + +// Register the offline app-shell service worker (production only, so it never +// interferes with the dev server / HMR). Pure progressive enhancement: if it fails +// or SWs are blocked, the app runs exactly as before. The SW uses skipWaiting + +// clients.claim, so a new deploy takes over on the next load. +if (import.meta.env.PROD && 'serviceWorker' in navigator) { + window.addEventListener('load', () => { + navigator.serviceWorker.register('/sw.js').catch(() => { + /* offline support is optional — ignore registration failures */ + }); + }); +}