@warlock.js/cache 5.53.1 → 5.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/cjs/index.cjs +158 -7
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/cache-manager.d.mts +12 -0
  5. package/esm/cache-manager.d.mts.map +1 -1
  6. package/esm/cache-manager.mjs +18 -0
  7. package/esm/cache-manager.mjs.map +1 -1
  8. package/esm/drivers/base-cache-driver.d.mts +11 -0
  9. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  10. package/esm/drivers/base-cache-driver.mjs +43 -6
  11. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  12. package/esm/drivers/file-cache-driver.d.mts +7 -0
  13. package/esm/drivers/file-cache-driver.d.mts.map +1 -1
  14. package/esm/drivers/file-cache-driver.mjs +14 -0
  15. package/esm/drivers/file-cache-driver.mjs.map +1 -1
  16. package/esm/drivers/lru-memory-cache-driver.d.mts +4 -0
  17. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  18. package/esm/drivers/lru-memory-cache-driver.mjs +13 -0
  19. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  20. package/esm/drivers/memory-cache-driver.d.mts +4 -0
  21. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  22. package/esm/drivers/memory-cache-driver.mjs +13 -0
  23. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  24. package/esm/drivers/mock-cache-driver.d.mts +4 -0
  25. package/esm/drivers/mock-cache-driver.d.mts.map +1 -1
  26. package/esm/drivers/mock-cache-driver.mjs +9 -0
  27. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  28. package/esm/drivers/null-cache-driver.d.mts +4 -0
  29. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  30. package/esm/drivers/null-cache-driver.mjs +6 -0
  31. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  32. package/esm/drivers/pg-cache-driver.d.mts +4 -0
  33. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  34. package/esm/drivers/pg-cache-driver.mjs +8 -0
  35. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  36. package/esm/drivers/redis-cache-driver.d.mts +7 -0
  37. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  38. package/esm/drivers/redis-cache-driver.mjs +18 -0
  39. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  40. package/esm/index.d.mts +2 -2
  41. package/esm/index.mjs +2 -2
  42. package/esm/scoped-cache.d.mts.map +1 -1
  43. package/esm/scoped-cache.mjs +5 -2
  44. package/esm/scoped-cache.mjs.map +1 -1
  45. package/esm/types.d.mts +53 -0
  46. package/esm/types.d.mts.map +1 -1
  47. package/esm/types.mjs.map +1 -1
  48. package/esm/utils.d.mts +6 -0
  49. package/esm/utils.d.mts.map +1 -1
  50. package/esm/utils.mjs +13 -1
  51. package/esm/utils.mjs.map +1 -1
  52. package/llms-full.txt +6 -0
  53. package/package.json +4 -4
  54. package/skills/cache-basics/SKILL.md +1 -0
  55. package/skills/configure-set-options/SKILL.md +2 -0
  56. package/skills/use-cache-namespace/SKILL.md +1 -0
  57. package/skills/use-cache-similarity/SKILL.md +1 -0
  58. package/skills/use-swr/SKILL.md +1 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,25 @@ All notable changes to `@warlock.js/cache` are documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `@warlock.js/*` packages are released in lockstep — every package shares the same version number, so a version below may list only the changes that affected this package.
6
6
 
7
+ ## 5.54.0 - 2026-11-16
8
+
9
+ ### Added
10
+
11
+ - `ttlJitter` on `set()`, `remember()` and `swr()` options spreads a relative TTL by up to that many percent either way for each write (`{ ttl: "1h", ttlJitter: 10 }` expires in 54 to 66 minutes), so entries written together no longer expire and miss together. It is skipped for `expiresAt`, `Infinity` and `0`.
12
+ - `swr({ failSafe: true })` returns the stale value when the refresh throws. A caller in the stale window then waits for the refresh (callers of one key share it); the failure is logged and emitted as an `error` event, and the next read tries again.
13
+ - `similar()` accepts a `filter({ key, value })` predicate that runs before `threshold` and `topK`, so `topK` counts only in-scope entries and a recall needs one query. The memory, LRU and memory-extended drivers honour it; `pg` ignores it, so callers that need a guarantee keep checking the returned hits. `cache.namespace(...)` scopes pass their prefix as the filter.
14
+ - `listKeys(namespace)` on the `memory`, `lru`, `memoryExtended`, `file`, `pg`, `redis`, `mock` and `null` drivers (optional on the `CacheDriver` interface): the live keys under a namespace, in the form `get()` and `remove()` accept, `globalPrefix` removed. `CacheManager` forwards it and adds `supportsListKeys()`. Custom drivers can ship it and use the new protected `unprefixKey()` and `inNamespace()` helpers.
15
+
16
+ ### Changed
17
+
18
+ - `has()` uses the driver's `exists()`, so no value is read or parsed. The `hit` and `miss` events it emits now carry the key only, without `value`; a listener that read `event.value` for `has()` calls gets `undefined`.
19
+ - Raised the `@mongez` dependency ranges to the 2026-11-16 releases (reinforcements 4.1.0).
20
+
21
+ ### Documentation
22
+
23
+ - The set-options, SWR, similarity and driver-interface pages and the matching skills describe `ttlJitter`, `failSafe`, the similarity `filter` and the new `has()` events.
24
+ - Cache driver interface and custom-driver pages, and the `use-cache-namespace` skill: `listKeys()`.
25
+
7
26
  ## 5.53.0 - 2026-11-11
