Something went wrong. Try again.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import { 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<string, string>;}
export interface FakeCachesHandle { /** the named caches currently standing, and their entries, for tests that want to look */ dump(): Record<string, Record<string, number>>; /** 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<string, Map<string, Stored>>(); const storeFor = (name: string): Map<string, Stored> => { 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<string, string> = {}; 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<string, Record<string, number>> = {}; 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); }, };}