@warlock.js/cache 5.52.0 → 5.53.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/cjs/index.cjs +528 -122
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/cache-manager.mjs.map +1 -1
  5. package/esm/cached/auto-key.d.mts +3 -1
  6. package/esm/cached/auto-key.d.mts.map +1 -1
  7. package/esm/cached/auto-key.mjs +9 -4
  8. package/esm/cached/auto-key.mjs.map +1 -1
  9. package/esm/cached/cached.mjs.map +1 -1
  10. package/esm/cached/normalize-args.mjs.map +1 -1
  11. package/esm/drivers/base-cache-driver.d.mts +40 -3
  12. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  13. package/esm/drivers/base-cache-driver.mjs +57 -7
  14. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  15. package/esm/drivers/clone-value.mjs +17 -0
  16. package/esm/drivers/clone-value.mjs.map +1 -0
  17. package/esm/drivers/file-cache-driver.d.mts +40 -2
  18. package/esm/drivers/file-cache-driver.d.mts.map +1 -1
  19. package/esm/drivers/file-cache-driver.mjs +142 -18
  20. package/esm/drivers/file-cache-driver.mjs.map +1 -1
  21. package/esm/drivers/in-memory-tag-index.d.mts +5 -0
  22. package/esm/drivers/in-memory-tag-index.d.mts.map +1 -1
  23. package/esm/drivers/in-memory-tag-index.mjs +17 -0
  24. package/esm/drivers/in-memory-tag-index.mjs.map +1 -1
  25. package/esm/drivers/lru-memory-cache-driver.d.mts +18 -1
  26. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  27. package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
  28. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  29. package/esm/drivers/memory-cache-driver.d.mts +16 -1
  30. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  31. package/esm/drivers/memory-cache-driver.mjs +34 -5
  32. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  33. package/esm/drivers/memory-extended-cache-driver.mjs.map +1 -1
  34. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  35. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  36. package/esm/drivers/null-cache-driver.mjs +22 -12
  37. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  38. package/esm/drivers/pg-cache-driver.d.mts +19 -0
  39. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  40. package/esm/drivers/pg-cache-driver.mjs +52 -26
  41. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  42. package/esm/drivers/redis-cache-driver.d.mts +29 -0
  43. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  44. package/esm/drivers/redis-cache-driver.mjs +70 -36
  45. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  46. package/esm/idempotent.mjs.map +1 -1
  47. package/esm/index.d.mts +2 -2
  48. package/esm/index.mjs +2 -2
  49. package/esm/list/memory-cache-list.mjs.map +1 -1
  50. package/esm/metrics.mjs.map +1 -1
  51. package/esm/scoped-cache.mjs.map +1 -1
  52. package/esm/structures/bloom-filter.mjs.map +1 -1
  53. package/esm/structures/cuckoo-filter.mjs.map +1 -1
  54. package/esm/structures/frequency-tracker.mjs.map +1 -1
  55. package/esm/structures/hash.mjs.map +1 -1
  56. package/esm/structures/hyperloglog.mjs.map +1 -1
  57. package/esm/structures/memory-structures-backend.mjs.map +1 -1
  58. package/esm/structures/redis-structures-backend.mjs.map +1 -1
  59. package/esm/structures/sizing.mjs.map +1 -1
  60. package/esm/structures/structures.mjs.map +1 -1
  61. package/esm/structures/types.mjs.map +1 -1
  62. package/esm/structures/unique-counter.mjs.map +1 -1
  63. package/esm/tag-sample.mjs +16 -0
  64. package/esm/tag-sample.mjs.map +1 -0
  65. package/esm/tagged-cache.d.mts +15 -0
  66. package/esm/tagged-cache.d.mts.map +1 -1
  67. package/esm/tagged-cache.mjs +31 -10
  68. package/esm/tagged-cache.mjs.map +1 -1
  69. package/esm/tagged-scoped-cache.mjs.map +1 -1
  70. package/esm/types.d.mts +24 -5
  71. package/esm/types.d.mts.map +1 -1
  72. package/esm/types.mjs.map +1 -1
  73. package/esm/utils.d.mts +20 -1
  74. package/esm/utils.d.mts.map +1 -1
  75. package/esm/utils.mjs +42 -3
  76. package/esm/utils.mjs.map +1 -1
  77. package/llms-full.txt +9 -6
  78. package/llms.txt +1 -1
  79. package/package.json +3 -3
  80. package/skills/cache-basics/SKILL.md +1 -1
  81. package/skills/pick-cache-driver/SKILL.md +1 -1
  82. package/skills/use-cache-namespace/SKILL.md +1 -0
  83. package/skills/use-cache-tags/SKILL.md +1 -1
  84. package/skills/use-cache-utils/SKILL.md +4 -2
  85. package/skills/use-cached-hof/SKILL.md +1 -1
@@ -1,6 +1,7 @@
1
1
  import { CacheConfigurationError, CacheError, CacheUnsupportedError } from "../types.mjs";
2
2
  import { parseTtl, safeErrorInfo } from "../utils.mjs";
3
3
  import { RedisStructuresBackend } from "../structures/redis-structures-backend.mjs";
4
+ import { sampleMembers } from "../tag-sample.mjs";
4
5
  import { BaseCacheDriver } from "./base-cache-driver.mjs";
5
6
  import { log } from "@warlock.js/logger";
6
7
 
@@ -186,6 +187,50 @@ var RedisCacheDriver = class extends BaseCacheDriver {
186
187
  await this.client?.del(this.parseKey(tagKey));
187
188
  }
188
189
  /**
190
+ * {@inheritdoc}
191
+ *
192
+ * `SRANDMEMBER key count`: transfers only the sampled members, however
193
+ * large the index is.
194
+ */
195
+ async tagSample(tagKey, count) {
196
+ if (count <= 0) return [];
197
+ const parsedKey = this.parseKey(tagKey);
198
+ return this.withTagSet(parsedKey, async (client) => {
199
+ if (typeof client.sRandMemberCount !== "function") return sampleMembers(await client.sMembers(parsedKey) ?? [], count);
200
+ return await client.sRandMemberCount(parsedKey, count) ?? [];
201
+ });
202
+ }
203
+ /**
204
+ * {@inheritdoc}
205
+ *
206
+ * `EXISTS`: no value transfer, no `hit`/`miss` events.
207
+ */
208
+ async exists(key) {
209
+ const parsedKey = this.parseKey(key);
210
+ const client = this.client;
211
+ if (typeof client?.exists !== "function") return await this.client?.get(parsedKey) != null;
212
+ return Number(await client.exists(parsedKey)) > 0;
213
+ }
214
+ /**
215
+ * {@inheritdoc}
216
+ *
217
+ * Issues every key's `DEL` (and its SWR sidecar's) at once, in chunks, so
218
+ * the client sends them pipelined instead of one round trip per key. Single
219
+ * key commands keep it cluster-slot safe.
220
+ */
221
+ async removeMany(keys) {
222
+ const parsedKeys = keys.map((key) => this.parseKey(key));
223
+ for (let start = 0; start < parsedKeys.length; start += REMOVE_BATCH_SIZE) {
224
+ const chunk = parsedKeys.slice(start, start + REMOVE_BATCH_SIZE);
225
+ for (const parsedKey of chunk) this.log("removing", parsedKey);
226
+ await Promise.all(chunk.flatMap((parsedKey) => [this.client?.del(parsedKey), this.client?.del(this.swrMetaKey(parsedKey))]));
227
+ for (const parsedKey of chunk) {
228
+ this.log("removed", parsedKey);
229
+ await this.emit("removed", { key: parsedKey });
230
+ }
231
+ }
232
+ }
233
+ /**
189
234
  * Run a SET command against a tag key, upgrading a pre-5.20 index first.
190
235
  *
191
236
  * Earlier versions stored the index as a JSON-array STRING under the same
@@ -223,6 +268,7 @@ var RedisCacheDriver = class extends BaseCacheDriver {
223
268
  const serialized = JSON.stringify(value);
224
269
  const hasExpiry = Boolean(ttl) && ttl !== Infinity;
225
270
  let reply;
271
+ let sidecarWrite;
226
272
  if (onConflict === "create") {
227
273
  const options = { NX: true };
228
274
  if (hasExpiry) options.EX = ttl;
@@ -231,19 +277,18 @@ var RedisCacheDriver = class extends BaseCacheDriver {
231
277
  const options = { XX: true };
232
278
  if (hasExpiry) options.EX = ttl;
233
279
  reply = await this.client?.set(parsedKey, serialized, options);
234
- } else if (hasExpiry) reply = await this.client?.set(parsedKey, serialized, { EX: ttl });
235
- else reply = await this.client?.set(parsedKey, serialized);
280
+ } else {
281
+ const write = hasExpiry ? this.client?.set(parsedKey, serialized, { EX: ttl }) : this.client?.set(parsedKey, serialized);
282
+ sidecarWrite = this.writeSwrSidecar(parsedKey, staleAt, hasExpiry ? ttl : void 0);
283
+ const [written] = await Promise.all([write, sidecarWrite]);
284
+ reply = written;
285
+ }
236
286
  if ((onConflict === "create" || onConflict === "update") && !(reply === "OK")) return {
237
287
  wasSet: false,
238
288
  existing: onConflict === "create" ? await this.get(key) : null
239
289
  };
240
290
  if (tags && tags.length > 0) await this.applyTags(key, tags);
241
- if (staleAt === void 0) await this.client?.del(this.swrMetaKey(parsedKey));
242
- else {
243
- const sidecarOptions = {};
244
- if (hasExpiry) sidecarOptions.EX = ttl;
245
- await this.client?.set(this.swrMetaKey(parsedKey), String(staleAt), sidecarOptions);
246
- }
291
+ if (!sidecarWrite) await this.writeSwrSidecar(parsedKey, staleAt, hasExpiry ? ttl : void 0);
247
292
  this.log("cached", parsedKey);
248
293
  await this.emit("set", {
249
294
  key: parsedKey,
@@ -274,6 +319,17 @@ var RedisCacheDriver = class extends BaseCacheDriver {
274
319
  return true;
275
320
  }
276
321
  /**
322
+ * Write (or clear) the SWR freshness sidecar of a key. A plain write
323
+ * (`staleAt` undefined) drops any marker left by an earlier SWR write,
324
+ * otherwise the old `staleAt` would apply to the new value; an SWR write
325
+ * stores it next to the value — keeping the main value JSON compatible with
326
+ * entries written before SWR landed.
327
+ */
328
+ async writeSwrSidecar(parsedKey, staleAt, ttl) {
329
+ if (staleAt === void 0) return this.client?.del(this.swrMetaKey(parsedKey));
330
+ return this.client?.set(this.swrMetaKey(parsedKey), String(staleAt), ttl === void 0 ? {} : { EX: ttl });
331
+ }
332
+ /**
277
333
  * Build the sidecar key Redis uses to track SWR freshness without
278
334
  * wrapping the main value JSON.
279
335
  */
@@ -325,32 +381,11 @@ var RedisCacheDriver = class extends BaseCacheDriver {
325
381
  }
326
382
  this.log("fetched", key);
327
383
  const parsedValue = JSON.parse(value);
328
- if (parsedValue === null || parsedValue === void 0) {
329
- await this.emit("hit", {
330
- key,
331
- value: parsedValue
332
- });
333
- return parsedValue;
334
- }
335
- const type = typeof parsedValue;
336
- if (type === "string" || type === "number" || type === "boolean") {
337
- await this.emit("hit", {
338
- key,
339
- value: parsedValue
340
- });
341
- return parsedValue;
342
- }
343
- try {
344
- const clonedValue = structuredClone(parsedValue);
345
- await this.emit("hit", {
346
- key,
347
- value: clonedValue
348
- });
349
- return clonedValue;
350
- } catch (error) {
351
- this.logError(`Failed to clone cached value for ${key}`, error);
352
- throw error;
353
- }
384
+ await this.emit("hit", {
385
+ key,
386
+ value: parsedValue
387
+ });
388
+ return parsedValue;
354
389
  }
