import { test } from 'node:test'; import assert from 'node:assert/strict'; import { snapshotFreshness } from '../src/lib/freshness.ts'; const now = Date.parse('2026-10-07T17:51:00.000Z'); const ago = minutes => new Date(now - minutes * 60_000).toISOString(); const snapshot = (minutes, updatedMinutes = minutes) => ({ data: { updatedAt: ago(updatedMinutes) }, savedAt: ago(minutes), saved: true }); test('a just saved response remains fresh when used from storage', () => { assert.deepEqual(snapshotFreshness(snapshot(1), 'departures', now), { checkedAt: ago(1), ageMs: 60_000, isOld: false, }); assert.equal(snapshotFreshness({ ...snapshot(1), saved: false }, 'departures', now).isOld, false); }); test('age warnings follow resource needs rather than network connectivity', () => { assert.equal(snapshotFreshness(snapshot(29.9), 'departures', now).isOld, false); assert.equal(snapshotFreshness(snapshot(30), 'departures', now).isOld, true); for (const resource of ['timetable', 'journey']) { assert.equal(snapshotFreshness(snapshot(1439), resource, now).isOld, false); assert.equal(snapshotFreshness(snapshot(1440), resource, now).isOld, true); } assert.equal(snapshotFreshness(snapshot(14), 'alerts', now).isOld, false); assert.equal(snapshotFreshness(snapshot(15), 'alerts', now).isOld, true); }); test('resaving an old server response cannot reset its freshness', () => { assert.equal(snapshotFreshness(snapshot(0, 45), 'departures', now).isOld, true); assert.equal(snapshotFreshness(snapshot(45, 0), 'departures', now).isOld, true); assert.equal(snapshotFreshness({ data: [], savedAt: ago(16) }, 'alerts', now).isOld, true); }); test('unavailable, legacy and clock-skewed timestamps are handled conservatively', () => { assert.deepEqual(snapshotFreshness(undefined, 'departures', now), { checkedAt: null, ageMs: null, isOld: false }); assert.equal(snapshotFreshness({ data: { updatedAt: 'invalid' }, savedAt: ago(1) }, 'departures', now).isOld, false); assert.equal(snapshotFreshness({ data: { updatedAt: ago(45) }, savedAt: 'invalid' }, 'departures', now).isOld, true); assert.deepEqual(snapshotFreshness({ data: {}, savedAt: 'invalid' }, 'departures', now), { checkedAt: null, ageMs: null, isOld: true }); assert.equal(snapshotFreshness(snapshot(-5), 'departures', now).ageMs, 0); assert.equal(snapshotFreshness(snapshot(-5, 45), 'departures', now).isOld, true); });