import { expect, test } from 'bun:test'; import { captainKey, cached, mapSettled } from './cache'; test('captainKey hashes the whole token, not a suffix', () => { expect(captainKey('sfk_aaaa12345678')).not.toBe(captainKey('sfk_bbbb12345678')); expect(captainKey('sfk_x')).not.toContain('sfk_x'); }); test('cached serves fresh hits without calling produce again', async () => { let calls = 0; const produce = async () => ++calls; expect(await cached('fresh', 60_000, produce)).toBe(1); expect(await cached('fresh', 60_000, produce)).toBe(1); expect(calls).toBe(1); }); test('cached serves stale values while refreshing in the background', async () => { let calls = 0; const produce = async () => ++calls; await cached('stale', 0, produce, { maxStaleMs: 60_000 }); expect(await cached('stale', 0, produce, { maxStaleMs: 60_000 })).toBe(1); // stale served await Bun.sleep(1); expect(calls).toBe(2); // refresh ran }); test('concurrent misses share one request', async () => { let calls = 0; const produce = async () => { calls++; await Bun.sleep(5); return 'v'; }; await Promise.all([cached('dedupe', 1000, produce), cached('dedupe', 1000, produce)]); expect(calls).toBe(1); }); test('mapSettled caps concurrency and keeps order', async () => { let active = 0; let peak = 0; const res = await mapSettled([1, 2, 3, 4, 5, 6, 7], 3, async (n) => { active++; peak = Math.max(peak, active); await Bun.sleep(2); active--; if (n === 4) throw new Error('boom'); return n * 10; }); expect(peak).toBeLessThanOrEqual(3); expect(res.map((r) => (r.status === 'fulfilled' ? r.value : 'x'))).toEqual([10, 20, 30, 'x', 50, 60, 70]); });