repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/web/lazy.ts
Raw/**
* Memoize a dynamic import so concurrent callers share one evaluation.
*
* Pi loads extensions through jiti with the module cache disabled.
* Two concurrent imports of the same module can then race: the second
* caller receives a partially initialized module whose top-level awaits
* have not finished and whose imported bindings are still `undefined`
* (for example `Cannot read properties of undefined (reading
* 'isCodexAvailable')` from parallel web searches).
*
* Routing every lazy import through one shared promise closes that window.
* A rejected load clears the memo so the next call retries.
*/
export function lazy<T>(load: () => Promise<T>): () => Promise<T> {
let promise: Promise<T> | undefined;
return () =>
(promise ??= load().catch((error: unknown) => {
promise = undefined;
throw error;
}));
}