/** Service worker cache rules (docs/07 ยง11), run against fake caches/fetch. */ import { beforeEach, expect, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; const ORIGIN = 'https://game.test'; const SRC = readFileSync(join(import.meta.dir, '../sw.js'), 'utf8'); class FakeCache { map = new Map(); async match(req: { url: string } | string) { return this.map.get(typeof req === 'string' ? new URL(req, ORIGIN).href : req.url)?.clone(); } async put(req: { url: string }, res: Response) { this.map.set(req.url, res); } async add(req: Request) { this.put(req, await net(req)); } async keys() { return [...this.map.keys()].map((url) => ({ url })); } async delete(req: { url: string }) { return this.map.delete(req.url); } } let stores: Map; let net: (req: { url: string }) => Promise; let fetched: string[]; let handlers: Record void>; const caches = { open: async (name: string) => stores.get(name) ?? stores.set(name, new FakeCache()).get(name)!, keys: async () => [...stores.keys()], delete: async (name: string) => stores.delete(name), match: async (req: string, opts: { cacheName: string }) => stores.get(opts.cacheName)?.match(req), }; const fetchFn = (req: { url: string }) => { fetched.push(new URL(req.url).pathname); return net(req); }; class RelRequest extends Request { constructor(url: string, init?: RequestInit) { super(new URL(url, ORIGIN), init); } } beforeEach(() => { stores = new Map(); fetched = []; handlers = {}; net = async (req) => new Response(`body of ${new URL(req.url).pathname}`, { headers: { 'Content-Type': 'text/javascript' } }); const self = { location: new URL(ORIGIN), addEventListener: (type: string, fn: (e: unknown) => void) => (handlers[type] = fn), skipWaiting: async () => {}, clients: { claim: async () => {} }, }; new Function('self', 'caches', 'fetch', 'Request', SRC)(self, caches, fetchFn, RelRequest); }); async function lifecycle(type: 'install' | 'activate') { const pending: Promise[] = []; handlers[type]!({ waitUntil: (p: Promise) => pending.push(p) }); await Promise.all(pending); } /** Dispatches a fetch; returns undefined when the worker leaves the request to the browser. */ async function request(path: string, opts: { mode?: string; method?: string; origin?: string } = {}) { let res: Promise | undefined; const pending: Promise[] = []; handlers.fetch!({ request: { url: new URL(path, opts.origin ?? ORIGIN).href, method: opts.method ?? 'GET', mode: opts.mode ?? 'cors' }, respondWith: (p: Promise) => (res = p), waitUntil: (p: Promise) => pending.push(p), }); const out = await res; await Promise.all(pending); return out; } test('install keeps the offline page; activate drops old caches only', async () => { stores.set('bg-shell-old', new FakeCache()); stores.set('bg-assets-v0', new FakeCache()); stores.set('someone-else', new FakeCache()); await lifecycle('install'); await lifecycle('activate'); const names = [...stores.keys()]; expect(names).toContain('someone-else'); expect(names.filter((n) => n.startsWith('bg-'))).toEqual([expect.stringMatching(/^bg-shell-/)]); expect(await (await caches.match('/offline.html', { cacheName: names.find((n) => n.startsWith('bg-shell-'))! }))?.text()).toBe('body of /offline.html'); }); test('API, WebSocket, health, internal, non-GET and other origins are never handled', async () => { await lifecycle('install'); for (const path of ['/api/me', '/api/admin/stats', '/ws', '/healthz', '/internal/metrics']) { expect(await request(path)).toBeUndefined(); expect(await request(path, { mode: 'navigate' })).toBeUndefined(); } expect(await request('/assets/a.js', { method: 'POST' })).toBeUndefined(); expect(await request('/assets/a.js', { origin: 'https://cdn.discordapp.com' })).toBeUndefined(); expect([...stores.keys()].filter((n) => n.startsWith('bg-assets'))).toEqual([]); }); test('pages come from the network and are never cached; offline shows the offline page', async () => { await lifecycle('install'); net = async () => new Response('v1', { headers: { 'Content-Type': 'text/html' } }); expect(await (await request('/r/123456', { mode: 'navigate' }))!.text()).toBe('v1'); net = async () => new Response('v2', { headers: { 'Content-Type': 'text/html' } }); expect(await (await request('/', { mode: 'navigate' }))!.text()).toBe('v2'); net = () => Promise.reject(new TypeError('Failed to fetch')); expect(await (await request('/', { mode: 'navigate' }))!.text()).toBe('body of /offline.html'); expect([...stores.values()].flatMap((c) => [...c.map.keys()]).map((u) => new URL(u).pathname)).toEqual(['/offline.html']); }); test('hashed assets are cache-first; HTML fallbacks and partial responses are not kept', async () => { expect(await (await request('/assets/a-1.js'))!.text()).toBe('body of /assets/a-1.js'); expect(await (await request('/assets/a-1.js'))!.text()).toBe('body of /assets/a-1.js'); expect(fetched).toEqual(['/assets/a-1.js']); net = async () => new Response('', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); await request('/assets/gone.js'); net = async () => new Response('part', { status: 206, headers: { 'Content-Type': 'audio/mpeg' } }); await request('/assets/s.mp3'); net = async () => new Response('err', { status: 500 }); await request('/assets/b.js'); expect([...stores.get('bg-assets-v1')!.map.keys()].map((u) => new URL(u).pathname)).toEqual(['/assets/a-1.js']); }); test('asset cache is bounded, oldest out first', async () => { for (let i = 0; i < 205; i++) await request(`/assets/f${i}.js`); const kept = [...stores.get('bg-assets-v1')!.map.keys()].map((u) => new URL(u).pathname); expect(kept.length).toBe(200); expect(kept[0]).toBe('/assets/f5.js'); expect(kept.at(-1)).toBe('/assets/f204.js'); });