import { vi } from "vitest"; /** * A Cache Storage stand-in for jsdom, which does not have one. * * Deliberately small: the warm cache's disk tier only ever `open`s one named cache and * `put`/`match`/`keys`/`delete` within it, and a fake that grew a body-stream layer of * its own would be testing itself rather than the tier. `match` mints a fresh Response * from stored bytes on every call, because a Response's body is single-use and the * real Cache Storage does not hand out one-shot entries. * * Entries are keyed by whatever string the caller passed, and credential-stripping of * stream URLs is the tier's own behaviour — under test, not modelled here. */ interface Stored { bytes: ArrayBuffer; headers: Record; } export interface FakeCachesHandle { /** the named caches currently standing, and their entries, for tests that want to look */ dump(): Record>; /** silently take one entry back, the way the browser does when the disk gets tight */ evict(name: string, url: string): void; } export function stubCaches(): FakeCachesHandle { const stores = new Map>(); const storeFor = (name: string): Map => { let s = stores.get(name); if (!s) { s = new Map(); stores.set(name, s); } return s; }; vi.stubGlobal("caches", { async open(name: string) { const s = storeFor(name); return { async put(url: string, res: Response) { const bytes = await res.arrayBuffer(); const headers: Record = {}; res.headers.forEach((v, k) => { headers[k] = v; }); s.set(url, { bytes, headers }); }, async match(url: string) { const e = s.get(url); if (!e) return undefined; return new Response(e.bytes.slice(0), { headers: e.headers }); }, async keys() { return [...s.keys()].map((url) => ({ url })); }, async delete(url: string) { return s.delete(url); }, }; }, async delete(name: string) { return stores.delete(name); }, async has(name: string) { return stores.has(name); }, async keys() { return [...stores.keys()]; }, }); return { dump() { const out: Record> = {}; for (const [name, s] of stores) { out[name] = {}; for (const [url, e] of s) out[name]![url] = e.bytes.byteLength; } return out; }, evict(name: string, url: string) { stores.get(name)?.delete(url); }, }; }