import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; /** Laadt sw.js in een minimale nep-serviceworker-omgeving en geeft de geregistreerde handlers terug. */ function loadServiceWorker({ fetchImpl }) { const listeners = {}; const store = new Map(); const cache = { async addAll(urls) { urls.forEach((u) => store.set(new URL(u, 'http://x/').href, new Response('shell'))); }, // De echte Cache API accepteert zowel een Request als een URL-string als sleutel. async put(req, res) { store.set(typeof req === 'string' ? req : req.url, res); }, async match(req) { return store.get(typeof req === 'string' ? req : req.url) || undefined; }, async keys() { return [...store.keys()].map((u) => new Request(u)); }, }; const sandbox = { self: { addEventListener: (type, fn) => { listeners[type] = fn; }, skipWaiting: async () => {}, clients: { claim: async () => {} }, location: new URL('http://x/'), }, caches: { open: async () => cache, keys: async () => ['weerscherm-v0', 'weerscherm-v1'], delete: async () => true }, fetch: fetchImpl, Response, Request, Headers, URL, AbortController, setTimeout, clearTimeout, console, }; vm.createContext(sandbox); vm.runInContext(readFileSync(new URL('../../public/sw.js', import.meta.url), 'utf8'), sandbox); return { listeners, store }; } function dispatchFetch(listeners, url) { let promise = null; listeners.fetch({ request: new Request(url), respondWith: (p) => { promise = p; }, }); return promise; } test('install caches the app shell', async () => { const { listeners, store } = loadServiceWorker({ fetchImpl: async () => new Response('x') }); let done = null; listeners.install({ waitUntil: (p) => { done = p; } }); await done; assert.ok(store.has('http://x/app.js')); assert.ok(store.has('http://x/index.html')); }); test('API request goes to the network first and is cached', async () => { const { listeners, store } = loadServiceWorker({ fetchImpl: async () => new Response('{"station":{}}', { status: 200, headers: { 'Content-Type': 'application/json' } }), }); const res = await dispatchFetch(listeners, 'http://x/api/data.php'); assert.equal(res.status, 200); assert.equal(res.headers.get('X-From-Cache'), null); assert.ok(store.has('http://x/api/data.php')); }); test('API request falls back to the cached response with X-From-Cache when offline', async () => { let online = true; const { listeners } = loadServiceWorker({ fetchImpl: async () => { if (!online) throw new TypeError('Failed to fetch'); return new Response('{"station":{"stale":false}}', { status: 200, headers: { 'Content-Type': 'application/json' } }); }, }); await dispatchFetch(listeners, 'http://x/api/data.php'); online = false; const res = await dispatchFetch(listeners, 'http://x/api/data.php'); assert.equal(res.status, 200); assert.equal(res.headers.get('X-From-Cache'), '1'); assert.equal(await res.text(), '{"station":{"stale":false}}'); }); test('API request without any cache gives a 503 offline JSON', async () => { const { listeners } = loadServiceWorker({ fetchImpl: async () => { throw new TypeError('offline'); } }); const res = await dispatchFetch(listeners, 'http://x/api/data.php'); assert.equal(res.status, 503); assert.deepEqual(await res.json(), { errors: ['offline'] }); }); test('shell request is served from cache without hitting the network', async () => { let calls = 0; const { listeners, store } = loadServiceWorker({ fetchImpl: async () => { calls++; return new Response('net'); } }); store.set('http://x/styles.css', new Response('cached css')); const res = await dispatchFetch(listeners, 'http://x/styles.css'); assert.equal(await res.text(), 'cached css'); assert.equal(calls, 0); }); test('cross-origin and non-GET requests are left alone', () => { const { listeners } = loadServiceWorker({ fetchImpl: async () => new Response('x') }); assert.equal(dispatchFetch(listeners, 'http://elders/api/data.php'), null); let handled = false; listeners.fetch({ request: new Request('http://x/api/data.php', { method: 'POST' }), respondWith: () => { handled = true; } }); assert.equal(handled, false); }); test('the radar image is network-first and cached under a key without querystring', async () => { const { listeners, store } = loadServiceWorker({ fetchImpl: async () => new Response('GIF89a', { status: 200, headers: { 'Content-Type': 'image/gif' } }), }); const res = await dispatchFetch(listeners, 'http://x/api/radar.php?t=123'); assert.equal(res.status, 200); assert.ok(store.has('http://x/api/radar.php'), 'sleutel zonder ?t=, anders loopt de cache vol met varianten'); assert.equal(store.has('http://x/api/radar.php?t=123'), false); }); test('an offline radar request falls back to the cached image, even with a different querystring', async () => { let online = true; const { listeners } = loadServiceWorker({ fetchImpl: async () => { if (!online) throw new TypeError('Failed to fetch'); return new Response('GIF89a', { status: 200, headers: { 'Content-Type': 'image/gif' } }); }, }); await dispatchFetch(listeners, 'http://x/api/radar.php?t=1'); online = false; const res = await dispatchFetch(listeners, 'http://x/api/radar.php?t=2'); assert.equal(res.status, 200); assert.equal(res.headers.get('X-From-Cache'), '1'); assert.equal(await res.text(), 'GIF89a'); }); test('an offline radar request without any cache gives a plain 503, not JSON', async () => { const { listeners } = loadServiceWorker({ fetchImpl: async () => { throw new TypeError('offline'); } }); const res = await dispatchFetch(listeners, 'http://x/api/radar.php?t=1'); assert.equal(res.status, 503); assert.equal(await res.text(), 'offline'); });