import { PromiseCacheCore } from './core.js'; import type { ErrorCallback, InvalidationConfig, PromiseCacheFetcher, PromiseCacheKeyAdapter, PromiseCacheKeyParser } from './types.js'; /** * Caches items by a key (string or another type) which are resolved by an async fetcher (`Promise`). * * Supports: * - custom key adapter and parser for non-string keys. * - direct manual cache manipulation. * - batching of fetches. * - auto-invalidation of cached items (time-based, callback-based, max items). * - error tracking per key. */ export declare class PromiseCache extends PromiseCacheCore { private readonly fetcher; private _batch; private _invalidationConfig; private _onError; private _initialValueFactory; /** * Creates an instance of PromiseCache. * @param fetcher Function to fetch data by key. * @param keyAdapter Optional function to adapt non-string keys to strings. * @param keyParser Optional function to parse string keys back to their original type. */ constructor(fetcher: PromiseCacheFetcher, keyAdapter?: PromiseCacheKeyAdapter, keyParser?: PromiseCacheKeyParser); /** * Provide a fetcher function that takes multiple ids and returns multiple results at once. Will be called with a slight delay to allow multiple ids to be collected. * * Warning: resolved array should have the same order as the input array. * * When provided, effectively replaces the main fetcher; but in case of fail, fallbacks to the main fetcher. */ useBatching(fetcher: (ids: K[]) => Promise, delay?: number): this; /** * Enables auto-invalidation of cached items by time. * * This is a convenience wrapper around {@link useInvalidation}. * * @param ms Time in milliseconds after which the item will be considered invalid. If null, auto-invalidation is disabled. * * @deprecated The `keepInstance` parameter is deprecated and ignored — stale values are now always kept during invalidation. * Use `invalidate()` followed by `get()` if you need to clear the stale value before re-fetching. */ useInvalidationTime(ms: number | null, _keepInstance?: boolean): this; /** * Configures advanced invalidation policy. * * The config object is stored as-is (not destructured), so getter-based fields will be re-evaluated on each access. * This allows consumers to provide dynamic invalidation policies. * * @param config The invalidation configuration. See {@link InvalidationConfig} for details. */ useInvalidation(config: InvalidationConfig | null): this; /** * Sets an error callback that is called when a fetcher fails. * * @param callback The callback to call on error. Receives the original key and the raw error. */ useOnError(callback: ErrorCallback | null): this; /** * Sets a default/initial value returned before the fetch completes or on error when no stale value exists. * * Accepts either a static value or a per-key factory function `(key: K) => TInitial`. * The value is **not** stored in the cache — it's a synthetic default (same as `LazyPromise`'s initial value). * * **Note:** Functions are always interpreted as factories. If `T` is a function type, * wrap it: `useInitialValue((key) => myFallbackFn)`. * * @param initial A value (non-function) or `(key: K) => TInitial` factory. * @returns `this` for chaining. */ useInitialValue(initial: TNewInitial | ((key: K) => TNewInitial)): PromiseCache; /** * Returns a promise that resolves to the cached value of the item if loaded already, otherwise starts fetching and the promise will be resolved to the final value. * * Consequent calls will return the same promise until it resolves. * * @param id The id of the item. * @returns A promise that resolves to the result, whether it's cached or freshly fetched. */ get(id: K): Promise; /** * Re-fetches the value for the specified key while keeping the stale cached value available. * * Does not change the loading status — consumers reading `getCurrent()` / `getLazy().value` * continue to see the stale value as if nothing happened. * * Implements "latest wins" concurrency: if multiple refreshes are called concurrently, * all promises resolve to the value from the latest refresh. * * On error, the stale value is preserved and the error is stored. * * @param id The key of the item to refresh. * @returns A promise resolving to the refreshed value, or the stale value on error. */ refresh(id: K): Promise; /** Clears the cache and resets the loading state. */ clear(): void; protected _getInitialValue(id: K): TInitial; protected getIsInvalidated(key: string): boolean; /** @override Stores the result for the specified key, enforcing max items. */ protected storeResult(key: string, res: T): void; /** * Unified fetch method with "latest wins" semantics. * * - Tracks the active factory promise per key via `_activeFetchPromises`. * - If superseded by a newer fetch, delegates to the newer promise. * - On error, preserves the stale cached value. * * @param id The original key. * @param key The string cache key. * @returns A promise resolving to the fetched/refreshed value, or the stale value on error. */ protected _doFetchAsync(id: K, key: string, refreshing: boolean): Promise; /** Performs a fetch operation in batch mode if available, otherwise uses the regular fetch. Throws on error. */ protected tryFetchInBatch(id: K, refreshing?: boolean): Promise; /** Handles a fetch error: stores it, logs it, and calls the onError callback. */ protected _handleError(id: K, err: unknown): void; /** * Enforces the max items limit by removing items to make room. * Strategy: first removes invalid items, then oldest valid items by timestamp. * Items currently being fetched (in-flight) are not evicted. * * Note: Phase 2 scans all timestamps linearly (O(n) per eviction). * This is acceptable for typical `maxItems` values (up to ~1000). * * @param incomingKey The key of the item about to be stored (excluded from eviction). */ private _enforceMaxItems; }