@warlock.js/cache 5.52.0 → 5.53.1

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 (64) 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/cached/auto-key.d.mts +3 -1
  5. package/esm/cached/auto-key.d.mts.map +1 -1
  6. package/esm/cached/auto-key.mjs +9 -4
  7. package/esm/cached/auto-key.mjs.map +1 -1
  8. package/esm/drivers/base-cache-driver.d.mts +40 -3
  9. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  10. package/esm/drivers/base-cache-driver.mjs +57 -7
  11. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  12. package/esm/drivers/clone-value.mjs +17 -0
  13. package/esm/drivers/clone-value.mjs.map +1 -0
  14. package/esm/drivers/file-cache-driver.d.mts +40 -2
  15. package/esm/drivers/file-cache-driver.d.mts.map +1 -1
  16. package/esm/drivers/file-cache-driver.mjs +142 -18
  17. package/esm/drivers/file-cache-driver.mjs.map +1 -1
  18. package/esm/drivers/in-memory-tag-index.d.mts +5 -0
  19. package/esm/drivers/in-memory-tag-index.d.mts.map +1 -1
  20. package/esm/drivers/in-memory-tag-index.mjs +17 -0
  21. package/esm/drivers/in-memory-tag-index.mjs.map +1 -1
  22. package/esm/drivers/lru-memory-cache-driver.d.mts +18 -1
  23. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  24. package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
  25. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  26. package/esm/drivers/memory-cache-driver.d.mts +16 -1
  27. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  28. package/esm/drivers/memory-cache-driver.mjs +34 -5
  29. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  30. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  31. package/esm/drivers/null-cache-driver.mjs +22 -12
  32. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  33. package/esm/drivers/pg-cache-driver.d.mts +19 -0
  34. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  35. package/esm/drivers/pg-cache-driver.mjs +52 -26
  36. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  37. package/esm/drivers/redis-cache-driver.d.mts +29 -0
  38. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  39. package/esm/drivers/redis-cache-driver.mjs +70 -36
  40. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  41. package/esm/index.d.mts +2 -2
  42. package/esm/index.mjs +2 -2
  43. package/esm/tag-sample.mjs +16 -0
  44. package/esm/tag-sample.mjs.map +1 -0
  45. package/esm/tagged-cache.d.mts +15 -0
  46. package/esm/tagged-cache.d.mts.map +1 -1
  47. package/esm/tagged-cache.mjs +31 -10
  48. package/esm/tagged-cache.mjs.map +1 -1
  49. package/esm/types.d.mts +24 -5
  50. package/esm/types.d.mts.map +1 -1
  51. package/esm/types.mjs.map +1 -1
  52. package/esm/utils.d.mts +20 -1
  53. package/esm/utils.d.mts.map +1 -1
  54. package/esm/utils.mjs +42 -3
  55. package/esm/utils.mjs.map +1 -1
  56. package/llms-full.txt +9 -6
  57. package/llms.txt +1 -1
  58. package/package.json +3 -3
  59. package/skills/cache-basics/SKILL.md +1 -1
  60. package/skills/pick-cache-driver/SKILL.md +1 -1
  61. package/skills/use-cache-namespace/SKILL.md +1 -0
  62. package/skills/use-cache-tags/SKILL.md +1 -1
  63. package/skills/use-cache-utils/SKILL.md +4 -2
  64. package/skills/use-cached-hof/SKILL.md +1 -1
package/esm/utils.mjs CHANGED
@@ -4,10 +4,49 @@ import ms from "ms";
4
4
 
5
5
  //#region ../../packages/cache/src/utils.ts
