Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions e2e/pwa.spec.ts
Original file line number Diff line number Diff line change
@@ -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 });
});
});
5 changes: 5 additions & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
{
Expand Down
185 changes: 185 additions & 0 deletions public/sw.js
Original file line number Diff line number Diff line change
@@ -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;
});
}),
);
});
Loading