export type LazyResource = { load: () => Promise; unload: () => void; isLoaded: () => boolean; }; export function createLazyResource( loader: () => Promise, dispose?: (value: T) => void ): LazyResource { let cached: T | null = null; let inflight: Promise | null = null; const load = async (): Promise => { if (cached) return cached; if (inflight) return inflight; inflight = (async () => { const value = await loader(); cached = value; inflight = null; return value; })(); return inflight; }; const unload = () => { if (cached && dispose) { try { dispose(cached); } catch (error) { console.error("[lazy-resource] failed to dispose resource", error); } } cached = null; inflight = null; }; return { load, unload, isLoaded: () => cached !== null }; }