import assert from 'node:assert/strict' import { test } from 'node:test' import { serviceWorkerJs } from '../src/sw.ts' const ORIGIN = 'https://pie.example.com' const js = serviceWorkerJs({ appBase: '', assetBase: '/assets', version: '8' }) function html(status = 200, body = '

live

') { const res = new Response(body, { status, headers: { 'content-type': 'text/html; charset=utf-8' } }) // Node's Response constructor uses type "default"; browsers mark same-origin fetch as "basic". Object.defineProperty(res, 'type', { value: 'basic' }) return res } function mockCaches(seed: Record = {}) { const store = new Map(Object.entries(seed).map(([key, res]) => [key, res.clone()])) const cache = { match(req: RequestInfo) { const key = typeof req === 'string' ? req : req.url const hit = store.get(key) return Promise.resolve(hit ? hit.clone() : undefined) }, put(req: RequestInfo, res: Response) { const key = typeof req === 'string' ? req : req.url store.set(key, res) return Promise.resolve() }, } return { store, open() { return Promise.resolve(cache) }, match(req: RequestInfo) { return cache.match(req) }, keys() { return Promise.resolve([...store.keys()]) }, delete(key: string) { return Promise.resolve(store.delete(key)) }, } } function loadPolicy(fetchImpl: typeof fetch, cachesImpl: ReturnType) { const self = { addEventListener() {}, location: { origin: ORIGIN }, clients: { claim() {}, matchAll() { return Promise.resolve([]) }, openWindow() {} }, skipWaiting() {}, registration: {}, } const fn = new Function( 'self', 'caches', 'fetch', `${js} return { networkFirst, isNetworkFailure, okHtml };`, ) return fn(self, cachesImpl, fetchImpl) as { networkFirst: (request: Request, key: string, check: (res: Response) => boolean, fallbackKey?: string) => Promise isNetworkFailure: (err: unknown) => boolean okHtml: (res: Response) => boolean } } async function flush() { await new Promise((resolve) => setImmediate(resolve)) await new Promise((resolve) => setImmediate(resolve)) } test('service worker has no navigation timeout and only falls back on network TypeError', () => { assert.match(js, /isNetworkFailure/) assert.match(js, /err\.name === 'TypeError'/) assert.doesNotMatch(js, /NAV_TIMEOUT_MS/) assert.doesNotMatch(js, /setTimeout\s*\(/) new Function(js) }) test('a slow live response is used instead of the offline page', async () => { const cachesImpl = mockCaches({ '/offline': html(200, '

offline

') }) let calls = 0 const fetchImpl = async () => { calls += 1 await new Promise((resolve) => setTimeout(resolve, 30)) return html(200, '

live

') } const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl) const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline') assert.equal(await res.text(), '

live

') assert.equal(calls, 1) await flush() assert.equal(cachesImpl.store.has('/'), true) }) test('redirects and other non-OK responses are passed through, not treated as offline', async () => { const cachesImpl = mockCaches({ '/offline': html(200, '

offline

') }) const fetchImpl = async () => new Response(null, { status: 302, headers: { location: '/e/smith-pies', 'content-type': 'text/html' } }) const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl) const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline') assert.equal(res.status, 302) assert.equal(res.headers.get('location'), '/e/smith-pies') await flush() assert.equal(cachesImpl.store.has('/'), false) }) test('a 500 HTML page is passed through and not cached as the app shell', async () => { const cachesImpl = mockCaches({ '/offline': html(200, '

offline

') }) const fetchImpl = async () => html(500, '

error

') const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl) const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline') assert.equal(res.status, 500) assert.equal(await res.text(), '

error

') await flush() assert.equal(cachesImpl.store.has('/'), false) }) test('a TypeError is retried once, and a later success is used', async () => { const cachesImpl = mockCaches({ '/offline': html(200, '

offline

') }) let calls = 0 const fetchImpl = async () => { calls += 1 if (calls === 1) throw new TypeError('Failed to fetch') return html(200, '

retried

') } const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl) const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline') assert.equal(await res.text(), '

retried

') assert.equal(calls, 2) }) test('two network failures fall back to the cached page, or /offline if none is saved', async () => { const withPage = mockCaches({ '/': html(200, '

cached

'), '/offline': html(200, '

offline

'), }) const fetchFail = async () => { throw new TypeError('Failed to fetch') } const policy1 = loadPolicy(fetchFail as typeof fetch, withPage) const cached = await policy1.networkFirst(new Request(`${ORIGIN}/`), '/', policy1.okHtml, '/offline') assert.equal(await cached.text(), '

cached

') const noPage = mockCaches({ '/offline': html(200, '

offline

') }) const policy2 = loadPolicy(fetchFail as typeof fetch, noPage) const offline = await policy2.networkFirst(new Request(`${ORIGIN}/`), '/', policy2.okHtml, '/offline') assert.equal(await offline.text(), '

offline

') }) test('a non-TypeError rejection is not treated as offline', async () => { const cachesImpl = mockCaches({ '/offline': html(200, '

offline

') }) const err = new Error('unexpected') const fetchImpl = async () => { throw err } const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl) await assert.rejects(() => networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline'), err) })