355
390
  /**
356
391
  * {@inheritDoc}
@@ -358,8 +393,7 @@ var RedisCacheDriver = class extends BaseCacheDriver {
358
393
  async remove(key) {
359
394
  key = this.parseKey(key);
360
395
  this.log("removing", key);
361
- await this.client?.del(key);
362
- await this.client?.del(this.swrMetaKey(key));
396
+ await Promise.all([this.client?.del(key), this.client?.del(this.swrMetaKey(key))]);
363
397
  this.log("removed", key);
364
398
  await this.emit("removed", { key });
365
399
  }
@@ -1 +1 @@
1
- {"version":3,"file":"redis-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/redis-cache-driver.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type { createClient } from \"redis\";\nimport type {\n CacheData,\n CacheDriver,\n CacheKey,\n CacheSetOptions,\n CacheSetResult,\n CacheTtl,\n RedisOptions,\n} from \"../types\";\nimport { CacheConfigurationError, CacheError, CacheUnsupportedError } from \"../types\";\nimport { parseTtl, safeErrorInfo } from \"../utils\";\nimport { RedisStructuresBackend } from \"../structures/redis-structures-backend\";\nimport type { CacheStructuresBackend, StructuresCapable } from \"../structures/types\";\nimport { BaseCacheDriver } from \"./base-cache-driver\";\n\n// ============================================================\n// Lazy-loaded Redis SDK Types\n// ============================================================\n\n/**\n * Cached Redis module (loaded once, reused)\n */\nlet RedisClient: typeof import(\"redis\");\n\nlet isModuleExists: boolean | null = null;\n\n/**\n * Installation instructions for Redis package\n */\nconst REDIS_INSTALL_INSTRUCTIONS = `\nRedis cache driver requires the redis package.\nInstall it with:\n\n npm install redis\n\nOr with your preferred package manager:\n\n pnpm add redis\n yarn add redis\n`.trim();\n\n/**\n * Load Redis module\n */\nasync function loadRedis() {\n try {\n RedisClient = await import(\"redis\");\n isModuleExists = true;\n } catch {\n isModuleExists = false;\n }\n}\n\nloadRedis();\n\n// ============================================================\n// Lua scripts (atomic ownership primitives)\n// ============================================================\n\n/** KEYS[1]=key, ARGV[1]=expected raw value. 1 when deleted, 0 when not the owner. */\nexport const REDIS_COMPARE_DELETE_SCRIPT = `if redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('DEL', KEYS[1]) return 1 else return 0 end`;\n\n/**\n * Compare-and-set used by `update()`.\n *\n * KEYS[1]=key; ARGV[1]=expected raw value (ignored when ARGV[3]=='1');\n * ARGV[2]=new raw value; ARGV[3]='1' when the key is expected to be missing;\n * ARGV[4]=ttl seconds to apply ('0' = no expiry); ARGV[5]='keep' to keep the\n * existing TTL instead (only when the key existed).\n *\n * Returns 1 when written, 0 when the current value no longer matches.\n * `KEEPTTL` requires Redis >= 6.\n */\nexport const REDIS_CAS_SET_SCRIPT = `local cur = redis.call('GET', KEYS[1])\nif ARGV[3] == '1' then\n if cur then return 0 end\nelseif cur ~= ARGV[1] then\n return 0\nend\nlocal ttl = tonumber(ARGV[4])\nif ARGV[5] == 'keep' and ARGV[3] ~= '1' then\n redis.call('SET', KEYS[1], ARGV[2], 'KEEPTTL')\nelseif ttl > 0 then\n redis.call('SET', KEYS[1], ARGV[2], 'EX', ttl)\nelse\n redis.call('SET', KEYS[1], ARGV[2])\nend\nreturn 1`;\n\n/** KEYS[1]=key. Fallback for clients without `getDel`: returns the value and deletes it. */\nexport const REDIS_GET_DEL_SCRIPT = `local v = redis.call('GET', KEYS[1])\nif v then redis.call('DEL', KEYS[1]) end\nreturn v`;\n\n/**\n * Increment that gives a counter without an expiry its per-call or default TTL,\n * in one round trip.\n *\n * KEYS[1]=key; ARGV[1]=amount; ARGV[2]=ttl seconds ('0' = none).\n *\n * Replaces `INCRBY` + `EXPIRE … NX`: the `NX` flag needs Redis >= 7.0, and on\n * Redis 6 the second command failed after the count had already gone up.\n * `TTL == -1` means \"exists without an expiry\", so a TTL set earlier (by\n * `set(..., { ttl })`) is never shortened or reset.\n */\nexport const REDIS_INCREMENT_SCRIPT = `local v = redis.call('INCRBY', KEYS[1], ARGV[1])\nlocal ttl = tonumber(ARGV[2])\nif ttl > 0 and redis.call('TTL', KEYS[1]) == -1 then\n redis.call('EXPIRE', KEYS[1], ttl)\nend\nreturn v`;\n\n/** Compare-and-set attempts before `update()` gives up under contention. */\nconst UPDATE_MAX_ATTEMPTS = 10;\n\n/** Keys deleted per UNLINK/DEL while draining a namespace. */\nconst REMOVE_BATCH_SIZE = 500;\n\n// ============================================================\n// RedisCacheDriver Class\n// ============================================================\n\nexport class RedisCacheDriver\n extends BaseCacheDriver<ReturnType<typeof createClient>, RedisOptions>\n implements CacheDriver<ReturnType<typeof createClient>, RedisOptions>, StructuresCapable\n{\n /**\n * Cache driver name\n */\n public name = \"redis\";\n\n /**\n * {@inheritdoc}\n */\n public setOptions(options: RedisOptions) {\n if (!options.url && !options.host) {\n throw new CacheConfigurationError(\n \"Redis driver requires either 'url' or 'host' option to be configured.\",\n );\n }\n\n return super.setOptions(options);\n }\n\n /**\n * {@inheritDoc}\n */\n public async removeNamespace(namespace: string) {\n namespace = this.parseKey(namespace);\n\n this.log(\"clearing\", namespace);\n\n // Escape Redis glob metacharacters so a namespace carrying `*`/`?`/`[`\n // cannot widen the match and delete keys outside its own prefix.\n const escaped = namespace.replace(/[\\\\*?[\\]]/g, \"\\\\$&\");\n\n // Match the namespace key itself plus `<ns>.*` — never bare `<ns>*`, which\n // would also swallow siblings like `users2`. An empty namespace (no prefix)\n // means \"everything\".\n const pattern = escaped === \"\" ? \"*\" : `${escaped}.*`;\n\n const deleted: string[] = [];\n\n if (this.client) {\n if (escaped !== \"\") {\n const removedSelf = await this.deleteKeys([namespace]);\n\n if (removedSelf > 0) {\n deleted.push(namespace);\n }\n }\n\n // `SCAN` (cursor-based, non-blocking) instead of `KEYS` — `KEYS` is O(N)\n // and blocks the single-threaded Redis event loop. Delete per batch while\n // scanning so memory stays bounded on large keyspaces.\n let batch: string[] = [];\n\n for await (const scanned of this.client.scanIterator({\n MATCH: pattern,\n COUNT: 100,\n })) {\n // node-redis 5 yields a batch of keys for each SCAN cursor response;\n // older supported clients yielded one key at a time. Normalize both\n // forms before passing keys to the command parser.\n const keys = Array.isArray(scanned) ? scanned : [scanned];\n\n for (const key of keys) {\n batch.push(key as unknown as string);\n\n if (batch.length >= REMOVE_BATCH_SIZE) {\n await this.deleteKeys(batch);\n deleted.push(...batch);\n batch = [];\n }\n }\n }\n\n if (batch.length > 0) {\n await this.deleteKeys(batch);\n deleted.push(...batch);\n }\n }\n\n if (deleted.length === 0) {\n this.log(\"notFound\", namespace);\n return;\n }\n\n this.log(\"cleared\", namespace);\n\n return deleted;\n }\n\n /**\n * Delete keys with `UNLINK` (non-blocking free), falling back to `DEL` when\n * the client lacks it. Returns the number of keys removed.\n */\n protected async deleteKeys(keys: string[]): Promise<number> {\n const client = this.client as any;\n\n if (typeof client.unlink === \"function\") {\n return Number(await client.unlink(keys)) || 0;\n }\n\n return Number(await client.del(keys)) || 0;\n }\n\n // ============================================================\n // Tag index — a native Redis SET per tag\n // ============================================================\n\n /**\n * {@inheritdoc}\n *\n * `SADD` — atomic across servers, so concurrent tagged writes on any number\n * of instances never drop a member. The set key lives inside the prefix\n * namespace, so `flush()` / `removeNamespace()` sweep it too.\n */\n public async tagAdd(tagKey: CacheKey, members: string[]): Promise<void> {\n if (members.length === 0) {\n return;\n }\n\n const parsedKey = this.parseKey(tagKey);\n\n await this.withTagSet(parsedKey, (client) => client.sAdd(parsedKey, members));\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagMembers(tagKey: CacheKey): Promise<string[]> {\n const parsedKey = this.parseKey(tagKey);\n\n return this.withTagSet(parsedKey, async (client) => (await client.sMembers(parsedKey)) ?? []);\n }\n\n /**\n * {@inheritdoc}\n *\n * `SREM` — Redis drops the set once its last member is removed.\n */\n public async tagRemove(tagKey: CacheKey, members: string[]): Promise<void> {\n if (members.length === 0) {\n return;\n }\n\n const parsedKey = this.parseKey(tagKey);\n\n await this.withTagSet(parsedKey, (client) => client.sRem(parsedKey, members));\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagDelete(tagKey: CacheKey): Promise<void> {\n await this.client?.del(this.parseKey(tagKey));\n }\n\n /**\n * Run a SET command against a tag key, upgrading a pre-5.20 index first.\n *\n * Earlier versions stored the index as a JSON-array STRING under the same\n * key, which makes any SET command fail with `WRONGTYPE`. On that error the\n * legacy array is read, the string deleted, its members re-added with\n * `SADD`, and the command retried once.\n */\n protected async withTagSet<T>(parsedKey: string, run: (client: any) => Promise<T>): Promise<T> {\n const client = this.client as any;\n\n try {\n return await run(client);\n } catch (error) {\n if (!/WRONGTYPE/i.test(String((error as Error)?.message ?? error))) {\n throw error;\n }\n\n const raw: string | null = await client.get(parsedKey);\n let legacy: unknown = [];\n\n try {\n legacy = raw === null ? [] : JSON.parse(raw);\n } catch {\n legacy = [];\n }\n\n await client.del(parsedKey);\n\n const members = Array.isArray(legacy)\n ? legacy.filter((member): member is string => typeof member === \"string\")\n : [];\n\n if (members.length > 0) {\n await client.sAdd(parsedKey, members);\n }\n\n return run(client);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public async set(\n key: CacheKey,\n value: any,\n ttlOrOptions?: CacheTtl | CacheSetOptions,\n ): Promise<any> {\n const parsedKey = this.parseKey(key);\n const { ttl, tags, onConflict, vector, staleAt } = this.resolveSetOptions(ttlOrOptions);\n\n if (vector) {\n throw new CacheUnsupportedError(\n \"'redis' driver does not yet support similarity retrieval. Phase 2 (RediSearch) is on the backlog — use a memory driver or the 'pg' driver (with pgvector) for now.\",\n );\n }\n\n this.log(\"caching\", parsedKey);\n\n const serialized = JSON.stringify(value);\n const hasExpiry = Boolean(ttl) && ttl !== Infinity;\n\n let reply: string | null | undefined;\n\n if (onConflict === \"create\") {\n const options: { NX: true; EX?: number } = { NX: true };\n if (hasExpiry) {\n options.EX = ttl as number;\n }\n reply = await this.client?.set(parsedKey, serialized, options);\n } else if (onConflict === \"update\") {\n const options: { XX: true; EX?: number } = { XX: true };\n if (hasExpiry) {\n options.EX = ttl as number;\n }\n reply = await this.client?.set(parsedKey, serialized, options);\n } else if (hasExpiry) {\n reply = await this.client?.set(parsedKey, serialized, { EX: ttl as number });\n } else {\n reply = await this.client?.set(parsedKey, serialized);\n }\n\n const wasSet = reply === \"OK\";\n\n if ((onConflict === \"create\" || onConflict === \"update\") && !wasSet) {\n const existing = onConflict === \"create\" ? ((await this.get(key)) as any) : null;\n return { wasSet: false, existing } satisfies CacheSetResult;\n }\n\n if (tags && tags.length > 0) {\n await this.applyTags(key, tags);\n }\n\n if (staleAt === undefined) {\n // A plain write invalidates any freshness marker left by an earlier SWR\n // write, otherwise the old `staleAt` would apply to the new value.\n await this.client?.del(this.swrMetaKey(parsedKey));\n } else {\n // Sidecar key for SWR freshness — keeps the main value JSON\n // backwards-compatible with entries written before SWR landed.\n const sidecarOptions: { EX?: number } = {};\n\n if (hasExpiry) {\n sidecarOptions.EX = ttl as number;\n }\n\n await this.client?.set(this.swrMetaKey(parsedKey), String(staleAt), sidecarOptions);\n }\n\n this.log(\"cached\", parsedKey);\n\n await this.emit(\"set\", { key: parsedKey, value, ttl });\n\n if (onConflict === \"create\" || onConflict === \"update\") {\n return { wasSet: true, existing: null } satisfies CacheSetResult;\n }\n\n return value;\n }\n\n /**\n * {@inheritdoc}\n *\n * Values are stored as `JSON.stringify(value)`, so the compare runs against\n * the serialized form inside Lua.\n */\n protected async deleteIfEquals(key: CacheKey, expected: unknown): Promise<boolean> {\n const parsedKey = this.parseKey(key);\n\n const deleted = await (this.client as any).eval(REDIS_COMPARE_DELETE_SCRIPT, {\n keys: [parsedKey],\n arguments: [JSON.stringify(expected)],\n });\n\n if (Number(deleted) !== 1) {\n return false;\n }\n\n // Mirror remove(): drop the SWR sidecar and emit the event.\n await this.client?.del(this.swrMetaKey(parsedKey));\n await this.emit(\"removed\", { key: parsedKey });\n\n return true;\n }\n\n /**\n * Build the sidecar key Redis uses to track SWR freshness without\n * wrapping the main value JSON.\n */\n protected swrMetaKey(parsedKey: string): string {\n return `${parsedKey}::swrmeta`;\n }\n\n /**\n * Read the raw {@link CacheData} wrapper, fetching the value and the\n * SWR sidecar in parallel. Returns `null` when the main key is missing\n * or expired (Redis handles expiry natively, so the absence of the\n * value alone tells us).\n */\n protected async getEntry(key: CacheKey): Promise<CacheData | null> {\n const parsedKey = this.parseKey(key);\n\n const [valueRaw, staleAtRaw] = await Promise.all([\n this.client?.get(parsedKey),\n this.client?.get(this.swrMetaKey(parsedKey)),\n ]);\n\n if (!valueRaw) {\n return null;\n }\n\n const data = JSON.parse(valueRaw);\n const staleAt = staleAtRaw ? Number(staleAtRaw) : undefined;\n\n return staleAt !== undefined ? { data, staleAt } : { data };\n }\n\n /**\n * {@inheritdoc}\n *\n * Redis tracks expiry natively (the payload carries no `expiresAt`), so read\n * the remaining lifetime with the `TTL` command. Redis returns `-2` for a\n * missing key and `-1` for a key with no expiry.\n */\n protected async getRemainingTtl(key: CacheKey): Promise<number | undefined> {\n const parsedKey = this.parseKey(key);\n const ttl = await this.client?.ttl(parsedKey);\n\n if (ttl === undefined || ttl === -2) {\n return undefined;\n }\n\n if (ttl === -1) {\n return Infinity;\n }\n\n return ttl;\n }\n\n /**\n * {@inheritDoc}\n */\n public async get(key: CacheKey) {\n key = this.parseKey(key);\n\n this.log(\"fetching\", key);\n\n const value = await this.client?.get(key);\n\n if (!value) {\n this.log(\"notFound\", key);\n // Emit miss event\n await this.emit(\"miss\", { key });\n return null;\n }\n\n this.log(\"fetched\", key);\n\n // Parse and return the value directly (Redis handles expiration natively)\n const parsedValue = JSON.parse(value);\n\n // Apply cloning for immutability protection\n if (parsedValue === null || parsedValue === undefined) {\n // Emit hit event\n await this.emit(\"hit\", { key, value: parsedValue });\n return parsedValue;\n }\n\n const type = typeof parsedValue;\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n // Emit hit event\n await this.emit(\"hit\", { key, value: parsedValue });\n return parsedValue;\n }\n\n try {\n const clonedValue = structuredClone(parsedValue);\n // Emit hit event\n await this.emit(\"hit\", { key, value: clonedValue });\n return clonedValue;\n } catch (error) {\n this.logError(`Failed to clone cached value for ${key}`, error);\n throw error;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public async remove(key: CacheKey) {\n key = this.parseKey(key);\n\n this.log(\"removing\", key);\n\n // Drop the SWR sidecar alongside the main key — keeps metadata from\n // surviving a `remove` and confusing a later `swr` read.\n // Two separate DELs (not one multi-key DEL) so it stays cluster-slot safe.\n await this.client?.del(key);\n await this.client?.del(this.swrMetaKey(key));\n\n this.log(\"removed\", key);\n\n await this.emit(\"removed\", { key });\n }\n\n /**\n * {@inheritDoc}\n *\n * WARNING: without a `globalPrefix` this runs `FLUSHDB`, which clears the\n * WHOLE selected Redis database (including keys not written by this driver).\n * Configure a `globalPrefix` to only delete this driver's keys.\n */\n public async flush() {\n this.log(\"flushing\");\n\n if (this.options.globalPrefix) {\n await this.removeNamespace(\"\");\n } else {\n await this.client?.flushDb();\n }\n\n this.log(\"flushed\");\n\n // Emit flushed event\n await this.emit(\"flushed\");\n }\n\n /**\n * {@inheritDoc}\n */\n public async connect() {\n if (this.clientDriver) return;\n\n if (!isModuleExists) {\n throw new Error(REDIS_INSTALL_INSTRUCTIONS);\n }\n\n const options = this.options;\n\n if (options && !options.url && options.host) {\n const auth =\n options.password || options.username ? `${options.username}:${options.password}@` : \"\";\n\n if (!options.url) {\n const host = options.host || \"localhost\";\n const port = options.port || 6379;\n options.url = `redis://${auth}${host}:${port}`;\n }\n }\n\n const clientOptions = {\n ...options,\n ...(this.options.clientOptions || {}),\n };\n\n try {\n this.log(\"connecting\");\n const { createClient } = RedisClient;\n\n this.client = createClient(clientOptions);\n\n this.client.on(\"error\", (error: Error) => {\n // Never pass the raw `error` object to the logger — connection\n // errors can carry the connection URL (with password) in the\n // message/cause. Only the redacted message survives past this point.\n const { message } = safeErrorInfo(error);\n\n if ((error as any).code === \"ECONNREFUSED\") {\n this.log(\"connectionFailed\", message);\n } else {\n this.log(\"error\", message);\n }\n });\n\n await this.client.connect();\n\n this.log(\"connected\");\n await this.emit(\"connected\");\n } catch (error) {\n // Boot-time cache connection failure is unrecoverable in practice —\n // `fatal` aligns Redis with the cascade drivers and herald connector\n // for clean \"page on fatal only\" alerting. Only the redacted\n // `{ message, code }` shape is logged; the raw error (which may carry\n // the connection URL/password) never reaches stdout or the logger.\n log.fatal(\"cache\", \"redis\", \"Failed to connect\", safeErrorInfo(error));\n await this.emit(\"error\", { error });\n\n // Drop the half-initialised client so a later connect() can retry.\n this.clientDriver = undefined as unknown as typeof this.clientDriver;\n\n throw error;\n }\n }\n\n /**\n * {@inheritDoc}\n *\n * Guards against disconnecting when the client was never created. The base\n * `client` getter falls back to `this` when no client is set, so we check\n * the backing `clientDriver` directly — using `this.client` for this guard\n * would always be truthy and crash with \"this.quit is not a function\".\n */\n public async disconnect() {\n if (!this.clientDriver) {\n return;\n }\n\n this.log(\"disconnecting\");\n\n await this.clientDriver.quit();\n\n this.log(\"disconnected\");\n await this.emit(\"disconnected\");\n }\n\n /**\n * {@inheritdoc}\n *\n * Atomic across servers: `GETDEL` (Redis >= 6.2), or an equivalent Lua\n * script when the client has no `getDel`. A value is handed out once.\n */\n public async pull(key: CacheKey): Promise<any | null> {\n const parsedKey = this.parseKey(key);\n const client = this.client as any;\n\n const raw: string | null | undefined =\n typeof client.getDel === \"function\"\n ? await client.getDel(parsedKey)\n : await client.eval(REDIS_GET_DEL_SCRIPT, { keys: [parsedKey], arguments: [] });\n\n if (raw === null || raw === undefined) {\n await this.emit(\"miss\", { key: parsedKey });\n\n return null;\n }\n\n await this.client?.del(this.swrMetaKey(parsedKey));\n\n const value = JSON.parse(raw);\n\n await this.emit(\"hit\", { key: parsedKey, value });\n await this.emit(\"removed\", { key: parsedKey });\n\n return value;\n }\n\n /**\n * {@inheritdoc}\n *\n * Atomic across servers via optimistic compare-and-set: read the raw value,\n * run `fn`, then write only if the value is still what was read (Lua), and\n * retry otherwise. `fn` may therefore run more than once under contention;\n * after {@link UPDATE_MAX_ATTEMPTS} lost races it throws {@link CacheError}.\n *\n * Without an explicit `ttl` the existing expiry is kept (`KEEPTTL`); a new\n * key gets the driver default TTL. Returning `null` deletes the key\n * (compare-and-delete).\n */\n public async 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 const parsedKey = this.parseKey(key);\n const client = this.client as any;\n\n const explicitTtl = options.ttl !== undefined ? parseTtl(options.ttl) : undefined;\n\n for (let attempt = 0; attempt < UPDATE_MAX_ATTEMPTS; attempt++) {\n const raw: string | null = (await client.get(parsedKey)) ?? null;\n const current = raw === null ? null : (JSON.parse(raw) as T);\n const result = await fn(current);\n\n if (result === null) {\n if (raw === null) {\n return null;\n }\n\n const deleted = await client.eval(REDIS_COMPARE_DELETE_SCRIPT, {\n keys: [parsedKey],\n arguments: [raw],\n });\n\n if (Number(deleted) === 1) {\n await this.client?.del(this.swrMetaKey(parsedKey));\n await this.emit(\"removed\", { key: parsedKey });\n\n return null;\n }\n\n continue;\n }\n\n const isNew = raw === null;\n const ttlSeconds = explicitTtl ?? (isNew ? this.ttl : 0);\n const keep = explicitTtl === undefined && !isNew;\n\n const written = await client.eval(REDIS_CAS_SET_SCRIPT, {\n keys: [parsedKey],\n arguments: [\n raw ?? \"\",\n JSON.stringify(result),\n isNew ? \"1\" : \"0\",\n String(Number.isFinite(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : 0),\n keep ? \"keep\" : \"\",\n ],\n });\n\n if (Number(written) === 1) {\n // A plain write invalidates any SWR freshness marker.\n await this.client?.del(this.swrMetaKey(parsedKey));\n await this.emit(\"set\", { key: parsedKey, value: result, ttl: ttlSeconds });\n\n return result;\n }\n }\n\n throw new CacheError(\n `cache.update(): '${parsedKey}' changed on every attempt (${UPDATE_MAX_ATTEMPTS} tries) — too much write contention.`,\n );\n }\n\n /**\n * Atomic increment using Redis native INCRBY command\n * {@inheritdoc}\n */\n public async increment(\n key: CacheKey,\n value: number = 1,\n options: { ttl?: CacheTtl } = {},\n ): Promise<number> {\n const parsedKey = this.parseKey(key);\n\n this.log(\"caching\", parsedKey);\n\n // Apply the per-call TTL (or driver default) when INCRBY creates a key,\n // atomically with the increment and without Redis 7's `EXPIRE … NX`.\n const ttl = options.ttl === undefined ? this.ttl : parseTtl(options.ttl);\n const defaultTtl = Number.isFinite(ttl) && ttl > 0 ? Math.ceil(ttl) : 0;\n const result =\n defaultTtl > 0\n ? Number(\n await (this.client as any)?.eval(REDIS_INCREMENT_SCRIPT, {\n keys: [parsedKey],\n arguments: [String(value), String(defaultTtl)],\n }),\n )\n : await this.client?.incrBy(parsedKey, value);\n\n this.log(\"cached\", parsedKey);\n\n // Emit set event\n await this.emit(\"set\", { key: parsedKey, value: result, ttl: undefined });\n\n return result || 0;\n }\n\n /**\n * {@inheritdoc}\n *\n * `PEXPIRE` (or `PERSIST` for no expiry) on the key and its freshness\n * sidecar: one atomic command, `0` when the key does not exist.\n */\n public async extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n const seconds = this.resolveExtendTtl(ttl);\n const parsedKey = this.parseKey(key);\n const client = this.client as any;\n\n const applied = Number.isFinite(seconds)\n ? await client.pExpire(parsedKey, Math.ceil(seconds * 1000))\n : await client.persist(parsedKey);\n\n // node-redis returns a boolean in v4 and a number in v5; `persist` also\n // returns false/0 for a live key that already had no expiry.\n if (!applied && Number.isFinite(seconds)) {\n return false;\n }\n\n if (!applied) {\n return Number(await client.exists(parsedKey)) > 0;\n }\n\n const sidecar = this.swrMetaKey(parsedKey);\n\n if (Number.isFinite(seconds)) {\n await client.pExpire(sidecar, Math.ceil(seconds * 1000));\n } else {\n await client.persist(sidecar);\n }\n\n return true;\n }\n\n private structureBackend?: RedisStructuresBackend;\n\n /**\n * {@inheritdoc}\n *\n * Uses RedisBloom (`BF.*`, `CF.*`, `CMS.*`, `TOPK.*`) when the server has\n * it, and plain Redis commands otherwise.\n */\n public structuresBackend(): CacheStructuresBackend {\n this.structureBackend ??= new RedisStructuresBackend(\n () => this.client as any,\n (key) => this.parseKey(key),\n );\n\n return this.structureBackend;\n }\n\n /**\n * Atomic decrement using Redis native DECRBY command\n * {@inheritdoc}\n */\n public async decrement(key: CacheKey, value: number = 1): Promise<number> {\n const parsedKey = this.parseKey(key);\n\n this.log(\"caching\", parsedKey);\n\n const result = await this.client?.decrBy(parsedKey, value);\n\n this.log(\"cached\", parsedKey);\n\n // Emit set event\n await this.emit(\"set\", { key: parsedKey, value: result, ttl: undefined });\n\n return result || 0;\n }\n\n /**\n * Set if not exists (atomic operation)\n * Returns true if key was set, false if key already existed\n */\n public async setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean> {\n const parsedKey = this.parseKey(key);\n\n this.log(\"caching\", parsedKey);\n\n if (ttl === undefined) {\n ttl = this.ttl;\n }\n\n let result: string | null;\n\n // Use Redis native SET with NX option\n if (ttl && ttl !== Infinity) {\n result = await this.client?.set(parsedKey, JSON.stringify(value), {\n NX: true,\n EX: ttl,\n });\n } else {\n result = await this.client?.set(parsedKey, JSON.stringify(value), {\n NX: true,\n });\n }\n\n const wasSet = result === \"OK\";\n\n if (wasSet) {\n this.log(\"cached\", parsedKey);\n // Emit set event\n await this.emit(\"set\", { key: parsedKey, value, ttl });\n } else {\n this.log(\"notFound\", parsedKey);\n }\n\n return wasSet;\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAI;AAEJ,IAAI,iBAAiC;;;;AAKrC,MAAM,6BAA6B;;;;;;;;;;EAUjC,KAAK;;;;AAKP,eAAe,YAAY;CACzB,IAAI;EACF,cAAc,MAAM,OAAO;EAC3B,iBA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mjs","names":[],"sources":["../../../../../../../packages/cache/src/idempotent.ts"],"sourcesContent":["import { log, maskEmailsInText } from \"@warlock.js/logger\";\nimport type { CacheDriver, CacheKey, CacheTtl } from \"./types\";\nimport { CacheConcurrencyError } from \"./types\";\nimport { parseCacheKey, parseTtl } from \"./utils\";\n\n/**\n * Options of `idempotent()`.\n */\nexport type IdempotentOptions = {\n /**\n * How long a successful result is kept and replayed. A number is seconds; a\n * string is a duration such as `\"24h\"`. `0` means in-flight dedupe only:\n * nothing is stored, and the next call after the run finishes runs again.\n */\n ttl: CacheTtl;\n /**\n * Cache driver name to store results in (and take the lock on). Defaults to\n * the current driver.\n */\n driver?: string;\n /**\n * Make concurrent calls on DIFFERENT servers run `fn` once, using the cache\n * lock. Without it, calls share a single run only inside one process; across\n * processes the stored result still prevents re-runs after the first one\n * finished. Needs a shared driver such as Redis or Postgres.\n */\n distributed?: boolean;\n /**\n * With `distributed`: how long the lock is held, which is also how long\n * another server waits for the result before giving up. Must exceed the\n * worst-case duration of `fn`. Default `\"30s\"`.\n */\n lockTtl?: CacheTtl;\n};\n\n/**\n * What is kept in the cache. The wrapper tells a stored `undefined`, `null` or\n * `false` result apart from \"nothing stored\".\n */\ntype StoredResult = { idempotent: true; result: unknown };\n\n/** In-flight runs, per driver instance and storage key. */\nexport type IdempotentFlights = WeakMap<object, Map<string, Promise<unknown>>>;\n\nconst MIN_POLL_MS = 25;\nconst MAX_POLL_MS = 250;\n\nconst sleep = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));\n\nasync function readStored(\n driver: CacheDriver<any, any>,\n storeKey: string,\n): Promise<StoredResult | null> {\n const value = await driver.get(storeKey);\n\n if (value && typeof value === \"object\" && (value as StoredResult).idempotent === true) {\n return value as StoredResult;\n }\n\n return null;\n}\n\nasync function store(\n driver: CacheDriver<any, any>,\n storeKey: string,\n result: unknown,\n seconds: number,\n) {\n try {\n await driver.set(storeKey, { idempotent: true, result } satisfies StoredResult, seconds);\n } catch (error) {\n // The work already happened: hand the result back instead of failing the\n // caller into a retry that would repeat it.\n log.error(\n \"cache\",\n \"idempotent\",\n maskEmailsInText(`Could not store the result of ${storeKey}: ${String(error)}`),\n );\n }\n}\n\n/**\n * Implementation behind `cache.idempotent()`.\n */\nexport function runIdempotent<T>(\n driver: CacheDriver<any, any>,\n flights: IdempotentFlights,\n key: CacheKey,\n fn: () => Promise<T>,\n options: IdempotentOptions,\n): Promise<T> {\n const seconds = parseTtl(options.ttl);\n const keyString = typeof key === \"string\" ? key : parseCacheKey(key);\n const storeKey = `idempotent.${keyString}`;\n\n const driverFlights = flights.get(driver) ?? new Map<string, Promise<unknown>>();\n\n flights.set(driver, driverFlights);\n\n const existing = driverFlights.get(storeKey);\n\n if (existing) {\n return existing as Promise<T>;\n }\n\n const run = async (): Promise<T> => {\n if (seconds === 0) {\n return fn();\n }\n\n const stored = await readStored(driver, storeKey);\n\n if (stored) {\n return stored.result as T;\n }\n\n if (options.distributed) {\n return runDistributed(driver, keyString, storeKey, fn, seconds, options);\n }\n\n const result = await fn();\n\n await store(driver, storeKey, result, seconds);\n\n return result;\n };\n\n const promise = run().finally(() => {\n if (driverFlights.get(storeKey) === promise) {\n driverFlights.delete(storeKey);\n }\n });\n\n driverFlights.set(storeKey, promise);\n\n return promise;\n}\n\nasync function runDistributed<T>(\n driver: CacheDriver<any, any>,\n keyString: string,\n storeKey: string,\n fn: () => Promise<T>,\n seconds: number,\n options: IdempotentOptions,\n): Promise<T> {\n const lockKey = `idempotent.lock.${keyString}`;\n const lockSeconds = parseTtl(options.lockTtl ?? \"30s\");\n const deadline = Date.now() + lockSeconds * 1000;\n let pause = MIN_POLL_MS;\n\n while (true) {\n const outcome = await driver.lock(lockKey, lockSeconds, async () => {\n // Another server may have finished between our read and the lock.\n const stored = await readStored(driver, storeKey);\n\n if (stored) {\n return stored.result as T;\n }\n\n const result = await fn();\n\n await store(driver, storeKey, result, seconds);\n\n return result;\n });\n\n if (outcome.acquired) {\n return outcome.value;\n }\n\n // Held elsewhere: wait for its result. If that run fails it stores\n // nothing and releases the lock, and the next loop takes it over.\n await sleep(pause);\n pause = Math.min(pause * 2, MAX_POLL_MS);\n\n const stored = await readStored(driver, storeKey);\n\n if (stored) {\n return stored.result as T;\n }\n\n if (Date.now() >= deadline) {\n throw new CacheConcurrencyError(\n `idempotent(\"${keyString}\") timed out after ${lockSeconds}s waiting for another run to finish.`,\n );\n }\n }\n}\n"],"mappings":";;;;;AA4CA,MAAM,cAAc;AACpB,MAAM,cAAc;AAEpB,MAAM,SAAS,iBAAyB,IAAI,SAAS,YAAY,WAAW,SAAS,YAAY,CAAC;AAElG,eAAe,WACb,QACA,UAC8B;CAC9B,MAAM,QAAQ,MAAM,OAAO,IAAI,QAAQ;CAEvC,IAAI,SAAS,OAAO,UAAU,YAAa,MAAuB,eAAe,MAC/E,OAAO;CAGT,OAAO;AACT;AAEA,eAAe,MACb,QACA,UACA,QACA,SACA;CACA,IAAI;EACF,MAAM,OAAO,IAAI,UAAU;GAAE,YAAY;GAAM;EAAO,GAA0B,OAAO;CACzF,SAAS,OAAO;EAGd,IAAI,MACF,SACA,cACA,iBAAiB,iCAAiC,SAAS,IAAI,OAAO,KAAK,GAAG,CAChF;CACF;AACF;;;;AAKA,SAAgB,cACd,QACA,SACA,KACA,IACA,SACY;CACZ,MAAM,UAAU,SAAS,QAAQ,GAAG;CACpC,MAAM,YAAY,OAAO,QAAQ,WAAW,MAAM,cAAc,GAAG;CACnE,MAAM,WAAW,cAAc;CAE/B,MAAM,gBAAgB,QAAQ,IAAI,MAAM,qBAAK,IAAI,IAA8B;CAE/E,QAAQ,IAAI,QAAQ,aAAa;CAEjC,MAAM,WAAW,cAAc,IAAI,QAAQ;CAE3C,IAAI,UACF,OAAO;CAGT,MAAM,MAAM,YAAwB;EAClC,IAAI,YAAY,GACd,OAAO,GAAG;EAGZ,MAAM,SAAS,MAAM,WAAW,QAAQ,QAAQ;EAEhD,IAAI,QACF,OAAO,OAAO;EAGhB,IAAI,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M,cAAc,SAAS,QAAQ,WAAW,KAAK;CACrD,MAAM,WAAW,KAAK,IAAI,IAAI,cAAc;CAC5C,IAAI,QAAQ;CAEZ,OAAO,MAAM;EACX,MAAM,UAAU,MAAM,OAAO,KAAK,SAAS,aAAa,YAAY;GAElE,MAAM,SAAS,MAAM,WAAW,QAAQ,QAAQ;GAEhD,IAAI,QACF,OAAO,OAAO;GAGhB,MAAM,SAAS,MAAM,GAAG;GAExB,MAAM,MAAM,QAAQ,UAAU,QAAQ,OAAO;GAE7C,OAAO;EACT,CAAC;EAED,IAAI,QAAQ,UACV,OAAO,QAAQ;EAKjB,MAAM,MAAM,KAAK;EACjB,QAAQ,KAAK,IAAI,QAAQ,GAAG,WAAW;EAEvC,MAAM,SAAS,MAAM,WAAW,QAAQ,QAAQ;EAEhD,IAAI,QACF,OAAO,OAAO;EAGhB,IAAI,KAAK,IAAI,KAAK,UAChB,MAAM,IAAI,sBACR,eAAe,UAAU,qBAAqB,YAAY,qCAC5D;CAEJ;AACF"}
package/esm/index.d.mts CHANGED
@@ -30,5 +30,5 @@ import "./list/index.mjs";
30
30
  import { ScopedCache } from "./scoped-cache.mjs";