8
27
 
9
28
  ### Upgrading
package/cjs/index.cjs CHANGED
@@ -248,6 +248,18 @@ function resolveTtl(ttl, expiresAt, fallback) {
248
248
  return fallback;
249
249
  }
250
250
  /**
251
+ * Spread a relative TTL by up to `jitterPercent` percent either way. An
252
+ * absolute deadline (`expiresAt`), an infinite or zero TTL, and a missing or
253
+ * non-positive percentage leave the TTL as it is. The result is at least 1.
254
+ */
255
+ function applyTtlJitter(ttl, jitterPercent, expiresAt) {
256
+ if (!jitterPercent || jitterPercent <= 0 || expiresAt !== void 0) return ttl;
257
+ if (!Number.isFinite(ttl) || ttl <= 0) return ttl;
258
+ const spread = Math.min(jitterPercent, 100) / 100;
259
+ const factor = 1 + (Math.random() * 2 - 1) * spread;
260
+ return Math.max(1, Math.round(ttl * factor));
261
+ }
262
+ /**
251
263
  * Combine any number of tag lists into a single deduped array, dropping
252
264
  * `undefined`/empty entries. Returns `undefined` when no tags survive — lets
253
265
  * callers skip emitting empty `tags: []` into option payloads.
@@ -1045,9 +1057,12 @@ var ScopedCache = class ScopedCache {
1045
1057
  * matches but other scopes do, the caller will see fewer hits than `topK`.
1046
1058
  */
1047
1059
  async similar(vector, options) {
1048
- const hits = await this.source.similar(vector, options);
1049
1060
  const parsedPrefix = this.source.parseKey(this.prefix);
1050
- return hits.filter((hit) => hit.key === parsedPrefix || hit.key.startsWith(parsedPrefix + "."));
1061
+ const inScope = (key) => key === parsedPrefix || key.startsWith(parsedPrefix + ".");
1062
+ return (await this.source.similar(vector, {
1063
+ ...options,
1064
+ filter: (hit) => inScope(hit.key) && (options.filter?.(hit) ?? true)
1065
+ })).filter((hit) => inScope(hit.key));
1051
1066
  }
1052
1067
  /**
1053
1068
  * Build the source-side key by prepending the scope prefix. Object keys
@@ -2050,6 +2065,24 @@ var CacheManager = class {
2050
2065
  }
2051
2066
  /**
2052
2067
  * {@inheritdoc}
2068
+ *
2069
+ * Reports an empty list when the current driver cannot enumerate its keys,
2070
+ * so check `supportsListKeys()` first when the difference matters.
2071
+ */
2072
+ async listKeys(namespace) {
2073
+ this.ensureDriverInitialized();
2074
+ return this.currentDriver.listKeys?.(namespace) ?? [];
2075
+ }
2076
+ /**
2077
+ * Whether the current driver can list the keys of a namespace
2078
+ * ({@link listKeys}).
2079
+ */
2080
+ supportsListKeys() {
2081
+ this.ensureDriverInitialized();
2082
+ return typeof this.currentDriver.listKeys === "function";
2083
+ }
2084
+ /**
2085
+ * {@inheritdoc}
2053
2086
  */
