import { Adapter, Stored } from './types.js'; import { Env } from '../boundary/components/env/types.js'; export type { Adapter, Encoded } from './types.js'; /** * Context passed to {@link CacheConfig.key}. Mirrors the shape an * `app.Resource` fetcher receives, restricted to the field the cache * needs to scope on: the live per-`` Env. Future-extensible * — new fields can land here without breaking the call shape. * * @template E The Env shape the cache is parameterised by. */ export type CacheContext = { readonly env: E; }; /** * Optional `key(context)` callback shared by both {@link CacheConfig} * variants. Derives a per-context cache scope. Called every time a * cache key is assembled with the same `{ env }` shape an * `app.Resource` fetcher receives; the returned string is prepended * to the per-resource namespace and params so different scopes * (e.g. one cache slot per access token, locale, or tenant id) can * coexist in the same backing store. Return `""`, `null`, or * `undefined` to skip prefixing — useful for "not signed in" * gaps where the scope is genuinely empty. */ type CacheKeyOnly = { readonly key?: (context: CacheContext) => string | null | undefined; readonly get?: never; readonly set?: never; readonly remove?: never; readonly keys?: never; }; type CacheAdapter = Adapter & { readonly key?: (context: CacheContext) => string | null | undefined; }; /** * Configuration accepted by the {@link Cache} factory. A discriminated * union with two shapes: * * - **Adapter-only / adapter + `key`** — supply the four * adapter methods (`get`/`set`/`remove`/`keys`) and an optional * `key(context)` callback. The cache is backed by the adapter; * persistence is the caller's responsibility. There is no `clear` * — the Cache layer synthesises one by iterating `keys()` * and removing only entries inside the `mh:` namespace it owns, * so third-party state on shared backends stays untouched. * - **`key`-only** — supply just `key(context)` (no adapter * methods at all). The cache falls back to a per-instance in-memory * adapter but still scopes every slot by the live Env, which is * useful for tests, ephemeral state, or signed-out sessions where * you want env-scoped isolation without touching storage. * * The split is enforced by the union: passing a partial adapter * (e.g. just `get`) is a type error — either all four required * adapter methods are present or none of them are. {@link Cache} also * accepts no argument at all for a plain in-memory cache. */ export type CacheConfig = CacheAdapter | CacheKeyOnly; /** * Persistence-aware cache for a single {@link Resource}. Wraps a * **strictly synchronous** {@link Adapter} (localStorage, MMKV, * chrome.storage with a sync facade, etc.) and traffics in {@link * Stored} envelopes — storage entries serialise as {@link * Encoded}`` so the `Temporal.Instant` timestamp survives the * string round-trip and `.exceeds({...})` can short-circuit on the * persisted timestamp after a reload. * * Every method on the Cache is sync — the model-literal sync * read has no place to wait, so the adapter contract foregoes * `Promise` entirely. Async backends (IndexedDB, AsyncStorage, * `chrome.storage.local`) need a sync facade hydrated at app entry; * see `recipes/storage.md` for the pattern. React Native projects * should reach for {@link https://github.com/mrousavy/react-native-mmkv * `react-native-mmkv`} — it's synchronous out of the box and * drops straight into the Adapter contract. * * Call with no arguments for an in-memory cache scoped to this * instance — useful for tests, ephemeral state, or when you * want a first-class cache object to share between Resources without * persistence. Pass an {@link Adapter} to back the cache with a * persistent store; when supplied, the adapter is the **only** tier * — the Cache does not maintain a separate in-memory mirror. * * `key(context)` is independently optional. Pass it alongside the * adapter methods to scope a persistent cache by the live Env, or on * its own (with no adapter) for an env-scoped in-memory cache. The * adapter methods are an all-or-nothing group: supply all four * (`get`/`set`/`remove`/`keys`) or none. Supplying a partial adapter * is a type error. * * The `E` generic lives on the {@link Cache} factory and on * {@link CacheConfig}: it parameterises the `key(context)` callback * at construction time so the caller can read `context.env.X` with * full typing. The returned {@link Cache} value is itself * env-agnostic — the runtime `scope(env)` method takes the * loose {@link Env} record and narrows internally before invoking * the callback — which keeps it freely assignable across * differently-typed Apps without variance gymnastics. * * @example * ```ts * // In-memory, scoped to this instance. * const cache = Cache(); * * // Persisted via localStorage. * const cache = Cache({ * get: (key) => localStorage.getItem(key), * set: (key, value) => localStorage.setItem(key, value), * remove: (key) => localStorage.removeItem(key), * keys: () => Object.keys(localStorage), * }); * * // Multi-tenant: writes go under `${accessToken}:…`. * type AppEnv = { session: { accessToken: string } | null }; * const cache = Cache({ * get: (key) => localStorage.getItem(key), * set: (key, value) => localStorage.setItem(key, value), * remove: (key) => localStorage.removeItem(key), * keys: () => Object.keys(localStorage), * key: ({ env }) => env.session?.accessToken ?? "", * }); * * // Env-scoped in-memory cache: no adapter, just `key`. * const cache = Cache({ * key: ({ env }) => env.session?.accessToken ?? "", * }); * * // Wire it into a Resource — successful runs write through automatically. * export const cat = Resource({ * cache, * fetch: (context) => fetchCat(context.controller.signal), * }); * ``` */ export type Cache = { /** * Returns the {@link Stored} envelope for `key`. The envelope is * `empty()` when nothing is persisted; otherwise it carries the * decoded payload and the timestamp recorded at write-time. * * @template T The payload type expected at `key`. * @param key Cache slot identifier — usually the JSON-stringified * call-site params, prefixed by the Resource's namespace. */ get(key: string): Stored; /** * Writes `value` to `key`. Skipped when the envelope has no concrete * payload (e.g. an `empty()` slot), since there is nothing meaningful * to persist. Serialisation, quota errors, and unserialisable payloads * are swallowed — writes are best-effort. * * @template T The payload type contained in `value`. * @param key Cache slot identifier — usually the JSON-stringified * call-site params, prefixed by the Resource's namespace. * @param value Stored envelope carrying the payload and its * write-time `Temporal.Instant`. */ set(key: string, value: Stored): void; /** * Drops a single cache slot. Best-effort — backing-store errors * are swallowed. * * @param key Cache slot identifier. */ remove(key: string): void; /** * Drops every cache slot in the backing store. Best-effort — * backing-store errors are swallowed. */ clear(): void; /** * Returns every key currently held by the backing store. Used by * partial-match eviction (`evict(where)`) to iterate slots whose * stored params satisfy a `where` pattern. */ keys(): Iterable; /** * Returns the per-context prefix derived from the configured * `key(context)`. The returned string is appended with `:` by the * Resource layer to compose the full cache key. Always `""` when * no `key` option was supplied or when the callback returned an * empty value — "no scope" is encoded as the empty string. * * Takes the loose {@link Env} record at runtime — the typed * `E` lives on the `key(context)` callback registered at * construction time, which the cache narrows to `E` internally * before invoking. * * @internal Public surface lives on the Resource layer; consumers * should not need to call this directly. */ scope(env: Env | undefined): string; }; /** * Constructs a {@link Cache} from `config`. The config object is a * discriminated union of two shapes: * * - Adapter methods (`get`/`set`/`remove`/`keys`) plus an optional * `key(context)`. * - Just `key(context)` — no adapter methods at all, which falls * back to a per-instance in-memory adapter while still scoping every * slot by the live Env. * * Supplying a partial adapter (e.g. just `get` and `set`, or omitting * `keys`) is a type error: the adapter members are an all-or-nothing * group. Omit `config` entirely for a plain in-memory cache. * * When `key` is supplied, it runs each time the Resource layer * assembles a cache key, receiving the same `{ env }` shape an * `app.Resource` fetcher sees; its return value is prepended * (separated by `:`) to the per-resource namespace and params JSON. * * @template E The Env shape `config.key` is typed against. Defaults * to the loose {@link Env} record so callers that don't scope by * env can keep using `Cache({ ...adapter })` without supplying a * generic. * @param config Optional config literal. Omit for an in-memory cache; * supply adapter methods for a persisted cache; supply `key` to * scope writes by the live Env (with or without an adapter). */ export declare function Cache(options?: CacheConfig): Cache;