31
31
  import { TaggedCache } from "./tagged-cache.mjs";
32
32
  import { TaggedScopedCache } from "./tagged-scoped-cache.mjs";
33
- import { CACHE_FOR, cosineSimilarity, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo } from "./utils.mjs";
34
- export { BaseCacheDriver, type BloomFilter, type BloomOptions, CACHE_FOR, CacheCall, CacheConcurrencyError, CacheConfigurationError, CacheConfigurations, CacheConflictPolicy, CacheConnectionError, CacheData, CacheDriver, CacheDriverNotInitializedError, CacheError, CacheEventData, CacheEventHandler, CacheEventType, CacheKey, CacheListAccessor, CacheManager, CacheMetricsCollector, CacheMetricsSnapshot, CacheNamespaceOptions, CacheOperationType, CacheSetOptions, CacheSetResult, CacheSimilarHit, CacheSimilarOptions, type CacheStructures, type CacheStructuresBackend, CacheSwrOptions, CacheTtl, CacheUnsupportedError, CachedFn, CachedOptions, type CuckooFilter, type CuckooOptions, DriverClass, FileCacheDriver, FileCacheOptions, type FrequencyEntry, type FrequencyOptions, type FrequencyTracker, type IdempotentOptions, LRUMemoryCacheDriver, LRUMemoryCacheOptions, LockOptions, LockOutcome, MemoryCacheDriver, MemoryCacheList, MemoryCacheOptions, MemoryExtendedCacheDriver, MemoryExtendedCacheOptions, MemoryStructuresBackend, MockCacheDriver, MockCacheOptions, type NativeStructures, NormalizedCachedConfig, NormalizedSetOptions, NullCacheDriver, NullCacheDriverOptions, PgCacheDriver, PgCacheOptions, PgClientLike, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisOptions, RedisStructuresBackend, RememberOptions, ScopedCache, ScopedCacheContract, type StructureOptions, type StructuresCapable, TaggedCache, TaggedCacheDriver, TaggedScopedCache, TaggedScopedCacheContract, type UniqueCounter, type UniqueCounterFactory, type UniqueCounterGroup, type UniqueCounterOptions, cache, cached, cosineSimilarity, deriveAutoKey, expiresAtToTtl, idempotent, injectTags, isStructuresCapable, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
33
+ import { CACHE_FOR, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo } from "./utils.mjs";
34
+ export { BaseCacheDriver, type BloomFilter, type BloomOptions, CACHE_FOR, CacheCall, CacheConcurrencyError, CacheConfigurationError, CacheConfigurations, CacheConflictPolicy, CacheConnectionError, CacheData, CacheDriver, CacheDriverNotInitializedError, CacheError, CacheEventData, CacheEventHandler, CacheEventType, CacheKey, CacheListAccessor, CacheManager, CacheMetricsCollector, CacheMetricsSnapshot, CacheNamespaceOptions, CacheOperationType, CacheSetOptions, CacheSetResult, CacheSimilarHit, CacheSimilarOptions, type CacheStructures, type CacheStructuresBackend, CacheSwrOptions, CacheTtl, CacheUnsupportedError, CachedFn, CachedOptions, type CuckooFilter, type CuckooOptions, DriverClass, FileCacheDriver, FileCacheOptions, type FrequencyEntry, type FrequencyOptions, type FrequencyTracker, type IdempotentOptions, LRUMemoryCacheDriver, LRUMemoryCacheOptions, LockOptions, LockOutcome, MemoryCacheDriver, MemoryCacheList, MemoryCacheOptions, MemoryExtendedCacheDriver, MemoryExtendedCacheOptions, MemoryStructuresBackend, MockCacheDriver, MockCacheOptions, type NativeStructures, NormalizedCachedConfig, NormalizedSetOptions, NullCacheDriver, NullCacheDriverOptions, PgCacheDriver, PgCacheOptions, PgClientLike, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisOptions, RedisStructuresBackend, RememberOptions, ScopedCache, ScopedCacheContract, type StructureOptions, type StructuresCapable, TaggedCache, TaggedCacheDriver, TaggedScopedCache, TaggedScopedCacheContract, type UniqueCounter, type UniqueCounterFactory, type UniqueCounterGroup, type UniqueCounterOptions, cache, cached, cosineSimilarity, deriveAutoKey, escapeCacheKeySegment, expiresAtToTtl, idempotent, injectTags, isStructuresCapable, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
package/esm/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CacheConcurrencyError, CacheConfigurationError, CacheConnectionError, CacheDriverNotInitializedError, CacheError, CacheUnsupportedError } from "./types.mjs";
2
- import { CACHE_FOR, cosineSimilarity, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo } from "./utils.mjs";
2
+ import { CACHE_FOR, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo } from "./utils.mjs";
3
3
  import { CacheMetricsCollector } from "./metrics.mjs";
4
4
  import { TaggedScopedCache } from "./tagged-scoped-cache.mjs";
5
5
  import { ScopedCache } from "./scoped-cache.mjs";
@@ -25,4 +25,4 @@ import { PgCacheDriver } from "./drivers/pg-cache-driver.mjs";
25
25
  import { REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver } from "./drivers/redis-cache-driver.mjs";
26
26
  import "./drivers/index.mjs";
27
27
 
28
- export { BaseCacheDriver, CACHE_FOR, CacheConcurrencyError, CacheConfigurationError, CacheConnectionError, CacheDriverNotInitializedError, CacheError, CacheManager, CacheMetricsCollector, CacheUnsupportedError, FileCacheDriver, LRUMemoryCacheDriver, MemoryCacheDriver, MemoryCacheList, MemoryExtendedCacheDriver, MemoryStructuresBackend, MockCacheDriver, NullCacheDriver, PgCacheDriver, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisStructuresBackend, ScopedCache, TaggedCache, TaggedScopedCache, cache, cached, cosineSimilarity, deriveAutoKey, expiresAtToTtl, idempotent, injectTags, isStructuresCapable, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
28
+ export { BaseCacheDriver, CACHE_FOR, CacheConcurrencyError, CacheConfigurationError, CacheConnectionError, CacheDriverNotInitializedError, CacheError, CacheManager, CacheMetricsCollector, CacheUnsupportedError, FileCacheDriver, LRUMemoryCacheDriver, MemoryCacheDriver, MemoryCacheList, MemoryExtendedCacheDriver, MemoryStructuresBackend, MockCacheDriver, NullCacheDriver, PgCacheDriver, REDIS_CAS_SET_SCRIPT, REDIS_COMPARE_DELETE_SCRIPT, REDIS_GET_DEL_SCRIPT, REDIS_INCREMENT_SCRIPT, RedisCacheDriver, RedisStructuresBackend, ScopedCache, TaggedCache, TaggedScopedCache, cache, cached, cosineSimilarity, deriveAutoKey, escapeCacheKeySegment, expiresAtToTtl, idempotent, injectTags, isStructuresCapable, mergeTagSets, normalizeCachedArgs, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
@@ -1 +1 @@
1
- {"version":3,"file":"memory-cache-list.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/list/memory-cache-list.ts"],"sourcesContent":["import type { CacheDriver, CacheKey, CacheListAccessor } from \"../types\";\n\n/**\n * Generic array-backed {@link CacheListAccessor}.\n *\n * Stores the full list as a single cache entry and performs read-mutate-write\n * for every operation. Correct for any driver, but O(n) per op. The Redis\n * driver overrides `list()` to return a native-command accessor instead.\n *\n * **Role.** Fallback list accessor bound to a driver + key. Every mutation\n * runs through `driver.update()`, so it is serialized in-process and keeps the\n * entry's remaining TTL.\n *\n * **Responsibility.**\n * - Owns: translating list operations into array mutations + driver writes.\n * - Does NOT own: cross-process concurrency control (callers should wrap in a\n * distributed lock when multi-process writers are possible), or tagging of\n * list entries.\n *\n * @example\n * // Never constructed directly — obtained via driver.list():\n * const list = cache.list<Event>(\"recent-events\");\n * await list.push(event);\n */\nexport class MemoryCacheList<T> implements CacheListAccessor<T> {\n public constructor(\n private readonly driver: CacheDriver<any, any>,\n private readonly key: CacheKey,\n ) {}\n\n /**\n * Read the backing array from the driver. Returns an empty array on miss.\n */\n private async read(): Promise<T[]> {\n const current = (await this.driver.get(this.key)) as T[] | null;\n return Array.isArray(current) ? [...current] : [];\n }\n\n /**\n * Serialized read-modify-write through `driver.update()`. No ttl is passed,\n * so the driver keeps the entry's remaining TTL. An empty list removes the\n * entry to keep the store clean.\n */\n private async mutate<R>(mutation: (items: T[]) => R): Promise<R> {\n let result!: R;\n\n await this.driver.update<T[]>(this.key, (current) => {\n const items = Array.isArray(current) ? [...current] : [];\n\n result = mutation(items);\n\n return items.length === 0 ? null : items;\n });\n\n return result;\n }\n\n /**\n * {@inheritdoc}\n */\n public push(...items: T[]): Promise<number> {\n return this.mutate((current) => {\n current.push(...items);\n\n return current.length;\n });\n }\n\n /**\n * {@inheritdoc}\n */\n public unshift(...items: T[]): Promise<number> {\n return this.mutate((current) => {\n current.unshift(...items);\n\n return current.length;\n });\n }\n\n /**\n * {@inheritdoc}\n */\n public pop(): Promise<T | null> {\n return this.mutate((current) => (current.length === 0 ? null : (current.pop() as T)));\n }\n\n /**\n * {@inheritdoc}\n */\n public shift(): Promise<T | null> {\n return this.mutate((current) => (current.length === 0 ? null : (current.shift() as T)));\n }\n\n /**\n * {@inheritdoc}\n */\n public async slice(start?: number, end?: number): Promise<T[]> {\n const current = await this.read();\n return current.slice(start, end);\n }\n\n /**\n * {@inheritdoc}\n */\n public async all(): Promise<T[]> {\n return this.read();\n }\n\n /**\n * {@inheritdoc}\n */\n public async length(): Promise<number> {\n const current = await this.read();\n return current.length;\n }\n\n /**\n * Keep the inclusive range `[start, end]` like Redis LTRIM; negative\n * indexes count from the end.\n */\n public async trim(start: number, end: number): Promise<void> {\n await this.mutate((current) => {\n const length = current.length;\n const from = start < 0 ? Math.max(length + start, 0) : start;\n const to = end < 0 ? length + end : end;\n const kept = current.slice(from, to + 1);\n\n current.splice(0, current.length, ...kept);\n });\n }\n\n /**\n * {@inheritdoc}\n */\n public async clear(): Promise<void> {\n await this.driver.remove(this.key);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,kBAAb,MAAgE;CAC9D,AAAO,YACL,AAAiB,QACjB,AAAiB,KACjB;EAFiB;EACA;CAChB;;;;CAKH,MAAc,OAAqB;EACjC,MAAM,UAAW,MAAM,KAAK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;CACtF;;;;CAKA,AAAO,QAA2B;EAChC,OAAO,KAAK,QAAQ,YAAa,QAAQ,WAAW,IAAI,OAAQ,QAAQ,MAAM,CAAQ;CACxF;;;;CAKA,MAAa,MAAM,OAAgB,KAA4B;EAE7D,QAAO,MADe,KAAK,KAAK,EAClB,CAAC,MAAM,OAAO,GAAG;CACjC;;;;CAKA,MAAa,MAAoB;EAC/B,OAAO,KAAK,KAAK;CACnB;;;;CAKA,MAAa,SAA0B;EAErC,QAAO,MADe,KAAK,KAAK,EAClB,CAAC;CACjB;;;;;CAMA,MAAa,KAAK,OAAe,KAA4B;EAC3D,MAAM,KAAK,QAAQ,YAAY;GAC7B,MAAM,SAAS,QAAQ;GACvB,MAAM,OAAO,QAAQ,IAAI,KAAK,IAAI,SAAS,OAAO,CAAC,IAAI;GACvD,MAAM,KAAK,MAAM,IAAI,SAAS,MAAM;GACpC,MAAM,OAAO,QAAQ,MAAM,MAAM,KAAK,CAAC;GAEvC,QAAQ,OAAO,GAAG,QAAQ,QAAQ,GAAG,IAAI;EAC3C,CAAC;CACH;;;;CAKA,MAAa,QAAuB;EAClC,MAAM,KAAK,OAAO,OAAO,KAAK,GAAG;CACnC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"metrics.mjs","names":[],"sources":["../../../../../../../packages/cache/src/metrics.ts"],"sourcesContent":["import type { CacheEventData, CacheMetricsSnapshot } from \"./types\";\n\n/**\n * Default size of the circular latency-sample buffer. 1000 samples covers\n * \"tell me the current p95\" for every realistic workload while keeping the\n * memory cost negligible (8KB at 8 bytes per number).\n */\nconst DEFAULT_LATENCY_BUFFER_SIZE = 1000;\n\n/**\n * Per-driver counter row tracked inside {@link CacheMetricsCollector}.\n *\n * Same shape as the public {@link CacheMetricsSnapshot} except for the lack\n * of `byDriver` (which is the breakdown itself) and the `latencySamples`\n * array — the buffer that p50/p95/p99 are computed from at snapshot time.\n */\ntype DriverCounters = {\n hits: number;\n misses: number;\n sets: number;\n removed: number;\n errors: number;\n latencySamples: number[];\n /** Pointer into `latencySamples` for the next write — circular buffer. */\n latencyCursor: number;\n};\n\n/**\n * Listens to `CacheManager` events and accumulates running counters + a\n * circular latency buffer per driver. Returned to consumers via\n * `cache.metrics()` as a {@link CacheMetricsSnapshot}.\n *\n * **Role.** Single-instance observability layer attached to the manager.\n * Subscribes once at construction; survives `cache.use()` driver switches\n * because the global event registry on the manager re-attaches handlers to\n * every loaded driver.\n *\n * **Responsibility.**\n * - Owns: per-driver and aggregate counters (`hits`, `misses`, `sets`,\n * `removed`, `errors`), the latency circular buffer, and snapshot\n * computation including hit-rate + percentile calculation.\n * - Does NOT own: event emission (driven by drivers via `BaseCacheDriver.emit`),\n * timing instrumentation (done at the manager level via `recordLatency`),\n * or persistence — every metric resets on `resetMetrics()` and on process\n * restart.\n *\n * @example\n * cache.metrics();\n * // {\n * // hits: 9821, misses: 173, hitRate: 0.983,\n * // latencyMs: { p50: 0.4, p95: 2.1, p99: 8.2, samples: 1000 },\n * // byDriver: { memory: { ... }, redis: { ... } },\n * // startedAt: 1714185600000,\n * // }\n */\nexport class CacheMetricsCollector {\n /**\n * Maximum number of latency samples retained per driver. Older samples\n * are overwritten in arrival order — quantile calc operates on whatever\n * window is currently in the buffer.\n */\n protected readonly bufferSize: number;\n\n /**\n * Aggregate counters across every driver. Mirrors what one driver bucket\n * holds — the snapshot reports both totals and per-driver breakdowns.\n */\n protected readonly aggregate: DriverCounters;\n\n /**\n * Per-driver buckets keyed by driver name (`\"memory\"`, `\"redis\"`, …).\n * Lazy-allocated on first event.\n */\n protected readonly byDriver: Map<string, DriverCounters> = new Map();\n\n /** Millisecond timestamp the collector last reset. */\n protected startedAt: number = Date.now();\n\n public constructor(bufferSize: number = DEFAULT_LATENCY_BUFFER_SIZE) {\n this.bufferSize = bufferSize;\n this.aggregate = this.createCounters();\n }\n\n /**\n * Increment the appropriate counters for a cache event. Called from the\n * manager's global listeners (one per event type).\n */\n public recordEvent(\n event: \"hit\" | \"miss\" | \"set\" | \"removed\" | \"error\",\n data: CacheEventData,\n ): void {\n const driverBucket = this.bucketFor(data.driver);\n const aggregate = this.aggregate;\n\n switch (event) {\n case \"hit\":\n aggregate.hits += 1;\n driverBucket.hits += 1;\n break;\n case \"miss\":\n aggregate.misses += 1;\n driverBucket.misses += 1;\n break;\n case \"set\":\n aggregate.sets += 1;\n driverBucket.sets += 1;\n break;\n case \"removed\":\n aggregate.removed += 1;\n driverBucket.removed += 1;\n break;\n case \"error\":\n aggregate.errors += 1;\n driverBucket.errors += 1;\n break;\n }\n }\n\n /**\n * Append a latency sample for `driver`. Called by the manager from its\n * timed wrappers around `get` / `set` / `remove`. Uses circular-buffer\n * semantics: oldest samples are overwritten once the buffer is full.\n */\n public recordLatency(driver: string, durationMs: number): void {\n this.appendLatency(this.aggregate, durationMs);\n this.appendLatency(this.bucketFor(driver), durationMs);\n }\n\n /**\n * Compute and return the current snapshot. Latency percentiles are\n * derived from a sorted copy of the buffer at call time — O(N log N)\n * on N=1000 is cheap enough that we don't bother caching.\n */\n public snapshot(): CacheMetricsSnapshot {\n const byDriver: Record<string, Omit<CacheMetricsSnapshot, \"byDriver\">> = {};\n\n for (const [driverName, bucket] of this.byDriver) {\n byDriver[driverName] = this.toRow(bucket);\n }\n\n return {\n ...this.toRow(this.aggregate),\n byDriver,\n startedAt: this.startedAt,\n };\n }\n\n /**\n * Wipe every counter, drop every latency sample, and reset `startedAt`.\n * The collector itself stays subscribed to events.\n */\n public reset(): void {\n this.resetCounters(this.aggregate);\n this.byDriver.clear();\n this.startedAt = Date.now();\n }\n\n /**\n * Locate the per-driver bucket, creating it on first reference. Driver\n * names are taken verbatim from `CacheEventData.driver`.\n */\n protected bucketFor(driverName: string): DriverCounters {\n let bucket = this.byDriver.get(driverName);\n\n if (!bucket) {\n bucket = this.createCounters();\n this.byDriver.set(driverName, bucket);\n }\n\n return bucket;\n }\n\n /**\n * Convert raw counters into the public snapshot row shape. Computes\n * `hitRate` and the latency percentiles on the fly.\n */\n protected toRow(bucket: DriverCounters): Omit<CacheMetricsSnapshot, \"byDriver\"> {\n const totalReads = bucket.hits + bucket.misses;\n const hitRate = totalReads === 0 ? 0 : bucket.hits / totalReads;\n const latency = this.computeLatency(bucket.latencySamples);\n\n return {\n hits: bucket.hits,\n misses: bucket.misses,\n sets: bucket.sets,\n removed: bucket.removed,\n errors: bucket.errors,\n hitRate,\n latencyMs: latency,\n startedAt: this.startedAt,\n };\n }\n\n /**\n * Sort a copy of the buffer and pick the percentile entries directly.\n * Empty buffers return zeroed percentiles so consumers can render\n * dashboards without null-checking.\n */\n protected computeLatency(samples: number[]): CacheMetricsSnapshot[\"latencyMs\"] {\n if (samples.length === 0) {\n return { p50: 0, p95: 0, p99: 0, samples: 0 };\n }\n\n const sorted = [...samples].sort((a, b) => a - b);\n const pick = (quantile: number): number => {\n const index = Math.min(sorted.length - 1, Math.floor(quantile * sorted.length));\n\n // `sorted` is non-empty (the `samples.length === 0` early return above)\n // and `index` is clamped to its last element, so this always hits — but\n // the clamp is arithmetic the compiler does not evaluate. `?? 0` states\n // the floor without asserting: a percentile of an empty set is 0, which\n // is exactly what the early return above already answers.\n return sorted[index] ?? 0;\n };\n\n return {\n p50: pick(0.5),\n p95: pick(0.95),\n p99: pick(0.99),\n samples: sorted.length,\n };\n }\n\n /**\n * Append a latency sample using circular-buffer semantics — overwrite the\n * oldest entry once the buffer is full instead of growing unbounded.\n */\n protected appendLatency(bucket: DriverCounters, durationMs: number): void {\n if (bucket.latencySamples.length < this.bufferSize) {\n bucket.latencySamples.push(durationMs);\n\n return;\n }\n\n bucket.latencySamples[bucket.latencyCursor] = durationMs;\n bucket.latencyCursor = (bucket.latencyCursor + 1) % this.bufferSize;\n }\n\n /** Build a fresh counter row with zeroed totals and an empty buffer. */\n protected createCounters(): DriverCounters {\n return {\n hits: 0,\n misses: 0,\n sets: 0,\n removed: 0,\n errors: 0,\n latencySamples: [],\n latencyCursor: 0,\n };\n }\n\n /** Reset an existing counter row in place. Used by `reset()` for the aggregate. */\n protected resetCounters(bucket: DriverCounters): void {\n bucket.hits = 0;\n bucket.misses = 0;\n bucket.sets = 0;\n bucket.removed = 0;\n bucket.errors = 0;\n bucket.latencySamples.length = 0;\n bucket.latencyCursor = 0;\n }\n}\n"],"mappings":";;;;;;AAOA,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDpC,IAAa,wBAAb,MAAmC;CAuBjC,AAAO,YAAY,aAAqB,6BAA6B;kCALV,IAAI,IAAI;mBAGrC,KAAK,IAAI;EAGrC,KAAK,aAAa;EAClB,KAAK,YAAY,KAAK,eAAe;CACvC;;;;;CAMA,AAAO,YACL,OACA,MACM;EACN,MAAM,eAAe,KAAK,UAAU,KAAK,MAAM;EAC/C,MAAM,YAAY,KAAK;EAEvB,QAAQ,OAAR;GACE,KAAK;IACH,UAAU,QAAQ;IAClB,aAAa,QAAQ;IACrB;GACF,KAAK;IACH,UAAU,UAAU;IACpB,aAAa,UAAU;IACvB;GACF,KAAK;IACH,UAAU,QAAQ;IAClB,aAAa,QAAQ;IACrB;GACF,KAAK;IACH,UAAU,WAAW;IACrB,aAAa,WAAW;IACxB;GACF,KAAK;IACH,UAAU,UAAU;IACpB,aAAa,UAAU;EAE3B;CACF;;;;;;CAOA,AAAO,cAAc,QAAgB,YAA0B;EAC7D,KAAK,cAAc,KAAK,WAAW,UAAU;EAC7C,KAAK,cAAc,KAAK,UAAU,MAAM,GAAG,UAAU;CACvD;;;;;;CAOA,AAAO,WAAiC;EACtC,MAAM,WAAmE,CAAC;EAE1E,KAAK,MAAM,CAAC,YAAY,WAAW,KAAK,UACtC,SAAS,cAAc,KAAK,MAAM,MAAM;EAG1C,OAAO;GACL,GAAG,KAAK,MAAM,KAAK,SAAS;GAC5B;GACA,WAAW,KAAK;EAClB;CACF;;;;;CAMA,AAAO,QAAc;EACnB,KAAK,cAAc,KAAK,SAAS;EACjC,KAAK,SAAS,MAAM;EACpB,KAAK,YAAY,KAAK,IAAI;CAC5B;;;;;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;GACR,gBAAgB,CAAC;GACjB,eAAe;EACjB;CACF;;CAGA,AAAU,cAAc,QAA8B;EACpD,OAAO,OAAO;EACd,OAAO,SAAS;EAChB,OAAO,OAAO;EACd,OAAO,UAAU;EACjB,OAAO,SAAS;EAChB,OAAO,eAAe,SAAS;EAC/B,OAAO,gBAAgB;CACzB;AACF"}
1
+ {"version":3,"file":"metrics.mjs","names":[],"sources":["../../../../../../../packages/cache/src/metrics.ts"],"mappings":";;;;;;AAOA,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDpC,IAAa,wBAAb,MAAmC;CAuBjC,AAAO,YAAY,aAAqB,6BAA6B;kCALV,IAAI,IAAI;mBAGrC,KAAK,IAAI;EAGrC,KAAK,aAAa;EAClB,KAAK,YAAY,KAAK,eAAe;CACvC;;;;;CAMA,AAAO,YACL,OACA,MACM;EACN,MAAM,eAAe,KAAK,UAAU,KAAK,MAAM;EAC/C,MAAM,YAAY,KAAK;EAEvB,QAAQ,OAAR;GACE,KAAK;IACH,UAAU,QAAQ;IAClB,aAAa,QAAQ;IACrB;GACF,KAAK;IACH,UAAU,UAAU;IACpB,aAAa,UAAU;IACvB;GACF,KAAK;IACH,UAAU,QAAQ;IAClB,aAAa,QAAQ;IACrB;GACF,KAAK;IACH,UAAU,WAAW;IACrB,aAAa,WAAW;IACxB;GACF,KAAK;IACH,UAAU,UAAU;IACpB,aAAa,UAAU;EAE3B;CACF;;;;;;CAOA,AAAO,cAAc,QAAgB,YAA0B;EAC7D,KAAK,cAAc,KAAK,WAAW,UAAU;EAC7C,KAAK,cAAc,KAAK,UAAU,MAAM,GAAG,UAAU;CACvD;;;;;;CAOA,AAAO,WAAiC;EACtC,MAAM,WAAmE,CAAC;EAE1E,KAAK,MAAM,CAAC,YAAY,WAAW,KAAK,UACtC,SAAS,cAAc,KAAK,MAAM,MAAM;EAG1C,OAAO;GACL,GAAG,KAAK,MAAM,KAAK,SAAS;GAC5B;GACA,WAAW,KAAK;EACl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iB,OAAO,gBAAgB,KAAK,KAAK;CAC3D;;CAGA,AAAU,iBAAiC;EACzC,OAAO;GACL,MAAM;GACN,QAAQ;GACR,MAAM;GACN,SAAS;GACT,QAAQ;GACR,gBAAgB,CAAC;GACjB,eAAe;EACjB;CACF;;CAGA,AAAU,cAAc,QAA8B;EACpD,OAAO,OAAO;EACd,OAAO,SAAS;EAChB,OAAO,OAAO;EACd,OAAO,UAAU;EACjB,OAAO,SAAS;EAChB,OAAO,eAAe,SAAS;EAC/B,OAAO,gBAAgB;CACzB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"scoped-cache.mjs","names":[],"sources":["../../../../../../../packages/cache/src/scoped-cache.ts"],"sourcesContent":["import { TaggedScopedCache } from \"./tagged-scoped-cache\";\nimport type {\n CacheDriver,\n CacheKey,\n CacheListAccessor,\n CacheNamespaceOptions,\n CacheSetOptions,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheSwrOptions,\n CacheTtl,\n LockOptions,\n LockOutcome,\n RememberOptions,\n ScopedCacheContract,\n TaggedScopedCacheContract,\n} from \"./types\";\nimport {\n mergeTagSets,\n normalizeToOptions,\n normalizeToRememberOptions,\n parseCacheKey,\n parseTtl,\n} from \"./utils\";\n\n/**\n * Scoped view over a cache source. Returned by `cache.namespace(prefix, options?)`.\n *\n * **Role.** A `ScopedCache` is a stateless wrapper that prepends a fixed\n * prefix to every key and applies optional default `ttl` / `tags` to every\n * write. Stores nothing itself — every call forwards to the underlying\n * `source` (typically the `CacheManager`, but any `CacheDriver` works).\n *\n * **Responsibility.**\n * - Owns: prefix-prepending of keys, normalization of nested-scope prefixes,\n * merging scope defaults into write options (`ttl`, `tags`), filtering\n * `similar()` hits to its own scope, and exposing `.clear()` as a sugar\n * for `removeNamespace(prefix)`.\n * - Does NOT own: actual storage, connection lifecycle, event listeners,\n * driver selection, or tag-index bookkeeping (delegated to the source's\n * tagged-cache machinery).\n *\n * Per-call options always win over scope defaults; tags merge additively\n * across (scope defaults + per-call) layers. Nested scopes inherit and may\n * override the parent's defaults — see {@link ScopedCache.namespace}.\n *\n * @example\n * const chat = cache.namespace(`chats.${id}`, { ttl: \"30d\" });\n *\n * await chat.set(\"messages.10\", msg); // 30d default\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call override\n * await chat.namespace(\"typing\", { ttl: \"5s\" }).set(\"user.42\", true);\n * await chat.clear();\n */\nexport class ScopedCache implements ScopedCacheContract {\n /**\n * Fully-qualified prefix prepended to every key handled by this scope.\n * Normalized through {@link parseCacheKey} on construction so colon-form\n * input (`\"chats:10\"`) and trailing dots compose cleanly with nested scopes.\n */\n public readonly prefix: string;\n\n /**\n * Underlying cache source. Public-readonly so co-located helpers\n * (`TaggedScopedCache`) can delegate without ceremony — not part of the\n * stable consumer API.\n *\n * @internal\n */\n public readonly source: CacheDriver<any, any>;\n\n /**\n * Defaults applied to every write through this scope. Per-call options\n * override `ttl`; `tags` merge additively across layers.\n *\n * @internal\n */\n public readonly defaults: CacheNamespaceOptions;\n\n /**\n * Build a scope. Constructed via `cache.namespace(prefix, options)` —\n * users never call this directly.\n */\n public constructor(\n source: CacheDriver<any, any>,\n prefix: string,\n defaults: CacheNamespaceOptions = {},\n ) {\n this.source = source;\n this.prefix = parseCacheKey(prefix);\n this.defaults = {\n ttl: defaults.ttl,\n tags: defaults.tags && defaults.tags.length > 0 ? [...defaults.tags] : undefined,\n };\n }\n\n /**\n * Build a nested scope. The child's prefix is `parent.child`; child options\n * override the parent's `ttl` and union into `tags`.\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 public namespace(prefix: string, options: CacheNamespaceOptions = {}): ScopedCacheContract {\n const childPrefix = `${this.prefix}.${parseCacheKey(prefix)}`;\n\n return new ScopedCache(this.source, childPrefix, {\n ttl: options.ttl ?? this.defaults.ttl,\n tags: mergeTagSets(this.defaults.tags, options.tags),\n });\n }\n\n /**\n * Return a one-shot tagged write handle. The handle's tags merge additively\n * with scope-level defaults — final tag list per write is the union of\n * (scope tags + handle tags + per-call tags), deduped.\n */\n public tags(tags: string[]): TaggedScopedCacheContract {\n return new TaggedScopedCache(this, tags);\n }\n\n /**\n * Wipe every entry under this scope's prefix. Sugar over\n * `source.removeNamespace(prefix)` — siblings outside the scope are\n * untouched.\n */\n public clear(): Promise<void> {\n return this.source.removeNamespace(this.prefix);\n }\n\n /**\n * Read the value at the scoped key. Forwards to the source after prefixing.\n */\n public get<T = any>(key: CacheKey): Promise<T | null> {\n return this.source.get<T>(this.scopedKey(key));\n }\n\n /**\n * Check presence of the scoped key without fetching the value.\n */\n public has(key: CacheKey): Promise<boolean> {\n return this.source.has(this.scopedKey(key));\n }\n\n /**\n * Batch-read scoped keys. Each input key is prefixed before forwarding.\n */\n public many(keys: CacheKey[]): Promise<any[]> {\n return this.source.many(keys.map((key) => this.scopedKey(key)));\n }\n\n /**\n * Read-and-remove. Returns the value or `null`; the entry is gone after.\n */\n public pull<T = any>(key: CacheKey): Promise<T | null> {\n return this.source.pull<T>(this.scopedKey(key));\n }\n\n /**\n * Write the scoped key. Per-call `ttl`/`tags` win over scope defaults;\n * `expiresAt` is preserved as-is (absolute deadlines are never overridden\n * by the scope's relative-ttl default).\n */\n public set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions): Promise<any> {\n return this.source.set(this.scopedKey(key), value, this.mergeSetOptions(ttlOrOptions));\n }\n\n /**\n * Batch-write under the scope. Caller's positional `ttl` wins; otherwise\n * the scope default is parsed to seconds (since `setMany` accepts only a\n * numeric ttl).\n */\n public setMany(items: Record<string, any>, ttl?: number): Promise<void> {\n const scoped: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(items)) {\n scoped[this.scopedKey(key)] = value;\n }\n\n return this.source.setMany(scoped, ttl ?? this.scopeTtlSeconds());\n }\n\n /**\n * Atomic create-or-skip on the scoped key. Throws when the underlying\n * source has no `setNX` (driver-specific — Redis-only today).\n */\n public setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean> {\n if (!this.source.setNX) {\n throw new Error(`setNX is not supported by the underlying cache source: ${this.source.name}`);\n }\n\n return this.source.setNX(this.scopedKey(key), value, ttl ?? this.scopeTtlSeconds());\n }\n\n /**\n * Permanent write (no expiration). Bypasses the scope's `ttl` default —\n * `forever` always means forever, regardless of scope policy.\n */\n public forever<T = any>(key: CacheKey, value: T): Promise<T> {\n return this.source.forever<T>(this.scopedKey(key), value);\n }\n\n /**\n * Remove a single scoped key.\n */\n public remove(key: CacheKey): Promise<void> {\n return this.source.remove(this.scopedKey(key));\n }\n\n /**\n * Read-or-compute. Cache-miss writes pick up the scope's default `ttl`\n * and `tags` unless the caller passed an options object that overrides.\n */\n public remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n return this.source.remember<T>(\n this.scopedKey(key),\n this.mergeRememberOptions(ttlOrOptions),\n callback,\n );\n }\n\n /**\n * Stale-while-revalidate on the scoped key. Scope-level `tags` merge\n * additively with `options.tags`; `freshTtl`/`staleTtl` always come from\n * the caller (no scope-default precedence — the SWR shape is too\n * specific to the call site to inherit).\n */\n public swr<T = any>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n const merged: CacheSwrOptions = {\n ...options,\n tags: mergeTagSets(this.defaults.tags, options.tags),\n };\n\n return this.source.swr<T>(this.scopedKey(key), merged, callback);\n }\n\n /**\n * Atomic counter increment on the scoped key. TTL is preserved by the\n * underlying driver — scope ttl is only applied on first write via `set`.\n */\n public increment(key: CacheKey, value?: number, options?: { ttl?: CacheTtl }): Promise<number> {\n return this.source.increment(this.scopedKey(key), value, {\n ttl: options?.ttl ?? this.defaults.ttl,\n });\n }\n\n /**\n * Reset the expiry of the scoped key to `ttl` from now. Resolves to `false`\n * when the key is missing. See `CacheDriver.extend`.\n */\n public extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n return this.source.extend(this.scopedKey(key), ttl);\n }\n\n /**\n * Atomic counter decrement on the scoped key. See {@link increment} for\n * TTL semantics.\n */\n public decrement(key: CacheKey, value?: number): Promise<number> {\n return this.source.decrement(this.scopedKey(key), value);\n }\n\n /**\n * Atomic read-modify-write. An explicit `options.ttl` always wins. Otherwise\n * the scope's default `ttl` is applied only when the key does not exist yet;\n * for an existing key no ttl is passed so the source preserves the entry's\n * remaining TTL.\n */\n public async 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 const scopedKey = this.scopedKey(key);\n\n return this.source.update<T>(scopedKey, fn, await this.writeOptions(scopedKey, options));\n }\n\n /**\n * Shallow-merge a partial object into the scoped entry. Same TTL semantics\n * as {@link update}.\n */\n public async merge<T extends Record<string, any> = Record<string, any>>(\n key: CacheKey,\n partial: Partial<T>,\n options?: { ttl?: CacheTtl },\n ): Promise<T> {\n const scopedKey = this.scopedKey(key);\n\n return this.source.merge<T>(scopedKey, partial, await this.writeOptions(scopedKey, options));\n }\n\n /**\n * Resolve the ttl options for update/merge: explicit ttl, else the scope\n * default only for keys that don't exist yet, else nothing (keep remaining).\n */\n private async writeOptions(\n scopedKey: CacheKey,\n options?: { ttl?: CacheTtl },\n ): Promise<{ ttl?: CacheTtl }> {\n if (options?.ttl !== undefined) {\n return { ttl: options.ttl };\n }\n\n if (this.defaults.ttl === undefined) {\n return {};\n }\n\n return (await this.source.has(scopedKey)) ? {} : { ttl: this.defaults.ttl };\n }\n\n /**\n * Return a list accessor bound to the scoped key. The accessor itself\n * does its own read-mutate-write under the prefixed entry.\n */\n public list<T = any>(key: CacheKey): CacheListAccessor<T> {\n return this.source.list<T>(this.scopedKey(key));\n }\n\n /**\n * Acquire a distributed lock on the scoped key. Caller's TTL wins; when\n * the options form omits `ttl`, the scope default fills in.\n */\n public lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>> {\n if (typeof ttlOrOptions === \"object\" && ttlOrOptions !== null) {\n const merged: Omit<LockOptions, \"driver\"> = {\n ...ttlOrOptions,\n ttl: ttlOrOptions.ttl ?? this.defaults.ttl ?? ttlOrOptions.ttl,\n };\n\n // The third coalesce is intentional — when both caller and scope omit\n // the TTL, we still pass the original (undefined) through so the source\n // raises its own validation error rather than us swallowing it silently.\n return this.source.lock<T>(this.scopedKey(key), merged, fn);\n }\n\n return this.source.lock<T>(this.scopedKey(key), ttlOrOptions, fn);\n }\n\n /**\n * Similarity retrieval, scope-isolated. Hits whose keys fall outside this\n * scope are filtered out before the result is returned. `topK` applies to\n * the underlying retrieval — when the scope contains fewer than `topK`\n * matches but other scopes do, the caller will see fewer hits than `topK`.\n */\n public async similar<T = any>(\n vector: number[],\n options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n const hits = await this.source.similar<T>(vector, options);\n const parsedPrefix = this.source.parseKey(this.prefix);\n\n return hits.filter((hit) => hit.key === parsedPrefix || hit.key.startsWith(parsedPrefix + \".\"));\n }\n\n /**\n * Build the source-side key by prepending the scope prefix. Object keys\n * are normalized via {@link parseCacheKey} first so they compose with the\n * prefix as plain dot-strings.\n */\n protected scopedKey(key: CacheKey): string {\n const keyString = typeof key === \"string\" ? key : parseCacheKey(key);\n\n if (!keyString) {\n return this.prefix;\n }\n\n return `${this.prefix}.${keyString}`;\n }\n\n /**\n * Coerce the polymorphic 3rd `set` argument into a {@link CacheSetOptions}\n * with scope defaults filled in. Per-call values always win; tags merge\n * additively. `expiresAt` is preserved without injecting the scope's `ttl`\n * default (absolute deadlines override relative ones).\n */\n protected mergeSetOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions | undefined {\n const options = normalizeToOptions(input);\n const ttl = options.ttl ?? (options.expiresAt === undefined ? this.defaults.ttl : undefined);\n const tags = mergeTagSets(this.defaults.tags, options.tags);\n\n const merged: CacheSetOptions = { ...options };\n\n if (ttl !== undefined) {\n merged.ttl = ttl;\n }\n\n if (tags !== undefined) {\n merged.tags = tags;\n }\n\n return merged;\n }\n\n /**\n * Same merge as {@link mergeSetOptions} but for the `remember()` shape\n * ({@link RememberOptions} — no `expiresAt`).\n */\n protected mergeRememberOptions(input: CacheTtl | RememberOptions): CacheTtl | RememberOptions {\n const options = normalizeToRememberOptions(input);\n const ttl = options.ttl ?? this.defaults.ttl;\n const tags = mergeTagSets(this.defaults.tags, options.tags);\n\n const merged: RememberOptions = { ...options };\n\n if (ttl !== undefined) {\n merged.ttl = ttl;\n }\n\n if (tags !== undefined) {\n merged.tags = tags;\n }\n\n return merged;\n }\n\n /**\n * Convert the scope's default `ttl` (which may be a duration string) into\n * seconds, for the few methods (`setMany`, `setNX`) that accept only a\n * numeric ttl.\n */\n protected scopeTtlSeconds(): number | undefined {\n if (this.defaults.ttl === undefined) {\n return undefined;\n }\n\n return parseTtl(this.defaults.ttl);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,cAAb,MAAa,YAA2C;;;;;CA6BtD,AAAO,YACL,QACA,QACA,WAAkC,CAAC,GACnC;EACA,KAAK,SAAS;EACd,KAAK,SAAS,cAAc,MAAM;EAClC,KAAK,WAAW;GACd,KAAK,SAAS;GACd,MAAM,SAAS,QAAQ,SAAS,KAAK,SAAS,IAAI,CAAC,GAAG,SAAS,IAAI,IAAI;EACzE;CACF;;;;;;;;;;CAWA,AAAO,UAAU,QAAgB,UAAiC,CAAC,GAAwB;EACzF,MAAM,cAAc,GAAG,KAAK,OAAO,GAAG,cAAc,MAAM;EAE1D,OAAO,IAAI,YAAY,KAAK,QAAQ,aAAa;GAC/C,KAAK,QAAQ,OAAO,KAAK,SAAS;GAClC,MAAM,aAAa,KAAK,SAAS,MAAM,QAAQ,IAAI;EACrD,CAAC;CACH;;;;;;CAOA,AAAO,KAAK,MAA2C;EACrD,OAAO,IAAI,k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AQ;EAE7C,IAAI,QAAQ,QACV,OAAO,MAAM;EAGf,IAAI,SAAS,QACX,OAAO,OAAO;EAGhB,OAAO;CACT;;;;;;CAOA,AAAU,kBAAsC;EAC9C,IAAI,KAAK,SAAS,QAAQ,QACxB;EAGF,OAAO,SAAS,KAAK,SAAS,GAAG;CACnC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"bloom-filter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/bloom-filter.ts"],"sourcesContent":["import { hashPair, probe } from \"./hash\";\nimport { bloomGeometry } from \"./sizing\";\nimport type { BloomOptions, CacheStructuresBackend, NativeStructures } from \"./types\";\n\nexport type StructureContext = {\n backend(): CacheStructuresBackend;\n /** Seconds, or undefined for no expiry. */\n ttl: number | undefined;\n};\n\nexport async function nativeOf(backend: CacheStructuresBackend): Promise<NativeStructures | null> {\n return backend.native ? backend.native() : null;\n}\n\n/**\n * Bloom filter: answers \"definitely not added\" or \"probably added\".\n * Items can be added but not removed or listed.\n */\nexport class BloomFilter {\n protected readonly bits: number;\n protected readonly hashes: number;\n protected readonly errorRate: number;\n protected readonly capacity: number;\n\n public constructor(\n protected readonly key: string,\n options: BloomOptions,\n protected readonly context: StructureContext,\n ) {\n this.errorRate = options.errorRate ?? 0.01;\n this.capacity = options.expectedItems;\n\n const geometry = bloomGeometry(options.expectedItems, this.errorRate);\n\n this.bits = geometry.bits;\n this.hashes = geometry.hashes;\n }\n\n protected positions(item: string): number[] {\n const hashes = hashPair(item);\n\n return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.bits));\n }\n\n /**\n * Add an item. Resolves to `true` when the item was not (probably) present\n * before and `false` when it probably was.\n */\n public async add(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.bloomAdd(this.key, value, {\n capacity: this.capacity,\n errorRate: this.errorRate,\n ttl: this.context.ttl,\n });\n }\n\n const previous = await backend.bitSet(this.key, this.positions(value), {\n ttl: this.context.ttl,\n });\n\n return previous.some((bit) => !bit);\n }\n\n /**\n * `false` means the item was definitely never added; `true` means it\n * probably was (a small, configured share of `true` answers are wrong).\n */\n public async mightContain(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.bloomExists(this.key, value);\n }\n\n const bits = await backend.bitGet(this.key, this.positions(value));\n\n return bits.every(Boolean);\n }\n}\n"],"mappings":";;;;AAUA,eAAsB,SAAS,SAAmE;CAChG,OAAO,QAAQ,SAAS,QAAQ,OAAO,IAAI;AAC7C;;;;;AAMA,IAAa,cAAb,MAAyB;CAMvB,AAAO,YACL,AAAmB,KACnB,SACA,AAAmB,SACnB;EAHmB;EAEA;EAEnB,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,WAAW,QAAQ;EAExB,MAAM,WAAW,cAAc,QAAQ,eAAe,KAAK,SAAS;EAEpE,KAAK,OAAO,SAAS;EACrB,KAAK,SAAS,SAAS;CACzB;CAEA,AAAU,UAAU,MAAwB;EAC1C,MAAM,SAAS,SAAS,IAAI;EAE5B,OAAO,MAAM,KAAK,EAAE,QAAQ,KAAK,OAAO,IAAI,GAAG,UAAU,MAAM,QAAQ,OAAO,KAAK,IAAI,CAAC;CAC1F;;;;;CAMA,MAAa,IAAI,MAAyC;EACxD,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM,UAAU,KAAK,QAAQ,QAAQ;EACrC,MAAM,SAAS,MAAM,SAAS,OAAO;EAErC,IAAI,QACF,OAAO,OAAO,SAAS,KAAK,KAAK,OAAO;GACtC,UAAU,KAAK;GACf,WAAW,KAAK;GAChB,KAAK,KAAK,QAAQ;EACpB,CAAC;EAOH,QAAO,MAJgB,QAAQ,OAAO,KAAK,KAAK,KAAK,UAAU,KAAK,GAAG,EACrE,KAAK,KAAK,QAAQ,IACpB,CAAC,EAEc,CAAC,MAAM,QAAQ,CAAC,GAAG;CACpC;;;;;CAMA,MAAa,aAAa,MAA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c,CAAC,MAAM,QAAQ,CAAC,GAAG;CACpC;;;;;CAMA,MAAa,aAAa,MAAyC;EACjE,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM,UAAU,KAAK,QAAQ,QAAQ;EACrC,MAAM,SAAS,MAAM,SAAS,OAAO;EAErC,IAAI,QACF,OAAO,OAAO,YAAY,KAAK,KAAK,KAAK;EAK3C,QAAO,MAFY,QAAQ,OAAO,KAAK,KAAK,KAAK,UAAU,KAAK,CAAC,EAEtD,CAAC,MAAM,OAAO;CAC3B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"cuckoo-filter.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/cuckoo-filter.ts"],"sourcesContent":["import { nativeOf, type StructureContext } from \"./bloom-filter\";\nimport { hashPair, probe } from \"./hash\";\nimport { bloomGeometry } from \"./sizing\";\nimport type { CuckooOptions } from \"./types\";\n\n/**\n * Membership filter that supports removal.\n *\n * With RedisBloom this is a real cuckoo filter (`CF.*`). Everywhere else it is\n * a counting Bloom filter: the same API and error rate, with one counter per\n * cell instead of one bit, so `remove()` can undo an `add()`.\n *\n * Never remove an item that was not added: on either implementation it\n * corrupts the filter and can hide other items.\n */\nexport class CuckooFilter {\n protected readonly cells: number;\n protected readonly hashes: number;\n protected readonly capacity: number;\n\n public constructor(\n protected readonly key: string,\n options: CuckooOptions,\n protected readonly context: StructureContext,\n ) {\n const geometry = bloomGeometry(options.expectedItems, options.errorRate ?? 0.01);\n\n this.cells = geometry.bits;\n this.hashes = geometry.hashes;\n this.capacity = options.expectedItems;\n }\n\n protected positions(item: string): number[] {\n const hashes = hashPair(item);\n\n return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.cells));\n }\n\n /**\n * Add an item. Resolves to `true` when stored.\n */\n public async add(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.cuckooAdd(this.key, value, {\n capacity: this.capacity,\n ttl: this.context.ttl,\n });\n }\n\n await backend.gridAdd(this.key, this.positions(value), 1, { ttl: this.context.ttl });\n\n return true;\n }\n\n /**\n * Remove an item that was added. Resolves to `true` when something was removed.\n */\n public async remove(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.cuckooRemove(this.key, value);\n }\n\n const positions = this.positions(value);\n const counts = await backend.gridGet(this.key, positions);\n\n if (counts.some((count) => count === 0)) {\n return false;\n }\n\n await backend.gridAdd(this.key, positions, -1);\n\n return true;\n }\n\n /**\n * `false` means definitely not present; `true` means probably present.\n */\n public async mightContain(item: string | number): Promise<boolean> {\n const value = String(item);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.cuckooExists(this.key, value);\n }\n\n const counts = await backend.gridGet(this.key, this.positions(value));\n\n return counts.every((count) => count > 0);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,IAAa,eAAb,MAA0B;CAKxB,AAAO,YACL,AAAmB,KACnB,SACA,AAAmB,SACnB;EAHmB;EAEA;EAEnB,MAAM,WAAW,cAAc,QAAQ,eAAe,QAAQ,aAAa,GAAI;EAE/E,KAAK,QAAQ,SAAS;EACtB,KAAK,SAAS,SAAS;EACvB,KAAK,WAAW,QAAQ;CAC1B;CAEA,AAAU,UAAU,MAAwB;EAC1C,MAAM,SAAS,SAAS,IAAI;EAE5B,OAAO,MAAM,KAAK,EAAE,QAAQ,KAAK,OAAO,IAAI,GAAG,UAAU,MAAM,QAAQ,OAAO,KAAK,KAAK,CAAC;CAC3F;;;;CAKA,MAAa,IAAI,MAAyC;EACxD,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM,UAAU,KAAK,QAAQ,QAAQ;EACrC,MAAM,SAAS,MAAM,SAAS,OAAO;EAErC,IAAI,QACF,OAAO,OAAO,UAAU,KAAK,KAAK,OAAO;GACvC,UAAU,KAAK;GACf,KAAK,KAAK,QAAQ;EACpB,CAAC;EAGH,MAAM,QAAQ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/structures/frequency-tracker.ts"],"sourcesContent":["import { nativeOf, type StructureContext } from \"./bloom-filter\";\nimport { hashPair, probe } from \"./hash\";\nimport { assertPositiveInteger } from \"./sizing\";\nimport type { FrequencyEntry, FrequencyOptions } from \"./types\";\n\n/**\n * Count-Min sketch with a Top-K list: how often a value was seen, and which\n * values are seen most. Estimates never fall below the true count; they can\n * only be too high.\n */\nexport class FrequencyTracker {\n protected readonly width: number;\n protected readonly depth: number;\n protected readonly topK: number;\n\n public constructor(\n protected readonly key: string,\n options: FrequencyOptions,\n protected readonly context: StructureContext,\n ) {\n this.width = options.width ?? 2000;\n this.depth = options.depth ?? 5;\n this.topK = options.topK ?? 10;\n\n assertPositiveInteger(\"width\", this.width);\n assertPositiveInteger(\"depth\", this.depth);\n assertPositiveInteger(\"topK\", this.topK);\n }\n\n protected cellsOf(item: string): number[] {\n const hashes = hashPair(item);\n\n return Array.from(\n { length: this.depth },\n (_, row) => row * this.width + probe(hashes, row, this.width),\n );\n }\n\n /**\n * Count `count` more occurrences of a value (default one).\n */\n public async add(value: string | number, count = 1): Promise<void> {\n assertPositiveInteger(\"count\", count);\n\n const item = String(value);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n await native.frequencyAdd(this.key, item, count, {\n width: this.width,\n depth: this.depth,\n topK: this.topK,\n ttl: this.context.ttl,\n });\n\n return;\n }\n\n const counters = await backend.gridAdd(this.key, this.cellsOf(item), count, {\n ttl: this.context.ttl,\n });\n\n await backend.rankedSet(`${this.key}.top`, item, Math.min(...counters), this.topK, {\n ttl: this.context.ttl,\n });\n }\n\n /**\n * Estimated number of times a value was counted. Never lower than the true\n * count; may be higher.\n */\n public async estimate(value: string | number): Promise<number> {\n const item = String(value);\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n\n if (native) {\n return native.frequencyEstimate(this.key, item);\n }\n\n const counters = await backend.gridGet(this.key, this.cellsOf(item));\n\n return Math.min(...counters);\n }\n\n /**\n * The most frequent values seen, highest count first. Holds at most `topK`\n * values; `count` defaults to all of them.\n */\n public async top(count = this.topK): Promise<FrequencyEntry[]> {\n const backend = this.context.backend();\n const native = await nativeOf(backend);\n const limit = Math.min(count, this.topK);\n const entries = native\n ? await native.frequencyTop(this.key, limit)\n : await backend.rankedTop(`${this.key}.top`, limit);\n\n return entries.map((entry) => ({ value: entry.member, count: entry.score }));\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAa,mBAAb,MAA8B;CAK5B,AAAO,YACL,AAAmB,KACnB,SACA,AAAmB,SACnB;EAHmB;EAEA;EAEnB,KAAK,QAAQ,QAAQ,SAAS;EAC9B,KAAK,QAAQ,QAAQ,SAAS;EAC9B,KAAK,OAAO,QAAQ,QAAQ;EAE5B,sBAAsB,SAAS,KAAK,KAAK;EACzC,sBAAsB,SAAS,KAAK,KAAK;EACzC,sBAAsB,QAAQ,KAAK,IAAI;CACzC;CAEA,AAAU,QAAQ,MAAwB;EACxC,MAAM,SAAS,SAAS,IAAI;EAE5B,OAAO,MAAM,KACX,EAAE,QAAQ,KAAK,MAAM,IACpB,GAAG,QAAQ,MAAM,KAAK,QAAQ,MAAM,QAAQ,KAAK,KAAK,KAAK,CAC9D;CACF;;;;CAKA,MAAa,IAAI,OAAwB,QAAQ,GAAkB;EACjE,sBAAsB,SAAS,KAAK;EAEpC,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,UAAU,KAAK,QAAQ,QAAQ;EACrC,MAAM,SAAS,MAAM,SAAS,OAAO;EAErC,IAAI,QAAQ;GACV,MAAM,OAAO,aAAa,KAAK,KAAK,MAAM,OAAO;IAC/C,OAAO,KAAK;IACZ,OAAO,KAAK;IACZ,MAAM,KAAK;IACX,KAAK,KAAK,QAAQ;GACpB,CAAC;GAED;EACF;EAEA,MAAM,WAAW,MAAM,QAAQ,QAAQ,KAAK,KAAK,KAAK,QAAQ,IAAI,GAAG,OAAO,EAC1E,KAAK,KAAK,QAAQ,IACpB,CAAC;EAED,MAAM,QAAQ,UAAU,GAAG,KA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QAJgB,SACZ,MAAM,OAAO,aAAa,KAAK,KAAK,KAAK,IACzC,MAAM,QAAQ,UAAU,GAAG,KAAK,IAAI,OAAO,KAAK,EAEtC,CAAC,KAAK,WAAW;GAAE,OAAO,MAAM;GAAQ,OAAO,MAAM;EAAM,EAAE;CAC7E;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"hash.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/hash.ts"],"sourcesContent":["const encoder = new TextEncoder();\n\n/**\n * MurmurHash3 (x86, 32-bit) over the UTF-8 bytes of `input`.\n *\n * Pure and deterministic: the same input and seed give the same hash on every\n * process, platform and release, which matters because the hashes decide where\n * an item lives in a structure stored in a shared cache.\n */\nexport function murmur3(input: string, seed: number): number {\n const bytes = encoder.encode(input);\n const length = bytes.length;\n const blocks = length >> 2;\n let hash = seed >>> 0;\n\n for (let index = 0; index < blocks; index++) {\n const offset = index << 2;\n let block =\n bytes[offset]! |\n (bytes[offset + 1]! << 8) |\n (bytes[offset + 2]! << 16) |\n (bytes[offset + 3]! << 24);\n\n block = Math.imul(block, 0xcc9e2d51);\n block = (block << 15) | (block >>> 17);\n block = Math.imul(block, 0x1b873593);\n\n hash ^= block;\n hash = (hash << 13) | (hash >>> 19);\n hash = (Math.imul(hash, 5) + 0xe6546b64) | 0;\n }\n\n let tail = 0;\n const tailOffset = blocks << 2;\n\n const remainder = length & 3;\n\n if (remainder === 3) {\n tail ^= bytes[tailOffset + 2]! << 16;\n }\n\n if (remainder >= 2) {\n tail ^= bytes[tailOffset + 1]! << 8;\n }\n\n if (remainder >= 1) {\n tail ^= bytes[tailOffset]!;\n tail = Math.imul(tail, 0xcc9e2d51);\n tail = (tail << 15) | (tail >>> 17);\n tail = Math.imul(tail, 0x1b873593);\n hash ^= tail;\n }\n\n hash ^= length;\n hash ^= hash >>> 16;\n hash = Math.imul(hash, 0x85ebca6b);\n hash ^= hash >>> 13;\n hash = Math.imul(hash, 0xc2b2ae35);\n hash ^= hash >>> 16;\n\n return hash >>> 0;\n}\n\n/**\n * Two independent 32-bit hashes of `item`, for double hashing. The second one\n * is forced odd so the probe sequence never collapses onto a few slots.\n */\nexport function hashPair(item: string): [number, number] {\n return [murmur3(item, 0x9747b28c), (murmur3(item, 0x5bd1e995) | 1) >>> 0];\n}\n\n/**\n * The `index`-th probe position of `item` inside `size` slots (enhanced double\n * hashing, so successive positions are well spread even for small `size`).\n */\nexport function probe(hashes: [number, number], index: number, size: number): number {\n const [first, second] = hashes;\n\n return ((first + index * second + index * index) % size) >>> 0;\n}\n\n/**\n * A 64-bit hash of `item` as two unsigned 32-bit halves.\n */\nexport function hash64(item: string): [number, number] {\n return [murmur3(item, 0x1b873593), murmur3(item, 0x85ebca6b)];\n}\n"],"mappings":";AAAA,MAAM,UAAU,IAAI,YAAY;;;;;;;;AAShC,SAAgB,QAAQ,OAAe,MAAsB;CAC3D,MAAM,QAAQ,QAAQ,OAAO,KAAK;CAClC,MAAM,SAAS,MAAM;CACrB,MAAM,SAAS,UAAU;CACzB,IAAI,OAAO,SAAS;CAEpB,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,SAAS;EAC3C,MAAM,SAAS,SAAS;EACxB,IAAI,QACF,MAAM,UACL,MAAM,SAAS,MAAO,IACtB,MAAM,SAAS,MAAO,KACtB,MAAM,SAAS,MAAO;EAEzB,QAAQ,KAAK,KAAK,OAAO,UAAU;EACnC,QAAS,SAAS,KAAO,UAAU;EACnC,QAAQ,KAAK,KAAK,OAAO,SAAU;EAEnC,QAAQ;EACR,OAAQ,QAAQ,KAAO,SAAS;EAChC,OAAQ,KAAK,KAAK,MAAM,CAAC,IAAI,aAAc;CAC7C;CAEA,IAAI,OAAO;CACX,MAAM,aAAa,UAAU;CAE7B,MAAM,YAAY,SAAS;CAE3B,IAAI,cAAc,GAChB,QAAQ,MAAM,aAAa,MAAO;CAGpC,IAAI,aAAa,GACf,QAAQ,MAAM,aAAa,MAAO;CAGpC,IAAI,aAAa,GAAG;EAClB,QAA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AO,SAAS;EAChC,OAAQ,KAAK,KAAK,MAAM,CAAC,IAAI,aAAc;CAC7C;CAEA,IAAI,OAAO;CACX,MAAM,aAAa,UAAU;CAE7B,MAAM,YAAY,SAAS;CAE3B,IAAI,cAAc,GAChB,QAAQ,MAAM,aAAa,MAAO;CAGpC,IAAI,aAAa,GACf,QAAQ,MAAM,aAAa,MAAO;CAGpC,IAAI,aAAa,GAAG;EAClB,QAAQ,MAAM;EACd,OAAO,KAAK,KAAK,MAAM,UAAU;EACjC,OAAQ,QAAQ,KAAO,SAAS;EAChC,OAAO,KAAK,KAAK,MAAM,SAAU;EACjC,QAAQ;CACV;CAEA,QAAQ;CACR,QAAQ,SAAS;CACjB,OAAO,KAAK,KAAK,MAAM,UAAU;CACjC,QAAQ,SAAS;CACjB,OAAO,KAAK,KAAK,MAAM,UAAU;CACjC,QAAQ,SAAS;CAEjB,OAAO,SAAS;AAClB;;;;;AAMA,SAAgB,SAAS,MAAgC;CACvD,OAAO,CAAC,QAAQ,MAAM,UAAU,IAAI,QAAQ,MAAM,UAAU,IAAI,OAAO,CAAC;AAC1E;;;;;AAMA,SAAgB,MAAM,QAA0B,OAAe,MAAsB;CACnF,MAAM,CAAC,OAAO,UAAU;CAExB,QAAS,QAAQ,QAAQ,SAAS,QAAQ,SAAS,SAAU;AAC/D;;;;AAKA,SAAgB,OAAO,MAAgC;CACrD,OAAO,CAAC,QAAQ,MAAM,SAAU,GAAG,QAAQ,MAAM,UAAU,CAAC;AAC9D"}
@@ -1 +1 @@
1
- {"version":3,"file":"hyperloglog.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/hyperloglog.ts"],"sourcesContent":["import { hash64 } from \"./hash\";\n\n/** Register index width: 2^14 = 16384 registers, about 12 KB, standard error 0.81%. */\nexport const HLL_PRECISION = 14;\nexport const HLL_REGISTERS = 1 << HLL_PRECISION;\n\nconst INDEX_SHIFT = 32 - HLL_PRECISION;\nconst HIGH_REMAINDER_BITS = INDEX_SHIFT;\nconst HIGH_REMAINDER_MASK = (1 << HIGH_REMAINDER_BITS) - 1;\nconst MAX_RANK = HIGH_REMAINDER_BITS + 32 + 1;\n\n/**\n * HyperLogLog cardinality estimator over a 64-bit hash.\n *\n * Used by the in-process structures backend; Redis uses its native\n * `PFADD` / `PFCOUNT` instead.\n */\nexport class HyperLogLog {\n public readonly registers: Uint8Array;\n\n public constructor(registers?: Uint8Array) {\n this.registers = registers ?? new Uint8Array(HLL_REGISTERS);\n }\n\n /**\n * Record `item`. Returns true when the estimate may have changed (a register\n * grew), which is also how `PFADD` reports a probably-new item.\n */\n public add(item: string): boolean {\n const [high, low] = hash64(item);\n const index = high >>> INDEX_SHIFT;\n const remainder = high & HIGH_REMAINDER_MASK;\n let rank: number;\n\n if (remainder !== 0) {\n rank = Math.clz32(remainder) - (32 - HIGH_REMAINDER_BITS) + 1;\n } else if (low !== 0) {\n rank = HIGH_REMAINDER_BITS + Math.clz32(low) + 1;\n } else {\n rank = MAX_RANK;\n }\n\n if (rank > this.registers[index]!) {\n this.registers[index] = rank;\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Fold `other` into this counter (register-wise maximum), so the result\n * counts the union of both sets.\n */\n public merge(other: HyperLogLog): this {\n for (let index = 0; index < HLL_REGISTERS; index++) {\n const value = other.registers[index]!;\n\n if (value > this.registers[index]!) {\n this.registers[index] = value;\n }\n }\n\n return this;\n }\n\n /**\n * Estimated number of distinct items.\n */\n public count(): number {\n let sum = 0;\n let zeros = 0;\n\n for (let index = 0; index < HLL_REGISTERS; index++) {\n const value = this.registers[index]!;\n\n sum += 2 ** -value;\n\n if (value === 0) {\n zeros++;\n }\n }\n\n const alpha = 0.7213 / (1 + 1.079 / HLL_REGISTERS);\n const estimate = (alpha * HLL_REGISTERS * HLL_REGISTERS) / sum;\n\n // Small range: linear counting is more accurate while many registers are empty.\n if (estimate <= 2.5 * HLL_REGISTERS && zeros > 0) {\n return Math.round(HLL_REGISTERS * Math.log(HLL_REGISTERS / zeros));\n }\n\n return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
@@ -1 +1 @@
1
- {"version":3,"file":"memory-structures-backend.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/memory-structures-backend.ts"],"sourcesContent":["import { HyperLogLog } from \"./hyperloglog\";\nimport type { CacheStructuresBackend, RankedEntry, StructureWrite } from \"./types\";\n\ntype Slot =\n | { type: \"bits\"; value: Uint8Array; expiresAt?: number }\n | { type: \"grid\"; value: Map<number, number>; expiresAt?: number }\n | { type: \"unique\"; value: HyperLogLog; expiresAt?: number }\n | { type: \"ranked\"; value: Map<string, number>; expiresAt?: number };\n\n/**\n * In-process implementation of the structure primitives, shared by the memory\n * family of drivers. State lives next to the driver's entries and follows its\n * `flush()` and `removeNamespace()`.\n */\nexport class MemoryStructuresBackend implements CacheStructuresBackend {\n protected slots = new Map<string, Slot>();\n\n /**\n * @param parseKey the owning driver's key parser (applies the cache prefix)\n */\n public constructor(protected readonly parseKey: (key: string) => string) {}\n\n /** Drop every structure. */\n public clear() {\n this.slots.clear();\n }\n\n /** Drop every structure whose parsed key starts with `prefix`. */\n public clearPrefix(prefix: string) {\n for (const key of [...this.slots.keys()]) {\n if (key.startsWith(prefix)) {\n this.slots.delete(key);\n }\n }\n }\n\n public async bitSet(key: string, offsets: number[], options?: StructureWrite) {\n const slot = this.slot(key, \"bits\", () => new Uint8Array(0), options);\n const maxOffset = offsets.reduce((max, offset) => Math.max(max, offset), 0);\n const needed = (maxOffset >> 3) + 1;\n\n if (slot.value.length < needed) {\n const grown = new Uint8Array(Math.max(needed, slot.value.length * 2));\n\n grown.set(slot.value);\n slot.value = grown;\n }\n\n return offsets.map((offset) => {\n const mask = 1 << (offset & 7);\n const byte = slot.value[offset >> 3] ?? 0;\n const previous = (byte & mask) !== 0;\n\n slot.value[offset >> 3] = byte | mask;\n\n return previous;\n });\n }\n\n public async bitGet(key: string, offsets: number[]) {\n const slot = this.find(key, \"bits\");\n\n return offsets.map((offset) => {\n const byte = slot?.value[offset >> 3];\n\n return byte !== undefined && (byte & (1 << (offset & 7))) !== 0;\n });\n }\n\n public async gridAdd(key: string, cells: number[], delta: number, options?: StructureWrite) {\n const slot = this.slot(key, \"grid\", () => new Map<number, number>(), options);\n\n return cells.map((cell) => {\n const next = Math.max(0, (slot.value.get(cell) ?? 0) + delta);\n\n if (next === 0) {\n slot.value.delete(cell);\n } else {\n slot.value.set(cell, next);\n }\n\n return next;\n });\n }\n\n public async gridGet(key: string, cells: number[]) {\n const slot = this.find(key, \"grid\");\n\n return cells.map((cell) => slot?.value.get(cell) ?? 0);\n }\n\n public async uniqueAdd(key: string, member: string, options?: StructureWrite) {\n return this.slot(key, \"unique\", () => new HyperLogLog(), options).value.add(member);\n }\n\n public async uniqueCount(keys: string[]) {\n const merged = new HyperLogLog();\n\n for (const key of keys) {\n const slot = this.find(key, \"unique\");\n\n if (slot) {\n merged.merge(slot.value);\n }\n }\n\n return merged.count();\n }\n\n public async rankedSet(\n key: string,\n member: string,\n score: number,\n capacity: number,\n options?: StructureWrite,\n ) {\n const slot = this.slot(key, \"ranked\", () => new Map<string, number>(), options);\n\n slot.value.set(member, score);\n\n if (slot.value.size > capacity) {\n let lowest: string | undefined;\n\n for (const [candidate, candidateScore] of slot.value) {\n if (lowest === undefined || candidateScore < slot.value.get(lowest)!) {\n lowest = candidate;\n }\n }\n\n slot.value.delete(lowest!);\n }\n }\n\n public async rankedTop(key: string, count: number): Promise<RankedEntry[]> {\n const slot = this.find(key, \"ranked\");\n\n if (!slot) {\n return [];\n }\n\n return [...slot.value]\n .map(([member, score]) => ({ member, score }))\n .sort((a, b) => b.score - a.score || (a.member < b.member ? -1 : 1))\n .slice(0, count);\n }\n\n protected find<T extends Slot[\"type\"]>(\n key: string,\n type: T,\n ): Extract<Slot, { type: T }> | undefined {\n const parsed = this.parseKey(key);\n const slot = this.slots.get(parsed);\n\n if (!slot) {\n return undefined;\n }\n\n if (slot.expiresAt !== undefined && slot.expiresAt <= Date.now()) {\n this.slots.delete(parsed);\n\n return undefined;\n }\n\n return slot.type === type ? (slot as Extract<Slot, { type: T }>) : undefined;\n }\n\n protected slot<T extends Slot[\"type\"]>(\n key: string,\n type: T,\n create: () => Extract<Slot, { type: T }>[\"value\"],\n options?: StructureWrite,\n ): Extract<Slot, { type: T }> {\n const existing = this.find(key, type);\n\n if (existing) {\n return existing;\n }\n\n const slot = { type, value: create() } as Slot;\n\n if (options?.ttl && Number.isFinite(options.ttl)) {\n slot.expiresAt = Date.now() + options.ttl * 1000;\n }\n\n this.slots.set(this.parseKey(key), slot);\n\n return slot as Extract<Slot, { type: T }>;\n }\n}\n"],"mappings":";;;;;;;;AAcA,IAAa,0BAAb,MAAuE;;;;CAMrE,AAAO,YAAY,AAAmB,UAAmC;EAAnC;+BALpB,IAAI,IAAkB;CAKkC;;CAG1E,AAAO,QAAQ;EACb,KAAK,MAAM,MAAM;CACnB;;CAGA,AAAO,YAAY,QAAgB;EACjC,KAAK,MAAM,OAAO,CAAC,GAAG,KAAK,MAAM,KAAK,CAAC,GACrC,IAAI,IAAI,WAAW,MAAM,GACvB,KAAK,MAAM,OAAO,GAAG;CAG3B;CAEA,MAAa,OAAO,KAAa,SAAmB,SAA0B;EAC5E,MAAM,OAAO,KAAK,KAAK,KAAK,8BAAc,IAAI,WAAW,CAAC,GAAG,OAAO;EAEpE,MAAM,UADY,QAAQ,QAAQ,KAAK,WAAW,KAAK,IAAI,KAAK,MAAM,GAAG,CACjD,KAAK,KAAK;EAElC,IAAI,KAAK,MAAM,SAAS,QAAQ;GAC9B,MAAM,QAAQ,IAAI,WAAW,KAAK,IAAI,QAAQ,KAAK,MAAM,SAAS,CAAC,CAAC;GAEpE,MAAM,IAAI,KAAK,KAAK;GACpB,KAAK,QAAQ;EACf;EAEA,OAAO,QAAQ,KAAK,WAAW;GAC7B,MAAM,OAAO,MAAM,SAAS;GAC5B,MAAM,OAAO,KAAK,MAAM,UAAU,MAAM;GACxC,MAAM,YAAY,OAAO,UAAU;GAEnC,KAAK,MAAM,UAAU,KAAK,OAAO;GAEjC,OAAO;E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AAO,UAAU;GAC9B,IAAI;GAEJ,KAAK,MAAM,CAAC,WAAW,mBAAmB,KAAK,OAC7C,IAAI,WAAW,UAAa,iBAAiB,KAAK,MAAM,IAAI,MAAM,GAChE,SAAS;GAIb,KAAK,MAAM,OAAO,MAAO;EAC3B;CACF;CAEA,MAAa,UAAU,KAAa,OAAuC;EACzE,MAAM,OAAO,KAAK,KAAK,KAAK,QAAQ;EAEpC,IAAI,CAAC,MACH,OAAO,CAAC;EAGV,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CACnB,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ;EAAM,EAAE,CAAC,CAC7C,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,CAAC,CACnE,MAAM,GAAG,KAAK;CACnB;CAEA,AAAU,KACR,KACA,MACwC;EACxC,MAAM,SAAS,KAAK,SAAS,GAAG;EAChC,MAAM,OAAO,KAAK,MAAM,IAAI,MAAM;EAElC,IAAI,CAAC,MACH;EAGF,IAAI,KAAK,cAAc,UAAa,KAAK,aAAa,KAAK,IAAI,GAAG;GAChE,KAAK,MAAM,OAAO,MAAM;GAExB;EACF;EAEA,OAAO,KAAK,SAAS,OAAQ,OAAsC;CACrE;CAEA,AAAU,KACR,KACA,MACA,QACA,SAC4B;EAC5B,MAAM,WAAW,KAAK,KAAK,KAAK,IAAI;EAEpC,IAAI,UACF,OAAO;EAGT,MAAM,OAAO;GAAE;GAAM,OAAO,OAAO;EAAE;EAErC,IAAI,SAAS,OAAO,OAAO,SAAS,QAAQ,GAAG,GAC7C,KAAK,YAAY,KAAK,IAAI,IAAI,QAAQ,MAAM;EAG9C,KAAK,MAAM,IAAI,KAAK,SAAS,GAAG,GAAG,IAAI;EAEvC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"memory-structures-backend.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/structures/memory-structures-backend.ts"],"mappings":";;;;;;;;AAcA,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