6
6
  /**
7
- * Make a proper key for the cache
7
+ * Characters that `parseCacheKey` strips or turns into the `.` separator.
8
+ * Inside a value they would make two different keys equal.
9
+ */
10
+ const KEY_SEPARATOR_CHARACTERS = /[%.,:{}"[\]]/g;
11
+ /**
12
+ * Escape a value for use as ONE segment of a cache key or namespace: the
13
+ * characters the key format treats as separators or strips (`.` `,` `:`
14
+ * `{` `}` `"` `[` `]`, and `%` itself) are percent-encoded, so the value can
15
+ * never reach into another key or namespace. Values without those
16
+ * characters are returned unchanged.
17
+ *
18
+ * Use it for request-derived text (slugs, search terms, ids from a client).
19
+ *
20
+ * @example
21
+ * cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);
22
+ * // slug "acme.billing" → namespace "tenant.acme%2Ebilling", never inside "tenant.acme"
23
+ */
24
+ function escapeCacheKeySegment(value) {
25
+ return value.replace(KEY_SEPARATOR_CHARACTERS, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
26
+ }
27
+ /**
28
+ * Escape every string (and object key) inside an object key, so a value that
29
+ * contains a separator cannot be read as two segments. Values without
30
+ * separator characters keep their exact previous encoding.
31
+ */
32
+ function escapeKeyObject(value) {
33
+ if (typeof value === "string") return escapeCacheKeySegment(value);
34
+ if (Array.isArray(value)) return value.map(escapeKeyObject);
35
+ if (value === null || typeof value !== "object" || value instanceof Date) return value;
36
+ const escaped = Object.create(null);
37
+ for (const [name, child] of Object.entries(value)) escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);
38
+ return escaped;
39
+ }
40
+ /**
41
+ * Make a proper key for the cache.
42
+ *
43
+ * String keys are used as they are (`:` and `,` become `.`; `{}"[]` are
44
+ * removed). In an object key, separator characters inside the object's keys
45
+ * and string values are escaped first (see {@link escapeCacheKeySegment}),
46
+ * so `{ a: "b.c" }` and `{ a: "b", c: "" }` are different keys.
8
47
  */
9
48
  function parseCacheKey(key, options = {}) {
10
- if (typeof key === "object") key = JSON.stringify(key);
49
+ if (typeof key === "object") key = JSON.stringify(escapeKeyObject(key));
11
50
  key = key.replace(/[{}"[\]]/g, "").replaceAll(/[:,]/g, ".");
12
51
  const cachePrefix = typeof options.globalPrefix === "function" ? options.globalPrefix() : options.globalPrefix;
13
52
  return rtrim(String(cachePrefix ? rtrim(cachePrefix, ".") + "." + key : key), ".");
@@ -259,5 +298,5 @@ let CACHE_FOR = /* @__PURE__ */ function(CACHE_FOR) {
259
298
  }({});
260
299
 
261
300
  //#endregion
262
- export { CACHE_FOR, cosineSimilarity, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
301
+ export { CACHE_FOR, cosineSimilarity, escapeCacheKeySegment, expiresAtToTtl, injectTags, mergeTagSets, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, parseTtl, redactCredentials, resolveTtl, safeErrorInfo };
263
302
  //# sourceMappingURL=utils.mjs.map
package/esm/utils.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"sourcesContent":["import { rtrim } from \"@mongez/reinforcements\";\nimport ms, { type StringValue } from \"ms\";\nimport type { CacheKey, CacheSetOptions, CacheTtl, RememberOptions } from \"./types\";\nimport { CacheConfigurationError } from \"./types\";\n\n/**\n * Make a proper key for the cache\n */\nexport function parseCacheKey(\n key: CacheKey,\n options: { globalPrefix?: string | (() => string) } = {},\n): string {\n if (typeof key === \"object\") {\n key = JSON.stringify(key);\n }\n\n // remove any curly braces and double quotes along with []\n key = key.replace(/[{}\"[\\]]/g, \"\").replaceAll(/[:,]/g, \".\");\n\n const cachePrefix =\n typeof options.globalPrefix === \"function\" ? options.globalPrefix() : options.globalPrefix;\n\n return rtrim(String(cachePrefix ? rtrim(cachePrefix, \".\") + \".\" + key : key), \".\");\n}\n\n/**\n * Parse a TTL value into seconds.\n *\n * Accepts:\n * - a number (seconds) — fractions are rounded UP to whole seconds\n * (so Redis `EX` never receives a fraction); `0` means \"no expiry\"\n * - `Infinity` — no expiration, returned unchanged\n * - a bare numeric string (e.g. `\"3600\"`, from env vars) — treated as seconds\n * - a human-readable duration string (e.g. `\"1h\"`, `\"30m\"`, `\"7d\"`) — parsed via `ms`,\n * then converted to seconds, rounding up\n *\n * Throws `CacheConfigurationError` on NaN, negative numbers, or unparseable strings.\n *\n * @example\n * parseTtl(3600); // 3600\n * parseTtl(0.5); // 1\n * parseTtl(\"3600\"); // 3600\n * parseTtl(\"500ms\"); // 1\n * parseTtl(\"1h\"); // 3600\n * parseTtl(\"7d\"); // 604800\n * parseTtl(Infinity); // Infinity\n */\nexport function parseTtl(input: CacheTtl): number {\n if (typeof input === \"number\") {\n if (Number.isNaN(input)) {\n throw new CacheConfigurationError(\"Invalid TTL: NaN.\");\n }\n\n if (input < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative number (${input}).`);\n }\n\n return Math.ceil(input);\n }\n\n if (typeof input !== \"string\" || input.trim() === \"\") {\n throw new CacheConfigurationError(\n `Invalid TTL: expected number or duration string, got ${typeof input}.`,\n );\n }\n\n const trimmed = input.trim();\n\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.ceil(Number(trimmed));\n }\n\n const milliseconds = ms(trimmed as StringValue);\n\n if (milliseconds === undefined || Number.isNaN(milliseconds)) {\n throw new CacheConfigurationError(\n `Invalid TTL duration string: \"${input}\". Expected forms like \"1h\", \"30m\", \"7d\".`,\n );\n }\n\n if (milliseconds < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative duration (\"${input}\").`);\n }\n\n return Math.ceil(milliseconds / 1000);\n}\n\n/**\n * Convert an absolute `expiresAt` (Date or epoch milliseconds) into a\n * relative TTL in seconds.\n *\n * Throws {@link CacheConfigurationError} when the deadline is in the past —\n * the caller almost certainly has a bug (stale timestamp, wrong unit, etc.)\n * and silently storing an already-expired entry would hide it.\n *\n * @example\n * expiresAtToTtl(new Date(Date.now() + 60_000)); // ~60\n * expiresAtToTtl(Date.now() + 30 * 60 * 1000); // ~1800\n */\nexport function expiresAtToTtl(expiresAt: number | Date): number {\n const deadline = expiresAt instanceof Date ? expiresAt.getTime() : expiresAt;\n const relativeMs = deadline - Date.now();\n\n if (relativeMs <= 0) {\n throw new CacheConfigurationError(\n `\\`expiresAt\\` must be in the future; got ${new Date(deadline).toISOString()}.`,\n );\n }\n\n return Math.ceil(relativeMs / 1000);\n}\n\n/**\n * Coerce the polymorphic 3rd `set` argument into a uniform `CacheSetOptions`\n * shape. Lets callers (and `BaseCacheDriver.resolveSetOptions`) skip per-shape\n * branching.\n *\n * - `undefined` / `null` → `{}` (resolves to driver-level defaults later)\n * - `number` / `string` (positional TTL) → `{ ttl }`\n * - already an options object → returned as-is\n */\nexport function normalizeToOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Sibling of {@link normalizeToOptions} for the `remember()` call site, where\n * the polymorphic 2nd argument is `CacheTtl | RememberOptions` (no `expiresAt`,\n * no `onConflict`). Returns the same shape so callers can `{ ...opts, ... }`\n * without branching.\n *\n * @example\n * normalizeToRememberOptions(60); // { ttl: 60 }\n * normalizeToRememberOptions(\"1h\"); // { ttl: \"1h\" }\n * normalizeToRememberOptions({ ttl: \"1h\", tags: [\"x\"] }); // returned as-is\n */\nexport function normalizeToRememberOptions(input?: CacheTtl | RememberOptions): RememberOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Resolve the final TTL in seconds for a `set` call. Precedence:\n *\n * 1. Caller's `ttl` (number or duration string) wins.\n * 2. Otherwise, caller's `expiresAt` is converted to relative seconds.\n * 3. Otherwise, `fallback` is used (driver-level default — typically\n * `Infinity` when no default is configured, meaning \"never expires\").\n *\n * Throws {@link CacheConfigurationError} when `ttl` and `expiresAt` are\n * supplied together (mutually exclusive).\n */\nexport function resolveTtl(\n ttl: CacheTtl | undefined,\n expiresAt: number | Date | undefined,\n fallback: number,\n): number {\n if (ttl !== undefined && expiresAt !== undefined) {\n throw new CacheConfigurationError(\n \"Cache set options cannot specify both `ttl` and `expiresAt` — choose one.\",\n );\n }\n\n if (ttl !== undefined) {\n return parseTtl(ttl);\n }\n\n if (expiresAt !== undefined) {\n return expiresAtToTtl(expiresAt);\n }\n\n return fallback;\n}\n\n/**\n * Combine any number of tag lists into a single deduped array, dropping\n * `undefined`/empty entries. Returns `undefined` when no tags survive — lets\n * callers skip emitting empty `tags: []` into option payloads.\n *\n * Used by scoped-cache merging where scope tags + handle tags + per-call tags\n * must union additively without duplicates.\n *\n * @example\n * mergeTagSets([\"a\", \"b\"], [\"b\", \"c\"]); // [\"a\", \"b\", \"c\"]\n * mergeTagSets(undefined, [\"x\"]); // [\"x\"]\n * mergeTagSets(undefined, undefined); // undefined\n * mergeTagSets([], []); // undefined\n */\nexport function mergeTagSets(...lists: (string[] | undefined)[]): string[] | undefined {\n const flat: string[] = [];\n\n for (const list of lists) {\n if (!list || list.length === 0) {\n continue;\n }\n\n flat.push(...list);\n }\n\n if (flat.length === 0) {\n return undefined;\n }\n\n return Array.from(new Set(flat));\n}\n\n/**\n * Add extra tags to any option-bag that already shapes `tags?: string[]`.\n * Pure — clones the input shape, never mutates. Tags are appended (caller\n * is responsible for de-duplication if needed; pair with {@link mergeTagSets}).\n *\n * @example\n * injectTags({ ttl: \"1h\" }, [\"unread\"]); // { ttl: \"1h\", tags: [\"unread\"] }\n * injectTags({ tags: [\"a\"] }, [\"b\"]); // { tags: [\"a\", \"b\"] }\n */\nexport function injectTags<T extends { tags?: string[] }>(options: T, extraTags: string[]): T {\n if (extraTags.length === 0) {\n return options;\n }\n\n return {\n ...options,\n tags: [...(options.tags ?? []), ...extraTags],\n };\n}\n\n/**\n * Cosine similarity between two equal-length numeric vectors.\n *\n * Returns a value in `[-1, 1]` where `1` means perfectly aligned, `0` means\n * orthogonal, and `-1` means opposing. For typical embedding spaces (where\n * vectors live in the positive cone) the practical range is `[0, 1]`.\n *\n * Throws {@link CacheConfigurationError} on dimension mismatch — fail loud at\n * the call site rather than silently returning a misleading score. A zero-norm\n * vector on either side returns `0` (no defined direction to compare).\n *\n * @example\n * cosineSimilarity([1, 0, 0], [1, 0, 0]); // 1\n * cosineSimilarity([1, 0, 0], [0, 1, 0]); // 0\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n throw new CacheConfigurationError(\n `Vector dimension mismatch: got ${a.length} and ${b.length}.`,\n );\n }\n\n if (a.length === 0) {\n throw new CacheConfigurationError(\n \"Vector dimension mismatch: empty vector cannot be compared.\",\n );\n }\n\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n const x = a[i];\n const y = b[i];\n\n if (x === undefined || y === undefined) {\n // Unreachable: both guards above establish `a.length === b.length` and\n // a non-zero length, so every index in range exists on both sides. Said\n // out loud rather than asserted with `as number`, because the two guards\n // that make it true are the kind of thing a later edit removes — and if\n // one ever did, an assertion would let `undefined` into the arithmetic\n // and return NaN as a similarity SCORE. A silently wrong ranking is\n // worse than a stopped one.\n break;\n }\n\n dot += x * y;\n normA += x * x;\n normB += y * y;\n }\n\n if (normA === 0 || normB === 0) {\n return 0;\n }\n\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Matches userinfo credentials embedded in a connection URL\n * (e.g. `redis://user:pass@host`). Node/Redis/Postgres client errors\n * frequently echo the target connection string — including the password —\n * back in `error.message` on connection failure.\n */\nconst CREDENTIALS_IN_URL = /(:\\/\\/)[^\\s/@]+:[^\\s/@]+@/g;\n\n/**\n * Strip embedded `user:pass@` credentials from a string before it reaches\n * any log sink.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(CREDENTIALS_IN_URL, \"$1[REDACTED]@\");\n}\n\n/**\n * Reduce an unknown thrown value to a log-safe `{ message, code? }` shape.\n * Callers must never log the raw error object itself — it may carry the\n * connection URL (with password) in the top-level message, `cause`, or\n * driver-specific fields, all of which `console.log`/`util.inspect` would\n * still print in full.\n */\nexport function safeErrorInfo(error: unknown): { message: string; code?: string } {\n if (error instanceof Error) {\n const info: { message: string; code?: string } = {\n message: redactCredentials(error.message),\n };\n\n const code = (error as any).code;\n if (code) info.code = String(code);\n\n return info;\n }\n\n return { message: redactCredentials(String(error)) };\n}\n\nexport enum CACHE_FOR {\n /**\n * Cache for 30 Minutes (in seconds)\n */\n HALF_HOUR = 1800,\n /**\n * Cache for 1 Hour (in seconds)\n */\n ONE_HOUR = 3600,\n /**\n * Cache for 12 Hours (in seconds)\n */\n HALF_DAY = 43200,\n /**\n * Cache for 24 Hours (in seconds)\n */\n ONE_DAY = 86400,\n /**\n * Cache for 7 Days (in seconds)\n */\n ONE_WEEK = 604800,\n /**\n * Cache for 15 Days (in seconds)\n */\n HALF_MONTH = 1296000,\n /**\n * Cache for 30 Days (in seconds)\n */\n ONE_MONTH = 2592000,\n /**\n * Cache for 60 Days (in seconds)\n */\n TWO_MONTHS = 5184000,\n /**\n * Cache for 180 Days (in seconds)\n */\n SIX_MONTHS = 15768000,\n /**\n * Cache for 365 Days (in seconds)\n */\n ONE_YEAR = 31536000,\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,cACd,KACA,UAAsD,CAAC,GAC/C;CACR,IAAI,OAAO,QAAQ,UACjB,MAAM,KAAK,UAAU,GAAG;CAI1B,MAAM,IAAI,QAAQ,aAAa,EAAE,CAAC,CAAC,WAAW,SAAS,GAAG;CAE1D,MAAM,cACJ,OAAO,QAAQ,iBAAiB,aAAa,QAAQ,aAAa,IAAI,QAAQ;CAEhF,OAAO,MAAM,OAAO,cAAc,MAAM,aAAa,GAAG,IAAI,MAAM,MAAM,GAAG,GAAG,GAAG;AACnF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,OAAyB;CAChD,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,OAAO,MAAM,KAAK,GACpB,MAAM,IAAI,wBAAwB,mBAAmB;EAGvD,IAAI,QAAQ,GACV,MAAM,IAAI,wBAAwB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Ae;AAC5D;;;;;;;;AASA,SAAgB,cAAc,OAAoD;CAChF,IAAI,iBAAiB,OAAO;EAC1B,MAAM,OAA2C,EAC/C,SAAS,kBAAkB,MAAM,OAAO,EAC1C;EAEA,MAAM,OAAQ,MAAc;EAC5B,IAAI,MAAM,KAAK,OAAO,OAAO,IAAI;EAEjC,OAAO;CACT;CAEA,OAAO,EAAE,SAAS,kBAAkB,OAAO,KAAK,CAAC,EAAE;AACrD;AAEA,IAAY,YAAL;;;;CAIL;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;AACF"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../packages/cache/src/utils.ts"],"sourcesContent":["import { rtrim } from \"@mongez/reinforcements\";\nimport ms, { type StringValue } from \"ms\";\nimport type { CacheKey, CacheSetOptions, CacheTtl, RememberOptions } from \"./types\";\nimport { CacheConfigurationError } from \"./types\";\n\n/**\n * Characters that `parseCacheKey` strips or turns into the `.` separator.\n * Inside a value they would make two different keys equal.\n */\nconst KEY_SEPARATOR_CHARACTERS = /[%.,:{}\"[\\]]/g;\n\n/**\n * Escape a value for use as ONE segment of a cache key or namespace: the\n * characters the key format treats as separators or strips (`.` `,` `:`\n * `{` `}` `\"` `[` `]`, and `%` itself) are percent-encoded, so the value can\n * never reach into another key or namespace. Values without those\n * characters are returned unchanged.\n *\n * Use it for request-derived text (slugs, search terms, ids from a client).\n *\n * @example\n * cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);\n * // slug \"acme.billing\" → namespace \"tenant.acme%2Ebilling\", never inside \"tenant.acme\"\n */\nexport function escapeCacheKeySegment(value: string): string {\n return value.replace(\n KEY_SEPARATOR_CHARACTERS,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`,\n );\n}\n\n/**\n * Escape every string (and object key) inside an object key, so a value that\n * contains a separator cannot be read as two segments. Values without\n * separator characters keep their exact previous encoding.\n */\nfunction escapeKeyObject(value: unknown): unknown {\n if (typeof value === \"string\") {\n return escapeCacheKeySegment(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(escapeKeyObject);\n }\n\n if (value === null || typeof value !== \"object\" || value instanceof Date) {\n return value;\n }\n\n // A null-prototype object keeps an own `__proto__` key as data.\n const escaped: Record<string, unknown> = Object.create(null);\n\n for (const [name, child] of Object.entries(value)) {\n escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);\n }\n\n return escaped;\n}\n\n/**\n * Make a proper key for the cache.\n *\n * String keys are used as they are (`:` and `,` become `.`; `{}\"[]` are\n * removed). In an object key, separator characters inside the object's keys\n * and string values are escaped first (see {@link escapeCacheKeySegment}),\n * so `{ a: \"b.c\" }` and `{ a: \"b\", c: \"\" }` are different keys.\n */\nexport function parseCacheKey(\n key: CacheKey,\n options: { globalPrefix?: string | (() => string) } = {},\n): string {\n if (typeof key === \"object\") {\n key = JSON.stringify(escapeKeyObject(key));\n }\n\n // remove any curly braces and double quotes along with []\n key = key.replace(/[{}\"[\\]]/g, \"\").replaceAll(/[:,]/g, \".\");\n\n const cachePrefix =\n typeof options.globalPrefix === \"function\" ? options.globalPrefix() : options.globalPrefix;\n\n return rtrim(String(cachePrefix ? rtrim(cachePrefix, \".\") + \".\" + key : key), \".\");\n}\n\n/**\n * Parse a TTL value into seconds.\n *\n * Accepts:\n * - a number (seconds) — fractions are rounded UP to whole seconds\n * (so Redis `EX` never receives a fraction); `0` means \"no expiry\"\n * - `Infinity` — no expiration, returned unchanged\n * - a bare numeric string (e.g. `\"3600\"`, from env vars) — treated as seconds\n * - a human-readable duration string (e.g. `\"1h\"`, `\"30m\"`, `\"7d\"`) — parsed via `ms`,\n * then converted to seconds, rounding up\n *\n * Throws `CacheConfigurationError` on NaN, negative numbers, or unparseable strings.\n *\n * @example\n * parseTtl(3600); // 3600\n * parseTtl(0.5); // 1\n * parseTtl(\"3600\"); // 3600\n * parseTtl(\"500ms\"); // 1\n * parseTtl(\"1h\"); // 3600\n * parseTtl(\"7d\"); // 604800\n * parseTtl(Infinity); // Infinity\n */\nexport function parseTtl(input: CacheTtl): number {\n if (typeof input === \"number\") {\n if (Number.isNaN(input)) {\n throw new CacheConfigurationError(\"Invalid TTL: NaN.\");\n }\n\n if (input < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative number (${input}).`);\n }\n\n return Math.ceil(input);\n }\n\n if (typeof input !== \"string\" || input.trim() === \"\") {\n throw new CacheConfigurationError(\n `Invalid TTL: expected number or duration string, got ${typeof input}.`,\n );\n }\n\n const trimmed = input.trim();\n\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.ceil(Number(trimmed));\n }\n\n const milliseconds = ms(trimmed as StringValue);\n\n if (milliseconds === undefined || Number.isNaN(milliseconds)) {\n throw new CacheConfigurationError(\n `Invalid TTL duration string: \"${input}\". Expected forms like \"1h\", \"30m\", \"7d\".`,\n );\n }\n\n if (milliseconds < 0) {\n throw new CacheConfigurationError(`Invalid TTL: negative duration (\"${input}\").`);\n }\n\n return Math.ceil(milliseconds / 1000);\n}\n\n/**\n * Convert an absolute `expiresAt` (Date or epoch milliseconds) into a\n * relative TTL in seconds.\n *\n * Throws {@link CacheConfigurationError} when the deadline is in the past —\n * the caller almost certainly has a bug (stale timestamp, wrong unit, etc.)\n * and silently storing an already-expired entry would hide it.\n *\n * @example\n * expiresAtToTtl(new Date(Date.now() + 60_000)); // ~60\n * expiresAtToTtl(Date.now() + 30 * 60 * 1000); // ~1800\n */\nexport function expiresAtToTtl(expiresAt: number | Date): number {\n const deadline = expiresAt instanceof Date ? expiresAt.getTime() : expiresAt;\n const relativeMs = deadline - Date.now();\n\n if (relativeMs <= 0) {\n throw new CacheConfigurationError(\n `\\`expiresAt\\` must be in the future; got ${new Date(deadline).toISOString()}.`,\n );\n }\n\n return Math.ceil(relativeMs / 1000);\n}\n\n/**\n * Coerce the polymorphic 3rd `set` argument into a uniform `CacheSetOptions`\n * shape. Lets callers (and `BaseCacheDriver.resolveSetOptions`) skip per-shape\n * branching.\n *\n * - `undefined` / `null` → `{}` (resolves to driver-level defaults later)\n * - `number` / `string` (positional TTL) → `{ ttl }`\n * - already an options object → returned as-is\n */\nexport function normalizeToOptions(input?: CacheTtl | CacheSetOptions): CacheSetOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Sibling of {@link normalizeToOptions} for the `remember()` call site, where\n * the polymorphic 2nd argument is `CacheTtl | RememberOptions` (no `expiresAt`,\n * no `onConflict`). Returns the same shape so callers can `{ ...opts, ... }`\n * without branching.\n *\n * @example\n * normalizeToRememberOptions(60); // { ttl: 60 }\n * normalizeToRememberOptions(\"1h\"); // { ttl: \"1h\" }\n * normalizeToRememberOptions({ ttl: \"1h\", tags: [\"x\"] }); // returned as-is\n */\nexport function normalizeToRememberOptions(input?: CacheTtl | RememberOptions): RememberOptions {\n if (input === undefined || input === null) {\n return {};\n }\n\n if (typeof input === \"number\" || typeof input === \"string\") {\n return { ttl: input };\n }\n\n return input;\n}\n\n/**\n * Resolve the final TTL in seconds for a `set` call. Precedence:\n *\n * 1. Caller's `ttl` (number or duration string) wins.\n * 2. Otherwise, caller's `expiresAt` is converted to relative seconds.\n * 3. Otherwise, `fallback` is used (driver-level default — typically\n * `Infinity` when no default is configured, meaning \"never expires\").\n *\n * Throws {@link CacheConfigurationError} when `ttl` and `expiresAt` are\n * supplied together (mutually exclusive).\n */\nexport function resolveTtl(\n ttl: CacheTtl | undefined,\n expiresAt: number | Date | undefined,\n fallback: number,\n): number {\n if (ttl !== undefined && expiresAt !== undefined) {\n throw new CacheConfigurationError(\n \"Cache set options cannot specify both `ttl` and `expiresAt` — choose one.\",\n );\n }\n\n if (ttl !== undefined) {\n return parseTtl(ttl);\n }\n\n if (expiresAt !== undefined) {\n return expiresAtToTtl(expiresAt);\n }\n\n return fallback;\n}\n\n/**\n * Combine any number of tag lists into a single deduped array, dropping\n * `undefined`/empty entries. Returns `undefined` when no tags survive — lets\n * callers skip emitting empty `tags: []` into option payloads.\n *\n * Used by scoped-cache merging where scope tags + handle tags + per-call tags\n * must union additively without duplicates.\n *\n * @example\n * mergeTagSets([\"a\", \"b\"], [\"b\", \"c\"]); // [\"a\", \"b\", \"c\"]\n * mergeTagSets(undefined, [\"x\"]); // [\"x\"]\n * mergeTagSets(undefined, undefined); // undefined\n * mergeTagSets([], []); // undefined\n */\nexport function mergeTagSets(...lists: (string[] | undefined)[]): string[] | undefined {\n const flat: string[] = [];\n\n for (const list of lists) {\n if (!list || list.length === 0) {\n continue;\n }\n\n flat.push(...list);\n }\n\n if (flat.length === 0) {\n return undefined;\n }\n\n return Array.from(new Set(flat));\n}\n\n/**\n * Add extra tags to any option-bag that already shapes `tags?: string[]`.\n * Pure — clones the input shape, never mutates. Tags are appended (caller\n * is responsible for de-duplication if needed; pair with {@link mergeTagSets}).\n *\n * @example\n * injectTags({ ttl: \"1h\" }, [\"unread\"]); // { ttl: \"1h\", tags: [\"unread\"] }\n * injectTags({ tags: [\"a\"] }, [\"b\"]); // { tags: [\"a\", \"b\"] }\n */\nexport function injectTags<T extends { tags?: string[] }>(options: T, extraTags: string[]): T {\n if (extraTags.length === 0) {\n return options;\n }\n\n return {\n ...options,\n tags: [...(options.tags ?? []), ...extraTags],\n };\n}\n\n/**\n * Cosine similarity between two equal-length numeric vectors.\n *\n * Returns a value in `[-1, 1]` where `1` means perfectly aligned, `0` means\n * orthogonal, and `-1` means opposing. For typical embedding spaces (where\n * vectors live in the positive cone) the practical range is `[0, 1]`.\n *\n * Throws {@link CacheConfigurationError} on dimension mismatch — fail loud at\n * the call site rather than silently returning a misleading score. A zero-norm\n * vector on either side returns `0` (no defined direction to compare).\n *\n * @example\n * cosineSimilarity([1, 0, 0], [1, 0, 0]); // 1\n * cosineSimilarity([1, 0, 0], [0, 1, 0]); // 0\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n throw new CacheConfigurationError(\n `Vector dimension mismatch: got ${a.length} and ${b.length}.`,\n );\n }\n\n if (a.length === 0) {\n throw new CacheConfigurationError(\n \"Vector dimension mismatch: empty vector cannot be compared.\",\n );\n }\n\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n const x = a[i];\n const y = b[i];\n\n if (x === undefined || y === undefined) {\n // Unreachable: both guards above establish `a.length === b.length` and\n // a non-zero length, so every index in range exists on both sides. Said\n // out loud rather than asserted with `as number`, because the two guards\n // that make it true are the kind of thing a later edit removes — and if\n // one ever did, an assertion would let `undefined` into the arithmetic\n // and return NaN as a similarity SCORE. A silently wrong ranking is\n // worse than a stopped one.\n break;\n }\n\n dot += x * y;\n normA += x * x;\n normB += y * y;\n }\n\n if (normA === 0 || normB === 0) {\n return 0;\n }\n\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Matches userinfo credentials embedded in a connection URL\n * (e.g. `redis://user:pass@host`). Node/Redis/Postgres client errors\n * frequently echo the target connection string — including the password —\n * back in `error.message` on connection failure.\n */\nconst CREDENTIALS_IN_URL = /(:\\/\\/)[^\\s/@]+:[^\\s/@]+@/g;\n\n/**\n * Strip embedded `user:pass@` credentials from a string before it reaches\n * any log sink.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(CREDENTIALS_IN_URL, \"$1[REDACTED]@\");\n}\n\n/**\n * Reduce an unknown thrown value to a log-safe `{ message, code? }` shape.\n * Callers must never log the raw error object itself — it may carry the\n * connection URL (with password) in the top-level message, `cause`, or\n * driver-specific fields, all of which `console.log`/`util.inspect` would\n * still print in full.\n */\nexport function safeErrorInfo(error: unknown): { message: string; code?: string } {\n if (error instanceof Error) {\n const info: { message: string; code?: string } = {\n message: redactCredentials(error.message),\n };\n\n const code = (error as any).code;\n if (code) info.code = String(code);\n\n return info;\n }\n\n return { message: redactCredentials(String(error)) };\n}\n\nexport enum CACHE_FOR {\n /**\n * Cache for 30 Minutes (in seconds)\n */\n HALF_HOUR = 1800,\n /**\n * Cache for 1 Hour (in seconds)\n */\n ONE_HOUR = 3600,\n /**\n * Cache for 12 Hours (in seconds)\n */\n HALF_DAY = 43200,\n /**\n * Cache for 24 Hours (in seconds)\n */\n ONE_DAY = 86400,\n /**\n * Cache for 7 Days (in seconds)\n */\n ONE_WEEK = 604800,\n /**\n * Cache for 15 Days (in seconds)\n */\n HALF_MONTH = 1296000,\n /**\n * Cache for 30 Days (in seconds)\n */\n ONE_MONTH = 2592000,\n /**\n * Cache for 60 Days (in seconds)\n */\n TWO_MONTHS = 5184000,\n /**\n * Cache for 180 Days (in seconds)\n */\n SIX_MONTHS = 15768000,\n /**\n * Cache for 365 Days (in seconds)\n */\n ONE_YEAR = 31536000,\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,2BAA2B;;;;;;;;;;;;;;AAejC,SAAgB,sBAAsB,OAAuB;CAC3D,OAAO,MAAM,QACX,2BACC,cAAc,IAAI,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG,GACvF;AACF;;;;;;AAOA,SAAS,gBAAgB,OAAyB;CAChD,IAAI,OAAO,UAAU,UACnB,OAAO,sBAAsB,KAAK;CAGpC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,eAAe;CAGlC,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,iBAAiB,MAClE,OAAO;CAIT,MAAM,UAAmC,OAAO,OAAO,IAAI;CAE3D,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,GAC9C,QAAQ,sBAAsB,IAAI,KAAK,gBAAgB,KAAK;CAG9D,OAAO;AACT;;;;;;;;;AAUA,SAAgB,cACd,KACA,UAAsD,CAAC,GAC/C;CACR,IAAI,OAAO,QAAQ,UACjB,MAAM,KAAK,UAAU,gBAAgB,GAAG,CAAC;CAI3C,MAAM,IAAI,QAAQ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,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;EACjC,MAAM,IAAI,EAAE;EACZ,MAAM,IAAI,EAAE;EAEZ,IAAI,MAAM,UAAa,MAAM,QAQ3B;EAGF,OAAO,IAAI;EACX,SAAS,IAAI;EACb,SAAS,IAAI;CACf;CAEA,IAAI,UAAU,KAAK,UAAU,GAC3B,OAAO;CAGT,OAAO,OAAO,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK;AAClD;;;;;;;AAQA,MAAM,qBAAqB;;;;;AAM3B,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,QAAQ,QAAQ,oBAAoB,eAAe;AAC5D;;;;;;;;AASA,SAAgB,cAAc,OAAoD;CAChF,IAAI,iBAAiB,OAAO;EAC1B,MAAM,OAA2C,EAC/C,SAAS,kBAAkB,MAAM,OAAO,EAC1C;EAEA,MAAM,OAAQ,MAAc;EAC5B,IAAI,MAAM,KAAK,OAAO,OAAO,IAAI;EAEjC,OAAO;CACT;CAEA,OAAO,EAAE,SAAS,kBAAkB,OAAO,KAAK,CAAC,EAAE;AACrD;AAEA,IAAY,YAAL;;;;CAIL;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;;;CAIA;;AACF"}
package/llms-full.txt CHANGED
@@ -224,7 +224,7 @@ cache.setCacheConfigurations(config);
224
224
  await cache.init();
225
225
  ```
226
226
 
227
- `logging` turns the per-operation key log (`<key> fetched`, `<key> not found`, ...) on or off. Email addresses inside logged keys are masked (`user.member@example.com` logs as `u***@example.com`), in operation lines and in error lines (which are written even with logging off); other personal data in a key is logged as is, so keep it out of keys or turn logging off in production.
227
+ `logging` turns the per-operation key log (`<key> fetched`, `<key> not found`, ...) on or off; it is off by default (`logging: true` turns it on). Errors and connection failures are always logged. Email addresses inside logged keys are masked (`user.member@example.com` logs as `u***@example.com`), in operation lines and in error lines (which are written even with logging off); other personal data in a key is logged as is, so keep it out of keys or turn logging off in production.
228
228
 
229
229
  ## Primary ops
230
230
 
@@ -760,7 +760,7 @@ Seven production drivers + a mock driver ship in-box. Pick by durability, scope,
760
760
 
761
761
  Memory, memoryExtended, lru and file caches are **per-process** (file: per host). With more than one server, use `redis` or `pg` for counters, throttles, one-time tokens (`pull`), shared `update`, `lock()` and tag invalidation; on memory each server counts and invalidates alone. `remember()`/`swr()`/`cached()` stampede protection is per process even on redis. Redis Cluster is unsupported.
762
762
 
763
- Driver storage notes: `memory` stores flat keys (`get("users")` after `set("users.1")` is a miss) and `maxSize` counts entries in LRU order; redis `flush()` without a `globalPrefix` runs `FLUSHDB` (whole database), so set a prefix.
763
+ Driver storage notes: `memory` stores flat keys (`get("users")` after `set("users.1")` is a miss) and `maxSize` counts entries in LRU order (default `10000`, `Infinity` for no limit); redis `flush()` without a `globalPrefix` runs `FLUSHDB` (whole database), so set a prefix.
764
764
 
765
765
  ## Global config TTL — accepts number or string
766
766
 
@@ -1558,6 +1558,7 @@ Note: scope `ttl` defaults are NOT applied to SWR — `freshTtl` / `staleTtl` al
1558
1558
 
1559
1559
  - Don't create a `cache.namespace(prefix)` for a single read/write — the boilerplate doesn't pay off until the prefix repeats. Inline `cache.set("prefix.foo", ...)` is fine.
1560
1560
  - Don't expect `cache.namespace(prefix).clear()` to do anything on the `null` driver — `removeNamespace` no-ops there (it caches nothing).
1561
+ - Don't put raw request values in a prefix: ``cache.namespace(`tenant.${slug}`)`` with `slug = "acme.billing"` lands inside `tenant.acme`. Use `escapeCacheKeySegment(slug)` (percent-encodes `.` `,` `:` `{` `}` `"` `[` `]` `%`).
1561
1562
  - Don't mix prefix separators. The convention is `.` (dot) — pick one and stick with it across scopes so nested prefixes compose predictably.
1562
1563
 
1563
1564
 
@@ -1771,7 +1772,7 @@ Subsequent `set("user:1", ...)` with **no** `tags` leaves previous associations
1771
1772
  | `redis` | ✓ (native SET inside the prefix) |
1772
1773
  | `pg` | ✓ (JSON-array merge on the index row) |
1773
1774
 
1774
- The index uses driver primitives (`tagAdd` / `tagMembers` / `tagRemove`), so concurrent tagged writes never drop members. It stores un-prefixed keys, `invalidate()` deletes exactly the members it read, writes prune up to 20 dead members, and `remove()` / `pull()` detach the key. Tags are global across scopes. Across servers, use `redis` or `pg` so every server shares one index.
1775
+ The index uses driver primitives (`tagAdd` / `tagMembers` / `tagRemove`), so concurrent tagged writes never drop members. A tagged write samples up to 20 members (`tagSample`) and checks them with `exists` (no value read, no hit/miss events), so its cost does not grow with the tag; `invalidate()` removes members in batches (`removeMany`). Custom drivers without these primitives fall back to `tagMembers` / `has()` / `remove()`. It stores un-prefixed keys, `invalidate()` deletes exactly the members it read, writes prune up to 20 dead members, and `remove()` / `pull()` detach the key. Tags are global across scopes. Across servers, use `redis` or `pg` so every server shares one index.
1775
1776
 
1776
1777
  ## SWR with tags
1777
1778
 
@@ -1895,7 +1896,7 @@ The per-key lock map lives on the driver instance and is cleared after each chai
1895
1896
 
1896
1897
  ---
1897
1898
  name: use-cache-utils
1898
- description: 'Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.'
1899
+ description: 'Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, escapeCacheKeySegment, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `escapeCacheKeySegment`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.'
1899
1900
  ---
1900
1901
 
1901
1902
  # Cache utilities
@@ -1940,10 +1941,12 @@ normalizeToRememberOptions("1h"); // { ttl: "1h" } (no expiresAt/onConflict)
1940
1941
  ## Key + tag helpers
1941
1942
 
1942
1943
  ```ts
1943
- import { parseCacheKey, mergeTagSets, injectTags } from "@warlock.js/cache";
1944
+ import { escapeCacheKeySegment, parseCacheKey, mergeTagSets, injectTags } from "@warlock.js/cache";
1944
1945
 
1945
1946
  parseCacheKey("users:1"); // "users.1"
1946
1947
  parseCacheKey({ page: 1, q: "John" }); // "page.1.q.John"
1948
+ parseCacheKey({ q: "a.b" }); // "q.a%2Eb" — separators inside object values are escaped
1949
+ escapeCacheKeySegment("acme.billing"); // "acme%2Ebilling" — one safe segment for a key or namespace
1947
1950
  parseCacheKey("user:1", { globalPrefix: "app" }); // "app.user.1"
1948
1951
 
1949
1952
  mergeTagSets(["a", "b"], ["b", "c"]); // ["a","b","c"] (deduped union)
@@ -2033,7 +2036,7 @@ cached(fn, {
2033
2036
  | Any args | `prefix.<16 hex>` — sha1 of a stable JSON encoding of the args, truncated |
2034
2037
  | `Map` / `Set` / function / symbol / class instance / circular | throws `CacheConfigurationError` |
2035
2038
 
2036
- The hash keeps distinct args on distinct keys (`("1.private", "")` ≠ `("1", "private")`). Object keys are sorted; `Date` → ISO string; order of args matters. Never build keys by hand: call `.invalidate(...args)`, which honours `config.driver`. When auto-key fails, use the options form with a custom `key` fn.
2039
+ The hash keeps distinct args on distinct keys (`("1.private", "")` ≠ `("1", "private")`). Object keys are sorted; `Date` → ISO string; `bigint` and `$`-prefixed object keys are encoded so they never collide with other args; an own `__proto__` key is kept; order of args matters. Never build keys by hand: call `.invalidate(...args)`, which honours `config.driver`. When auto-key fails, use the options form with a custom `key` fn.
2037
2040
 
2038
2041
  **Upgrade (5.20):** the key format changed from dot-joined args, so old entries are never read and every call misses once.
2039
2042
 
package/llms.txt CHANGED
@@ -26,6 +26,6 @@
26
26
  - [use-cache-structures](@warlock.js/cache/skills/use-cache-structures/SKILL.md): Probabilistic structures on the cache manager — cache.structures.bloom, cuckoo, uniqueCounter (HyperLogLog, .merge), frequency (Count-Min + Top-K) on redis and memory drivers. Triggers: `cache.structures`, "username taken check", "daily active users", "top search terms", "bloom filter"; other drivers throw `CacheUnsupportedError`. Skip: exact sets — `cache.list`; exact counters — `use-cache-atomic`.
27
27
  - [use-cache-tags](@warlock.js/cache/skills/use-cache-tags/SKILL.md): Tag-based invalidation — attach tags on write, then cache.tags([...]).invalidate() drops every key bound to any of those tags. Triggers: `cache.tags`, `invalidate`, `cache.set` with `tags`; "invalidate every key tagged users", "drop everything for tenant 42", "bulk cache invalidation without knowing keys", "tag a cached value"; typical import `import { cache } from "@warlock.js/cache"`. Skip: prefix-based drop — the `use-cache-namespace` topic; HOF memoization with tags — the `use-cached-hof` topic; SWR — the `use-swr` topic; competing libs `cache-manager` tags, Next.js `revalidateTag`.
28
28
  - [use-cache-update-merge](@warlock.js/cache/skills/use-cache-update-merge/SKILL.md): Atomic read-modify-write via cache.update(key, fn) (callback receives current) or cache.merge(key, partial) (shallow merge). Per-key chain lock serializes concurrent in-process callers. Triggers: `cache.update`, `cache.merge`, `cache.increment`, `cache.pull`; "atomically update a cached counter", "change one field on a cached object", "avoid get-spread-set race", "serialize concurrent cache writers"; typical import `import { cache } from "@warlock.js/cache"`. Skip: cross-process locking — the `use-cache-lock` topic; conditional create/update — the `configure-set-options` topic; competing libs `lodash.merge`, raw redis `WATCH`/`MULTI`.
29
- - [use-cache-utils](@warlock.js/cache/skills/use-cache-utils/SKILL.md): Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.
29
+ - [use-cache-utils](@warlock.js/cache/skills/use-cache-utils/SKILL.md): Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, escapeCacheKeySegment, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `escapeCacheKeySegment`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.
30
30
  - [use-cached-hof](@warlock.js/cache/skills/use-cached-hof/SKILL.md): Wrap an async function with cached(fn, options) — declare the caching strategy once, call from many sites, get a bound .invalidate(...args) helper. Triggers: `cached`, `invalidate`, `key`, `ttl`, `tags`, `driver`; "wrap a DB lookup with caching", "memoize a function and invalidate by args", "one declaration many call sites", "auto-derive cache key from args"; typical import `import { cached } from "@warlock.js/cache"`. Skip: one-shot memoization — the `apply-cache-patterns` topic (`cache.remember`); tag bulk drop — the `use-cache-tags` topic; competing libs `p-memoize`, `mem`, `lodash.memoize`.
31
31
  - [use-swr](@warlock.js/cache/skills/use-swr/SKILL.md): Stale-while-revalidate via cache.swr(key, {freshTtl, staleTtl}, fn) — returns cached instantly when fresh, returns cached + background refresh when stale, blocks only when fully expired. Triggers: `cache.swr`, `freshTtl`, `staleTtl`, `tags`, `driver`, `stale_at`; "serve stale while refreshing", "degrade when upstream is down", "never block on cache miss"; typical import `import { cache } from "@warlock.js/cache"`. Skip: block-until-fresh memoization — the `apply-cache-patterns` topic; observing refresh failures — the `observe-cache` topic; competing libs `swr` (React, client-side).
package/package.json CHANGED
@@ -5,9 +5,9 @@
5
5
  "environment": "server"
6
6
  },
7
7
  "dependencies": {
8
- "@warlock.js/fs": "5.52.0",
8
+ "@warlock.js/fs": "5.53.1",
9
9
  "@mongez/reinforcements": "^4.0.2",
10
- "@warlock.js/logger": "5.52.0",
10
+ "@warlock.js/logger": "5.53.1",
11
11
  "ms": "^2.1.3"
12
12
  },
13
13
  "peerDependencies": {
@@ -47,7 +47,7 @@
47
47
  ],
48
48
  "author": "hassanzohdy",
49
49
  "license": "MIT",
50
- "version": "5.52.0",
50
+ "version": "5.53.1",
51
51
  "main": "./cjs/index.cjs",
52
52
  "module": "./esm/index.mjs",
53
53
  "types": "./esm/index.d.mts",
@@ -61,7 +61,7 @@ cache.setCacheConfigurations(config);
61
61
  await cache.init();
62
62
  ```
63
63
 
64
- `logging` turns the per-operation key log (`<key> fetched`, `<key> not found`, ...) on or off. Email addresses inside logged keys are masked (`user.member@example.com` logs as `u***@example.com`), in operation lines and in error lines (which are written even with logging off); other personal data in a key is logged as is, so keep it out of keys or turn logging off in production.
64
+ `logging` turns the per-operation key log (`<key> fetched`, `<key> not found`, ...) on or off; it is off by default (`logging: true` turns it on). Errors and connection failures are always logged. Email addresses inside logged keys are masked (`user.member@example.com` logs as `u***@example.com`), in operation lines and in error lines (which are written even with logging off); other personal data in a key is logged as is, so keep it out of keys or turn logging off in production.
65
65
 
66
66
  ## Primary ops
67
67
 
@@ -36,7 +36,7 @@ Seven production drivers + a mock driver ship in-box. Pick by durability, scope,
36
36
 
37
37
  Memory, memoryExtended, lru and file caches are **per-process** (file: per host). With more than one server, use `redis` or `pg` for counters, throttles, one-time tokens (`pull`), shared `update`, `lock()` and tag invalidation; on memory each server counts and invalidates alone. `remember()`/`swr()`/`cached()` stampede protection is per process even on redis. Redis Cluster is unsupported.
38
38
 
39
- Driver storage notes: `memory` stores flat keys (`get("users")` after `set("users.1")` is a miss) and `maxSize` counts entries in LRU order; redis `flush()` without a `globalPrefix` runs `FLUSHDB` (whole database), so set a prefix.
39
+ Driver storage notes: `memory` stores flat keys (`get("users")` after `set("users.1")` is a miss) and `maxSize` counts entries in LRU order (default `10000`, `Infinity` for no limit); redis `flush()` without a `globalPrefix` runs `FLUSHDB` (whole database), so set a prefix.
40
40
 
41
41
  ## Global config TTL — accepts number or string
42
42
 
@@ -83,4 +83,5 @@ Note: scope `ttl` defaults are NOT applied to SWR — `freshTtl` / `staleTtl` al
83
83
 
84
84
  - Don't create a `cache.namespace(prefix)` for a single read/write — the boilerplate doesn't pay off until the prefix repeats. Inline `cache.set("prefix.foo", ...)` is fine.
85
85
  - Don't expect `cache.namespace(prefix).clear()` to do anything on the `null` driver — `removeNamespace` no-ops there (it caches nothing).
86
+ - Don't put raw request values in a prefix: ``cache.namespace(`tenant.${slug}`)`` with `slug = "acme.billing"` lands inside `tenant.acme`. Use `escapeCacheKeySegment(slug)` (percent-encodes `.` `,` `:` `{` `}` `"` `[` `]` `%`).
86
87
  - Don't mix prefix separators. The convention is `.` (dot) — pick one and stick with it across scopes so nested prefixes compose predictably.
@@ -56,7 +56,7 @@ Subsequent `set("user:1", ...)` with **no** `tags` leaves previous associations
56
56
  | `redis` | ✓ (native SET inside the prefix) |
57
57
  | `pg` | ✓ (JSON-array merge on the index row) |
58
58
 
59
- The index uses driver primitives (`tagAdd` / `tagMembers` / `tagRemove`), so concurrent tagged writes never drop members. It stores un-prefixed keys, `invalidate()` deletes exactly the members it read, writes prune up to 20 dead members, and `remove()` / `pull()` detach the key. Tags are global across scopes. Across servers, use `redis` or `pg` so every server shares one index.
59
+ The index uses driver primitives (`tagAdd` / `tagMembers` / `tagRemove`), so concurrent tagged writes never drop members. A tagged write samples up to 20 members (`tagSample`) and checks them with `exists` (no value read, no hit/miss events), so its cost does not grow with the tag; `invalidate()` removes members in batches (`removeMany`). Custom drivers without these primitives fall back to `tagMembers` / `has()` / `remove()`. It stores un-prefixed keys, `invalidate()` deletes exactly the members it read, writes prune up to 20 dead members, and `remove()` / `pull()` detach the key. Tags are global across scopes. Across servers, use `redis` or `pg` so every server shares one index.
60
60
 
61
61
  ## SWR with tags
62
62
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: use-cache-utils
3
- description: 'Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.'
3
+ description: 'Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, escapeCacheKeySegment, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `escapeCacheKeySegment`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.'
4
4
  ---
5
5
 
6
6
  # Cache utilities
@@ -45,10 +45,12 @@ normalizeToRememberOptions("1h"); // { ttl: "1h" } (no expiresAt/onConflict)
45
45
  ## Key + tag helpers
46
46
 
47
47
  ```ts
48
- import { parseCacheKey, mergeTagSets, injectTags } from "@warlock.js/cache";
48
+ import { escapeCacheKeySegment, parseCacheKey, mergeTagSets, injectTags } from "@warlock.js/cache";
49
49
 
50
50
  parseCacheKey("users:1"); // "users.1"
51
51
  parseCacheKey({ page: 1, q: "John" }); // "page.1.q.John"
52
+ parseCacheKey({ q: "a.b" }); // "q.a%2Eb" — separators inside object values are escaped
53
+ escapeCacheKeySegment("acme.billing"); // "acme%2Ebilling" — one safe segment for a key or namespace
52
54
  parseCacheKey("user:1", { globalPrefix: "app" }); // "app.user.1"
53
55
 
54
56
  mergeTagSets(["a", "b"], ["b", "c"]); // ["a","b","c"] (deduped union)
@@ -45,7 +45,7 @@ cached(fn, {
45
45
  | Any args | `prefix.<16 hex>` — sha1 of a stable JSON encoding of the args, truncated |
46
46
  | `Map` / `Set` / function / symbol / class instance / circular | throws `CacheConfigurationError` |
47
47
 
48
- The hash keeps distinct args on distinct keys (`("1.private", "")` ≠ `("1", "private")`). Object keys are sorted; `Date` → ISO string; order of args matters. Never build keys by hand: call `.invalidate(...args)`, which honours `config.driver`. When auto-key fails, use the options form with a custom `key` fn.
48
+ The hash keeps distinct args on distinct keys (`("1.private", "")` ≠ `("1", "private")`). Object keys are sorted; `Date` → ISO string; `bigint` and `$`-prefixed object keys are encoded so they never collide with other args; an own `__proto__` key is kept; order of args matters. Never build keys by hand: call `.invalidate(...args)`, which honours `config.driver`. When auto-key fails, use the options form with a custom `key` fn.
49
49
 
50
50
  **Upgrade (5.20):** the key format changed from dot-joined args, so old entries are never read and every call misses once.
51
51