2054
2087
  async flush() {
2055
2088
  this.ensureDriverInitialized();
@@ -2963,6 +2996,25 @@ var BaseCacheDriver = class {
2963
2996
  return parseCacheKey(key, this.options);
2964
2997
  }
2965
2998
  /**
2999
+ * The key as a caller wrote it: `parseKey()` output with the configured
3000
+ * `globalPrefix` removed, so the result can go back through `get()` /
3001
+ * `remove()` without the prefix being applied twice.
3002
+ */
3003
+ unprefixKey(parsedKey) {
3004
+ const configured = this.options.globalPrefix;
3005
+ const prefix = typeof configured === "function" ? configured() : configured;
3006
+ if (!prefix) return parsedKey;
3007
+ const lead = (0, _mongez_reinforcements.rtrim)(prefix, ".") + ".";
3008
+ return parsedKey.startsWith(lead) ? parsedKey.slice(lead.length) : parsedKey;
3009
+ }
3010
+ /**
3011
+ * Whether a parsed `key` sits in the parsed `namespace` (the namespace key
3012
+ * itself or `<namespace>.*`); an empty namespace matches everything.
3013
+ */
3014
+ inNamespace(key, namespace) {
3015
+ return namespace === "" || key === namespace || key.startsWith(namespace + ".");
3016
+ }
3017
+ /**
2966
3018
  * {@inheritdoc}
2967
3019
  */
2968
3020
  setOptions(options) {
@@ -3025,7 +3077,7 @@ var BaseCacheDriver = class {
3025
3077
  resolveSetOptions(ttlOrOptions) {
3026
3078
  const options = normalizeToOptions(ttlOrOptions);
3027
3079
  return {
3028
- ttl: resolveTtl(options.ttl, options.expiresAt, this.ttl),
3080
+ ttl: applyTtlJitter(resolveTtl(options.ttl, options.expiresAt, this.ttl), options.ttlJitter, options.expiresAt),
3029
3081
  tags: options.tags,
3030
3082
  onConflict: options.onConflict ?? "upsert",
3031
3083
  vector: options.vector,
@@ -3156,7 +3208,9 @@ var BaseCacheDriver = class {
3156
3208
  * {@inheritdoc}
3157
3209
  */
3158
3210
  async has(key) {
3159
- return await this.get(key) !== null;
3211
+ const found = await this.exists(key);
3212
+ await this.emit(found ? "hit" : "miss", { key: this.parseKey(key) });
3213
+ return found;
3160
3214
  }
3161
3215
  /**
3162
3216
  * Run `task` once per key at a time: concurrent callers for the same
@@ -3206,7 +3260,8 @@ var BaseCacheDriver = class {
3206
3260
  if (typeof ttlOrOptions === "number" || typeof ttlOrOptions === "string") return { ttl: ttlOrOptions };
3207
3261
  return {
3208
3262
  ttl: ttlOrOptions.ttl,
3209
- tags: ttlOrOptions.tags
3263
+ tags: ttlOrOptions.tags,
3264
+ ttlJitter: ttlOrOptions.ttlJitter
3210
3265
  };
3211
3266
  }
3212
3267
  /**
@@ -3233,6 +3288,18 @@ var BaseCacheDriver = class {
3233
3288
  const isExpired = entry?.expiresAt !== void 0 && entry.expiresAt <= now;
3234
3289
  if (!entry || isExpired) return this.singleFlight(this.swrFetchInFlight, parsedKey, () => this.swrFetchAndStore(key, options, callback, freshSeconds, staleSeconds));
3235
3290
  if (entry.staleAt === void 0 || entry.staleAt > now) return entry.data;
3291
+ if (options.failSafe) return this.singleFlight(this.swrFetchInFlight, parsedKey, async () => {
3292
+ try {
3293
+ return await this.swrFetchAndStore(key, options, callback, freshSeconds, staleSeconds);
3294
+ } catch (error) {
3295
+ this.logError(`SWR refresh failed for ${parsedKey}, serving the stale value`, error);
3296
+ await this.emit("error", {
3297
+ key: parsedKey,
3298
+ error
3299
+ });
3300
+ return entry.data;
3301
+ }
3302
+ });
3236
3303
  this.scheduleSwrRefresh(parsedKey, key, options, callback, freshSeconds, staleSeconds);
3237
3304
  return entry.data;
3238
3305
  }
@@ -3279,7 +3346,8 @@ var BaseCacheDriver = class {
3279
3346
  await this.set(key, result, {
3280
3347
  ttl: staleSeconds,
3281
3348
  staleAt: Date.now() + freshSeconds * 1e3,
3282
- tags: options.tags
3349
+ tags: options.tags,
3350
+ ttlJitter: options.ttlJitter
3283
3351
  });
3284
3352
  return result;
3285
3353
  }
@@ -3298,7 +3366,8 @@ var BaseCacheDriver = class {
3298
3366
  await this.set(key, result, {
3299
3367
  ttl: staleSeconds,
3300
3368
  staleAt: Date.now() + freshSeconds * 1e3,
3301
- tags: options.tags
3369
+ tags: options.tags,
3370
+ ttlJitter: options.ttlJitter
3302
3371
  });
3303
3372
  } catch (error) {
3304
3373
  this.logError(`SWR background refresh failed for ${parsedKey}`, error);
@@ -3758,6 +3827,20 @@ var FileCacheDriver = class extends BaseCacheDriver {
3758
3827
  /**
3759
3828
  * {@inheritdoc}
3760
3829
  *
3830
+ * Reads the entry directory names, so a key whose entry expired but was
3831
+ * not read since is still listed; `get()` reports it missing.
3832
+ */
3833
+ async listKeys(namespace) {
3834
+ const parsed = this.parseKey(namespace);
3835
+ try {
3836
+ return (await (0, _warlock_js_fs.listDirectoriesAsync)(this.containedPath("")).catch(() => [])).map((entryPath) => this.decodeKeySegment(path.default.basename(entryPath))).filter((key) => this.inNamespace(key, parsed)).map((key) => this.unprefixKey(key));
3837
+ } catch {
3838
+ return [];
3839
+ }
3840
+ }
3841
+ /**
3842
+ * {@inheritdoc}
3843
+ *
3761
3844
  * `onConflict: "create"` is exclusive (temp file + hard link, so `lock()`
3762
3845
  * is safe across concurrent writers). `onConflict: "update"` is NOT atomic:
3763
3846
  * the existence probe and the write are separate steps.
@@ -4242,6 +4325,15 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
4242
4325
  /**
4243
4326
  * {@inheritdoc}
4244
4327
  */
4328
+ async listKeys(namespace) {
4329
+ const parsed = this.parseKey(namespace);
4330
+ const keys = [];
4331
+ for (const [key, node] of this.cache) if (this.inNamespace(key, parsed) && !node.isExpired) keys.push(this.unprefixKey(key));
4332
+ return keys;
4333
+ }
4334
+ /**
4335
+ * {@inheritdoc}
4336
+ */
4245
4337
  structuresBackend() {
4246
4338
  this.structureStore ??= new MemoryStructuresBackend((key) => this.parseKey(key));
4247
4339
  return this.structureStore;
@@ -4567,6 +4659,10 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
4567
4659
  if (!node.vector) continue;
4568
4660
  if (node.isExpired) continue;
4569
4661
  if (tagFilter && !tagFilter.has(parsedKey)) continue;
4662
+ if (options.filter && !options.filter({
4663
+ key: parsedKey,
4664
+ value: node.value
4665
+ })) continue;
4570
4666
  const score = cosineSimilarity(vector, node.vector);
4571
4667
  if (options.threshold !== void 0 && score < options.threshold) continue;
4572
4668
  let value = node.value;
@@ -4741,6 +4837,15 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
4741
4837
  }
4742
4838
  /**
4743
4839
  * {@inheritdoc}
4840
+ */
4841
+ async listKeys(namespace) {
4842
+ const parsed = this.parseKey(namespace);
4843
+ const keys = [];
4844
+ for (const key of [...this.entries.keys()]) if (this.inNamespace(key, parsed) && this.readLive(key)) keys.push(this.unprefixKey(key));
4845
+ return keys;
4846
+ }
4847
+ /**
4848
+ * {@inheritdoc}
4744
4849
  *
4745
4850
  * The conditional check and the write run with no `await` in between, so
4746
4851
  * `onConflict` decisions are atomic within the process.
@@ -5004,6 +5109,10 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
5004
5109
  if (tagFilter && !tagFilter.has(parsedKey)) continue;
5005
5110
  const entry = this.readLive(parsedKey);
5006
5111
  if (!entry) continue;
5112
+ if (options.filter && !options.filter({
5113
+ key: parsedKey,
5114
+ value: entry.data
5115
+ })) continue;
5007
5116
  const value = cloneValue(entry.data);
5008
5117
  const score = cosineSimilarity(vector, stored);
5009
5118
  if (options.threshold !== void 0 && score < options.threshold) continue;
@@ -5127,6 +5236,15 @@ var MockCacheDriver = class extends BaseCacheDriver {
5127
5236
  this.log("cleared", parsed);
5128
5237
  }
5129
5238
  /**
5239
+ * {@inheritdoc}
5240
+ */
5241
+ async listKeys(namespace) {
5242
+ const parsed = this.parseKey(namespace);
5243
+ this.recordCall("listKeys", parsed, [namespace]);
5244
+ const now = Date.now();
5245
+ return [...this.storage.entries()].filter(([key, data]) => this.inNamespace(key, parsed) && (data.expiresAt === void 0 || data.expiresAt > now)).map(([key]) => this.unprefixKey(key));
5246
+ }
5247
+ /**
5130
5248
  * Standard `set` with full `onConflict` support. Honors scope-default TTL
5131
5249
  * via {@link BaseCacheDriver.resolveSetOptions}.
5132
5250
  */
@@ -5440,6 +5558,12 @@ var NullCacheDriver = class extends BaseCacheDriver {
5440
5558
  return this;
5441
5559
  }
5442
5560
  /**
5561
+ * {@inheritdoc}
5562
+ */
5563
+ async listKeys(_namespace) {
5564
+ return [];
5565
+ }
5566
+ /**
5443
5567
  * The key as it may appear in a log line: parsed, with email addresses masked
5444
5568
  */
5445
5569
  loggableKey(key) {
@@ -6135,6 +6259,14 @@ var PgCacheDriver = class extends BaseCacheDriver {
6135
6259
  }
6136
6260
  /**
6137
6261
  * {@inheritdoc}
6262
+ */
6263
+ async listKeys(namespace) {
6264
+ const parsed = this.parseKey(namespace);
6265
+ const t = this.table;
6266
+ return (parsed === "" ? await this.pgClient.query(`SELECT key FROM ${t} WHERE (expires_at IS NULL OR expires_at > now())`) : await this.pgClient.query(`SELECT key FROM ${t} WHERE (key = $1 OR key LIKE $2 ESCAPE '\\') AND (expires_at IS NULL OR expires_at > now())`, [parsed, `${parsed.replace(/\\/g, "\\\\").replace(/_/g, "\\_").replace(/%/g, "\\%")}.%`])).rows.map((row) => this.unprefixKey(row.key));
6267
+ }
6268
+ /**
6269
+ * {@inheritdoc}
6138
6270
  *
6139
6271
  * Honors `globalPrefix` — when configured, scopes the flush to entries
6140
6272
  * under the prefix rather than truncating the entire table (which could
@@ -6346,6 +6478,24 @@ var RedisCacheDriver = class extends BaseCacheDriver {
6346
6478
  return deleted;
6347
6479
  }
6348
6480
  /**
6481
+ * {@inheritdoc}
6482
+ *
6483
+ * Walks the keyspace with `SCAN` (never `KEYS`), matching the namespace key
6484
+ * itself plus `<namespace>.*`.
6485
+ */
6486
+ async listKeys(namespace) {
6487
+ if (!this.client) return [];
6488
+ const parsed = this.parseKey(namespace);
6489
+ const escaped = parsed.replace(/[\\*?[\]]/g, "\\$&");
6490
+ const found = /* @__PURE__ */ new Set();
6491
+ if (escaped !== "" && await this.client.exists(parsed)) found.add(parsed);
6492
+ for await (const scanned of this.client.scanIterator({
6493
+ MATCH: escaped === "" ? "*" : `${escaped}.*`,
6494
+ COUNT: 100
6495
+ })) for (const key of Array.isArray(scanned) ? scanned : [scanned]) found.add(key);
6496
+ return [...found].map((key) => this.unprefixKey(key));
6497
+ }
6498
+ /**
6349
6499
  * Delete keys with `UNLINK` (non-blocking free), falling back to `DEL` when
6350
6500
  * the client lacks it. Returns the number of keys removed.
6351
6501
  */
@@ -6867,6 +7017,7 @@ exports.RedisStructuresBackend = RedisStructuresBackend;
6867
7017
  exports.ScopedCache = ScopedCache;
6868
7018
  exports.TaggedCache = TaggedCache;
6869
7019
  exports.TaggedScopedCache = TaggedScopedCache;
7020
+ exports.applyTtlJitter = applyTtlJitter;
6870
7021
  exports.cache = cache;
6871
7022
  exports.cached = cached;
6872
7023
  exports.cosineSimilarity = cosineSimilarity;