@warlock.js/cache 5.53.1 → 5.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/cjs/index.cjs +158 -7
- package/cjs/index.cjs.map +1 -1
- package/esm/cache-manager.d.mts +12 -0
- package/esm/cache-manager.d.mts.map +1 -1
- package/esm/cache-manager.mjs +18 -0
- package/esm/cache-manager.mjs.map +1 -1
- package/esm/drivers/base-cache-driver.d.mts +11 -0
- package/esm/drivers/base-cache-driver.d.mts.map +1 -1
- package/esm/drivers/base-cache-driver.mjs +43 -6
- package/esm/drivers/base-cache-driver.mjs.map +1 -1
- package/esm/drivers/file-cache-driver.d.mts +7 -0
- package/esm/drivers/file-cache-driver.d.mts.map +1 -1
- package/esm/drivers/file-cache-driver.mjs +14 -0
- package/esm/drivers/file-cache-driver.mjs.map +1 -1
- package/esm/drivers/lru-memory-cache-driver.d.mts +4 -0
- package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
- package/esm/drivers/lru-memory-cache-driver.mjs +13 -0
- package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
- package/esm/drivers/memory-cache-driver.d.mts +4 -0
- package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
- package/esm/drivers/memory-cache-driver.mjs +13 -0
- package/esm/drivers/memory-cache-driver.mjs.map +1 -1
- package/esm/drivers/mock-cache-driver.d.mts +4 -0
- package/esm/drivers/mock-cache-driver.d.mts.map +1 -1
- package/esm/drivers/mock-cache-driver.mjs +9 -0
- package/esm/drivers/mock-cache-driver.mjs.map +1 -1
- package/esm/drivers/null-cache-driver.d.mts +4 -0
- package/esm/drivers/null-cache-driver.d.mts.map +1 -1
- package/esm/drivers/null-cache-driver.mjs +6 -0
- package/esm/drivers/null-cache-driver.mjs.map +1 -1
- package/esm/drivers/pg-cache-driver.d.mts +4 -0
- package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
- package/esm/drivers/pg-cache-driver.mjs +8 -0
- package/esm/drivers/pg-cache-driver.mjs.map +1 -1
- package/esm/drivers/redis-cache-driver.d.mts +7 -0
- package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
- package/esm/drivers/redis-cache-driver.mjs +18 -0
- package/esm/drivers/redis-cache-driver.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/esm/scoped-cache.d.mts.map +1 -1
- package/esm/scoped-cache.mjs +5 -2
- package/esm/scoped-cache.mjs.map +1 -1
- package/esm/types.d.mts +53 -0
- package/esm/types.d.mts.map +1 -1
- package/esm/types.mjs.map +1 -1
- package/esm/utils.d.mts +6 -0
- package/esm/utils.d.mts.map +1 -1
- package/esm/utils.mjs +13 -1
- package/esm/utils.mjs.map +1 -1
- package/llms-full.txt +6 -0
- package/package.json +4 -4
- package/skills/cache-basics/SKILL.md +1 -0
- package/skills/configure-set-options/SKILL.md +2 -0
- package/skills/use-cache-namespace/SKILL.md +1 -0
- package/skills/use-cache-similarity/SKILL.md +1 -0
- package/skills/use-swr/SKILL.md +1 -0
package/esm/types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../packages/cache/src/types.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport type { RedisClientOptions } from \"redis\";\nimport type {\n BaseCacheDriver,\n FileCacheDriver,\n LRUMemoryCacheDriver,\n MemoryCacheDriver,\n MockCacheDriver,\n MemoryExtendedCacheDriver,\n NullCacheDriver,\n PgCacheDriver,\n RedisCacheDriver,\n} from \"./drivers\";\n\n/**\n * Base error class for cache-related errors\n */\nexport class CacheError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheError\";\n }\n}\n\n/**\n * Error thrown when cache connection fails\n */\nexport class CacheConnectionError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConnectionError\";\n }\n}\n\n/**\n * Error thrown when cache driver configuration is invalid\n */\nexport class CacheConfigurationError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConfigurationError\";\n }\n}\n\n/**\n * Error thrown when cache driver is not initialized\n */\nexport class CacheDriverNotInitializedError extends CacheError {\n public constructor(\n message: string = \"No cache driver initialized. Call cache.init() or cache.use() first.\",\n ) {\n super(message);\n this.name = \"CacheDriverNotInitializedError\";\n }\n}\n\n/**\n * Error thrown when a driver does not implement a requested operation.\n *\n * Raised when a caller invokes a method the driver cannot fulfill —\n * e.g. `update()` on the file driver before the file-lock primitive lands.\n */\nexport class CacheUnsupportedError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheUnsupportedError\";\n }\n}\n\n/**\n * Error thrown when an optimistic-concurrency update exhausts its retry budget.\n */\nexport class CacheConcurrencyError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConcurrencyError\";\n }\n}\n\n/**\n * TTL shape accepted by set/remember/config calls.\n *\n * - `number` — seconds\n * - `string` — human-readable duration parsed via `ms` (`\"1h\"`, `\"30m\"`, `\"7d\"`, `\"2 weeks\"`, …)\n * - `Infinity` — no expiration\n */\nexport type CacheTtl = number | string;\n\n/**\n * Conflict resolution policy for `set` operations.\n *\n * - `\"create\"` — set only if the key does not exist (Redis `NX`)\n * - `\"update\"` — set only if the key already exists (Redis `XX`)\n * - `\"upsert\"` — default; overwrite whether the key exists or not\n */\nexport type CacheConflictPolicy = \"create\" | \"update\" | \"upsert\";\n\n/**\n * Result of a conditional write (`onConflict: \"create\" | \"update\"`).\n */\nexport type CacheSetResult<T = any> = {\n /**\n * Whether the write actually took effect.\n */\n wasSet: boolean;\n /**\n * The existing value when the write was rejected. Undefined for successful writes\n * and for unconditional `upsert` writes.\n */\n existing: T | null;\n};\n\n/**\n * Options for `lock()` — TTL is required (forgotten locks would stay forever),\n * `owner` identifies who holds the lock (handy for debugging), `driver` routes\n * the call through a non-default driver.\n *\n * @example\n * await cache.lock(\"lock.import\", { ttl: \"5m\", driver: \"redis\" }, async () => {\n * await runImport();\n * });\n */\nexport type LockOptions = {\n /**\n * How long the lock lives before auto-release. Required — guards against\n * forgotten locks if the process crashes between acquire and release.\n */\n ttl: CacheTtl;\n /**\n * Identifying value stored under the lock key. Defaults to `pid.<process.pid>`.\n * Use a custom owner when you want a human-readable label (e.g. `\"worker.jobs-2\"`).\n */\n owner?: string;\n /**\n * Per-call driver override by registered name. Manager-level only.\n */\n driver?: string;\n};\n\n/**\n * Discriminated-union result of `lock()`. Unambiguous even when the wrapped\n * function legitimately returns `undefined` — the `acquired` flag tells you\n * whether `fn` ran at all.\n *\n * @example\n * const outcome = await cache.lock(\"lock.x\", \"1m\", async () => computeValue());\n * if (outcome.acquired) {\n * console.log(\"ran, got\", outcome.value);\n * } else {\n * console.log(\"skipped — someone else holds the lock\");\n * }\n */\nexport type LockOutcome<T> = { acquired: true; value: T } | { acquired: false };\n\n/**\n * Options for `remember()` when you need more than just a TTL — e.g. attaching\n * tags to the cache-miss write, or routing the single call to a non-default driver.\n *\n * Passed in the TTL position: `cache.remember(key, { ttl: \"1h\", tags: [\"users\"] }, fn)`.\n *\n * @example\n * await cache.remember(\"user.1\", { ttl: \"1h\", tags: [\"users\"] }, () =>\n * db.users.find(1),\n * );\n */\nexport type RememberOptions = {\n /**\n * TTL applied on cache miss. Accepts seconds (number) or duration string.\n */\n ttl?: CacheTtl;\n /**\n * Tags attached to the entry created on miss. Invalidate via `cache.tags([...]).invalidate()`.\n */\n tags?: string[];\n /**\n * Per-call driver override. Routes this remember call (both read and write)\n * to the named driver without mutating `currentDriver`.\n */\n driver?: string;\n};\n\n/**\n * Rich options for the `set` call-site. Mutually exclusive with a positional TTL.\n *\n * @example\n * await cache.set(\"user:1\", user, {\n * ttl: \"1h\",\n * tags: [\"users\", \"active\"],\n * onConflict: \"create\",\n * });\n */\nexport type CacheSetOptions = {\n /**\n * Relative TTL (seconds or duration string). Mutually exclusive with `expiresAt`.\n */\n ttl?: CacheTtl;\n /**\n * Absolute expiration as a Unix epoch in milliseconds or a Date. Mutually exclusive with `ttl`.\n */\n expiresAt?: number | Date;\n /**\n * Tags attached to this entry for tag-based invalidation. Inline equivalent of\n * `cache.tags([...]).set(key, value)`.\n */\n tags?: string[];\n /**\n * Conflict resolution policy. Defaults to `\"upsert\"`.\n */\n onConflict?: CacheConflictPolicy;\n /**\n * Per-call namespace override. Applied ahead of `globalPrefix` for this write only.\n */\n namespace?: string;\n /**\n * Per-call driver override by registered name. Routes this write to a non-default driver\n * without mutating `currentDriver`.\n */\n driver?: string;\n /**\n * Optional embedding vector indexed alongside the entry for similarity retrieval\n * via `cache.similar(...)`. Drivers without similarity support throw\n * {@link CacheUnsupportedError} when this option is supplied.\n *\n * Cache is embedding-agnostic — callers compute the vector with whichever embedder\n * they like and pass the result here.\n *\n * @example\n * await cache.set(\"doc.123\", doc, { vector: await embed(doc.text), ttl: \"1d\" });\n */\n vector?: number[];\n /**\n * Freshness deadline as a Unix epoch in milliseconds. Primarily set by\n * {@link CacheSwrOptions} flow — entries with `staleAt` in the future are\n * considered \"fresh\" by `cache.swr()`; entries past `staleAt` but before\n * `expiresAt` are \"stale-but-revalidatable.\"\n *\n * Direct callers can pin this manually when bypassing `swr()`, but the\n * common path is `cache.swr(key, { freshTtl, staleTtl }, fn)`.\n */\n staleAt?: number;\n};\n\n/**\n * Options for `cache.namespace(prefix, options)` — defaults applied to every\n * write produced through the returned scope.\n *\n * Per-call options always win over scope defaults. Tags merge additively\n * (scope tags + call tags, deduped). Nested scopes inherit from the parent;\n * the child's own values override.\n */\nexport type CacheNamespaceOptions = {\n /**\n * Default TTL for writes inside this scope. Same shape as everywhere else\n * — number of seconds or a duration string (`\"1h\"`, `\"30d\"`, …).\n */\n ttl?: CacheTtl;\n /**\n * Tags auto-attached to every write inside this scope. Useful for cross-scope\n * invalidation hooks (e.g. tag every entry with `user.<id>` so a single\n * `cache.flushTag(\"user.42\")` wipes the user's footprint everywhere).\n *\n * Merged additively with per-call tags; scope tags are never replaced.\n */\n tags?: string[];\n};\n\n/**\n * Options for `cache.swr(key, options, callback)` — stale-while-revalidate.\n *\n * Two TTLs split the entry's lifecycle into three windows:\n * - `now < freshTtl` → fresh, return cached value, no upstream call.\n * - `freshTtl <= now < staleTtl` → stale-but-revalidatable, return cached\n * value immediately, kick off `callback` in the background to refresh.\n * - `now >= staleTtl` → expired, block on `callback` like a normal miss.\n *\n * Concurrent SWR callers in the stale window all return the cached value;\n * the background refresh runs exactly once per key (deduped via the\n * driver's per-key lock map).\n *\n * If the background refresh fails, the stale entry is preserved and the\n * error is logged + emitted on the `error` event. Callers that received\n * the stale value never see the failure — they got their data.\n */\nexport type CacheSwrOptions = {\n /**\n * How long the value is considered fresh. Within this window, SWR returns\n * the cached value with no upstream call. Accepts seconds or duration\n * string (`\"1m\"`, `\"30s\"`).\n */\n freshTtl: CacheTtl;\n /**\n * Total lifetime of the entry (must be greater than `freshTtl`). Between\n * `freshTtl` and `staleTtl`, SWR returns the stale value and triggers a\n * background refresh. Past `staleTtl`, SWR blocks and refetches.\n */\n staleTtl: CacheTtl;\n /**\n * Optional tags applied on the first miss-fetch and on every successful\n * background refresh. Same semantics as `CacheSetOptions.tags`.\n */\n tags?: string[];\n /**\n * Per-call driver override by registered name. Routes both the read and\n * any write/refresh through the named driver without mutating\n * `currentDriver`. Same semantics as `RememberOptions.driver`.\n */\n driver?: string;\n};\n\n/**\n * Options for `cache.similar(vector, options)` — similarity retrieval against\n * stored entries previously written with `set({ vector })`.\n */\nexport type CacheSimilarOptions = {\n /**\n * Maximum number of hits to return. Required — no implicit default keeps\n * callers from accidentally pulling the entire candidate set.\n */\n topK: number;\n /**\n * Cosine similarity floor in `[0, 1]`. Hits scoring strictly below this are\n * filtered out before `topK` truncation.\n */\n threshold?: number;\n /**\n * Optional tag filter. Only entries tagged with at least one of the given\n * tags are considered (matches the union semantics elsewhere in the package).\n */\n tags?: string[];\n};\n\n/**\n * One result from a `similar()` query — the original key, its stored value,\n * and the cosine similarity to the query vector.\n */\nexport type CacheSimilarHit<T = unknown> = {\n /**\n * The original cache key, post-`parseKey` normalization.\n */\n key: string;\n /**\n * Stored value, deep-cloned to protect the cache from accidental mutation\n * (same semantics as `get`).\n */\n value: T;\n /**\n * Cosine similarity in `[0, 1]`. Higher means more similar.\n */\n score: number;\n};\n\n/**\n * Cache key type - can be a string or an object\n */\nexport type CacheKey = string | GenericObject;\n\nexport type CacheOperationType =\n | \"fetching\"\n | \"fetched\"\n | \"caching\"\n | \"cached\"\n | \"flushing\"\n | \"flushed\"\n | \"removing\"\n | \"removed\"\n | \"clearing\"\n | \"cleared\"\n | \"expired\"\n | \"notFound\"\n | \"connecting\"\n | \"error\"\n | \"connectionFailed\"\n | \"connected\"\n | \"disconnecting\"\n | \"disconnected\";\n\n/**\n * Cache event types for observability\n */\nexport type CacheEventType =\n | \"hit\"\n | \"miss\"\n | \"set\"\n | \"removed\"\n | \"invalidated\"\n | \"flushed\"\n | \"expired\"\n | \"connected\"\n | \"disconnected\"\n | \"error\";\n\n/**\n * Cache event data structure\n */\nexport type CacheEventData = {\n /**\n * The cache key involved in the event\n */\n key?: string;\n /**\n * The value (for set/hit events)\n */\n value?: any;\n /**\n * TTL in seconds (for set events)\n */\n ttl?: number;\n /**\n * Driver name that emitted the event\n */\n driver: string;\n /**\n * Error object (for error events)\n */\n error?: any;\n /**\n * Namespace (for namespace operations)\n */\n namespace?: string;\n /** Tags passed to `tags([...]).invalidate()` (`invalidated` events only). */\n tags?: string[];\n /** Keys a tag invalidation removed (`invalidated` events only). */\n keys?: string[];\n /** How long the operation took, in milliseconds (`invalidated` events only). */\n durationMs?: number;\n};\n\n/**\n * Event handler function type\n */\nexport type CacheEventHandler = (eventData: CacheEventData) => void | Promise<void>;\n\n/**\n * Per-operation latency + counter snapshot returned by `cache.metrics()`.\n *\n * The shape is a single recursive level — the top object covers all drivers\n * and each entry under `byDriver` repeats the same fields without nesting\n * further. Use this for ad-hoc dashboards, exporters to Prometheus / StatsD,\n * or just `console.log` during development.\n */\nexport type CacheMetricsSnapshot = {\n /** Cumulative cache hits across the lifetime of the collector. */\n hits: number;\n /** Cumulative cache misses (lookups that returned null). */\n misses: number;\n /** Cumulative successful writes. */\n sets: number;\n /** Cumulative key removals. */\n removed: number;\n /** Cumulative cache errors emitted via the `error` event. */\n errors: number;\n /** `hits / (hits + misses)` — `0` when no read ops have happened yet. */\n hitRate: number;\n /** Latency percentiles in milliseconds, computed from a circular buffer. */\n latencyMs: {\n p50: number;\n p95: number;\n p99: number;\n /** Size of the underlying buffer at snapshot time (capped at the configured max). */\n samples: number;\n };\n /** Per-driver breakdowns keyed by driver name (`\"memory\"`, `\"redis\"`, …). */\n byDriver: Record<string, Omit<CacheMetricsSnapshot, \"byDriver\">>;\n /** Millisecond timestamp the collector last reset (or was instantiated). */\n startedAt: number;\n};\n\n/**\n * Tagged cache interface for working with cache tags\n */\nexport interface TaggedCacheDriver {\n /**\n * Set a value in cache with tags\n */\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n /**\n * Get a value from cache (checks tags)\n */\n get(key: CacheKey): Promise<any | null>;\n /**\n * Remove a specific key\n */\n remove(key: CacheKey): Promise<void>;\n /**\n * Invalidate (clear) all keys associated with the current tags\n */\n invalidate(): Promise<void>;\n /**\n * Flush all keys associated with the current tags\n * @deprecated Use invalidate() instead\n */\n flush(): Promise<void>;\n /**\n * Check if a key exists\n */\n has(key: CacheKey): Promise<boolean>;\n /**\n * Remember pattern with tags\n */\n remember(key: CacheKey, ttl: number, callback: () => Promise<any>): Promise<any>;\n /**\n * Pull value with tags\n */\n pull(key: CacheKey): Promise<any | null>;\n /**\n * Forever with tags\n */\n forever(key: CacheKey, value: any): Promise<any>;\n /**\n * Increment with tags\n */\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n /**\n * Decrement with tags\n */\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n}\n\nexport type MemoryCacheOptions = {\n /**\n * The global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for the cache. Accepts a number of seconds or a human-readable\n * duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Maximum number of entries. When exceeded, the least recently used\n * entries are evicted. `Infinity` (or `0`) removes the limit.\n *\n * @default 10000\n */\n maxSize?: number;\n};\n\nexport type MemoryExtendedCacheOptions = MemoryCacheOptions;\n\nexport type LRUMemoryCacheOptions = {\n /**\n * The maximum number of items in the cache\n *\n * @default 1000\n */\n capacity?: number;\n /**\n * The global prefix for the cache key. Applied via `parseCacheKey`, same\n * semantics as the other drivers.\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for new entries. Accepts a number of seconds or a\n * human-readable duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n};\n\nexport type FileCacheOptions = {\n /**\n * The global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for the cache. Accepts a number of seconds or a human-readable\n * duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default 0\n */\n ttl?: CacheTtl;\n /**\n * Storage cache directory\n *\n * @default storagePath(\"cache\")\n */\n directory: string | (() => string);\n /**\n * File name\n *\n * @default cache.json\n */\n fileName?: string | (() => string);\n};\n\nexport type RedisOptions = {\n /**\n * Redis Port\n *\n * @default 6379\n */\n port?: number;\n /**\n * Redis Host\n */\n host?: string;\n /**\n * Redis Username\n */\n username?: string;\n /**\n * Redis Password\n */\n password?: string;\n /**\n * Redis URL\n *\n * If used, it will override the host and port options\n */\n url?: string;\n /**\n * Global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL. Accepts a number of seconds or a human-readable duration string\n * like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Redis client options\n */\n clientOptions?: RedisClientOptions;\n};\n\nexport type NullCacheDriverOptions = GenericObject;\n\n/**\n * Options accepted by {@link MockCacheDriver}. Same shape as the memory\n * driver — only `globalPrefix` and `ttl` apply, since the mock's storage is\n * a plain `Map` with no eviction policy.\n */\nexport type MockCacheOptions = {\n /**\n * Global key prefix, applied via `parseKey` (matches the other drivers).\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL for new entries. Accepts seconds or a duration string.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n};\n\n/**\n * One row in {@link MockCacheDriver.callLog} — captures every public op\n * the driver received in arrival order. Useful for behavioral assertions\n * in downstream tests (\"did my service actually invalidate the cache?\").\n */\nexport type CacheCall = {\n /**\n * Operation name as it appears on the driver contract — `\"set\"`, `\"get\"`,\n * `\"remove\"`, `\"flush\"`, `\"removeNamespace\"`, `\"has\"`, etc.\n */\n operation: string;\n /**\n * Post-`parseKey` cache key when the op is key-addressed; `undefined` for\n * keyless ops (`flush`, `connect`, `disconnect`).\n */\n key?: string;\n /**\n * Raw arguments passed to the call site, in declaration order. Lets\n * callers assert on TTLs, options objects, vector payloads, etc.\n */\n args: unknown[];\n /**\n * `Date.now()` when the call was recorded. Useful for timing-related\n * assertions (e.g. \"the second invalidation came within 100ms\").\n */\n timestamp: number;\n};\n\n/**\n * Minimal `pg`-compatible client surface the cache driver depends on.\n *\n * Both `pg.Pool` and `pg.Client` from the `pg` package satisfy this — the\n * driver only ever calls `query(text, values)`. Typing it loosely keeps\n * `pg` strictly optional: consumers without the `pg` package installed\n * never hit a missing import.\n */\nexport type PgClientLike = {\n query(text: string, values?: unknown[]): Promise<{ rows: any[]; rowCount?: number | null }>;\n};\n\nexport type PgCacheOptions = {\n /**\n * User-supplied `pg.Pool` or `pg.Client`. The driver does NOT own the\n * connection lifecycle — `cache.disconnect()` will not close this client.\n */\n client: PgClientLike;\n /**\n * Database table name. Default: `\"warlock_cache\"`.\n *\n * Sanitized: only `[A-Za-z0-9_]` are allowed; anything else throws\n * {@link CacheConfigurationError} at `setOptions` time.\n */\n table?: string;\n /**\n * Global key prefix, applied via `parseKey` (same semantics as the other drivers).\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL for new entries. Accepts seconds or a duration string\n * (`\"1h\"`, `\"7d\"`, …).\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Optional pgvector configuration. When present, the driver provisions an\n * `embedding VECTOR(dimensions)` column + similarity index, and `similar()`\n * queries via the `<=>` cosine-distance operator.\n *\n * Requires the pgvector extension (`CREATE EXTENSION vector;`) — the driver\n * verifies its presence on the first vector operation and throws\n * {@link CacheConfigurationError} if missing.\n *\n * Omit this block (or remove it) to run the driver in KV-only mode —\n * `set({ vector })` and `similar()` then throw {@link CacheUnsupportedError}.\n */\n vector?: {\n /**\n * Vector dimension count. Must match the embedder you use throughout the\n * lifetime of the table. Mixing dimensions on the same table is unsupported.\n */\n dimensions: number;\n /**\n * pgvector index strategy. `hnsw` (default) is faster to query and slightly\n * slower to build; `ivfflat` is faster to build but typically slower to query.\n *\n * @default \"hnsw\"\n */\n index?: \"hnsw\" | \"ivfflat\";\n };\n};\n\nexport interface CacheDriver<ClientType, Options> {\n /**\n * The cache driver options\n */\n options: Options;\n /**\n * Cache driver name\n */\n name: string;\n /**\n * Set logging state\n */\n setLoggingState(shouldLog: boolean): any;\n /**\n * Remove all cached items by namespace\n */\n removeNamespace(namespace: string): Promise<any>;\n /**\n * Set the cache driver options\n */\n setOptions(options: Options): any;\n /**\n * Parse the key to be used in the cache\n */\n parseKey(key: CacheKey): string;\n /**\n * Set a value in the cache.\n *\n * @param key The cache key, could be an object or string\n * @param value The value to be stored in the cache\n * @param ttlOrOptions Either a TTL (seconds number, or duration string like `\"1h\"`),\n * or a full {@link CacheSetOptions} object.\n *\n * @example\n * // Positional TTL (back-compat)\n * await cache.set(\"user:1\", user, 3600);\n *\n * @example\n * // Human-readable duration\n * await cache.set(\"user:1\", user, \"1h\");\n *\n * @example\n * // Rich options\n * await cache.set(\"user:1\", user, { ttl: \"1h\", tags: [\"users\"], onConflict: \"create\" });\n */\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n /**\n * Get a value from the cache\n */\n get<T = any>(key: CacheKey): Promise<T | null>;\n /**\n * Remove a value from the cache\n */\n remove(key: CacheKey): Promise<void>;\n /**\n * Flush the entire cache\n */\n flush(): Promise<void>;\n /**\n * Connect to the cache driver\n */\n connect(): Promise<any>;\n /**\n * The cache client\n */\n client?: ClientType;\n /**\n * Disconnect the cache driver\n */\n disconnect(): Promise<void>;\n /**\n * Check if a key exists in the cache without fetching its value\n */\n has(key: CacheKey): Promise<boolean>;\n /**\n * Get value from cache or execute callback and cache the result.\n *\n * The second argument accepts a TTL (number of seconds or duration string like `\"1h\"`)\n * or a full {@link RememberOptions} object when you need to attach tags or route to\n * a non-default driver.\n *\n * @example\n * // Positional TTL — the common case\n * const user = await cache.remember(\"user.1\", \"1h\", () => db.users.find(1));\n *\n * @example\n * // Options form — tag the cache-miss write for bulk invalidation\n * const user = await cache.remember(\"user.1\", { ttl: \"1h\", tags: [\"users\"] }, () =>\n * db.users.find(1),\n * );\n */\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n /**\n * Stale-while-revalidate. Returns the cached value when fresh; returns\n * the stale value + kicks off a background refresh when within the\n * `freshTtl..staleTtl` window; blocks like a normal miss when past\n * `staleTtl`. Concurrent stale-window callers share one in-flight\n * refresh.\n *\n * Background refresh failures preserve the stale entry and emit an\n * `error` event — the stale-returning caller never sees the failure.\n *\n * @example\n * const product = await cache.swr(\n * \"product.42\",\n * { freshTtl: \"1m\", staleTtl: \"1h\" },\n * () => db.products.find(42),\n * );\n */\n swr<T = any>(key: CacheKey, options: CacheSwrOptions, callback: () => Promise<T>): Promise<T>;\n /**\n * Get a value and remove it, handing it out exactly once.\n *\n * Atomicity: across servers on `redis` (`GETDEL`) and `pg`\n * (`DELETE … RETURNING`); within the process on `memory`, `memoryExtended`,\n * `lru` and `mock`; serialized per key within the process only on `file`.\n */\n pull<T = any>(key: CacheKey): Promise<T | null>;\n /**\n * Set a value in cache permanently (no expiration)\n */\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n /**\n * Read, transform, and write a cached value without losing concurrent updates.\n *\n * The callback receives the current value (or `null` on miss) and returns the\n * next value. Returning `null` removes the key. TTL is preserved unless\n * explicitly overridden via options.\n *\n * Atomicity: across servers on `redis` and `pg` (optimistic\n * compare-and-set with retries — `fn` may run more than once under\n * contention, so keep it side-effect free). On every other driver updates\n * are serialized per key within ONE process only. `file` does not support it.\n *\n * @example\n * await cache.update<User>(\"user:1\", (current) => {\n * if (!current) return null;\n * return { ...current, lastSeen: Date.now() };\n * });\n */\n update<T = any>(\n key: CacheKey,\n fn: (current: T | null) => T | null | Promise<T | null>,\n options?: { ttl?: CacheTtl },\n ): Promise<T | null>;\n /**\n * Shallow-merge a partial object into a cached value.\n *\n * If the key is missing, treats the current value as `{}`. Preserves TTL by default.\n *\n * @example\n * await cache.merge<User>(\"user:1\", { name: \"Jane\" });\n */\n merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T>;\n /**\n * List sub-API factory — returns a {@link CacheListAccessor} bound to the given key.\n *\n * @example\n * const recent = cache.list<Event>(\"recent-events\");\n * await recent.push(event);\n * const last10 = await recent.slice(0, 10);\n */\n list<T = any>(key: CacheKey): CacheListAccessor<T>;\n /**\n * Acquire a distributed lock, run `fn`, and auto-release. Returns a\n * {@link LockOutcome} so callers can distinguish \"ran and produced this value\"\n * from \"skipped because someone else holds the lock.\"\n *\n * Built on top of `set({ onConflict: \"create\" })` — Redis-native, emulated\n * on other drivers (single-process semantics elsewhere).\n *\n * @example\n * const outcome = await cache.lock(\"lock.import\", \"5m\", async () => {\n * await runImport();\n * return \"done\";\n * });\n */\n lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>>;\n /**\n * Increment a numeric value in cache. A missing key starts from 0 with the\n * per-call `options.ttl` (or driver default); an existing expiry is preserved.\n * An explicit TTL also repairs a live counter with no expiry.\n * Supply the TTL on every call for expiring counters: a separate seed may\n * expire before the atomic increment recreates the key.\n *\n * Atomicity: across servers on `redis` (`INCRBY`) and `pg` (single\n * upsert statement); within the process on `memory`, `memoryExtended`,\n * `lru` and `mock`; serialized per key within the process only on `file`.\n *\n * @param key The cache key\n * @param value The value to increment by (default 1)\n */\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n /**\n * Decrement a numeric value in cache\n *\n * @param key The cache key\n * @param value The value to decrement by (default 1)\n */\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Keep an entry and make it expire `ttl` from now (a sliding expiry).\n *\n * The deadline is RESET to `ttl` from the moment of the call; `ttl` is not\n * added to the time the entry had left. Resolves to `false` when the key is\n * missing or already expired (nothing is created). `0` or `Infinity` removes\n * the expiry.\n *\n * @param key The cache key\n * @param ttl Seconds, or a duration string such as `\"30m\"`\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n /**\n * Get multiple values from cache at once\n */\n many(keys: CacheKey[]): Promise<any[]>;\n /**\n * Set multiple values in cache at once\n */\n setMany(items: Record<string, any>, ttl?: number): Promise<void>;\n /**\n * Register an event listener\n */\n on(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Remove an event listener\n */\n off(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Register a one-time event listener\n */\n once(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Set if not exists (atomic operation)\n * Returns true if key was set, false if key already existed\n * Note: Not all drivers support this operation\n */\n setNX?(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n /**\n * Create a tagged cache instance for the given tags\n */\n tags(tags: string[]): TaggedCacheDriver;\n /**\n * Tag-index primitive: add `members` (normalized, un-prefixed cache keys)\n * to the index stored under `tagKey`. Optional — `TaggedCache` falls back to\n * a get/set array when a driver has none.\n *\n * Built-in drivers: redis → a native SET (`SADD`, atomic across servers);\n * pg → one atomic upsert of a JSON array row; memory / lru / mock → an\n * in-process set that is never evicted or expired; file (base default) →\n * a get/set array serialized per tag key in this process only.\n */\n tagAdd?(tagKey: CacheKey, members: string[]): Promise<void>;\n /**\n * Tag-index primitive: the members stored under `tagKey` (empty when none).\n */\n tagMembers?(tagKey: CacheKey): Promise<string[]>;\n /**\n * Tag-index primitive: remove `members` from `tagKey`. Members added\n * concurrently and not listed are kept.\n */\n tagRemove?(tagKey: CacheKey, members: string[]): Promise<void>;\n /**\n * Tag-index primitive: drop the whole index stored under `tagKey`.\n */\n tagDelete?(tagKey: CacheKey): Promise<void>;\n /**\n * Tag-index primitive: up to `count` members of `tagKey` picked at random\n * (every member when the index is smaller). Lets a tagged write check a\n * sample of the index without reading all of it.\n */\n tagSample?(tagKey: CacheKey, count: number): Promise<string[]>;\n /**\n * Whether a live (unexpired) entry exists for `key`, without reading its\n * value, emitting `hit`/`miss` or logging. Used by tag-index pruning.\n */\n exists?(key: CacheKey): Promise<boolean>;\n /**\n * Remove several keys in as few round trips as the backend allows. Each key\n * emits `removed`, as `remove()` does. Used by tag invalidation.\n */\n removeMany?(keys: CacheKey[]): Promise<void>;\n /**\n * Similarity retrieval. Returns the nearest stored entries to `vector` by\n * cosine similarity, ordered by descending score.\n *\n * Drivers without a similarity index throw {@link CacheUnsupportedError}.\n * Memory-family drivers brute-force scan in O(N) — suitable for development\n * but not for production knowledge bases beyond a few thousand entries; use\n * the `pg` driver (with pgvector) or `redis` driver (with RediSearch) instead.\n *\n * @example\n * const hits = await cache.similar(await embed(query), { topK: 5, threshold: 0.7 });\n */\n similar<T = any>(vector: number[], options: CacheSimilarOptions): Promise<CacheSimilarHit<T>[]>;\n}\n\n/**\n * Accessor for list-shaped cached values.\n *\n * Defaults to read-mutate-write semantics on non-native drivers (memory, file, LRU).\n * The Redis driver overrides this with native `LPUSH` / `RPUSH` / `LRANGE` / `LTRIM` for O(1) ops.\n */\nexport interface CacheListAccessor<T = any> {\n /**\n * Append one or more items to the tail of the list. Returns the new length.\n */\n push(...items: T[]): Promise<number>;\n /**\n * Prepend one or more items to the head of the list. Returns the new length.\n */\n unshift(...items: T[]): Promise<number>;\n /**\n * Remove and return the tail item, or `null` if the list is empty.\n */\n pop(): Promise<T | null>;\n /**\n * Remove and return the head item, or `null` if the list is empty.\n */\n shift(): Promise<T | null>;\n /**\n * Return a slice of the list. End is exclusive, mirroring `Array.prototype.slice`.\n */\n slice(start?: number, end?: number): Promise<T[]>;\n /**\n * Return the full list.\n */\n all(): Promise<T[]>;\n /**\n * Return the length of the list.\n */\n length(): Promise<number>;\n /**\n * Trim the list to the inclusive range `[start, end]`. Outside elements are dropped.\n */\n trim(start: number, end: number): Promise<void>;\n /**\n * Remove the entire list.\n */\n clear(): Promise<void>;\n}\n\n/**\n * One-shot tagged handle returned by `ScopedCacheContract.tags(...)`.\n *\n * Identical write surface to {@link TaggedCacheDriver}, except the underlying\n * scope's prefix is applied to every key and the scope's default TTL/tags\n * still flow through. Tags supplied here merge additively with scope-level\n * tags.\n */\nexport interface TaggedScopedCacheContract {\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n get<T = any>(key: CacheKey): Promise<T | null>;\n has(key: CacheKey): Promise<boolean>;\n remove(key: CacheKey): Promise<void>;\n pull<T = any>(key: CacheKey): Promise<T | null>;\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n /**\n * Invalidate every entry tagged with the union of scope tags + handle tags.\n * Forwarded to the underlying tag index — tags are global, scope-agnostic.\n */\n invalidate(): Promise<void>;\n}\n\n/**\n * Scoped view over the cache. Returned by `cache.namespace(prefix, options?)`.\n *\n * A scope prepends its `prefix` to every key, applies optional default TTL/tags\n * to every write, and forwards everything else to the underlying source. It\n * stores nothing of its own — purely a convenience wrapper.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * await chat.set(\"messages.1\", msg); // → \"chats.10.messages.1\", TTL 30d\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call ttl wins\n * await chat.clear(); // wipe the whole scope\n */\nexport interface ScopedCacheContract {\n /** The fully-qualified prefix this scope prepends to every key. */\n readonly prefix: string;\n\n /**\n * Nested scope. Inherits the parent's defaults; child's own options override.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * const typing = chat.namespace(\"typing\", { ttl: \"5s\" });\n * // typing.prefix === \"chats.10.typing\"\n */\n namespace(prefix: string, options?: CacheNamespaceOptions): ScopedCacheContract;\n\n /**\n * One-shot tagged write handle. Tags merge additively with scope defaults.\n */\n tags(tags: string[]): TaggedScopedCacheContract;\n\n /** Wipe every entry under this scope's prefix. Sugar for `removeNamespace(prefix)`. */\n clear(): Promise<void>;\n\n // Reads\n get<T = any>(key: CacheKey): Promise<T | null>;\n has(key: CacheKey): Promise<boolean>;\n many(keys: CacheKey[]): Promise<any[]>;\n pull<T = any>(key: CacheKey): Promise<T | null>;\n\n // Writes\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n setMany(items: Record<string, any>, ttl?: number): Promise<void>;\n setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n remove(key: CacheKey): Promise<void>;\n\n // Read-or-compute\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n swr<T = any>(key: CacheKey, options: CacheSwrOptions, callback: () => Promise<T>): Promise<T>;\n\n // Mutations\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n update<T = any>(\n key: CacheKey,\n fn: (current: T | null) => T | null | Promise<T | null>,\n options?: { ttl?: CacheTtl },\n ): Promise<T | null>;\n merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T>;\n\n // Structured accessors\n list<T = any>(key: CacheKey): CacheListAccessor<T>;\n\n // Coordination\n lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>>;\n\n // Similarity (delegated; throws CacheUnsupportedError if the driver lacks it)\n similar<T = any>(vector: number[], options: CacheSimilarOptions): Promise<CacheSimilarHit<T>[]>;\n}\n\nexport type CacheData = {\n /**\n * Value stored in the cache\n */\n data: any;\n /**\n * The expiration date in milliseconds\n */\n expiresAt?: number;\n /**\n * Time to live in seconds\n */\n ttl?: number;\n /**\n * Freshness deadline as a millisecond timestamp. Used by `swr()` — entries\n * with `staleAt` in the future are \"fresh\"; past `staleAt` but before\n * `expiresAt` are \"stale-but-revalidatable\" and trigger a background\n * refresh on the next read. Optional — entries written through plain\n * `set()` skip this field entirely and `swr()` treats them as always-fresh.\n */\n staleAt?: number;\n};\n\nexport type DriverClass = new () => CacheDriver<any, any>;\n\ntype DefaultDrivers =\n | \"redis\"\n | \"file\"\n | \"memory\"\n | \"memoryExtended\"\n | \"null\"\n | \"lru\"\n | \"pg\"\n | \"mock\";\n\ntype MergeWithDefaultDrivers<T> = T extends undefined ? DefaultDrivers : DefaultDrivers | T;\n\nexport type CacheConfigurations<\n T extends string | undefined = undefined,\n DriverName = MergeWithDefaultDrivers<T>,\n> = {\n /**\n * The default cache driver name\n */\n default?: DriverName;\n /**\n * Log every cache operation (fetching, caching, removing…) at `info` /\n * `success`. Off by default: the lines cost CPU on every cache call and\n * put cache keys in the logs. Errors and connection failures are logged\n * either way.\n *\n * @default false\n */\n logging?: boolean;\n /**\n * The cache drivers list\n */\n drivers: {\n redis?: typeof RedisCacheDriver;\n file?: typeof FileCacheDriver;\n null?: typeof NullCacheDriver;\n memory?: typeof MemoryCacheDriver;\n memoryExtended?: typeof MemoryExtendedCacheDriver;\n lru?: typeof LRUMemoryCacheDriver;\n pg?: typeof PgCacheDriver;\n mock?: typeof MockCacheDriver;\n } & {\n [key in Extract<T, string>]?: typeof BaseCacheDriver<any, any> | undefined;\n };\n /**\n * The cache driver options\n */\n options: {\n redis?: RedisOptions;\n file?: FileCacheOptions;\n memory?: MemoryCacheOptions;\n memoryExtended?: MemoryExtendedCacheOptions;\n null?: NullCacheDriverOptions;\n lru?: LRUMemoryCacheOptions;\n pg?: PgCacheOptions;\n mock?: MockCacheOptions;\n } & {\n [key in Extract<T, string>]?: GenericObject;\n };\n};\n"],"mappings":";;;;AAiBA,IAAa,aAAb,cAAgC,MAAM;CACpC,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,uBAAb,cAA0C,WAAW;CACnD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,0BAAb,cAA6C,WAAW;CACtD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,iCAAb,cAAoD,WAAW;CAC7D,AAAO,YACL,UAAkB,wEAClB;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../packages/cache/src/types.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport type { RedisClientOptions } from \"redis\";\nimport type {\n BaseCacheDriver,\n FileCacheDriver,\n LRUMemoryCacheDriver,\n MemoryCacheDriver,\n MockCacheDriver,\n MemoryExtendedCacheDriver,\n NullCacheDriver,\n PgCacheDriver,\n RedisCacheDriver,\n} from \"./drivers\";\n\n/**\n * Base error class for cache-related errors\n */\nexport class CacheError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheError\";\n }\n}\n\n/**\n * Error thrown when cache connection fails\n */\nexport class CacheConnectionError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConnectionError\";\n }\n}\n\n/**\n * Error thrown when cache driver configuration is invalid\n */\nexport class CacheConfigurationError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConfigurationError\";\n }\n}\n\n/**\n * Error thrown when cache driver is not initialized\n */\nexport class CacheDriverNotInitializedError extends CacheError {\n public constructor(\n message: string = \"No cache driver initialized. Call cache.init() or cache.use() first.\",\n ) {\n super(message);\n this.name = \"CacheDriverNotInitializedError\";\n }\n}\n\n/**\n * Error thrown when a driver does not implement a requested operation.\n *\n * Raised when a caller invokes a method the driver cannot fulfill —\n * e.g. `update()` on the file driver before the file-lock primitive lands.\n */\nexport class CacheUnsupportedError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheUnsupportedError\";\n }\n}\n\n/**\n * Error thrown when an optimistic-concurrency update exhausts its retry budget.\n */\nexport class CacheConcurrencyError extends CacheError {\n public constructor(message: string) {\n super(message);\n this.name = \"CacheConcurrencyError\";\n }\n}\n\n/**\n * TTL shape accepted by set/remember/config calls.\n *\n * - `number` — seconds\n * - `string` — human-readable duration parsed via `ms` (`\"1h\"`, `\"30m\"`, `\"7d\"`, `\"2 weeks\"`, …)\n * - `Infinity` — no expiration\n */\nexport type CacheTtl = number | string;\n\n/**\n * Conflict resolution policy for `set` operations.\n *\n * - `\"create\"` — set only if the key does not exist (Redis `NX`)\n * - `\"update\"` — set only if the key already exists (Redis `XX`)\n * - `\"upsert\"` — default; overwrite whether the key exists or not\n */\nexport type CacheConflictPolicy = \"create\" | \"update\" | \"upsert\";\n\n/**\n * Result of a conditional write (`onConflict: \"create\" | \"update\"`).\n */\nexport type CacheSetResult<T = any> = {\n /**\n * Whether the write actually took effect.\n */\n wasSet: boolean;\n /**\n * The existing value when the write was rejected. Undefined for successful writes\n * and for unconditional `upsert` writes.\n */\n existing: T | null;\n};\n\n/**\n * Options for `lock()` — TTL is required (forgotten locks would stay forever),\n * `owner` identifies who holds the lock (handy for debugging), `driver` routes\n * the call through a non-default driver.\n *\n * @example\n * await cache.lock(\"lock.import\", { ttl: \"5m\", driver: \"redis\" }, async () => {\n * await runImport();\n * });\n */\nexport type LockOptions = {\n /**\n * How long the lock lives before auto-release. Required — guards against\n * forgotten locks if the process crashes between acquire and release.\n */\n ttl: CacheTtl;\n /**\n * Identifying value stored under the lock key. Defaults to `pid.<process.pid>`.\n * Use a custom owner when you want a human-readable label (e.g. `\"worker.jobs-2\"`).\n */\n owner?: string;\n /**\n * Per-call driver override by registered name. Manager-level only.\n */\n driver?: string;\n};\n\n/**\n * Discriminated-union result of `lock()`. Unambiguous even when the wrapped\n * function legitimately returns `undefined` — the `acquired` flag tells you\n * whether `fn` ran at all.\n *\n * @example\n * const outcome = await cache.lock(\"lock.x\", \"1m\", async () => computeValue());\n * if (outcome.acquired) {\n * console.log(\"ran, got\", outcome.value);\n * } else {\n * console.log(\"skipped — someone else holds the lock\");\n * }\n */\nexport type LockOutcome<T> = { acquired: true; value: T } | { acquired: false };\n\n/**\n * Options for `remember()` when you need more than just a TTL — e.g. attaching\n * tags to the cache-miss write, or routing the single call to a non-default driver.\n *\n * Passed in the TTL position: `cache.remember(key, { ttl: \"1h\", tags: [\"users\"] }, fn)`.\n *\n * @example\n * await cache.remember(\"user.1\", { ttl: \"1h\", tags: [\"users\"] }, () =>\n * db.users.find(1),\n * );\n */\nexport type RememberOptions = {\n /**\n * TTL applied on cache miss. Accepts seconds (number) or duration string.\n */\n ttl?: CacheTtl;\n /**\n * Tags attached to the entry created on miss. Invalidate via `cache.tags([...]).invalidate()`.\n */\n tags?: string[];\n /**\n * Spread the TTL by up to this many percent, either way, so entries written\n * together do not all expire together. Same semantics as `CacheSetOptions.ttlJitter`.\n */\n ttlJitter?: number;\n /**\n * Per-call driver override. Routes this remember call (both read and write)\n * to the named driver without mutating `currentDriver`.\n */\n driver?: string;\n};\n\n/**\n * Rich options for the `set` call-site. Mutually exclusive with a positional TTL.\n *\n * @example\n * await cache.set(\"user:1\", user, {\n * ttl: \"1h\",\n * tags: [\"users\", \"active\"],\n * onConflict: \"create\",\n * });\n */\nexport type CacheSetOptions = {\n /**\n * Relative TTL (seconds or duration string). Mutually exclusive with `expiresAt`.\n */\n ttl?: CacheTtl;\n /**\n * Absolute expiration as a Unix epoch in milliseconds or a Date. Mutually exclusive with `ttl`.\n */\n expiresAt?: number | Date;\n /**\n * Spread the TTL by up to this many percent, either way (a random factor per\n * write), so entries written together do not all expire together. `10` turns\n * a one-hour TTL into 54 to 66 minutes. Applies to relative TTLs only (`ttl`\n * or the driver default), never to `expiresAt` or `Infinity`. `0` or omitted\n * disables it; values are clamped to 0..100.\n */\n ttlJitter?: number;\n /**\n * Tags attached to this entry for tag-based invalidation. Inline equivalent of\n * `cache.tags([...]).set(key, value)`.\n */\n tags?: string[];\n /**\n * Conflict resolution policy. Defaults to `\"upsert\"`.\n */\n onConflict?: CacheConflictPolicy;\n /**\n * Per-call namespace override. Applied ahead of `globalPrefix` for this write only.\n */\n namespace?: string;\n /**\n * Per-call driver override by registered name. Routes this write to a non-default driver\n * without mutating `currentDriver`.\n */\n driver?: string;\n /**\n * Optional embedding vector indexed alongside the entry for similarity retrieval\n * via `cache.similar(...)`. Drivers without similarity support throw\n * {@link CacheUnsupportedError} when this option is supplied.\n *\n * Cache is embedding-agnostic — callers compute the vector with whichever embedder\n * they like and pass the result here.\n *\n * @example\n * await cache.set(\"doc.123\", doc, { vector: await embed(doc.text), ttl: \"1d\" });\n */\n vector?: number[];\n /**\n * Freshness deadline as a Unix epoch in milliseconds. Primarily set by\n * {@link CacheSwrOptions} flow — entries with `staleAt` in the future are\n * considered \"fresh\" by `cache.swr()`; entries past `staleAt` but before\n * `expiresAt` are \"stale-but-revalidatable.\"\n *\n * Direct callers can pin this manually when bypassing `swr()`, but the\n * common path is `cache.swr(key, { freshTtl, staleTtl }, fn)`.\n */\n staleAt?: number;\n};\n\n/**\n * Options for `cache.namespace(prefix, options)` — defaults applied to every\n * write produced through the returned scope.\n *\n * Per-call options always win over scope defaults. Tags merge additively\n * (scope tags + call tags, deduped). Nested scopes inherit from the parent;\n * the child's own values override.\n */\nexport type CacheNamespaceOptions = {\n /**\n * Default TTL for writes inside this scope. Same shape as everywhere else\n * — number of seconds or a duration string (`\"1h\"`, `\"30d\"`, …).\n */\n ttl?: CacheTtl;\n /**\n * Tags auto-attached to every write inside this scope. Useful for cross-scope\n * invalidation hooks (e.g. tag every entry with `user.<id>` so a single\n * `cache.flushTag(\"user.42\")` wipes the user's footprint everywhere).\n *\n * Merged additively with per-call tags; scope tags are never replaced.\n */\n tags?: string[];\n};\n\n/**\n * Options for `cache.swr(key, options, callback)` — stale-while-revalidate.\n *\n * Two TTLs split the entry's lifecycle into three windows:\n * - `now < freshTtl` → fresh, return cached value, no upstream call.\n * - `freshTtl <= now < staleTtl` → stale-but-revalidatable, return cached\n * value immediately, kick off `callback` in the background to refresh.\n * - `now >= staleTtl` → expired, block on `callback` like a normal miss.\n *\n * Concurrent SWR callers in the stale window all return the cached value;\n * the background refresh runs exactly once per key (deduped via the\n * driver's per-key lock map).\n *\n * If the background refresh fails, the stale entry is preserved and the\n * error is logged + emitted on the `error` event. Callers that received\n * the stale value never see the failure — they got their data.\n */\nexport type CacheSwrOptions = {\n /**\n * How long the value is considered fresh. Within this window, SWR returns\n * the cached value with no upstream call. Accepts seconds or duration\n * string (`\"1m\"`, `\"30s\"`).\n */\n freshTtl: CacheTtl;\n /**\n * Total lifetime of the entry (must be greater than `freshTtl`). Between\n * `freshTtl` and `staleTtl`, SWR returns the stale value and triggers a\n * background refresh. Past `staleTtl`, SWR blocks and refetches.\n */\n staleTtl: CacheTtl;\n /**\n * Serve the stale value when the refresh throws. With `failSafe: true` a\n * caller that finds the entry in its stale window waits for the refresh\n * (callers of the same key share one) and gets the stale value back if the\n * callback throws; the failure is logged and emitted as an `error` event.\n * Without it the stale value is returned at once and the refresh runs in the\n * background.\n */\n failSafe?: boolean;\n /**\n * Spread `staleTtl` and `freshTtl` by up to this many percent, either way.\n * Same semantics as `CacheSetOptions.ttlJitter`.\n */\n ttlJitter?: number;\n /**\n * Optional tags applied on the first miss-fetch and on every successful\n * background refresh. Same semantics as `CacheSetOptions.tags`.\n */\n tags?: string[];\n /**\n * Per-call driver override by registered name. Routes both the read and\n * any write/refresh through the named driver without mutating\n * `currentDriver`. Same semantics as `RememberOptions.driver`.\n */\n driver?: string;\n};\n\n/**\n * Options for `cache.similar(vector, options)` — similarity retrieval against\n * stored entries previously written with `set({ vector })`.\n */\nexport type CacheSimilarOptions = {\n /**\n * Maximum number of hits to return. Required — no implicit default keeps\n * callers from accidentally pulling the entire candidate set.\n */\n topK: number;\n /**\n * Cosine similarity floor in `[0, 1]`. Hits scoring strictly below this are\n * filtered out before `topK` truncation.\n */\n threshold?: number;\n /**\n * Optional tag filter. Only entries tagged with at least one of the given\n * tags are considered (matches the union semantics elsewhere in the package).\n */\n tags?: string[];\n /**\n * Keep only the entries this predicate accepts, before `threshold` and `topK`\n * apply, so `topK` counts in-scope entries only (one query, no widening). It\n * receives the parsed key and the stored value, and runs in process: the\n * memory and LRU drivers honour it; a driver that searches in the\n * database (`pg`) ignores it, so callers that need a hard guarantee keep\n * checking the returned hits too.\n *\n * @example\n * await cache.similar(vector, { topK: 5, filter: (hit) => hit.key.startsWith(\"tenant.7.\") });\n */\n filter?: (hit: { key: string; value: any }) => boolean;\n};\n\n/**\n * One result from a `similar()` query — the original key, its stored value,\n * and the cosine similarity to the query vector.\n */\nexport type CacheSimilarHit<T = unknown> = {\n /**\n * The original cache key, post-`parseKey` normalization.\n */\n key: string;\n /**\n * Stored value, deep-cloned to protect the cache from accidental mutation\n * (same semantics as `get`).\n */\n value: T;\n /**\n * Cosine similarity in `[0, 1]`. Higher means more similar.\n */\n score: number;\n};\n\n/**\n * Cache key type - can be a string or an object\n */\nexport type CacheKey = string | GenericObject;\n\nexport type CacheOperationType =\n | \"fetching\"\n | \"fetched\"\n | \"caching\"\n | \"cached\"\n | \"flushing\"\n | \"flushed\"\n | \"removing\"\n | \"removed\"\n | \"clearing\"\n | \"cleared\"\n | \"expired\"\n | \"notFound\"\n | \"connecting\"\n | \"error\"\n | \"connectionFailed\"\n | \"connected\"\n | \"disconnecting\"\n | \"disconnected\";\n\n/**\n * Cache event types for observability\n */\nexport type CacheEventType =\n | \"hit\"\n | \"miss\"\n | \"set\"\n | \"removed\"\n | \"invalidated\"\n | \"flushed\"\n | \"expired\"\n | \"connected\"\n | \"disconnected\"\n | \"error\";\n\n/**\n * Cache event data structure\n */\nexport type CacheEventData = {\n /**\n * The cache key involved in the event\n */\n key?: string;\n /**\n * The value (for set/hit events)\n */\n value?: any;\n /**\n * TTL in seconds (for set events)\n */\n ttl?: number;\n /**\n * Driver name that emitted the event\n */\n driver: string;\n /**\n * Error object (for error events)\n */\n error?: any;\n /**\n * Namespace (for namespace operations)\n */\n namespace?: string;\n /** Tags passed to `tags([...]).invalidate()` (`invalidated` events only). */\n tags?: string[];\n /** Keys a tag invalidation removed (`invalidated` events only). */\n keys?: string[];\n /** How long the operation took, in milliseconds (`invalidated` events only). */\n durationMs?: number;\n};\n\n/**\n * Event handler function type\n */\nexport type CacheEventHandler = (eventData: CacheEventData) => void | Promise<void>;\n\n/**\n * Per-operation latency + counter snapshot returned by `cache.metrics()`.\n *\n * The shape is a single recursive level — the top object covers all drivers\n * and each entry under `byDriver` repeats the same fields without nesting\n * further. Use this for ad-hoc dashboards, exporters to Prometheus / StatsD,\n * or just `console.log` during development.\n */\nexport type CacheMetricsSnapshot = {\n /** Cumulative cache hits across the lifetime of the collector. */\n hits: number;\n /** Cumulative cache misses (lookups that returned null). */\n misses: number;\n /** Cumulative successful writes. */\n sets: number;\n /** Cumulative key removals. */\n removed: number;\n /** Cumulative cache errors emitted via the `error` event. */\n errors: number;\n /** `hits / (hits + misses)` — `0` when no read ops have happened yet. */\n hitRate: number;\n /** Latency percentiles in milliseconds, computed from a circular buffer. */\n latencyMs: {\n p50: number;\n p95: number;\n p99: number;\n /** Size of the underlying buffer at snapshot time (capped at the configured max). */\n samples: number;\n };\n /** Per-driver breakdowns keyed by driver name (`\"memory\"`, `\"redis\"`, …). */\n byDriver: Record<string, Omit<CacheMetricsSnapshot, \"byDriver\">>;\n /** Millisecond timestamp the collector last reset (or was instantiated). */\n startedAt: number;\n};\n\n/**\n * Tagged cache interface for working with cache tags\n */\nexport interface TaggedCacheDriver {\n /**\n * Set a value in cache with tags\n */\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n /**\n * Get a value from cache (checks tags)\n */\n get(key: CacheKey): Promise<any | null>;\n /**\n * Remove a specific key\n */\n remove(key: CacheKey): Promise<void>;\n /**\n * Invalidate (clear) all keys associated with the current tags\n */\n invalidate(): Promise<void>;\n /**\n * Flush all keys associated with the current tags\n * @deprecated Use invalidate() instead\n */\n flush(): Promise<void>;\n /**\n * Check if a key exists\n */\n has(key: CacheKey): Promise<boolean>;\n /**\n * Remember pattern with tags\n */\n remember(key: CacheKey, ttl: number, callback: () => Promise<any>): Promise<any>;\n /**\n * Pull value with tags\n */\n pull(key: CacheKey): Promise<any | null>;\n /**\n * Forever with tags\n */\n forever(key: CacheKey, value: any): Promise<any>;\n /**\n * Increment with tags\n */\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n /**\n * Decrement with tags\n */\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n}\n\nexport type MemoryCacheOptions = {\n /**\n * The global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for the cache. Accepts a number of seconds or a human-readable\n * duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Maximum number of entries. When exceeded, the least recently used\n * entries are evicted. `Infinity` (or `0`) removes the limit.\n *\n * @default 10000\n */\n maxSize?: number;\n};\n\nexport type MemoryExtendedCacheOptions = MemoryCacheOptions;\n\nexport type LRUMemoryCacheOptions = {\n /**\n * The maximum number of items in the cache\n *\n * @default 1000\n */\n capacity?: number;\n /**\n * The global prefix for the cache key. Applied via `parseCacheKey`, same\n * semantics as the other drivers.\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for new entries. Accepts a number of seconds or a\n * human-readable duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n};\n\nexport type FileCacheOptions = {\n /**\n * The global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * The default TTL for the cache. Accepts a number of seconds or a human-readable\n * duration string like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default 0\n */\n ttl?: CacheTtl;\n /**\n * Storage cache directory\n *\n * @default storagePath(\"cache\")\n */\n directory: string | (() => string);\n /**\n * File name\n *\n * @default cache.json\n */\n fileName?: string | (() => string);\n};\n\nexport type RedisOptions = {\n /**\n * Redis Port\n *\n * @default 6379\n */\n port?: number;\n /**\n * Redis Host\n */\n host?: string;\n /**\n * Redis Username\n */\n username?: string;\n /**\n * Redis Password\n */\n password?: string;\n /**\n * Redis URL\n *\n * If used, it will override the host and port options\n */\n url?: string;\n /**\n * Global prefix for the cache key\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL. Accepts a number of seconds or a human-readable duration string\n * like `\"1h\"`, `\"30m\"`, `\"7d\"`.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Redis client options\n */\n clientOptions?: RedisClientOptions;\n};\n\nexport type NullCacheDriverOptions = GenericObject;\n\n/**\n * Options accepted by {@link MockCacheDriver}. Same shape as the memory\n * driver — only `globalPrefix` and `ttl` apply, since the mock's storage is\n * a plain `Map` with no eviction policy.\n */\nexport type MockCacheOptions = {\n /**\n * Global key prefix, applied via `parseKey` (matches the other drivers).\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL for new entries. Accepts seconds or a duration string.\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n};\n\n/**\n * One row in {@link MockCacheDriver.callLog} — captures every public op\n * the driver received in arrival order. Useful for behavioral assertions\n * in downstream tests (\"did my service actually invalidate the cache?\").\n */\nexport type CacheCall = {\n /**\n * Operation name as it appears on the driver contract — `\"set\"`, `\"get\"`,\n * `\"remove\"`, `\"flush\"`, `\"removeNamespace\"`, `\"has\"`, etc.\n */\n operation: string;\n /**\n * Post-`parseKey` cache key when the op is key-addressed; `undefined` for\n * keyless ops (`flush`, `connect`, `disconnect`).\n */\n key?: string;\n /**\n * Raw arguments passed to the call site, in declaration order. Lets\n * callers assert on TTLs, options objects, vector payloads, etc.\n */\n args: unknown[];\n /**\n * `Date.now()` when the call was recorded. Useful for timing-related\n * assertions (e.g. \"the second invalidation came within 100ms\").\n */\n timestamp: number;\n};\n\n/**\n * Minimal `pg`-compatible client surface the cache driver depends on.\n *\n * Both `pg.Pool` and `pg.Client` from the `pg` package satisfy this — the\n * driver only ever calls `query(text, values)`. Typing it loosely keeps\n * `pg` strictly optional: consumers without the `pg` package installed\n * never hit a missing import.\n */\nexport type PgClientLike = {\n query(text: string, values?: unknown[]): Promise<{ rows: any[]; rowCount?: number | null }>;\n};\n\nexport type PgCacheOptions = {\n /**\n * User-supplied `pg.Pool` or `pg.Client`. The driver does NOT own the\n * connection lifecycle — `cache.disconnect()` will not close this client.\n */\n client: PgClientLike;\n /**\n * Database table name. Default: `\"warlock_cache\"`.\n *\n * Sanitized: only `[A-Za-z0-9_]` are allowed; anything else throws\n * {@link CacheConfigurationError} at `setOptions` time.\n */\n table?: string;\n /**\n * Global key prefix, applied via `parseKey` (same semantics as the other drivers).\n */\n globalPrefix?: string | (() => string);\n /**\n * Default TTL for new entries. Accepts seconds or a duration string\n * (`\"1h\"`, `\"7d\"`, …).\n *\n * @default Infinity\n */\n ttl?: CacheTtl;\n /**\n * Optional pgvector configuration. When present, the driver provisions an\n * `embedding VECTOR(dimensions)` column + similarity index, and `similar()`\n * queries via the `<=>` cosine-distance operator.\n *\n * Requires the pgvector extension (`CREATE EXTENSION vector;`) — the driver\n * verifies its presence on the first vector operation and throws\n * {@link CacheConfigurationError} if missing.\n *\n * Omit this block (or remove it) to run the driver in KV-only mode —\n * `set({ vector })` and `similar()` then throw {@link CacheUnsupportedError}.\n */\n vector?: {\n /**\n * Vector dimension count. Must match the embedder you use throughout the\n * lifetime of the table. Mixing dimensions on the same table is unsupported.\n */\n dimensions: number;\n /**\n * pgvector index strategy. `hnsw` (default) is faster to query and slightly\n * slower to build; `ivfflat` is faster to build but typically slower to query.\n *\n * @default \"hnsw\"\n */\n index?: \"hnsw\" | \"ivfflat\";\n };\n};\n\nexport interface CacheDriver<ClientType, Options> {\n /**\n * The cache driver options\n */\n options: Options;\n /**\n * Cache driver name\n */\n name: string;\n /**\n * Set logging state\n */\n setLoggingState(shouldLog: boolean): any;\n /**\n * Remove all cached items by namespace\n */\n removeNamespace(namespace: string): Promise<any>;\n /**\n * List the live keys stored under `namespace` (the namespace key itself and\n * every `<namespace>.*` key; an empty namespace lists everything), in the\n * form `get()` and `remove()` accept, so a caller can delete or read exactly\n * the entries it owns instead of sweeping with `similar()`.\n *\n * Optional: a driver that cannot enumerate its keys leaves it out, and\n * callers fall back to what they did before. Shipped by the memory, LRU\n * memory, extended memory, file, Postgres, Redis, mock and null drivers.\n */\n listKeys?(namespace: string): Promise<string[]>;\n /**\n * Set the cache driver options\n */\n setOptions(options: Options): any;\n /**\n * Parse the key to be used in the cache\n */\n parseKey(key: CacheKey): string;\n /**\n * Set a value in the cache.\n *\n * @param key The cache key, could be an object or string\n * @param value The value to be stored in the cache\n * @param ttlOrOptions Either a TTL (seconds number, or duration string like `\"1h\"`),\n * or a full {@link CacheSetOptions} object.\n *\n * @example\n * // Positional TTL (back-compat)\n * await cache.set(\"user:1\", user, 3600);\n *\n * @example\n * // Human-readable duration\n * await cache.set(\"user:1\", user, \"1h\");\n *\n * @example\n * // Rich options\n * await cache.set(\"user:1\", user, { ttl: \"1h\", tags: [\"users\"], onConflict: \"create\" });\n */\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n /**\n * Get a value from the cache\n */\n get<T = any>(key: CacheKey): Promise<T | null>;\n /**\n * Remove a value from the cache\n */\n remove(key: CacheKey): Promise<void>;\n /**\n * Flush the entire cache\n */\n flush(): Promise<void>;\n /**\n * Connect to the cache driver\n */\n connect(): Promise<any>;\n /**\n * The cache client\n */\n client?: ClientType;\n /**\n * Disconnect the cache driver\n */\n disconnect(): Promise<void>;\n /**\n * Check if a key exists in the cache without fetching its value\n */\n has(key: CacheKey): Promise<boolean>;\n /**\n * Get value from cache or execute callback and cache the result.\n *\n * The second argument accepts a TTL (number of seconds or duration string like `\"1h\"`)\n * or a full {@link RememberOptions} object when you need to attach tags or route to\n * a non-default driver.\n *\n * @example\n * // Positional TTL — the common case\n * const user = await cache.remember(\"user.1\", \"1h\", () => db.users.find(1));\n *\n * @example\n * // Options form — tag the cache-miss write for bulk invalidation\n * const user = await cache.remember(\"user.1\", { ttl: \"1h\", tags: [\"users\"] }, () =>\n * db.users.find(1),\n * );\n */\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n /**\n * Stale-while-revalidate. Returns the cached value when fresh; returns\n * the stale value + kicks off a background refresh when within the\n * `freshTtl..staleTtl` window; blocks like a normal miss when past\n * `staleTtl`. Concurrent stale-window callers share one in-flight\n * refresh.\n *\n * Background refresh failures preserve the stale entry and emit an\n * `error` event — the stale-returning caller never sees the failure.\n *\n * @example\n * const product = await cache.swr(\n * \"product.42\",\n * { freshTtl: \"1m\", staleTtl: \"1h\" },\n * () => db.products.find(42),\n * );\n */\n swr<T = any>(key: CacheKey, options: CacheSwrOptions, callback: () => Promise<T>): Promise<T>;\n /**\n * Get a value and remove it, handing it out exactly once.\n *\n * Atomicity: across servers on `redis` (`GETDEL`) and `pg`\n * (`DELETE … RETURNING`); within the process on `memory`, `memoryExtended`,\n * `lru` and `mock`; serialized per key within the process only on `file`.\n */\n pull<T = any>(key: CacheKey): Promise<T | null>;\n /**\n * Set a value in cache permanently (no expiration)\n */\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n /**\n * Read, transform, and write a cached value without losing concurrent updates.\n *\n * The callback receives the current value (or `null` on miss) and returns the\n * next value. Returning `null` removes the key. TTL is preserved unless\n * explicitly overridden via options.\n *\n * Atomicity: across servers on `redis` and `pg` (optimistic\n * compare-and-set with retries — `fn` may run more than once under\n * contention, so keep it side-effect free). On every other driver updates\n * are serialized per key within ONE process only. `file` does not support it.\n *\n * @example\n * await cache.update<User>(\"user:1\", (current) => {\n * if (!current) return null;\n * return { ...current, lastSeen: Date.now() };\n * });\n */\n update<T = any>(\n key: CacheKey,\n fn: (current: T | null) => T | null | Promise<T | null>,\n options?: { ttl?: CacheTtl },\n ): Promise<T | null>;\n /**\n * Shallow-merge a partial object into a cached value.\n *\n * If the key is missing, treats the current value as `{}`. Preserves TTL by default.\n *\n * @example\n * await cache.merge<User>(\"user:1\", { name: \"Jane\" });\n */\n merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T>;\n /**\n * List sub-API factory — returns a {@link CacheListAccessor} bound to the given key.\n *\n * @example\n * const recent = cache.list<Event>(\"recent-events\");\n * await recent.push(event);\n * const last10 = await recent.slice(0, 10);\n */\n list<T = any>(key: CacheKey): CacheListAccessor<T>;\n /**\n * Acquire a distributed lock, run `fn`, and auto-release. Returns a\n * {@link LockOutcome} so callers can distinguish \"ran and produced this value\"\n * from \"skipped because someone else holds the lock.\"\n *\n * Built on top of `set({ onConflict: \"create\" })` — Redis-native, emulated\n * on other drivers (single-process semantics elsewhere).\n *\n * @example\n * const outcome = await cache.lock(\"lock.import\", \"5m\", async () => {\n * await runImport();\n * return \"done\";\n * });\n */\n lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>>;\n /**\n * Increment a numeric value in cache. A missing key starts from 0 with the\n * per-call `options.ttl` (or driver default); an existing expiry is preserved.\n * An explicit TTL also repairs a live counter with no expiry.\n * Supply the TTL on every call for expiring counters: a separate seed may\n * expire before the atomic increment recreates the key.\n *\n * Atomicity: across servers on `redis` (`INCRBY`) and `pg` (single\n * upsert statement); within the process on `memory`, `memoryExtended`,\n * `lru` and `mock`; serialized per key within the process only on `file`.\n *\n * @param key The cache key\n * @param value The value to increment by (default 1)\n */\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n /**\n * Decrement a numeric value in cache\n *\n * @param key The cache key\n * @param value The value to decrement by (default 1)\n */\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Keep an entry and make it expire `ttl` from now (a sliding expiry).\n *\n * The deadline is RESET to `ttl` from the moment of the call; `ttl` is not\n * added to the time the entry had left. Resolves to `false` when the key is\n * missing or already expired (nothing is created). `0` or `Infinity` removes\n * the expiry.\n *\n * @param key The cache key\n * @param ttl Seconds, or a duration string such as `\"30m\"`\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n /**\n * Get multiple values from cache at once\n */\n many(keys: CacheKey[]): Promise<any[]>;\n /**\n * Set multiple values in cache at once\n */\n setMany(items: Record<string, any>, ttl?: number): Promise<void>;\n /**\n * Register an event listener\n */\n on(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Remove an event listener\n */\n off(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Register a one-time event listener\n */\n once(event: CacheEventType, handler: CacheEventHandler): this;\n /**\n * Set if not exists (atomic operation)\n * Returns true if key was set, false if key already existed\n * Note: Not all drivers support this operation\n */\n setNX?(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n /**\n * Create a tagged cache instance for the given tags\n */\n tags(tags: string[]): TaggedCacheDriver;\n /**\n * Tag-index primitive: add `members` (normalized, un-prefixed cache keys)\n * to the index stored under `tagKey`. Optional — `TaggedCache` falls back to\n * a get/set array when a driver has none.\n *\n * Built-in drivers: redis → a native SET (`SADD`, atomic across servers);\n * pg → one atomic upsert of a JSON array row; memory / lru / mock → an\n * in-process set that is never evicted or expired; file (base default) →\n * a get/set array serialized per tag key in this process only.\n */\n tagAdd?(tagKey: CacheKey, members: string[]): Promise<void>;\n /**\n * Tag-index primitive: the members stored under `tagKey` (empty when none).\n */\n tagMembers?(tagKey: CacheKey): Promise<string[]>;\n /**\n * Tag-index primitive: remove `members` from `tagKey`. Members added\n * concurrently and not listed are kept.\n */\n tagRemove?(tagKey: CacheKey, members: string[]): Promise<void>;\n /**\n * Tag-index primitive: drop the whole index stored under `tagKey`.\n */\n tagDelete?(tagKey: CacheKey): Promise<void>;\n /**\n * Tag-index primitive: up to `count` members of `tagKey` picked at random\n * (every member when the index is smaller). Lets a tagged write check a\n * sample of the index without reading all of it.\n */\n tagSample?(tagKey: CacheKey, count: number): Promise<string[]>;\n /**\n * Whether a live (unexpired) entry exists for `key`, without reading its\n * value, emitting `hit`/`miss` or logging. Used by tag-index pruning.\n */\n exists?(key: CacheKey): Promise<boolean>;\n /**\n * Remove several keys in as few round trips as the backend allows. Each key\n * emits `removed`, as `remove()` does. Used by tag invalidation.\n */\n removeMany?(keys: CacheKey[]): Promise<void>;\n /**\n * Similarity retrieval. Returns the nearest stored entries to `vector` by\n * cosine similarity, ordered by descending score.\n *\n * Drivers without a similarity index throw {@link CacheUnsupportedError}.\n * Memory-family drivers brute-force scan in O(N) — suitable for development\n * but not for production knowledge bases beyond a few thousand entries; use\n * the `pg` driver (with pgvector) or `redis` driver (with RediSearch) instead.\n *\n * @example\n * const hits = await cache.similar(await embed(query), { topK: 5, threshold: 0.7 });\n */\n similar<T = any>(vector: number[], options: CacheSimilarOptions): Promise<CacheSimilarHit<T>[]>;\n}\n\n/**\n * Accessor for list-shaped cached values.\n *\n * Defaults to read-mutate-write semantics on non-native drivers (memory, file, LRU).\n * The Redis driver overrides this with native `LPUSH` / `RPUSH` / `LRANGE` / `LTRIM` for O(1) ops.\n */\nexport interface CacheListAccessor<T = any> {\n /**\n * Append one or more items to the tail of the list. Returns the new length.\n */\n push(...items: T[]): Promise<number>;\n /**\n * Prepend one or more items to the head of the list. Returns the new length.\n */\n unshift(...items: T[]): Promise<number>;\n /**\n * Remove and return the tail item, or `null` if the list is empty.\n */\n pop(): Promise<T | null>;\n /**\n * Remove and return the head item, or `null` if the list is empty.\n */\n shift(): Promise<T | null>;\n /**\n * Return a slice of the list. End is exclusive, mirroring `Array.prototype.slice`.\n */\n slice(start?: number, end?: number): Promise<T[]>;\n /**\n * Return the full list.\n */\n all(): Promise<T[]>;\n /**\n * Return the length of the list.\n */\n length(): Promise<number>;\n /**\n * Trim the list to the inclusive range `[start, end]`. Outside elements are dropped.\n */\n trim(start: number, end: number): Promise<void>;\n /**\n * Remove the entire list.\n */\n clear(): Promise<void>;\n}\n\n/**\n * One-shot tagged handle returned by `ScopedCacheContract.tags(...)`.\n *\n * Identical write surface to {@link TaggedCacheDriver}, except the underlying\n * scope's prefix is applied to every key and the scope's default TTL/tags\n * still flow through. Tags supplied here merge additively with scope-level\n * tags.\n */\nexport interface TaggedScopedCacheContract {\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n get<T = any>(key: CacheKey): Promise<T | null>;\n has(key: CacheKey): Promise<boolean>;\n remove(key: CacheKey): Promise<void>;\n pull<T = any>(key: CacheKey): Promise<T | null>;\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n /**\n * Invalidate every entry tagged with the union of scope tags + handle tags.\n * Forwarded to the underlying tag index — tags are global, scope-agnostic.\n */\n invalidate(): Promise<void>;\n}\n\n/**\n * Scoped view over the cache. Returned by `cache.namespace(prefix, options?)`.\n *\n * A scope prepends its `prefix` to every key, applies optional default TTL/tags\n * to every write, and forwards everything else to the underlying source. It\n * stores nothing of its own — purely a convenience wrapper.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * await chat.set(\"messages.1\", msg); // → \"chats.10.messages.1\", TTL 30d\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call ttl wins\n * await chat.clear(); // wipe the whole scope\n */\nexport interface ScopedCacheContract {\n /** The fully-qualified prefix this scope prepends to every key. */\n readonly prefix: string;\n\n /**\n * Nested scope. Inherits the parent's defaults; child's own options override.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * const typing = chat.namespace(\"typing\", { ttl: \"5s\" });\n * // typing.prefix === \"chats.10.typing\"\n */\n namespace(prefix: string, options?: CacheNamespaceOptions): ScopedCacheContract;\n\n /**\n * One-shot tagged write handle. Tags merge additively with scope defaults.\n */\n tags(tags: string[]): TaggedScopedCacheContract;\n\n /** Wipe every entry under this scope's prefix. Sugar for `removeNamespace(prefix)`. */\n clear(): Promise<void>;\n\n // Reads\n get<T = any>(key: CacheKey): Promise<T | null>;\n has(key: CacheKey): Promise<boolean>;\n many(keys: CacheKey[]): Promise<any[]>;\n pull<T = any>(key: CacheKey): Promise<T | null>;\n\n // Writes\n set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any>;\n setMany(items: Record<string, any>, ttl?: number): Promise<void>;\n setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean>;\n forever<T = any>(key: CacheKey, value: T): Promise<T>;\n remove(key: CacheKey): Promise<void>;\n\n // Read-or-compute\n remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T>;\n swr<T = any>(key: CacheKey, options: CacheSwrOptions, callback: () => Promise<T>): Promise<T>;\n\n // Mutations\n increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number>;\n decrement(key: CacheKey, value?: number): Promise<number>;\n /**\n * Reset the entry's expiry to `ttl` from now. See `CacheDriver.extend`.\n */\n extend(key: CacheKey, ttl: CacheTtl): Promise<boolean>;\n update<T = any>(\n key: CacheKey,\n fn: (current: T | null) => T | null | Promise<T | null>,\n options?: { ttl?: CacheTtl },\n ): Promise<T | null>;\n merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T>;\n\n // Structured accessors\n list<T = any>(key: CacheKey): CacheListAccessor<T>;\n\n // Coordination\n lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>>;\n\n // Similarity (delegated; throws CacheUnsupportedError if the driver lacks it)\n similar<T = any>(vector: number[], options: CacheSimilarOptions): Promise<CacheSimilarHit<T>[]>;\n}\n\nexport type CacheData = {\n /**\n * Value stored in the cache\n */\n data: any;\n /**\n * The expiration date in milliseconds\n */\n expiresAt?: number;\n /**\n * Time to live in seconds\n */\n ttl?: number;\n /**\n * Freshness deadline as a millisecond timestamp. Used by `swr()` — entries\n * with `staleAt` in the future are \"fresh\"; past `staleAt` but before\n * `expiresAt` are \"stale-but-revalidatable\" and trigger a background\n * refresh on the next read. Optional — entries written through plain\n * `set()` skip this field entirely and `swr()` treats them as always-fresh.\n */\n staleAt?: number;\n};\n\nexport type DriverClass = new () => CacheDriver<any, any>;\n\ntype DefaultDrivers =\n | \"redis\"\n | \"file\"\n | \"memory\"\n | \"memoryExtended\"\n | \"null\"\n | \"lru\"\n | \"pg\"\n | \"mock\";\n\ntype MergeWithDefaultDrivers<T> = T extends undefined ? DefaultDrivers : DefaultDrivers | T;\n\nexport type CacheConfigurations<\n T extends string | undefined = undefined,\n DriverName = MergeWithDefaultDrivers<T>,\n> = {\n /**\n * The default cache driver name\n */\n default?: DriverName;\n /**\n * Log every cache operation (fetching, caching, removing…) at `info` /\n * `success`. Off by default: the lines cost CPU on every cache call and\n * put cache keys in the logs. Errors and connection failures are logged\n * either way.\n *\n * @default false\n */\n logging?: boolean;\n /**\n * The cache drivers list\n */\n drivers: {\n redis?: typeof RedisCacheDriver;\n file?: typeof FileCacheDriver;\n null?: typeof NullCacheDriver;\n memory?: typeof MemoryCacheDriver;\n memoryExtended?: typeof MemoryExtendedCacheDriver;\n lru?: typeof LRUMemoryCacheDriver;\n pg?: typeof PgCacheDriver;\n mock?: typeof MockCacheDriver;\n } & {\n [key in Extract<T, string>]?: typeof BaseCacheDriver<any, any> | undefined;\n };\n /**\n * The cache driver options\n */\n options: {\n redis?: RedisOptions;\n file?: FileCacheOptions;\n memory?: MemoryCacheOptions;\n memoryExtended?: MemoryExtendedCacheOptions;\n null?: NullCacheDriverOptions;\n lru?: LRUMemoryCacheOptions;\n pg?: PgCacheOptions;\n mock?: MockCacheOptions;\n } & {\n [key in Extract<T, string>]?: GenericObject;\n };\n};\n"],"mappings":";;;;AAiBA,IAAa,aAAb,cAAgC,MAAM;CACpC,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,uBAAb,cAA0C,WAAW;CACnD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,0BAAb,cAA6C,WAAW;CACtD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,iCAAb,cAAoD,WAAW;CAC7D,AAAO,YACL,UAAkB,wEAClB;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,wBAAb,cAA2C,WAAW;CACpD,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
|
package/esm/utils.d.mts
CHANGED
|
@@ -95,6 +95,12 @@ export declare function normalizeToRememberOptions(input?: CacheTtl | RememberOp
|
|
|
95
95
|
* supplied together (mutually exclusive).
|
|
96
96
|
*/
|
|
97
97
|
export declare function resolveTtl(ttl: CacheTtl | undefined, expiresAt: number | Date | undefined, fallback: number): number;
|
|
98
|
+
/**
|
|
99
|
+
* Spread a relative TTL by up to `jitterPercent` percent either way. An
|
|
100
|
+
* absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or
|
|
101
|
+
* non-positive percentage leave the TTL as it is. The result is at least 1.
|
|
102
|
+
*/
|
|
103
|
+
export declare function applyTtlJitter(ttl: number, jitterPercent: number | undefined, expiresAt?: number | Date): number;
|
|
98
104
|
/**
|
|
99
105
|
* Combine any number of tag lists into a single deduped array, dropping
|
|
100
106
|
* `undefined`/empty entries. Returns `undefined` when no tags survive — lets
|
package/esm/utils.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"mappings":";;;;;;;;;;;;;;;wBAwBgB,sBAAsB;;;;;;;;;wBA2CtB,cACd,KAAK,UACL;EAAW;;;;;;;;;;;;;;;;;;;;;;;;wBAqCG,SAAS,OAAO;;;;;;;;;;;;;wBAoDhB,eAAe,oBAAoB;;;;;;;;;;wBAsBnC,mBAAmB,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBxD,2BAA2B,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBhE,WACd,KAAK,sBACL,oBAAoB,kBACpB;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"mappings":";;;;;;;;;;;;;;;wBAwBgB,sBAAsB;;;;;;;;;wBA2CtB,cACd,KAAK,UACL;EAAW;;;;;;;;;;;;;;;;;;;;;;;;wBAqCG,SAAS,OAAO;;;;;;;;;;;;;wBAoDhB,eAAe,oBAAoB;;;;;;;;;;wBAsBnC,mBAAmB,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBxD,2BAA2B,QAAQ,WAAW,kBAAkB;;;;;;;;;;;;wBAuBhE,WACd,KAAK,sBACL,oBAAoB,kBACpB;;;;;;wBAwBc,eACd,aACA,mCACA,qBAAqB;;;;;;;;;;;;;;;wBAyBP,gBAAgB;;;;;;;;;;wBA2BhB,WAAW;EAAY;GAAmB,SAAS,GAAG,sBAAsB;;;;;;;;;;;;;;;;wBA0B5E,iBAAiB,aAAa;;;;;wBAwD9B,kBAAkB;;;;;;;;wBAWlB,cAAc;EAAmB;EAAiB;;oBAetD;;;;EAIV;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA;;;;EAIA"}
|
package/esm/utils.mjs
CHANGED
|
@@ -153,6 +153,18 @@ function resolveTtl(ttl, expiresAt, fallback) {
|
|
|
153
153
|
return fallback;
|
|
154
154
|
}
|
|
155
155
|
/**
|
|
156
|
+
* Spread a relative TTL by up to `jitterPercent` percent either way. An
|
|
157
|
+
* absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or
|
|
158
|
+
* non-positive percentage leave the TTL as it is. The result is at least 1.
|
|
159
|
+
*/
|
|
160
|
+
function applyTtlJitter(ttl, jitterPercent, expiresAt) {
|
|
161
|
+
if (!jitterPercent || jitterPercent <= 0 || expiresAt !== void 0) return ttl;
|
|
162
|
+
if (!Number.isFinite(ttl) || ttl <= 0) return ttl;
|
|
163
|
+
const spread = Math.min(jitterPercent, 100) / 100;
|
|
164
|
+
const factor = 1 + (Math.random() * 2 - 1) * spread;
|
|
165
|
+
return Math.max(1, Math.round(ttl * factor));
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
156
168
|
* Combine any number of tag lists into a single deduped array, dropping
|
|
157
169
|
* `undefined`/empty entries. Returns `undefined` when no tags survive — lets
|
|
158
170
|
* callers skip emitting empty `tags: []` into option payloads.
|
|
@@ -298,5 +310,5 @@ let CACHE_FOR = /* @__PURE__ */ function(CACHE_FOR) {
|
|
|
298
310
|
}({});
|
|
299
311
|
|
|
300
312
|
//#endregion
|
|
301
|
-
export { CACHE_FOR, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
|
|
313
|
+
export { CACHE_FOR, applyTtlJitter, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
|
|
302
314
|
//# sourceMappingURL=utils.mjs.map
|
package/esm/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"sourcesContent":["import { rtrim } from \"@mongez/reinforcements\";\nimport ms, { type StringValue } from \"ms\";\nimport type { CacheKey, CacheSetOptions, CacheTtl, RememberOptions } from \"./types\";\nimport { CacheConfigurationError } from \"./types\";\n\n/**\n * Characters that `parseCacheKey` strips or turns into the `.` separator.\n * Inside a value they would make two different keys equal.\n */\nconst KEY_SEPARATOR_CHARACTERS = /[%.,:{}\"[\\]]/g;\n\n/**\n * Escape a value for use as ONE segment of a cache key or namespace: the\n * characters the key format treats as separators or strips (`.` `,` `:`\n * `{` `}` `\"` `[` `]`, and `%` itself) are percent-encoded, so the value can\n * never reach into another key or namespace. Values without those\n * characters are returned unchanged.\n *\n * Use it for request-derived text (slugs, search terms, ids from a client).\n *\n * @example\n * cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);\n * // slug \"acme.billing\" → namespace \"tenant.acme%2Ebilling\", never inside \"tenant.acme\"\n */\nexport function escapeCacheKeySegment(value: string): string {\n return value.replace(\n KEY_SEPARATOR_CHARACTERS,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`,\n );\n}\n\n/**\n * Escape every string (and object key) inside an object key, so a value that\n * contains a separator cannot be read as two segments. Values without\n * separator characters keep their exact previous encoding.\n */\nfunction escapeKeyObject(value: unknown): unknown {\n if (typeof value === \"string\") {\n return escapeCacheKeySegment(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(escapeKeyObject);\n }\n\n if (value === null || typeof value !== \"object\" || value instanceof Date) {\n return value;\n }\n\n // A null-prototype object keeps an own `__proto__` key as data.\n const escaped: Record<string, unknown> = Object.create(null);\n\n for (const [name, child] of Object.entries(value)) {\n escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);\n }\n\n return escaped;\n}\n\n/**\n * Make a proper key for the cache.\n *\n * String keys are used as they are (`:` and `,` become `.`; `{}\"[]` are\n * removed). In an object key, separator characters inside the object's keys\n * and string values are escaped first (see {@link escapeCacheKeySegment}),\n * so `{ a: \"b.c\" }` and `{ a: \"b\", c: \"\" }` are different keys.\n */\nexport function parseCacheKey(\n key: CacheKey,\n options: { globalPrefix?: string | (() => string) } = {},\n): string {\n if (typeof key === \"object\") {\n key = JSON.stringify(escapeKeyObject(key));\n }\n\n // remove any curly braces and double quotes along with []\n key = key.replace(/[{}\"[\\]]/g, \"\").replaceAll(/[:,]/g, \".\");\n\n const cachePrefix =\n typeof options.globalPrefix === \"function\" ? options.globalPrefix() : options.globalPrefix;\n\n return rtrim(String(cachePrefix ? rtrim(cachePrefix, \".\") + \".\" + key : key), \".\");\n}\n\n/**\n * Parse a TTL value into seconds.\n *\n * Accepts:\n * - a number (seconds) — fractions are rounded UP to whole seconds\n * (so Redis `EX` never receives a fraction); `0` means \"no expiry\"\n * - `Infinity` — no expiration, returned unchanged\n * - a bare numeric string (e.g. `\"3600\"`, from env vars) — treated as seconds\n * - a human-readable duration string (e.g. `\"1h\"`, `\"30m\"`, `\"7d\"`) — parsed via `ms`,\n * then converted to seconds, rounding up\n *\n * Throws `CacheConfigurationError` on NaN, negative numbers, or unparseable strings.\n *\n * @example\n * parseTtl(3600); // 3600\n * parseTtl(0.5); // 1\n * parseTtl(\"3600\"); // 3600\n * parseTtl(\"500ms\"); // 1\n * parseTtl(\"1h\"); // 3600\n * parseTtl(\"7d\"); // 604800\n * parseTtl(Infinity); // Infinity\n */\nexport function parseTtl(input: CacheTtl): number {\n if (typeof input === \"number\") {\n if (Number.isNaN(input)) {\n throw new CacheConfigurationError(\"Invalid TTL: NaN.\");\n }\n\n if (input < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative number (${input}).`);\n }\n\n return Math.ceil(input);\n }\n\n if (typeof input !== \"string\" || input.trim() === \"\") {\n throw new CacheConfigurationError(\n `Invalid TTL: expected number or duration string, got ${typeof input}.`,\n );\n }\n\n const trimmed = input.trim();\n\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.ceil(Number(trimmed));\n }\n\n const milliseconds = ms(trimmed as StringValue);\n\n if (milliseconds === undefined || Number.isNaN(milliseconds)) {\n throw new CacheConfigurationError(\n `Invalid TTL duration string: \"${input}\". Expected forms like \"1h\", \"30m\", \"7d\".`,\n );\n }\n\n if (milliseconds < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative duration (\"${input}\").`);\n }\n\n return Math.ceil(milliseconds / 1000);\n}\n\n/**\n * Convert an absolute `expiresAt` (Date or epoch milliseconds) into a\n * relative TTL in seconds.\n *\n * Throws {@link CacheConfigurationError} when the deadline is in the past —\n * the caller almost certainly has a bug (stale timestamp, wrong unit, etc.)\n * and silently storing an already-expired entry would hide it.\n *\n * @example\n * expiresAtToTtl(new Date(Date.now() + 60_000)); // ~60\n * expiresAtToTtl(Date.now() + 30 * 60 * 1000); // ~1800\n */\nexport function expiresAtToTtl(expiresAt: number | Date): number {\n const deadline = expiresAt instanceof Date ? expiresAt.getTime() : expiresAt;\n const relativeMs = deadline - Date.now();\n\n if (relativeMs <= 0) {\n throw new CacheConfigurationError(\n `\\`expiresAt\\` must be in the future; got ${new Date(deadline).toISOString()}.`,\n );\n }\n\n return Math.ceil(relativeMs / 1000);\n}\n\n/**\n * Coerce the polymorphic 3rd `set` argument into a uniform `CacheSetOptions`\n * shape. Lets callers (and `BaseCacheDriver.resolveSetOptions`) skip per-shape\n * branching.\n *\n * - `undefined` / `null` → `{}` (resolves to driver-level defaults later)\n * - `number` / `string` (positional TTL) → `{ ttl }`\n * - already an options object → returned as-is\n */\nexport function normalizeToOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Sibling of {@link normalizeToOptions} for the `remember()` call site, where\n * the polymorphic 2nd argument is `CacheTtl | RememberOptions` (no `expiresAt`,\n * no `onConflict`). Returns the same shape so callers can `{ ...opts, ... }`\n * without branching.\n *\n * @example\n * normalizeToRememberOptions(60); // { ttl: 60 }\n * normalizeToRememberOptions(\"1h\"); // { ttl: \"1h\" }\n * normalizeToRememberOptions({ ttl: \"1h\", tags: [\"x\"] }); // returned as-is\n */\nexport function normalizeToRememberOptions(input?: CacheTtl | RememberOptions): RememberOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Resolve the final TTL in seconds for a `set` call. Precedence:\n *\n * 1. Caller's `ttl` (number or duration string) wins.\n * 2. Otherwise, caller's `expiresAt` is converted to relative seconds.\n * 3. Otherwise, `fallback` is used (driver-level default — typically\n * `Infinity` when no default is configured, meaning \"never expires\").\n *\n * Throws {@link CacheConfigurationError} when `ttl` and `expiresAt` are\n * supplied together (mutually exclusive).\n */\nexport function resolveTtl(\n ttl: CacheTtl | undefined,\n expiresAt: number | Date | undefined,\n fallback: number,\n): number {\n if (ttl !== undefined && expiresAt !== undefined) {\n throw new CacheConfigurationError(\n \"Cache set options cannot specify both `ttl` and `expiresAt` — choose one.\",\n );\n }\n\n if (ttl !== undefined) {\n return parseTtl(ttl);\n }\n\n if (expiresAt !== undefined) {\n return expiresAtToTtl(expiresAt);\n }\n\n return fallback;\n}\n\n/**\n * Combine any number of tag lists into a single deduped array, dropping\n * `undefined`/empty entries. Returns `undefined` when no tags survive — lets\n * callers skip emitting empty `tags: []` into option payloads.\n *\n * Used by scoped-cache merging where scope tags + handle tags + per-call tags\n * must union additively without duplicates.\n *\n * @example\n * mergeTagSets([\"a\", \"b\"], [\"b\", \"c\"]); // [\"a\", \"b\", \"c\"]\n * mergeTagSets(undefined, [\"x\"]); // [\"x\"]\n * mergeTagSets(undefined, undefined); // undefined\n * mergeTagSets([], []); // undefined\n */\nexport function mergeTagSets(...lists: (string[] | undefined)[]): string[] | undefined {\n const flat: string[] = [];\n\n for (const list of lists) {\n if (!list || list.length === 0) {\n continue;\n }\n\n flat.push(...list);\n }\n\n if (flat.length === 0) {\n return undefined;\n }\n\n return Array.from(new Set(flat));\n}\n\n/**\n * Add extra tags to any option-bag that already shapes `tags?: string[]`.\n * Pure — clones the input shape, never mutates. Tags are appended (caller\n * is responsible for de-duplication if needed; pair with {@link mergeTagSets}).\n *\n * @example\n * injectTags({ ttl: \"1h\" }, [\"unread\"]); // { ttl: \"1h\", tags: [\"unread\"] }\n * injectTags({ tags: [\"a\"] }, [\"b\"]); // { tags: [\"a\", \"b\"] }\n */\nexport function injectTags<T extends { tags?: string[] }>(options: T, extraTags: string[]): T {\n if (extraTags.length === 0) {\n return options;\n }\n\n return {\n ...options,\n tags: [...(options.tags ?? []), ...extraTags],\n };\n}\n\n/**\n * Cosine similarity between two equal-length numeric vectors.\n *\n * Returns a value in `[-1, 1]` where `1` means perfectly aligned, `0` means\n * orthogonal, and `-1` means opposing. For typical embedding spaces (where\n * vectors live in the positive cone) the practical range is `[0, 1]`.\n *\n * Throws {@link CacheConfigurationError} on dimension mismatch — fail loud at\n * the call site rather than silently returning a misleading score. A zero-norm\n * vector on either side returns `0` (no defined direction to compare).\n *\n * @example\n * cosineSimilarity([1, 0, 0], [1, 0, 0]); // 1\n * cosineSimilarity([1, 0, 0], [0, 1, 0]); // 0\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n throw new CacheConfigurationError(\n `Vector dimension mismatch: got ${a.length} and ${b.length}.`,\n );\n }\n\n if (a.length === 0) {\n throw new CacheConfigurationError(\n \"Vector dimension mismatch: empty vector cannot be compared.\",\n );\n }\n\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n const x = a[i];\n const y = b[i];\n\n if (x === undefined || y === undefined) {\n // Unreachable: both guards above establish `a.length === b.length` and\n // a non-zero length, so every index in range exists on both sides. Said\n // out loud rather than asserted with `as number`, because the two guards\n // that make it true are the kind of thing a later edit removes — and if\n // one ever did, an assertion would let `undefined` into the arithmetic\n // and return NaN as a similarity SCORE. A silently wrong ranking is\n // worse than a stopped one.\n break;\n }\n\n dot += x * y;\n normA += x * x;\n normB += y * y;\n }\n\n if (normA === 0 || normB === 0) {\n return 0;\n }\n\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Matches userinfo credentials embedded in a connection URL\n * (e.g. `redis://user:pass@host`). Node/Redis/Postgres client errors\n * frequently echo the target connection string — including the password —\n * back in `error.message` on connection failure.\n */\nconst CREDENTIALS_IN_URL = /(:\\/\\/)[^\\s/@]+:[^\\s/@]+@/g;\n\n/**\n * Strip embedded `user:pass@` credentials from a string before it reaches\n * any log sink.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(CREDENTIALS_IN_URL, \"$1[REDACTED]@\");\n}\n\n/**\n * Reduce an unknown thrown value to a log-safe `{ message, code? }` shape.\n * Callers must never log the raw error object itself — it may carry the\n * connection URL (with password) in the top-level message, `cause`, or\n * driver-specific fields, all of which `console.log`/`util.inspect` would\n * still print in full.\n */\nexport function safeErrorInfo(error: unknown): { message: string; code?: string } {\n if (error instanceof Error) {\n const info: { message: string; code?: string } = {\n message: redactCredentials(error.message),\n };\n\n const code = (error as any).code;\n if (code) info.code = String(code);\n\n return info;\n }\n\n return { message: redactCredentials(String(error)) };\n}\n\nexport enum CACHE_FOR {\n /**\n * Cache for 30 Minutes (in seconds)\n */\n HALF_HOUR = 1800,\n /**\n * Cache for 1 Hour (in seconds)\n */\n ONE_HOUR = 3600,\n /**\n * Cache for 12 Hours (in seconds)\n */\n HALF_DAY = 43200,\n /**\n * Cache for 24 Hours (in seconds)\n */\n ONE_DAY = 86400,\n /**\n * Cache for 7 Days (in seconds)\n */\n ONE_WEEK = 604800,\n /**\n * Cache for 15 Days (in seconds)\n */\n HALF_MONTH = 1296000,\n /**\n * Cache for 30 Days (in seconds)\n */\n ONE_MONTH = 2592000,\n /**\n * Cache for 60 Days (in seconds)\n */\n TWO_MONTHS = 5184000,\n /**\n * Cache for 180 Days (in seconds)\n */\n SIX_MONTHS = 15768000,\n /**\n * Cache for 365 Days (in seconds)\n */\n ONE_YEAR = 31536000,\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"sourcesContent":["import { rtrim } from \"@mongez/reinforcements\";\nimport ms, { type StringValue } from \"ms\";\nimport type { CacheKey, CacheSetOptions, CacheTtl, RememberOptions } from \"./types\";\nimport { CacheConfigurationError } from \"./types\";\n\n/**\n * Characters that `parseCacheKey` strips or turns into the `.` separator.\n * Inside a value they would make two different keys equal.\n */\nconst KEY_SEPARATOR_CHARACTERS = /[%.,:{}\"[\\]]/g;\n\n/**\n * Escape a value for use as ONE segment of a cache key or namespace: the\n * characters the key format treats as separators or strips (`.` `,` `:`\n * `{` `}` `\"` `[` `]`, and `%` itself) are percent-encoded, so the value can\n * never reach into another key or namespace. Values without those\n * characters are returned unchanged.\n *\n * Use it for request-derived text (slugs, search terms, ids from a client).\n *\n * @example\n * cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);\n * // slug \"acme.billing\" → namespace \"tenant.acme%2Ebilling\", never inside \"tenant.acme\"\n */\nexport function escapeCacheKeySegment(value: string): string {\n return value.replace(\n KEY_SEPARATOR_CHARACTERS,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`,\n );\n}\n\n/**\n * Escape every string (and object key) inside an object key, so a value that\n * contains a separator cannot be read as two segments. Values without\n * separator characters keep their exact previous encoding.\n */\nfunction escapeKeyObject(value: unknown): unknown {\n if (typeof value === \"string\") {\n return escapeCacheKeySegment(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(escapeKeyObject);\n }\n\n if (value === null || typeof value !== \"object\" || value instanceof Date) {\n return value;\n }\n\n // A null-prototype object keeps an own `__proto__` key as data.\n const escaped: Record<string, unknown> = Object.create(null);\n\n for (const [name, child] of Object.entries(value)) {\n escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);\n }\n\n return escaped;\n}\n\n/**\n * Make a proper key for the cache.\n *\n * String keys are used as they are (`:` and `,` become `.`; `{}\"[]` are\n * removed). In an object key, separator characters inside the object's keys\n * and string values are escaped first (see {@link escapeCacheKeySegment}),\n * so `{ a: \"b.c\" }` and `{ a: \"b\", c: \"\" }` are different keys.\n */\nexport function parseCacheKey(\n key: CacheKey,\n options: { globalPrefix?: string | (() => string) } = {},\n): string {\n if (typeof key === \"object\") {\n key = JSON.stringify(escapeKeyObject(key));\n }\n\n // remove any curly braces and double quotes along with []\n key = key.replace(/[{}\"[\\]]/g, \"\").replaceAll(/[:,]/g, \".\");\n\n const cachePrefix =\n typeof options.globalPrefix === \"function\" ? options.globalPrefix() : options.globalPrefix;\n\n return rtrim(String(cachePrefix ? rtrim(cachePrefix, \".\") + \".\" + key : key), \".\");\n}\n\n/**\n * Parse a TTL value into seconds.\n *\n * Accepts:\n * - a number (seconds) — fractions are rounded UP to whole seconds\n * (so Redis `EX` never receives a fraction); `0` means \"no expiry\"\n * - `Infinity` — no expiration, returned unchanged\n * - a bare numeric string (e.g. `\"3600\"`, from env vars) — treated as seconds\n * - a human-readable duration string (e.g. `\"1h\"`, `\"30m\"`, `\"7d\"`) — parsed via `ms`,\n * then converted to seconds, rounding up\n *\n * Throws `CacheConfigurationError` on NaN, negative numbers, or unparseable strings.\n *\n * @example\n * parseTtl(3600); // 3600\n * parseTtl(0.5); // 1\n * parseTtl(\"3600\"); // 3600\n * parseTtl(\"500ms\"); // 1\n * parseTtl(\"1h\"); // 3600\n * parseTtl(\"7d\"); // 604800\n * parseTtl(Infinity); // Infinity\n */\nexport function parseTtl(input: CacheTtl): number {\n if (typeof input === \"number\") {\n if (Number.isNaN(input)) {\n throw new CacheConfigurationError(\"Invalid TTL: NaN.\");\n }\n\n if (input < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative number (${input}).`);\n }\n\n return Math.ceil(input);\n }\n\n if (typeof input !== \"string\" || input.trim() === \"\") {\n throw new CacheConfigurationError(\n `Invalid TTL: expected number or duration string, got ${typeof input}.`,\n );\n }\n\n const trimmed = input.trim();\n\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.ceil(Number(trimmed));\n }\n\n const milliseconds = ms(trimmed as StringValue);\n\n if (milliseconds === undefined || Number.isNaN(milliseconds)) {\n throw new CacheConfigurationError(\n `Invalid TTL duration string: \"${input}\". Expected forms like \"1h\", \"30m\", \"7d\".`,\n );\n }\n\n if (milliseconds < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative duration (\"${input}\").`);\n }\n\n return Math.ceil(milliseconds / 1000);\n}\n\n/**\n * Convert an absolute `expiresAt` (Date or epoch milliseconds) into a\n * relative TTL in seconds.\n *\n * Throws {@link CacheConfigurationError} when the deadline is in the past —\n * the caller almost certainly has a bug (stale timestamp, wrong unit, etc.)\n * and silently storing an already-expired entry would hide it.\n *\n * @example\n * expiresAtToTtl(new Date(Date.now() + 60_000)); // ~60\n * expiresAtToTtl(Date.now() + 30 * 60 * 1000); // ~1800\n */\nexport function expiresAtToTtl(expiresAt: number | Date): number {\n const deadline = expiresAt instanceof Date ? expiresAt.getTime() : expiresAt;\n const relativeMs = deadline - Date.now();\n\n if (relativeMs <= 0) {\n throw new CacheConfigurationError(\n `\\`expiresAt\\` must be in the future; got ${new Date(deadline).toISOString()}.`,\n );\n }\n\n return Math.ceil(relativeMs / 1000);\n}\n\n/**\n * Coerce the polymorphic 3rd `set` argument into a uniform `CacheSetOptions`\n * shape. Lets callers (and `BaseCacheDriver.resolveSetOptions`) skip per-shape\n * branching.\n *\n * - `undefined` / `null` → `{}` (resolves to driver-level defaults later)\n * - `number` / `string` (positional TTL) → `{ ttl }`\n * - already an options object → returned as-is\n */\nexport function normalizeToOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Sibling of {@link normalizeToOptions} for the `remember()` call site, where\n * the polymorphic 2nd argument is `CacheTtl | RememberOptions` (no `expiresAt`,\n * no `onConflict`). Returns the same shape so callers can `{ ...opts, ... }`\n * without branching.\n *\n * @example\n * normalizeToRememberOptions(60); // { ttl: 60 }\n * normalizeToRememberOptions(\"1h\"); // { ttl: \"1h\" }\n * normalizeToRememberOptions({ ttl: \"1h\", tags: [\"x\"] }); // returned as-is\n */\nexport function normalizeToRememberOptions(input?: CacheTtl | RememberOptions): RememberOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Resolve the final TTL in seconds for a `set` call. Precedence:\n *\n * 1. Caller's `ttl` (number or duration string) wins.\n * 2. Otherwise, caller's `expiresAt` is converted to relative seconds.\n * 3. Otherwise, `fallback` is used (driver-level default — typically\n * `Infinity` when no default is configured, meaning \"never expires\").\n *\n * Throws {@link CacheConfigurationError} when `ttl` and `expiresAt` are\n * supplied together (mutually exclusive).\n */\nexport function resolveTtl(\n ttl: CacheTtl | undefined,\n expiresAt: number | Date | undefined,\n fallback: number,\n): number {\n if (ttl !== undefined && expiresAt !== undefined) {\n throw new CacheConfigurationError(\n \"Cache set options cannot specify both `ttl` and `expiresAt` — choose one.\",\n );\n }\n\n if (ttl !== undefined) {\n return parseTtl(ttl);\n }\n\n if (expiresAt !== undefined) {\n return expiresAtToTtl(expiresAt);\n }\n\n return fallback;\n}\n\n/**\n * Spread a relative TTL by up to `jitterPercent` percent either way. An\n * absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or\n * non-positive percentage leave the TTL as it is. The result is at least 1.\n */\nexport function applyTtlJitter(\n ttl: number,\n jitterPercent: number | undefined,\n expiresAt?: number | Date,\n): number {\n if (!jitterPercent || jitterPercent <= 0 || expiresAt !== undefined) return ttl;\n if (!Number.isFinite(ttl) || ttl <= 0) return ttl;\n\n const spread = Math.min(jitterPercent, 100) / 100;\n const factor = 1 + (Math.random() * 2 - 1) * spread;\n\n return Math.max(1, Math.round(ttl * factor));\n}\n\n/**\n * Combine any number of tag lists into a single deduped array, dropping\n * `undefined`/empty entries. Returns `undefined` when no tags survive — lets\n * callers skip emitting empty `tags: []` into option payloads.\n *\n * Used by scoped-cache merging where scope tags + handle tags + per-call tags\n * must union additively without duplicates.\n *\n * @example\n * mergeTagSets([\"a\", \"b\"], [\"b\", \"c\"]); // [\"a\", \"b\", \"c\"]\n * mergeTagSets(undefined, [\"x\"]); // [\"x\"]\n * mergeTagSets(undefined, undefined); // undefined\n * mergeTagSets([], []); // undefined\n */\nexport function mergeTagSets(...lists: (string[] | undefined)[]): string[] | undefined {\n const flat: string[] = [];\n\n for (const list of lists) {\n if (!list || list.length === 0) {\n continue;\n }\n\n flat.push(...list);\n }\n\n if (flat.length === 0) {\n return undefined;\n }\n\n return Array.from(new Set(flat));\n}\n\n/**\n * Add extra tags to any option-bag that already shapes `tags?: string[]`.\n * Pure — clones the input shape, never mutates. Tags are appended (caller\n * is responsible for de-duplication if needed; pair with {@link mergeTagSets}).\n *\n * @example\n * injectTags({ ttl: \"1h\" }, [\"unread\"]); // { ttl: \"1h\", tags: [\"unread\"] }\n * injectTags({ tags: [\"a\"] }, [\"b\"]); // { tags: [\"a\", \"b\"] }\n */\nexport function injectTags<T extends { tags?: string[] }>(options: T, extraTags: string[]): T {\n if (extraTags.length === 0) {\n return options;\n }\n\n return {\n ...options,\n tags: [...(options.tags ?? []), ...extraTags],\n };\n}\n\n/**\n * Cosine similarity between two equal-length numeric vectors.\n *\n * Returns a value in `[-1, 1]` where `1` means perfectly aligned, `0` means\n * orthogonal, and `-1` means opposing. For typical embedding spaces (where\n * vectors live in the positive cone) the practical range is `[0, 1]`.\n *\n * Throws {@link CacheConfigurationError} on dimension mismatch — fail loud at\n * the call site rather than silently returning a misleading score. A zero-norm\n * vector on either side returns `0` (no defined direction to compare).\n *\n * @example\n * cosineSimilarity([1, 0, 0], [1, 0, 0]); // 1\n * cosineSimilarity([1, 0, 0], [0, 1, 0]); // 0\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n throw new CacheConfigurationError(\n `Vector dimension mismatch: got ${a.length} and ${b.length}.`,\n );\n }\n\n if (a.length === 0) {\n throw new CacheConfigurationError(\n \"Vector dimension mismatch: empty vector cannot be compared.\",\n );\n }\n\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n const x = a[i];\n const y = b[i];\n\n if (x === undefined || y === undefined) {\n // Unreachable: both guards above establish `a.length === b.length` and\n // a non-zero length, so every index in range exists on both sides. Said\n // out loud rather than asserted with `as number`, because the two guards\n // that make it true are the kind of thing a later edit removes — and if\n // one ever did, an assertion would let `undefined` into the arithmetic\n // and return NaN as a similarity SCORE. A silently wrong ranking is\n // worse than a stopped one.\n break;\n }\n\n dot += x * y;\n normA += x * x;\n normB += y * y;\n }\n\n if (normA === 0 || normB === 0) {\n return 0;\n }\n\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Matches userinfo credentials embedded in a connection URL\n * (e.g. `redis://user:pass@host`). Node/Redis/Postgres client errors\n * frequently echo the target connection string — including the password —\n * back in `error.message` on connection failure.\n */\nconst CREDENTIALS_IN_URL = /(:\\/\\/)[^\\s/@]+:[^\\s/@]+@/g;\n\n/**\n * Strip embedded `user:pass@` credentials from a string before it reaches\n * any log sink.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(CREDENTIALS_IN_URL, \"$1[REDACTED]@\");\n}\n\n/**\n * Reduce an unknown thrown value to a log-safe `{ message, code? }` shape.\n * Callers must never log the raw error object itself — it may carry the\n * connection URL (with password) in the top-level message, `cause`, or\n * driver-specific fields, all of which `console.log`/`util.inspect` would\n * still print in full.\n */\nexport function safeErrorInfo(error: unknown): { message: string; code?: string } {\n if (error instanceof Error) {\n const info: { message: string; code?: string } = {\n message: redactCredentials(error.message),\n };\n\n const code = (error as any).code;\n if (code) info.code = String(code);\n\n return info;\n }\n\n return { message: redactCredentials(String(error)) };\n}\n\nexport enum CACHE_FOR {\n /**\n * Cache for 30 Minutes (in seconds)\n */\n HALF_HOUR = 1800,\n /**\n * Cache for 1 Hour (in seconds)\n */\n ONE_HOUR = 3600,\n /**\n * Cache for 12 Hours (in seconds)\n */\n HALF_DAY = 43200,\n /**\n * Cache for 24 Hours (in seconds)\n */\n ONE_DAY = 86400,\n /**\n * Cache for 7 Days (in seconds)\n */\n ONE_WEEK = 604800,\n /**\n * Cache for 15 Days (in seconds)\n */\n HALF_MONTH = 1296000,\n /**\n * Cache for 30 Days (in seconds)\n */\n ONE_MONTH = 2592000,\n /**\n * Cache for 60 Days (in seconds)\n */\n TWO_MONTHS = 5184000,\n /**\n * Cache for 180 Days (in seconds)\n */\n SIX_MONTHS = 15768000,\n /**\n * Cache for 365 Days (in seconds)\n */\n ONE_YEAR = 31536000,\n}\n"],"mappings":"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"}
|
package/llms-full.txt
CHANGED
|
@@ -288,6 +288,7 @@ const user = await cache.remember("user.1", "1h", async () => db.users.find(1));
|
|
|
288
288
|
- Don't run `cache.similar()` against memory drivers in production with large datasets — O(N) brute force.
|
|
289
289
|
- Don't auto-migrate the `pg` table from app code. The driver exposes `driver.schema()` returning DDL.
|
|
290
290
|
- Don't switch embedders without re-embedding the entire vector index.
|
|
291
|
+
- `has(key)` uses the driver `exists()` (no value read) and emits `hit` / `miss` with the key only, without `value`.
|
|
291
292
|
|
|
292
293
|
|
|
293
294
|
## configure-pg-cache `@warlock.js/cache/skills/configure-pg-cache/SKILL.md`
|
|
@@ -515,6 +516,8 @@ await cache.set("k", v, 3600); // seconds
|
|
|
515
516
|
await cache.set("k", v, undefined); // same as no TTL
|
|
516
517
|
```
|
|
517
518
|
|
|
519
|
+
- `ttlJitter: <percent>` spreads the TTL by up to that many percent either way per write (`{ ttl: "1h", ttlJitter: 10 }` expires in 54-66 minutes) so entries written together do not expire together; ignored for `expiresAt` / `Infinity`; also accepted by `remember()` and `swr()` options. `applyTtlJitter(ttl, percent, expiresAt?)` is the helper that computes it.
|
|
520
|
+
|
|
518
521
|
|
|
519
522
|
## handle-cache-errors `@warlock.js/cache/skills/handle-cache-errors/SKILL.md`
|
|
520
523
|
|
|
@@ -1491,6 +1494,7 @@ await chat.set("messages.10", msg); // chats.<id>.messages.10, 30d, user.<userId
|
|
|
1491
1494
|
await chat.set("draft", d, { ttl: "1h" }); // per-call ttl wins
|
|
1492
1495
|
await chat.tags(["unread"]).set("ping", p); // tags merge: user.<userId> + unread
|
|
1493
1496
|
await chat.clear(); // sugar for removeNamespace
|
|
1497
|
+
const keys = await cache.listKeys("chats.7"); // live keys under a prefix, ready for get() / remove(); optional on custom drivers
|
|
1494
1498
|
```
|
|
1495
1499
|
|
|
1496
1500
|
Scopes are pure views — same connection, same driver, no extra state. Per-call options always win over scope defaults; tags merge additively.
|
|
@@ -1658,6 +1662,7 @@ See the `configure-pg-cache` topic.
|
|
|
1658
1662
|
- Don't mix vector dimensions in the same driver — re-embed when models change.
|
|
1659
1663
|
- Don't expect `similar()` to surface a missing vector (`set` without the `vector` option). Plain KV entries stay out of the similarity index.
|
|
1660
1664
|
- Don't use `topK: 0` or negative — `pg` rejects with `CacheConfigurationError`; memory drivers return `[]` but it's a code smell.
|
|
1665
|
+
- `filter: ({ key, value }) => boolean` runs before `threshold` / `topK`, so `topK` counts in-scope entries only (one query). Honoured by the memory, LRU and memory-extended drivers; `pg` ignores it, so re-check hits when you need a guarantee. A `cache.namespace()` scope passes its prefix as the filter.
|
|
1661
1666
|
|
|
1662
1667
|
|
|
1663
1668
|
## use-cache-structures `@warlock.js/cache/skills/use-cache-structures/SKILL.md`
|
|
@@ -2197,5 +2202,6 @@ await feed.swr("home", { freshTtl: "30s", staleTtl: "10m", tags: ["computed"] },
|
|
|
2197
2202
|
- Don't pick `freshTtl` to be the _same_ as `staleTtl` thinking it disables the stale window — that throws. Pick a tight `freshTtl` and wider `staleTtl` that reflects how stale your product can tolerate being.
|
|
2198
2203
|
- Don't ignore `error` events. A persistent stream of refresh failures means upstream is broken and the cache is masking it.
|
|
2199
2204
|
- Don't reach for SWR on the null driver — it caches nothing, so SWR always blocks.
|
|
2205
|
+
- `failSafe: true` makes a stale-window caller wait for the refresh (callers of one key share it) and return the stale value when the callback throws; the failure is logged and emitted as an `error` event. Default (off): stale value at once, refresh in the background.
|
|
2200
2206
|
|
|
2201
2207
|
|
package/package.json
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
"environment": "server"
|
|
6
6
|
},
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@warlock.js/fs": "5.
|
|
9
|
-
"@mongez/reinforcements": "^4.0
|
|
10
|
-
"@warlock.js/logger": "5.
|
|
8
|
+
"@warlock.js/fs": "5.55.0",
|
|
9
|
+
"@mongez/reinforcements": "^4.1.0",
|
|
10
|
+
"@warlock.js/logger": "5.55.0",
|
|
11
11
|
"ms": "^2.1.3"
|
|
12
12
|
},
|
|
13
13
|
"peerDependencies": {
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
],
|
|
48
48
|
"author": "hassanzohdy",
|
|
49
49
|
"license": "MIT",
|
|
50
|
-
"version": "5.
|
|
50
|
+
"version": "5.55.0",
|
|
51
51
|
"main": "./cjs/index.cjs",
|
|
52
52
|
"module": "./esm/index.mjs",
|
|
53
53
|
"types": "./esm/index.d.mts",
|
|
@@ -125,3 +125,4 @@ const user = await cache.remember("user.1", "1h", async () => db.users.find(1));
|
|
|
125
125
|
- Don't run `cache.similar()` against memory drivers in production with large datasets — O(N) brute force.
|
|
126
126
|
- Don't auto-migrate the `pg` table from app code. The driver exposes `driver.schema()` returning DDL.
|
|
127
127
|
- Don't switch embedders without re-embedding the entire vector index.
|
|
128
|
+
- `has(key)` uses the driver `exists()` (no value read) and emits `hit` / `miss` with the key only, without `value`.
|
|
@@ -100,3 +100,5 @@ await cache.set("k", v); // no TTL — driver default
|
|
|
100
100
|
await cache.set("k", v, 3600); // seconds
|
|
101
101
|
await cache.set("k", v, undefined); // same as no TTL
|
|
102
102
|
```
|
|
103
|
+
|
|
104
|
+
- `ttlJitter: <percent>` spreads the TTL by up to that many percent either way per write (`{ ttl: "1h", ttlJitter: 10 }` expires in 54-66 minutes) so entries written together do not expire together; ignored for `expiresAt` / `Infinity`; also accepted by `remember()` and `swr()` options. `applyTtlJitter(ttl, percent, expiresAt?)` is the helper that computes it.
|
|
@@ -16,6 +16,7 @@ await chat.set("messages.10", msg); // chats.<id>.messages.10, 30d, user.<userId
|
|
|
16
16
|
await chat.set("draft", d, { ttl: "1h" }); // per-call ttl wins
|
|
17
17
|
await chat.tags(["unread"]).set("ping", p); // tags merge: user.<userId> + unread
|
|
18
18
|
await chat.clear(); // sugar for removeNamespace
|
|
19
|
+
const keys = await cache.listKeys("chats.7"); // live keys under a prefix, ready for get() / remove(); optional on custom drivers
|
|
19
20
|
```
|
|
20
21
|
|
|
21
22
|
Scopes are pure views — same connection, same driver, no extra state. Per-call options always win over scope defaults; tags merge additively.
|
|
@@ -92,3 +92,4 @@ See the `configure-pg-cache` topic.
|
|
|
92
92
|
- Don't mix vector dimensions in the same driver — re-embed when models change.
|
|
93
93
|
- Don't expect `similar()` to surface a missing vector (`set` without the `vector` option). Plain KV entries stay out of the similarity index.
|
|
94
94
|
- Don't use `topK: 0` or negative — `pg` rejects with `CacheConfigurationError`; memory drivers return `[]` but it's a code smell.
|
|
95
|
+
- `filter: ({ key, value }) => boolean` runs before `threshold` / `topK`, so `topK` counts in-scope entries only (one query). Honoured by the memory, LRU and memory-extended drivers; `pg` ignores it, so re-check hits when you need a guarantee. A `cache.namespace()` scope passes its prefix as the filter.
|
package/skills/use-swr/SKILL.md
CHANGED
|
@@ -98,3 +98,4 @@ await feed.swr("home", { freshTtl: "30s", staleTtl: "10m", tags: ["computed"] },
|
|
|
98
98
|
- Don't pick `freshTtl` to be the _same_ as `staleTtl` thinking it disables the stale window — that throws. Pick a tight `freshTtl` and wider `staleTtl` that reflects how stale your product can tolerate being.
|
|
99
99
|
- Don't ignore `error` events. A persistent stream of refresh failures means upstream is broken and the cache is masking it.
|
|
100
100
|
- Don't reach for SWR on the null driver — it caches nothing, so SWR always blocks.
|
|
101
|
+
- `failSafe: true` makes a stale-window caller wait for the refresh (callers of one key share it) and return the stale value when the callback throws; the failure is logged and emitted as an `error` event. Default (off): stale value at once, refresh in the background.
|