@warlock.js/cache 5.53.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 (37) hide show
  1. package/cjs/index.cjs.map +1 -1
  2. package/esm/cache-manager.mjs.map +1 -1
  3. package/esm/cached/auto-key.mjs.map +1 -1
  4. package/esm/cached/cached.mjs.map +1 -1
  5. package/esm/cached/normalize-args.mjs.map +1 -1
  6. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  7. package/esm/drivers/clone-value.mjs.map +1 -1
  8. package/esm/drivers/file-cache-driver.mjs.map +1 -1
  9. package/esm/drivers/in-memory-tag-index.mjs.map +1 -1
  10. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  11. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  12. package/esm/drivers/memory-extended-cache-driver.mjs.map +1 -1
  13. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  14. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  15. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  16. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  17. package/esm/idempotent.mjs.map +1 -1
  18. package/esm/list/memory-cache-list.mjs.map +1 -1
  19. package/esm/metrics.mjs.map +1 -1
  20. package/esm/scoped-cache.mjs.map +1 -1
  21. package/esm/structures/bloom-filter.mjs.map +1 -1
  22. package/esm/structures/cuckoo-filter.mjs.map +1 -1
  23. package/esm/structures/frequency-tracker.mjs.map +1 -1
  24. package/esm/structures/hash.mjs.map +1 -1
  25. package/esm/structures/hyperloglog.mjs.map +1 -1
  26. package/esm/structures/memory-structures-backend.mjs.map +1 -1
  27. package/esm/structures/redis-structures-backend.mjs.map +1 -1
  28. package/esm/structures/sizing.mjs.map +1 -1
  29. package/esm/structures/structures.mjs.map +1 -1
  30. package/esm/structures/types.mjs.map +1 -1
  31. package/esm/structures/unique-counter.mjs.map +1 -1
  32. package/esm/tag-sample.mjs.map +1 -1
  33. package/esm/tagged-cache.mjs.map +1 -1
  34. package/esm/tagged-scoped-cache.mjs.map +1 -1
  35. package/esm/types.mjs.map +1 -1
  36. package/esm/utils.mjs.map +1 -1
  37. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"cache-manager.mjs","names":[],"sources":["../../../../../../../packages/cache/src/cache-manager.ts"],"mappings":";;;;;;;;AA2BA,IAAa,eAAb,MAA2D;;uBASK,CAAC;wCAKpC,IAAI,IAA4C;wBAK3B;GAC9C,SAAS,CAAC;GACV,SAAS,CAAC;EACZ;8CAK8E,IAAI,IAAI;cAYxE;2CA2emC,IAAI,QAAQ;oBAmCf,uBAAuB;GACnE,KAAK,wBAAwB;GAE7B,OAAO,oBAAoB,KAAK,aAAc;EAChD,CAAC;;;;;CA7gBD,IAAW,SAAS;EAClB,OAAO,KAAK,eAAe;CAC7B;;;;CAKA,AAAO,uBAAuB,gBAAqC;EACjE,KAAK,eAAe,UAAU,eAAe;EAC7C,KAAK,eAAe,UAAU,eAAe;EAC7C,KAAK,eAAe,UAAU,eAAe;EAC7C,KAAK,eAAe,UAAU,eAAe;CAC/C;;;;CAKA,AAAO,gBAAgB,cAAuB;EAC5C,KAAK,wBAAwB;EAE7B,KAAK,cAAe,gBAAgB,YAAY;CAClD;;;;;;;;;;;;;;;;;;;CAoBA,MAAa,IAAI,QAAwC,gBAAsC;EAC7F,IAAI,OAAO,WAAW,UAAU;GAC9B,MAAM,iBAAiB,MAAM,KAAK,KAAK,QAAQ,cAAc;GAE7D,IAAI,CAAC,gBACH,MAAM,IAAI,wBACR,gBAAgB,OAAO,kFACzB;GAGF,SAAS;EACX;EAEA,KAAK,sBAAsB,MAAM;EAEjC,IAAI,KAAK,eAAe,YAAY,QAClC,OAAO,gBAAgB,KAAK,eAAe,OAAO;EAGpD,KAAK,gBAAgB;EAErB,OAAO;CACT;;;;CAKA,AAAU,0BAAgC;EACxC,IAAI,CAAC,KAAK,eACR,MAAM,IAAI,+BAA+B;CAE7C;;;;;;;;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"sources":["../../../../../../../packages/cache/src/cache-manager.ts"],"sourcesContent":["import { runIdempotent, type IdempotentFlights, type IdempotentOptions } from \"./idempotent\";\nimport { CacheMetricsCollector } from \"./metrics\";\nimport { ScopedCache } from \"./scoped-cache\";\nimport { createStructures, structuresBackendOf, type CacheStructures } from \"./structures\";\nimport type {\n CacheConfigurations,\n CacheDriver,\n CacheEventHandler,\n CacheEventType,\n CacheKey,\n CacheListAccessor,\n CacheMetricsSnapshot,\n CacheNamespaceOptions,\n CacheSetOptions,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheSwrOptions,\n CacheTtl,\n DriverClass,\n LockOptions,\n LockOutcome,\n RememberOptions,\n ScopedCacheContract,\n TaggedCacheDriver,\n} from \"./types\";\nimport { CacheConfigurationError, CacheDriverNotInitializedError } from \"./types\";\n\nexport class CacheManager implements CacheDriver<any, any> {\n /**\n * Cache Driver\n */\n public currentDriver?: CacheDriver<any, any>;\n\n /**\n * Loaded drivers\n */\n public loadedDrivers: Record<string, CacheDriver<any, any>> = {};\n\n /**\n * In-flight `load()` promises, so concurrent callers share one `connect()`.\n */\n protected loadingDrivers = new Map<string, Promise<CacheDriver<any, any>>>();\n\n /**\n * Configurations list\n */\n protected configurations: CacheConfigurations = {\n drivers: {},\n options: {},\n };\n\n /**\n * Global event listeners\n */\n protected globalEventListeners: Map<CacheEventType, Set<CacheEventHandler>> = new Map();\n\n /**\n * Metrics collector — lazy on first {@link metrics} call so apps that\n * never read metrics pay zero cost. Once instantiated, it stays\n * subscribed to events for the manager's lifetime.\n */\n protected metricsCollector?: CacheMetricsCollector;\n\n /**\n * {@inheritdoc}\n */\n public name = \"cacheManager\";\n\n /**\n * {@inheritdoc}\n */\n public get client() {\n return this.currentDriver?.client;\n }\n\n /**\n * Set the cache configurations\n */\n public setCacheConfigurations(configurations: CacheConfigurations) {\n this.configurations.default = configurations.default;\n this.configurations.drivers = configurations.drivers;\n this.configurations.options = configurations.options;\n this.configurations.logging = configurations.logging;\n }\n\n /**\n * Set logging state\n */\n public setLoggingState(loggingState: boolean) {\n this.ensureDriverInitialized();\n\n this.currentDriver!.setLoggingState(loggingState);\n }\n\n /**\n * Switch the manager to a registered driver, optionally injecting runtime\n * options that merge over the static config.\n *\n * The string form looks the driver up in `setCacheConfigurations({ drivers })`,\n * loads it (or returns the cached instance), and sets it as `currentDriver`.\n * The instance form takes a pre-built driver and bypasses the registry; the\n * `runtimeOptions` argument is silently ignored in that case because the\n * instance was constructed externally.\n *\n * Runtime options merge over `config.options[name]` per-key — runtime wins.\n * Use this for constructor-only knobs that can't live in static config\n * (e.g. `pg`'s `client: pg.Pool`).\n *\n * @example\n * const pool = new Pool({ connectionString });\n * await cache.use(\"pg\", { client: pool });\n */\n public async use(driver: string | CacheDriver<any, any>, runtimeOptions?: Record<string, any>) {\n if (typeof driver === \"string\") {\n const driverInstance = await this.load(driver, runtimeOptions);\n\n if (!driverInstance) {\n throw new CacheConfigurationError(\n `Cache driver ${driver} is not found, please declare it in the cache drivers in the configurations list.`,\n );\n }\n\n driver = driverInstance;\n }\n\n this.attachGlobalListeners(driver);\n\n if (this.configurations.logging !== undefined) {\n driver.setLoggingState(this.configurations.logging);\n }\n\n this.currentDriver = driver;\n\n return this;\n }\n\n /**\n * Ensure driver is initialized before operations\n */\n protected ensureDriverInitialized(): void {\n if (!this.currentDriver) {\n throw new CacheDriverNotInitializedError();\n }\n }\n\n /**\n * Return the running metrics snapshot — counters, hit-rate, latency\n * percentiles, per-driver breakdowns. Lazy-attaches the collector on\n * first call so apps that never read metrics pay zero cost.\n *\n * @example\n * const m = cache.metrics();\n * console.log(`hit rate: ${(m.hitRate * 100).toFixed(1)}%`);\n * console.log(`p95: ${m.latencyMs.p95.toFixed(2)}ms`);\n */\n public metrics(): CacheMetricsSnapshot {\n return this.ensureMetricsCollector().snapshot();\n }\n\n /**\n * Wipe every counter + latency sample and reset `startedAt` to now.\n * The collector itself stays subscribed to events.\n */\n public resetMetrics(): void {\n this.ensureMetricsCollector().reset();\n }\n\n /**\n * Lazy-construct the metrics collector and wire it to the global event\n * bus. Subsequent calls return the same instance — survives `cache.use()`\n * driver switches because handlers attach via `on()` and re-bind to every\n * loaded driver.\n */\n protected ensureMetricsCollector(): CacheMetricsCollector {\n if (this.metricsCollector) {\n return this.metricsCollector;\n }\n\n const collector = new CacheMetricsCollector();\n\n this.on(\"hit\", (data) => collector.recordEvent(\"hit\", data));\n this.on(\"miss\", (data) => collector.recordEvent(\"miss\", data));\n this.on(\"set\", (data) => collector.recordEvent(\"set\", data));\n this.on(\"removed\", (data) => collector.recordEvent(\"removed\", data));\n this.on(\"error\", (data) => collector.recordEvent(\"error\", data));\n\n this.metricsCollector = collector;\n\n return collector;\n }\n\n /**\n * Time the body, record the elapsed milliseconds against the metrics\n * collector for the given driver (defaults to the current driver's name).\n * Pass-through if the collector hasn't been instantiated yet — apps that\n * don't read metrics never pay for sample collection.\n */\n protected async timed<T>(body: () => Promise<T>, driverName?: string): Promise<T> {\n if (!this.metricsCollector) {\n return body();\n }\n\n const start = performance.now();\n\n try {\n return await body();\n } finally {\n const elapsed = performance.now() - start;\n const name = driverName ?? this.currentDriver?.name ?? \"unknown\";\n this.metricsCollector.recordLatency(name, elapsed);\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public async get<T = any>(key: CacheKey): Promise<T | null> {\n this.ensureDriverInitialized();\n return this.timed(() => this.currentDriver!.get<T>(key));\n }\n\n /**\n * Set a value in the cache.\n *\n * Accepts a positional TTL (number of seconds or duration string like `\"1h\"`)\n * or a rich {@link CacheSetOptions} object supporting `ttl`, `expiresAt`,\n * `tags`, `onConflict`, `namespace`, and per-call `driver` overrides.\n */\n public async set(key: CacheKey, value: any, ttlOrOptions?: CacheTtl | CacheSetOptions) {\n this.ensureDriverInitialized();\n\n const driverOverride =\n ttlOrOptions && typeof ttlOrOptions === \"object\" && \"driver\" in ttlOrOptions\n ? ttlOrOptions.driver\n : undefined;\n\n if (driverOverride) {\n const driver = await this.load(driverOverride);\n return this.timed(() => driver.set(key, value, ttlOrOptions), driver.name);\n }\n\n return this.timed(() => this.currentDriver!.set(key, value, ttlOrOptions));\n }\n\n /**\n * {@inheritdoc}\n */\n public async remove(key: CacheKey) {\n this.ensureDriverInitialized();\n return this.timed(() => this.currentDriver!.remove(key));\n }\n\n /**\n * {@inheritdoc}\n */\n public async removeNamespace(namespace: string) {\n this.ensureDriverInitialized();\n return this.currentDriver!.removeNamespace(namespace);\n }\n\n /**\n * {@inheritdoc}\n */\n public async flush() {\n this.ensureDriverInitialized();\n return this.currentDriver!.flush();\n }\n\n /**\n * {@inheritdoc}\n */\n public async connect() {\n this.ensureDriverInitialized();\n return this.currentDriver!.connect();\n }\n\n /**\n * {@inheritdoc}\n */\n public parseKey(key: CacheKey) {\n this.ensureDriverInitialized();\n return this.currentDriver!.parseKey(key);\n }\n\n /**\n * {@inheritdoc}\n */\n public get options() {\n this.ensureDriverInitialized();\n return this.currentDriver!.options;\n }\n\n /**\n * {@inheritdoc}\n */\n public setOptions(options: Record<string, any>) {\n this.ensureDriverInitialized();\n return this.currentDriver!.setOptions(options || {});\n }\n\n /**\n * Return the loaded driver instance for `driverName`, loading it on first\n * call. Optional `runtimeOptions` follow the same merge-over-config rules\n * as {@link load}; passing options after the driver has already been\n * loaded throws to avoid silent swallowing.\n */\n public async driver(driverName: string, runtimeOptions?: Record<string, any>) {\n if (this.loadedDrivers[driverName]) {\n this.assertNoConflictingReload(driverName, runtimeOptions);\n\n return this.loadedDrivers[driverName];\n }\n\n return this.load(driverName, runtimeOptions);\n }\n\n /**\n * Initialize the cache manager and pick the default driver\n */\n public async init() {\n const defaultCacheDriverName = this.configurations.default;\n\n if (!defaultCacheDriverName) {\n return;\n }\n\n const driver = await this.driver(defaultCacheDriverName);\n\n await this.use(driver);\n }\n\n /**\n * Load and connect the registered driver named `driver`. First-call wins —\n * subsequent calls without `runtimeOptions` return the cached instance, and\n * subsequent calls *with* `runtimeOptions` throw {@link CacheConfigurationError}\n * to avoid silently dropping the new options.\n *\n * `runtimeOptions` merge over `config.options[driver]` per-key (runtime wins),\n * letting consumers split static knobs (table, ttl, globalPrefix) from\n * constructor-only ones (pg's `client`, custom adapters, etc.).\n *\n * @example\n * const pool = new Pool({ connectionString });\n * const pg = await cache.load(\"pg\", { client: pool });\n */\n public async load(driver: string, runtimeOptions?: Record<string, any>) {\n if (this.loadedDrivers[driver]) {\n this.assertNoConflictingReload(driver, runtimeOptions);\n\n return this.loadedDrivers[driver];\n }\n\n const inFlight = this.loadingDrivers.get(driver);\n\n if (inFlight) {\n this.assertNoConflictingReload(driver, runtimeOptions);\n\n return inFlight;\n }\n\n const Driver = this.configurations.drivers[\n driver as keyof typeof this.configurations.drivers\n ] as DriverClass | undefined;\n\n if (!Driver) {\n throw new CacheConfigurationError(\n `Cache driver ${driver} is not found, please declare it in the cache drivers in the configurations list.`,\n );\n }\n\n const driverInstance = new Driver();\n const configOptions =\n this.configurations.options[driver as keyof typeof this.configurations.options] || {};\n\n driverInstance.setOptions({ ...configOptions, ...(runtimeOptions ?? {}) });\n\n const promise = (async () => {\n try {\n await driverInstance.connect();\n\n this.attachGlobalListeners(driverInstance);\n\n this.loadedDrivers[driver] = driverInstance;\n\n return driverInstance as CacheDriver<any, any>;\n } finally {\n this.loadingDrivers.delete(driver);\n }\n })();\n\n this.loadingDrivers.set(driver, promise);\n\n return promise;\n }\n\n /**\n * Guard against silently dropping runtime options on a re-load. Once a\n * driver has been instantiated, its options are frozen — calling `load` /\n * `driver` / `use` again with a non-empty `runtimeOptions` would otherwise\n * appear to work but actually use the original options. We throw instead\n * so the misuse surfaces at the call site.\n */\n protected assertNoConflictingReload(\n driverName: string,\n runtimeOptions: Record<string, any> | undefined,\n ): void {\n if (runtimeOptions === undefined) {\n return;\n }\n\n if (Object.keys(runtimeOptions).length === 0) {\n return;\n }\n\n throw new CacheConfigurationError(\n `Cache driver '${driverName}' is already loaded; runtime options on subsequent calls are ignored — register a second driver name if you need a different configuration.`,\n );\n }\n\n /**\n * Register and bind a driver\n */\n public registerDriver(driverName: string, driverClass: DriverClass) {\n (this.configurations.drivers as Record<string, DriverClass>)[driverName] = driverClass;\n }\n\n /**\n * Disconnect the cache manager\n */\n public async disconnect() {\n const drivers = new Set<any>(Object.values(this.loadedDrivers));\n\n if (this.currentDriver) {\n drivers.add(this.currentDriver);\n }\n\n await Promise.allSettled([...drivers].map((driver) => driver.disconnect()));\n\n for (const name of Object.keys(this.loadedDrivers)) {\n delete this.loadedDrivers[name];\n }\n\n this.loadingDrivers.clear();\n }\n\n /**\n * {@inheritdoc}\n */\n public async has(key: CacheKey): Promise<boolean> {\n this.ensureDriverInitialized();\n return this.currentDriver!.has(key);\n }\n\n /**\n * {@inheritdoc}\n */\n public async remember<T = any>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n this.ensureDriverInitialized();\n\n const driverOverride =\n ttlOrOptions && typeof ttlOrOptions === \"object\" && \"driver\" in ttlOrOptions\n ? ttlOrOptions.driver\n : undefined;\n\n if (driverOverride) {\n const driver = await this.load(driverOverride);\n return driver.remember(key, ttlOrOptions, callback);\n }\n\n return this.currentDriver!.remember(key, ttlOrOptions, callback);\n }\n\n /**\n * Stale-while-revalidate. Returns cached when fresh, returns the stale\n * value plus a background refresh when within `freshTtl..staleTtl`,\n * blocks like a normal miss past `staleTtl`. Honors per-call `driver`\n * override the same way `remember()` does.\n *\n * @example\n * const product = await cache.swr(\n * \"product.42\",\n * { freshTtl: \"1m\", staleTtl: \"1h\" },\n * () => db.products.find(42),\n * );\n */\n public async swr<T = any>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n this.ensureDriverInitialized();\n\n const driverOverride = options.driver;\n\n if (driverOverride) {\n const driver = await this.load(driverOverride);\n\n return driver.swr<T>(key, options, callback);\n }\n\n return this.currentDriver!.swr<T>(key, options, callback);\n }\n\n /**\n * {@inheritdoc}\n */\n public async pull(key: CacheKey): Promise<any | null> {\n this.ensureDriverInitialized();\n return this.currentDriver!.pull(key);\n }\n\n /**\n * {@inheritdoc}\n */\n public async forever(key: CacheKey, value: any): Promise<any> {\n this.ensureDriverInitialized();\n return this.currentDriver!.forever(key, value);\n }\n\n /**\n * {@inheritdoc}\n */\n public async increment(\n key: CacheKey,\n value?: number,\n options?: { ttl?: CacheTtl },\n ): Promise<number> {\n this.ensureDriverInitialized();\n return this.currentDriver!.increment(key, value, options);\n }\n\n /**\n * {@inheritdoc}\n */\n public async decrement(key: CacheKey, value?: number): Promise<number> {\n this.ensureDriverInitialized();\n return this.currentDriver!.decrement(key, value);\n }\n\n /**\n * {@inheritdoc}\n *\n * @example\n * await cache.extend(`session.${id}`, \"30m\"); // active again: 30 minutes from now\n */\n public async extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n this.ensureDriverInitialized();\n return this.currentDriver!.extend(key, ttl);\n }\n\n /**\n * In-flight `idempotent()` runs, per driver.\n */\n protected idempotentFlights: IdempotentFlights = new WeakMap();\n\n /**\n * Run `fn` once per `key`: concurrent calls share the single run, and repeat\n * calls within `ttl` get the stored result instead of running again. Use it\n * for work that must not repeat, such as charging a payment, handling a\n * webhook delivery or a retried job.\n *\n * A run that throws stores nothing: every caller sharing that run gets the\n * error, and the next call runs `fn` again. `ttl: 0` only shares in-flight\n * runs and never touches the store. See {@link IdempotentOptions} for\n * `distributed`.\n *\n * @example\n * const charge = await cache.idempotent(`charge.${orderId}`, () => gateway.charge(order), {\n * ttl: \"24h\",\n * });\n */\n public async idempotent<T>(\n key: CacheKey,\n fn: () => Promise<T>,\n options: IdempotentOptions,\n ): Promise<T> {\n this.ensureDriverInitialized();\n\n const driver = options.driver ? await this.load(options.driver) : this.currentDriver!;\n\n return runIdempotent(driver, this.idempotentFlights, key, fn, options);\n }\n\n /**\n * Probabilistic structures (Bloom and cuckoo filters, unique counters,\n * frequency tracking) stored in the current driver. Supported on the `redis`\n * and memory drivers; others throw `CacheUnsupportedError`.\n */\n public readonly structures: CacheStructures = createStructures(() => {\n this.ensureDriverInitialized();\n\n return structuresBackendOf(this.currentDriver!);\n });\n\n /**\n * {@inheritdoc}\n */\n public async many(keys: CacheKey[]): Promise<any[]> {\n this.ensureDriverInitialized();\n return this.currentDriver!.many(keys);\n }\n\n /**\n * {@inheritdoc}\n */\n public async setMany(items: Record<string, any>, ttl?: number): Promise<void> {\n this.ensureDriverInitialized();\n return this.currentDriver!.setMany(items, ttl);\n }\n\n /**\n * Register a global event listener (applies to all drivers)\n */\n public on(event: CacheEventType, handler: CacheEventHandler): this {\n if (!this.globalEventListeners.has(event)) {\n this.globalEventListeners.set(event, new Set());\n }\n this.globalEventListeners.get(event)!.add(handler);\n\n // Also attach to current driver if exists\n if (this.currentDriver) {\n this.currentDriver.on(event, handler);\n }\n\n // Attach to all loaded drivers\n for (const driver of Object.values(this.loadedDrivers)) {\n driver.on(event, handler);\n }\n\n return this;\n }\n\n /**\n * Remove a global event listener\n */\n public off(event: CacheEventType, handler: CacheEventHandler): this {\n const handlers = this.globalEventListeners.get(event);\n if (handlers) {\n handlers.delete(handler);\n }\n\n // Also remove from current driver\n if (this.currentDriver) {\n this.currentDriver.off(event, handler);\n }\n\n // Remove from all loaded drivers\n for (const driver of Object.values(this.loadedDrivers)) {\n driver.off(event, handler);\n }\n\n return this;\n }\n\n /**\n * Register a one-time global event listener\n */\n public once(event: CacheEventType, handler: CacheEventHandler): this {\n const onceHandler: CacheEventHandler = async (data) => {\n await handler(data);\n this.off(event, onceHandler);\n };\n return this.on(event, onceHandler);\n }\n\n /**\n * Attach global listeners to a driver\n */\n protected attachGlobalListeners(driver: CacheDriver<any, any>) {\n for (const [event, handlers] of this.globalEventListeners) {\n for (const handler of handlers) {\n driver.on(event, handler);\n }\n }\n }\n\n /**\n * Set if not exists (atomic operation)\n * Returns true if key was set, false if key already existed\n * Note: Only supported by drivers that implement setNX (e.g., Redis)\n */\n public async setNX(key: CacheKey, value: any, ttl?: number): Promise<boolean> {\n this.ensureDriverInitialized();\n\n if (!this.currentDriver!.setNX) {\n throw new Error(\n `setNX is not supported by the current cache driver: ${this.currentDriver!.name}`,\n );\n }\n\n return this.currentDriver!.setNX(key, value, ttl);\n }\n\n /**\n * Create a tagged cache instance for the given tags\n */\n public tags(tags: string[]): TaggedCacheDriver {\n this.ensureDriverInitialized();\n return this.currentDriver!.tags(tags);\n }\n\n /**\n * Atomically read, transform, and write a cached value. Delegates to the current driver.\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 this.ensureDriverInitialized();\n return this.currentDriver!.update<T>(key, fn, options);\n }\n\n /**\n * Shallow-merge a partial object into a cached value.\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 this.ensureDriverInitialized();\n return this.currentDriver!.merge<T>(key, partial, options);\n }\n\n /**\n * Obtain a list accessor bound to the current driver.\n */\n public list<T = any>(key: CacheKey): CacheListAccessor<T> {\n this.ensureDriverInitialized();\n return this.currentDriver!.list<T>(key);\n }\n\n /**\n * Acquire a distributed lock, run `fn`, and auto-release. Returns a\n * {@link LockOutcome} discriminated union so callers can distinguish\n * \"ran and got this value\" from \"skipped because someone else holds it\".\n *\n * Honors the `driver` option for per-call driver override, same as `set`\n * and `remember`.\n *\n * @example\n * const outcome = await cache.lock(\"lock.import\", \"5m\", async () => {\n * await runImport();\n * return \"done\";\n * });\n * if (!outcome.acquired) {\n * console.log(\"another worker is already importing\");\n * }\n */\n public async lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | LockOptions,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>> {\n this.ensureDriverInitialized();\n\n const driverOverride =\n ttlOrOptions && typeof ttlOrOptions === \"object\" && \"driver\" in ttlOrOptions\n ? ttlOrOptions.driver\n : undefined;\n\n const driver = driverOverride ? await this.load(driverOverride) : this.currentDriver!;\n\n return driver.lock<T>(key, ttlOrOptions as CacheTtl | Omit<LockOptions, \"driver\">, fn);\n }\n\n /**\n * Similarity retrieval. Delegates to the current driver's `similar()` impl.\n *\n * Drivers that lack a similarity index throw {@link CacheUnsupportedError}.\n *\n * @example\n * const hits = await cache.similar(await embed(query), { topK: 5, threshold: 0.7 });\n */\n /**\n * Create a scoped view over the cache. Every key written through the\n * returned scope is automatically prefixed with `prefix`; optional defaults\n * (`ttl`, `tags`) flow through every write inside the scope.\n *\n * Per-call options always win over scope defaults. Scope tags merge\n * additively with per-call tags. Nested scopes inherit from the parent.\n *\n * @example\n * const chat = cache.namespace(\"chats.10\", { ttl: \"30d\" });\n * await chat.set(\"messages.1\", msg); // → \"chats.10.messages.1\", 30d\n * await chat.set(\"draft\", d, { ttl: \"1h\" }); // per-call ttl wins\n * await chat.namespace(\"typing\", { ttl: \"5s\" }).set(\"user.42\", true);\n * await chat.clear(); // wipe the whole scope\n */\n public namespace(prefix: string, options?: CacheNamespaceOptions): ScopedCacheContract {\n this.ensureDriverInitialized();\n return new ScopedCache(this, prefix, options);\n }\n\n public async similar<T = any>(\n vector: number[],\n options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n this.ensureDriverInitialized();\n return this.currentDriver!.similar<T>(vector, options);\n }\n}\n\nexport const cache = new CacheManager();\n\n/**\n * Run `fn` once per `key` on the default `cache`. See {@link CacheManager.idempotent}.\n */\nexport function idempotent<T>(\n key: CacheKey,\n fn: () => Promise<T>,\n options: IdempotentOptions,\n): Promise<T> {\n return cache.idempotent(key, fn, options);\n}\n"],"mappings":";;;;;;;;AA2BA,IAAa,eAAb,MAA2D;;uBASK,CAAC;wCAKpC,IAAI,IAA4C;wBAK3B;GAC9C,SAAS,CAAC;GACV,SAAS,CAAC;EACZ;8CAK8E,IAAI,IAAI;cAYxE;2CA2emC,IAAI,QAAQ;oBAmCf,uBAAuB;GACnE,KAAK,wBAAwB;GAE7B,OAAO,oBAAoB,KAAK,aAAc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AM,aAAa,IAAI,WAAW,GAAG,IAAI,IAAI,QAAQ;GAErD,IAAI,cAAc,UAAW,IAAgC,MAAM,QAAQ,IAAI;EACjF;EAEA,SAAS;CACX;CAEA,KAAK,OAAO,GAAG;CAEf,OAAO;AACT"}
1
+ {"version":3,"file":"auto-key.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/cached/auto-key.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { CacheConfigurationError } from \"../types\";\n\n/**\n * Derive a cache key from a prefix and a set of function arguments.\n *\n * The key is `<prefix>.<hash>` where `hash` is the first 16 hex chars of the\n * sha1 of a stable JSON encoding of the args. Hashing keeps the mapping\n * injective — raw punctuation-joined segments can be folded together by\n * `parseCacheKey` (e.g. `(\"1.private\", \"\")` vs `(\"1\", \"private\")`).\n *\n * Encoding rules: object keys are sorted, `Date` → ISO string, `undefined` →\n * `{\"$u\":1}`, `bigint` → `{\"$b\":\"<decimal>\"}`. Object keys that start with\n * `$` get one more `$`, so an argument can never spell one of those markers,\n * and an own `__proto__` key is kept as data.\n *\n * No args → the prefix alone.\n *\n * Map, Set, functions, symbols and class instances cannot be encoded stably\n * and throw `CacheConfigurationError`; supply a custom `key` function instead.\n *\n * @example\n * deriveAutoKey(\"featured\", []); // \"featured\"\n * deriveAutoKey(\"user\", [42]); // \"user.<16 hex chars>\"\n */\nexport function deriveAutoKey(prefix: string, args: readonly unknown[]): string {\n if (args.length === 0) {\n return prefix;\n }\n\n let encoded: string;\n\n try {\n encoded = JSON.stringify(args.map((arg) => normalize(arg, prefix, new Set())));\n } catch (error) {\n if (error instanceof CacheConfigurationError) {\n throw error;\n }\n\n throw new CacheConfigurationError(\n `cached(): could not derive an auto-key from args for prefix \"${prefix}\". ` +\n `The args are not serializable. Use the options form with a custom key function. ` +\n `Original error: ${(error as Error).message}`,\n );\n }\n\n const hash = createHash(\"sha1\").update(encoded).digest(\"hex\").slice(0, 16);\n\n return `${prefix}.${hash}`;\n}\n\nfunction unsupported(prefix: string, what: string): never {\n throw new CacheConfigurationError(\n `cached(): cannot derive an auto-key for prefix \"${prefix}\" from ${what}. ` +\n `Use the options form with a custom key function.`,\n );\n}\n\nfunction normalize(value: unknown, prefix: string, seen: Set<object>): unknown {\n if (value === undefined) return { $u: 1 };\n if (value === null) return null;\n\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return value;\n case \"number\":\n // NaN / Infinity would collapse to null in JSON\n return Number.isFinite(value) ? value : { $n: String(value) };\n case \"bigint\":\n return { $b: value.toString() };\n case \"function\":\n return unsupported(prefix, \"a function argument\");\n case \"symbol\":\n return unsupported(prefix, \"a symbol argument\");\n }\n\n const obj = value as object;\n\n if (obj instanceof Date) {\n return Number.isNaN(obj.getTime()) ? { $d: \"invalid\" } : obj.toISOString();\n }\n\n if (obj instanceof Map) return unsupported(prefix, \"a Map argument\");\n if (obj instanceof Set) return unsupported(prefix, \"a Set argument\");\n\n if (seen.has(obj)) {\n throw new CacheConfigurationError(\n `cached(): could not derive an auto-key for prefix \"${prefix}\": circular reference in args. ` +\n `Use the options form with a custom key function.`,\n );\n }\n\n seen.add(obj);\n\n let result: unknown;\n\n if (Array.isArray(obj)) {\n result = obj.map((item) => normalize(item, prefix, seen));\n } else {\n const proto = Object.getPrototypeOf(obj);\n\n if (proto !== Object.prototype && proto !== null) {\n unsupported(prefix, \"a class instance argument\");\n }\n\n // Null prototype: an own `__proto__` key stays a key instead of setting\n // the prototype (and vanishing from the encoding).\n const out: Record<string, unknown> = Object.create(null);\n\n for (const key of Object.keys(obj).sort()) {\n // `$`-keys are doubled so `{ $u: 1 }` from an argument never equals the\n // `undefined` marker.\n const encodedKey = key.startsWith(\"$\") ? `$${key}` : key;\n\n out[encodedKey] = normalize((obj as Record<string, unknown>)[key], prefix, seen);\n }\n\n result = out;\n }\n\n seen.delete(obj);\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,cAAc,QAAgB,MAAkC;CAC9E,IAAI,KAA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;CAEJ,IAAI,MAAM,QAAQ,GAAG,GACnB,SAAS,IAAI,KAAK,SAAS,UAAU,MAAM,QAAQ,IAAI,CAAC;MACnD;EACL,MAAM,QAAQ,OAAO,eAAe,GAAG;EAEvC,IAAI,UAAU,OAAO,aAAa,UAAU,MAC1C,YAAY,QAAQ,2BAA2B;EAKjD,MAAM,MAA+B,OAAO,OAAO,IAAI;EAEvD,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;GAGzC,MAAM,aAAa,IAAI,WAAW,GAAG,IAAI,IAAI,QAAQ;GAErD,IAAI,cAAc,UAAW,IAAgC,MAAM,QAAQ,IAAI;EACjF;EAEA,SAAS;CACX;CAEA,KAAK,OAAO,GAAG;CAEf,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"cached.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/cached/cached.ts"],"mappings":";;;;AA+DA,SAAgB,OACd,IACA,iBACA,UACmB;CACnB,MAAM,SAAS,oBAA0B,iBAAiB,QAAQ;CAIlE,MAAM,8BAA+C;EACnD,KAAK,OAAO;EACZ,MAAM,OAAO;EACb,QAAQ,OAAO;CACjB;CAEA,MAAM,WAAW,OAAO,GAAG,SAA2B;EACpD,MAAM,MAAM,OAAO,IAAI,GAAG,IAAI;EAC9B,OAAO,MAAM,SAAY,KAAK,qBAAqB,SAAS,GAAG,GAAG,IAAI,CAAC;CACzE;CAEA,QAAQ,aAAa,OAAO,GAAG,SAA8B;EAC3D,MAAM,MAAM,OAAO,IAAI,GAAG,IAAI;EAC9B,IAAI,OAAO,QAAQ;GACjB,OAAO,MAAM,MAAM,OAAO,OAAO,MAAM,EAAC,CAAE,OAAO,GAAG;GACpD;EACF;EAEA,MAAM,MAAM,OAAO,GAAG;CACxB;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"cached.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/cached/cached.ts"],"sourcesContent":["import { cache } from \"../cache-manager\";\nimport type { CacheTtl, RememberOptions } from \"../types\";\nimport type { CachedOptions } from \"./normalize-args\";\nimport { normalizeCachedArgs } from \"./normalize-args\";\n\n/**\n * The shape returned by `cached()`. Callable like the wrapped function, plus\n * helpers for manual invalidation.\n */\nexport type CachedFn<Args extends unknown[], R> = ((...args: Args) => Promise<R>) & {\n /**\n * Drop the cache entry for a specific argument combination.\n *\n * @example\n * const getUser = cached((id: number) => db.users.find(id), \"user\", \"1h\");\n * await getUser.invalidate(42); // drops \"user.42\"\n */\n invalidate(...args: Args): Promise<void>;\n};\n\n/**\n * Wrap an async function so every invocation runs through the cache.\n *\n * Uses `cache.remember()` internally — inherits its stampede-protection\n * guarantees. Three calling shapes, `fn` always first.\n *\n * @example\n * // Shorthand — prefix auto-expands with the function's arguments.\n * // getUser(42) caches under \"user.42\".\n * const getUser = cached(\n * (id: number) => db.users.find(id),\n * \"user\",\n * \"1h\",\n * );\n *\n * @example\n * // Options form — custom key function, tags, per-call driver override.\n * const searchProducts = cached(\n * (filters: ProductFilters) => db.products.search(filters),\n * {\n * key: (filters) => `products.search.${filters.category}.${filters.sort}`,\n * ttl: \"15m\",\n * tags: [\"products\"],\n * },\n * );\n *\n * @example\n * // Manual invalidation — uses the same key scheme the wrapper uses internally.\n * await getUser.invalidate(42);\n */\nexport function cached<Args extends unknown[], R>(\n fn: (...args: Args) => Promise<R>,\n prefix: string,\n): CachedFn<Args, R>;\nexport function cached<Args extends unknown[], R>(\n fn: (...args: Args) => Promise<R>,\n prefix: string,\n ttl: CacheTtl,\n): CachedFn<Args, R>;\nexport function cached<Args extends unknown[], R>(\n fn: (...args: Args) => Promise<R>,\n options: CachedOptions<Args>,\n): CachedFn<Args, R>;\nexport function cached<Args extends unknown[], R>(\n fn: (...args: Args) => Promise<R>,\n prefixOrOptions: string | CachedOptions<Args>,\n maybeTtl?: CacheTtl,\n): CachedFn<Args, R> {\n const config = normalizeCachedArgs<Args>(prefixOrOptions, maybeTtl);\n\n // Build the RememberOptions payload once per call. `ttl` may still be undefined\n // here — that's fine, `remember` falls back to the driver's default TTL.\n const buildRememberOptions = (): RememberOptions => ({\n ttl: config.ttl,\n tags: config.tags,\n driver: config.driver,\n });\n\n const wrapper = (async (...args: Args): Promise<R> => {\n const key = config.key(...args);\n return cache.remember<R>(key, buildRememberOptions(), () => fn(...args));\n }) as CachedFn<Args, R>;\n\n wrapper.invalidate = async (...args: Args): Promise<void> => {\n const key = config.key(...args);\n if (config.driver) {\n await (await cache.driver(config.driver)).remove(key);\n return;\n }\n\n await cache.remove(key);\n };\n\n return wrapper;\n}\n"],"mappings":";;;;AA+DA,SAAgB,OACd,IACA,iBACA,UACmB;CACnB,MAAM,SAAS,oBAA0B,iBAAiB,QAAQ;CAIlE,MAAM,8BAA+C;EACnD,KAAK,OAAO;EACZ,MAAM,OAAO;EACb,QAAQ,OAAO;CACjB;CAEA,MAAM,WAAW,OAAO,GAAG,SAA2B;EACpD,MAAM,MAAM,OAAO,IAAI,GAAG,IAAI;EAC9B,OAAO,MAAM,SAAY,KAAK,qBAAqB,SAAS,GAAG,GAAG,IAAI,CAAC;CACzE;CAEA,QAAQ,aAAa,OAAO,GAAG,SAA8B;EAC3D,MAAM,MAAM,OAAO,IAAI,GAAG,IAAI;EAC9B,IAAI,OAAO,QAAQ;GACjB,OAAO,MAAM,MAAM,OAAO,OAAO,MAAM,EAAC,CAAE,OAAO,GAAG;GACpD;EACF;EAEA,MAAM,MAAM,OAAO,GAAG;CACxB;CAEA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize-args.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/cached/normalize-args.ts"],"mappings":";;;;;;;AAiDA,SAAgB,oBACd,iBACA,UAC8B;CAC9B,IAAI,OAAO,oBAAoB,UAAU;EACvC,MAAM,SAAS;EACf,OAAO;GACL,MAAM,GAAG,SAAe,cAAc,QAAQ,IAAI;GAClD,KAAK;EACP;CACF;CAEA,OAAO;EACL,KAAK,gBAAgB;EACrB,KAAK,gBAAgB;EACrB,MAAM,gBAAgB;EACtB,QAAQ,gBAAgB;CAC1B;AACF"}
1
+ {"version":3,"file":"normalize-args.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/cached/normalize-args.ts"],"sourcesContent":["import type { CacheTtl } from \"../types\";\nimport { deriveAutoKey } from \"./auto-key\";\n\n/**\n * Options accepted by the `cached()` factory in its verbose form. `key` is the\n * decisive escape hatch when the shorthand's auto-key rules don't fit.\n *\n * @see cached\n */\nexport type CachedOptions<Args extends unknown[]> = {\n /**\n * Derive a cache key from the wrapped function's arguments. Must be pure and\n * deterministic — every call with equivalent inputs should produce the same\n * key.\n */\n key: (...args: Args) => string;\n /**\n * Optional TTL on cache miss. Falls back to the driver's default TTL when omitted.\n */\n ttl?: CacheTtl;\n /**\n * Optional tags attached to every cache-miss write this wrapper produces.\n * Invalidate them the usual way via `cache.tags([...]).invalidate()`.\n */\n tags?: string[];\n /**\n * Per-call driver override. Routes every call produced by this wrapper to\n * the named driver without mutating `currentDriver`.\n */\n driver?: string;\n};\n\n/**\n * Normalized form of the factory arguments — a single shape every call path\n * in `cached()` operates on. Users never see this type.\n *\n * @internal\n */\nexport type NormalizedCachedConfig<Args extends unknown[]> = {\n key: (...args: Args) => string;\n ttl?: CacheTtl;\n tags?: string[];\n driver?: string;\n};\n\n/**\n * Resolve the positional-or-options arguments of `cached()` into a single\n * normalized config. Keeps the wrapper body free of shape-checks.\n */\nexport function normalizeCachedArgs<Args extends unknown[]>(\n prefixOrOptions: string | CachedOptions<Args>,\n maybeTtl?: CacheTtl,\n): NormalizedCachedConfig<Args> {\n if (typeof prefixOrOptions === \"string\") {\n const prefix = prefixOrOptions;\n return {\n key: (...args: Args) => deriveAutoKey(prefix, args),\n ttl: maybeTtl,\n };\n }\n\n return {\n key: prefixOrOptions.key,\n ttl: prefixOrOptions.ttl,\n tags: prefixOrOptions.tags,\n driver: prefixOrOptions.driver,\n };\n}\n"],"mappings":";;;;;;;AAiDA,SAAgB,oBACd,iBACA,UAC8B;CAC9B,IAAI,OAAO,oBAAoB,UAAU;EACvC,MAAM,SAAS;EACf,OAAO;GACL,MAAM,GAAG,SAAe,cAAc,QAAQ,IAAI;GAClD,KAAK;EACP;CACF;CAEA,OAAO;EACL,KAAK,gBAAgB;EACrB,KAAK,gBAAgB;EACrB,MAAM,gBAAgB;EACtB,QAAQ,gBAAgB;CAC1B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"base-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/base-cache-driver.ts"],"mappings":";;;;;;;;;AAmEA,MAAM,WAAW;CACf,UAAU;CACV,SAAS;CACT,UAAU;CACV,SAAS;CACT,SAAS;CACT,QAAQ;CACR,UAAU;CACV,SAAS;CACT,UAAU;CACV,SAAS;CACT,SAAS;CACT,UAAU;CACV,YAAY;CACZ,WAAW;CACX,eAAe;CACf,cAAc;CACd,kBAAkB;CAClB,OAAO;AACT;AAEA,IAAsB,kBAAtB,MAG8C;;mBAab;wCAsCyC,IAAI,IAAI;0CAwTxB,IAAI,IAAI;0CAKR,IAAI,IAAI;sCAKX,IAAI,IAAI;sCAQT,IAAI,IAAI;;;;;CA3W5D,IAAW,SAAS;EAClB,OAAQ,KAAK,gBAAgB;CAC/B;;;;CAKA,AAAO,gBAAgB,WAAoB;EACzC,KAAK,YAAY;EAEjB,OAAO;CACT;;;;CAKA,IAAW,OAAO,QAAoB;EACpC,KAAK,eAAe;CACtB;;;;CAoBA,AAAO,SAAS,KAAe;EAC7B,OAAO,cAAc,KAAK,KAAK,OAAO;CACxC;;;;CAKA,AAAO,WAAW,SAAkB;EAClC,KAAK,UAAU,WAAW,CAAC;EAC3B,OAAO;CACT;;;;CAKA,AAAO,GAAG,OAAuB,SAAkC;EACjE,IAAI,CAAC,KAAK,eAAe,IAAI,KAAK,GAChC,KAAK,eAAe,IAAI,uBAAO,IAAI,IAAI,CAAC;EAE1C,KAAK,eAAe,IAAI,KAAK,CAAC,CAAE,IAAI,OAAO;EAC3C,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AAS,UAAU,KAAK,cAAc,GAChD,MAAM,IAAI,wBACR,qDAAqD,OAAO,GAAG,EAAE,mEACnE;EAIF,MAAM,YAAY,GAAG,SAAS,OAAO,QAAQ,MAAM,GAAG,WAAW;EAEjE,MAAM,YAAa,MAAM,KAAK,IAAI,KAAK,WAAW;GAChD,YAAY;GACZ;EACF,CAAC;EAUD,IAAI,EAJF,OAAO,cAAc,YAAY,cAAc,QAAQ,YAAY,YAC9D,UAA6B,SAC9B,OAGJ,OAAO,EAAE,UAAU,MAAM;EAG3B,IAAI;GAEF,OAAO;IAAE,UAAU;IAAM,aADL,GAAG;GACQ;EACjC,UAAU;GAKR,IAAI;IACF,MAAM,KAAK,eAAe,KAAK,SAAS;GAC1C,SAAS,OAAO;IACd,KAAK,SAAS,2BAA2B,KAAK,SAAS,GAAG,KAAK,KAAK;GACtE;EACF;CACF;;;;;;;;CASA,MAAgB,eAAe,KAAe,UAAqC;EACjF,IAAK,MAAM,KAAK,IAAI,GAAG,MAAO,UAC5B,OAAO;EAGT,MAAM,KAAK,OAAO,GAAG;EAErB,OAAO;CACT;;;;;;;;CASA,MAAa,QACX,SACA,UAC+B;EAC/B,MAAM,IAAI,sBACR,IAAI,KAAK,KAAK,yHAChB;CACF;;;;CAKA,AAAU,qBAAqB,cAG7B;EACA,IAAI,OAAO,iBAAiB,YAAY,OAAO,iBAAiB,UAC9D,OAAO,EAAE,KAAK,aAAa;EAG7B,OAAO;GAAE,KAAK,aAAa;GAAK,OAAO,aAAa;EAAM;CAC5D;AACF"}
1
+ {"version":3,"file":"base-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/base-cache-driver.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { log, maskEmailsInText } from \"@warlock.js/logger\";\nimport { MemoryCacheList } from \"../list/memory-cache-list\";\nimport { sampleMembers } from \"../tag-sample\";\nimport { TaggedCache } from \"../tagged-cache\";\nimport type {\n CacheConflictPolicy,\n CacheData,\n CacheDriver,\n CacheEventData,\n CacheEventHandler,\n CacheEventType,\n CacheKey,\n CacheListAccessor,\n CacheOperationType,\n CacheSetOptions,\n CacheSetResult,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheSwrOptions,\n CacheTtl,\n LockOptions,\n LockOutcome,\n RememberOptions,\n} from \"../types\";\nimport { CacheConfigurationError, CacheUnsupportedError } from \"../types\";\nimport { normalizeToOptions, parseCacheKey, parseTtl, resolveTtl, safeErrorInfo } from \"../utils\";\n\n/**\n * Normalized form of the 3rd `set` argument.\n *\n * All drivers operate on this shape internally regardless of whether the caller\n * passed a positional TTL, a duration string, or a rich options object.\n */\nexport type NormalizedSetOptions = {\n /**\n * Final TTL in seconds — already merged with the driver-level default\n * (`this.options.ttl`). `Infinity` means \"no expiration\".\n *\n * Always populated. Drivers do NOT need to fall back to `this.ttl`\n * themselves — `resolveSetOptions` does the merge centrally so that\n * every driver respects the configured default without ceremony.\n */\n ttl: number;\n /**\n * Inline tag list, or undefined when none were provided.\n */\n tags?: string[];\n /**\n * Conflict policy. Defaults to `\"upsert\"`.\n */\n onConflict: CacheConflictPolicy;\n /**\n * Optional embedding vector for similarity retrieval. Drivers that do not\n * support similarity must throw {@link CacheUnsupportedError} when this is\n * present (rather than silently dropping it).\n */\n vector?: number[];\n /**\n * Optional freshness deadline as a millisecond timestamp. Set by `swr()`\n * to mark when the entry stops being \"fresh\" and becomes\n * \"stale-but-revalidatable.\" Drivers route this through\n * `prepareDataForStorage` so it persists in the wrapper.\n */\n staleAt?: number;\n};\n\nconst messages = {\n clearing: \"Clearing namespace\",\n cleared: \"Namespace cleared\",\n fetching: \"Fetching key\",\n fetched: \"Key fetched\",\n caching: \"Caching key\",\n cached: \"Key cached\",\n flushing: \"Flushing cache\",\n flushed: \"Cache flushed\",\n removing: \"Removing key\",\n removed: \"Key removed\",\n expired: \"Key expired\",\n notFound: \"Key not found\",\n connecting: \"Connecting to the cache engine.\",\n connected: \"Connected to the cache engine.\",\n disconnecting: \"Disconnecting from the cache engine.\",\n disconnected: \"Disconnected from the cache engine.\",\n connectionFailed: \"Failed to connect to the cache engine.\",\n error: \"Error occurred\",\n};\n\nexport abstract class BaseCacheDriver<\n ClientType,\n Options extends Record<string, any>,\n> implements CacheDriver<ClientType, Options> {\n /**\n * CLient driver\n */\n protected clientDriver!: ClientType;\n\n /**\n * Whether each operation (fetching, caching, removing…) is logged. Off by\n * default: per-operation lines cost CPU on every cache call and put cache\n * keys in production logs. Errors and connection failures are always\n * logged. Turn it on with the `logging: true` cache option or\n * `setLoggingState(true)`.\n */\n protected shouldLog: boolean = false;\n\n /**\n * {@inheritdoc}\n */\n public get client() {\n return (this.clientDriver || this) as unknown as ClientType;\n }\n\n /**\n * Set logging state\n */\n public setLoggingState(shouldLog: boolean) {\n this.shouldLog = shouldLog;\n\n return this;\n }\n\n /**\n * Set client driver\n */\n public set client(client: ClientType) {\n this.clientDriver = client;\n }\n\n /**\n * Get the cache driver name\n */\n public abstract name: string;\n\n /**\n * Options list\n */\n public options!: Options;\n\n /**\n * Event listeners storage\n */\n protected eventListeners: Map<CacheEventType, Set<CacheEventHandler>> = new Map();\n\n /**\n * {@inheritdoc}\n */\n public parseKey(key: CacheKey) {\n return parseCacheKey(key, this.options);\n }\n\n /**\n * {@inheritdoc}\n */\n public setOptions(options: Options) {\n this.options = options || {};\n return this;\n }\n\n /**\n * Register an event listener\n */\n public on(event: CacheEventType, handler: CacheEventHandler): this {\n if (!this.eventListeners.has(event)) {\n this.eventListeners.set(event, new Set());\n }\n this.eventListeners.get(event)!.add(handler);\n return this;\n }\n\n /**\n * Remove an event listener\n */\n public off(event: CacheEventType, handler: CacheEventHandler): this {\n const handlers = this.eventListeners.get(event);\n if (handlers) {\n handlers.delete(handler);\n }\n return this;\n }\n\n /**\n * Register a one-time event listener\n */\n public once(event: CacheEventType, handler: CacheEventHandler): this {\n const onceHandler: CacheEventHandler = async (data) => {\n await handler(data);\n this.off(event, onceHandler);\n };\n return this.on(event, onceHandler);\n }\n\n /**\n * Emit an event to all registered listeners\n */\n protected async emit(event: CacheEventType, data: Partial<CacheEventData> = {}): Promise<void> {\n const handlers = this.eventListeners.get(event);\n if (!handlers || handlers.size === 0) return;\n\n const eventData: CacheEventData = {\n driver: this.name,\n ...data,\n };\n\n // Execute all handlers\n const promises: Promise<void>[] = [];\n for (const handler of handlers) {\n try {\n const result = handler(eventData);\n if (result instanceof Promise) {\n promises.push(result);\n }\n } catch (error) {\n this.logError(`Error in event handler for '${event}'`, error);\n }\n }\n\n // Wait for all async handlers\n if (promises.length > 0) {\n await Promise.allSettled(promises);\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public abstract removeNamespace(namespace: string): Promise<any>;\n\n /**\n * {@inheritdoc}\n */\n public abstract set(\n key: CacheKey,\n value: any,\n ttlOrOptions?: CacheTtl | CacheSetOptions,\n ): Promise<any>;\n\n /**\n * Normalize the 3rd argument of a `set` call into a single shape every driver\n * can act on. Handles TTL parsing (number | string | Infinity), `expiresAt` →\n * relative TTL conversion, and mutual-exclusion validation.\n *\n * @throws {CacheConfigurationError} when `ttl` and `expiresAt` are passed together\n * or an unparseable duration string is supplied.\n */\n protected resolveSetOptions(ttlOrOptions?: CacheTtl | CacheSetOptions): NormalizedSetOptions {\n const options = normalizeToOptions(ttlOrOptions);\n\n return {\n ttl: resolveTtl(options.ttl, options.expiresAt, this.ttl),\n tags: options.tags,\n onConflict: options.onConflict ?? \"upsert\",\n vector: options.vector,\n staleAt: options.staleAt,\n };\n }\n\n /**\n * Resolve the union of cache keys associated with any of the given tags.\n * Used by `similar()` to narrow the candidate pool before similarity ranking.\n *\n * Returns `null` when no tags are passed (callers should treat that as \"no filter\").\n * Keys come back parsed (prefixed) — the index stores them un-prefixed, but\n * callers match them against their own parsed storage keys.\n */\n protected async getKeysForTags(tags: string[] | undefined): Promise<Set<string> | null> {\n if (!tags || tags.length === 0) {\n return null;\n }\n\n const allKeys = new Set<string>();\n for (const tag of tags) {\n const keys = await this.tagMembers(`cache:tags:${tag}`);\n for (const k of keys) {\n allKeys.add(this.parseKey(k));\n }\n }\n\n return allKeys;\n }\n\n // ============================================================\n // Tag index primitives\n // ============================================================\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: the index is an ordinary entry holding a string\n * array, read-modified-written under {@link runSerialized} — correct within\n * THIS process only. Drivers with a native primitive override it (redis SET,\n * pg atomic upsert, the in-process drivers' {@link InMemoryTagIndex}).\n */\n public async tagAdd(tagKey: CacheKey, members: string[]): Promise<void> {\n if (members.length === 0) {\n return;\n }\n\n await this.runSerialized(this.parseKey(tagKey), async () => {\n const current = await this.readTagArray(tagKey);\n const merged = new Set(current);\n\n for (const member of members) {\n merged.add(member);\n }\n\n if (merged.size !== current.length) {\n await this.set(tagKey, [...merged], Infinity);\n }\n });\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagMembers(tagKey: CacheKey): Promise<string[]> {\n return this.readTagArray(tagKey);\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: serialized read-filter-write (process-local); an\n * emptied index is removed.\n */\n public async tagRemove(tagKey: CacheKey, members: string[]): Promise<void> {\n if (members.length === 0) {\n return;\n }\n\n await this.runSerialized(this.parseKey(tagKey), async () => {\n const current = await this.readTagArray(tagKey);\n const dropped = new Set(members);\n const kept = current.filter((member) => !dropped.has(member));\n\n if (kept.length === current.length) {\n return;\n }\n\n if (kept.length === 0) {\n await this.remove(tagKey);\n } else {\n await this.set(tagKey, kept, Infinity);\n }\n });\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagDelete(tagKey: CacheKey): Promise<void> {\n await this.runSerialized(this.parseKey(tagKey), () => this.remove(tagKey));\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: reads every member and picks a random window.\n * Drivers with a native random-member command override it (redis\n * `SRANDMEMBER`, the in-process drivers' index).\n */\n public async tagSample(tagKey: CacheKey, count: number): Promise<string[]> {\n return sampleMembers(await this.tagMembers(tagKey), count);\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: the raw entry read (no `hit`/`miss` on drivers\n * that override {@link getEntry}). Drivers with a cheaper existence check\n * override it.\n */\n public async exists(key: CacheKey): Promise<boolean> {\n return (await this.getEntry(key)) !== null;\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: `remove()` per key, one after another. Drivers\n * with a network round trip per command override it.\n */\n public async removeMany(keys: CacheKey[]): Promise<void> {\n for (const key of keys) {\n await this.remove(key);\n }\n }\n\n /**\n * The index stored as a plain entry, or `[]`. Non-string members (a corrupted\n * or foreign value) are ignored rather than trusted.\n */\n protected async readTagArray(tagKey: CacheKey): Promise<string[]> {\n const value = await this.get(tagKey);\n\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.filter((member): member is string => typeof member === \"string\");\n }\n\n /**\n * Apply tag relationships after a successful write. Called by drivers once\n * the value is in storage.\n *\n * Pass the caller's key, not the parsed one: the tag index stores keys\n * un-prefixed so `invalidate()` can delete them through `remove(key)`.\n */\n protected async applyTags(key: CacheKey, tags: string[]): Promise<void> {\n if (tags.length === 0) {\n return;\n }\n\n const tagged = this.tags(tags);\n await (tagged as TaggedCache).storeTagRelationship(key);\n }\n\n /**\n * {@inheritdoc}\n */\n public abstract get(key: CacheKey): Promise<any>;\n\n /**\n * {@inheritdoc}\n */\n public abstract remove(key: CacheKey): Promise<void>;\n\n /**\n * {@inheritdoc}\n */\n public abstract flush(): Promise<void>;\n\n /**\n * Remove an entry by its already-parsed key (prefix applied). `remove()`\n * parses its key again, which would apply a `globalPrefix` twice; drivers\n * that store by parsed key override this. The default calls `remove()`.\n */\n protected async removeParsed(parsedKey: string): Promise<void> {\n await this.remove(parsedKey);\n }\n\n /**\n * {@inheritdoc}\n */\n public async has(key: CacheKey): Promise<boolean> {\n const value = await this.get(key);\n // Event is emitted by get() method\n return value !== null;\n }\n\n /**\n * In-flight `remember()` computations, one per parsed key (stampede guard).\n */\n protected rememberInFlight: Map<string, Promise<any>> = new Map();\n\n /**\n * In-flight `swr()` cold-miss fetches, one per parsed key.\n */\n protected swrFetchInFlight: Map<string, Promise<any>> = new Map();\n\n /**\n * In-flight `swr()` stale-window background refreshes, one per parsed key.\n */\n protected swrRefreshes: Map<string, Promise<void>> = new Map();\n\n /**\n * Per-key serialization chains for the in-process read-modify-write\n * operations (`update`, and the default `increment` / `pull`). Kept apart\n * from the stampede maps so a `remember()` can never break an update chain,\n * and never receives an unrelated promise.\n */\n protected updateChains: Map<string, Promise<any>> = new Map();\n\n /**\n * Run `task` once per key at a time: concurrent callers for the same\n * `parsedKey` share the in-flight promise registered in `inFlight`.\n */\n protected singleFlight<T>(\n inFlight: Map<string, Promise<any>>,\n parsedKey: string,\n task: () => Promise<T>,\n ): Promise<T> {\n const existing = inFlight.get(parsedKey);\n\n if (existing) {\n return existing as Promise<T>;\n }\n\n const promise: Promise<T> = task().finally(() => {\n if (inFlight.get(parsedKey) === promise) {\n inFlight.delete(parsedKey);\n }\n });\n\n inFlight.set(parsedKey, promise);\n\n return promise;\n }\n\n /**\n * Chain `task` after every earlier serialized task for the same key, so\n * read-modify-write callers in THIS process run one at a time. This is\n * process-local: it does not coordinate with other servers.\n */\n protected runSerialized<T>(parsedKey: string, task: () => Promise<T>): Promise<T> {\n const previous = this.updateChains.get(parsedKey) ?? Promise.resolve();\n\n const next = previous.catch(() => undefined).then(task);\n\n this.updateChains.set(parsedKey, next);\n\n // Clean up the slot once this link finishes, but only if nobody chained a\n // follow-up onto it meanwhile. The trailing catch keeps a rejected link\n // from surfacing as an unhandled rejection here (the caller still sees it).\n next\n .finally(() => {\n if (this.updateChains.get(parsedKey) === next) {\n this.updateChains.delete(parsedKey);\n }\n })\n .catch(() => undefined);\n\n return next;\n }\n\n /**\n * {@inheritdoc}\n */\n public async remember(\n key: CacheKey,\n ttlOrOptions: CacheTtl | RememberOptions,\n callback: () => Promise<any>,\n ): Promise<any> {\n const parsedKey = this.parseKey(key);\n\n // The options-form lets callers forward tags / driver-override through to\n // the cache-miss write. Normalize both shapes into a single CacheSetOptions\n // blob so there's one path from here on.\n const setOptions = this.normalizeRememberOptions(ttlOrOptions);\n\n // Only a real miss (`null`) recomputes: cached falsy values such as\n // `0`, `false` and `\"\"` are returned as-is.\n const cachedValue = await this.get(key);\n\n if (cachedValue !== null && cachedValue !== undefined) {\n return cachedValue;\n }\n\n return this.singleFlight(this.rememberInFlight, parsedKey, async () => {\n const result = await callback();\n\n await this.set(key, result, setOptions);\n\n return result;\n });\n }\n\n /**\n * Resolve the TTL-or-options arg of `remember` into a `CacheSetOptions` object\n * that can be passed straight to `set()`. Keeps the implementation unbranched.\n */\n protected normalizeRememberOptions(ttlOrOptions: CacheTtl | RememberOptions): CacheSetOptions {\n if (typeof ttlOrOptions === \"number\" || typeof ttlOrOptions === \"string\") {\n return { ttl: ttlOrOptions };\n }\n\n return {\n ttl: ttlOrOptions.ttl,\n tags: ttlOrOptions.tags,\n };\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: read raw entry, branch on freshness/staleness,\n * trigger background refresh in the stale window, fall through to\n * `callback` on miss/expiry. Concurrent cold-miss callers share one fetch\n * ({@link swrFetchInFlight}); concurrent stale-window callers share one\n * background refresh ({@link swrRefreshes}).\n *\n * Drivers without a real {@link getEntry} override degrade gracefully —\n * the synthetic entry has no `staleAt`, which the freshness check treats\n * as \"always fresh,\" so SWR behaves like a TTL-only cached read on those\n * drivers (no background refresh, but no double-fetch either).\n */\n public async swr<T = any>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n ): Promise<T> {\n const parsedKey = this.parseKey(key);\n const freshSeconds = parseTtl(options.freshTtl);\n const staleSeconds = parseTtl(options.staleTtl);\n\n if (staleSeconds <= freshSeconds) {\n throw new Error(\n `cache.swr: 'staleTtl' (${staleSeconds}s) must be greater than 'freshTtl' (${freshSeconds}s).`,\n );\n }\n\n const entry = await this.getEntry(key);\n const now = Date.now();\n\n const isExpired = entry?.expiresAt !== undefined && entry.expiresAt <= now;\n\n if (!entry || isExpired) {\n return this.singleFlight(this.swrFetchInFlight, parsedKey, () =>\n this.swrFetchAndStore<T>(key, options, callback, freshSeconds, staleSeconds),\n );\n }\n\n const isFresh = entry.staleAt === undefined || entry.staleAt > now;\n\n if (isFresh) {\n return entry.data as T;\n }\n\n this.scheduleSwrRefresh<T>(parsedKey, key, options, callback, freshSeconds, staleSeconds);\n\n return entry.data as T;\n }\n\n /**\n * Read the raw {@link CacheData} wrapper for a key, including any\n * `expiresAt` / `staleAt` metadata. Default implementation falls back to\n * `get()` and synthesizes a metadata-less wrapper — drivers that store\n * the wrapper directly (memory, lru, file, redis, pg, mock) override\n * this to return real metadata so SWR can branch on freshness.\n */\n protected async getEntry(key: CacheKey): Promise<CacheData | null> {\n const value = await this.get(key);\n\n if (value === null) {\n return null;\n }\n\n return { data: value };\n }\n\n /**\n * Remaining lifetime of an existing entry, in seconds — used by TTL-preserving\n * writes such as `update()` / `merge()` when the caller passes no explicit\n * `ttl`.\n *\n * - `Infinity` — the entry exists with no expiry (preserve \"never expires\").\n * - positive number — seconds left before the entry expires.\n * - `undefined` — the key is missing or already past its deadline; the caller\n * should fall back to the driver default TTL.\n *\n * Default reads `expiresAt` from {@link getEntry}, which the metadata-aware\n * drivers (memory, lru, mock, pg) populate. Drivers that track TTL natively\n * and don't carry `expiresAt` in their payload (Redis) override this.\n */\n protected async getRemainingTtl(key: CacheKey): Promise<number | undefined> {\n const entry = await this.getEntry(key);\n\n if (!entry) {\n return undefined;\n }\n\n if (!entry.expiresAt || entry.expiresAt === Infinity) {\n return Infinity;\n }\n\n const remainingSeconds = Math.ceil((entry.expiresAt - Date.now()) / 1000);\n\n return remainingSeconds > 0 ? remainingSeconds : undefined;\n }\n\n /**\n * Block-and-fetch path of `swr()`: invoked on miss or past-`staleTtl`\n * expiry. Writes through `set()` with the SWR options translated into\n * standard `CacheSetOptions` (ttl = staleTtl, staleAt = now + freshTtl).\n */\n protected async swrFetchAndStore<T>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n freshSeconds: number,\n staleSeconds: number,\n ): Promise<T> {\n const result = await callback();\n\n await this.set(key, result, {\n ttl: staleSeconds,\n staleAt: Date.now() + freshSeconds * 1000,\n tags: options.tags,\n });\n\n return result;\n }\n\n /**\n * Stale-window background refresh. Registers a single in-flight promise\n * per parsed key so concurrent SWR callers share one refresh. Failed\n * refreshes preserve the stale entry, log via `logError`, and emit on\n * `error` — the stale-returning caller never sees the failure.\n */\n protected scheduleSwrRefresh<T>(\n parsedKey: string,\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n freshSeconds: number,\n staleSeconds: number,\n ): void {\n if (this.swrRefreshes.has(parsedKey)) {\n return;\n }\n\n let refresh!: Promise<void>;\n refresh = (async () => {\n try {\n const result = await callback();\n\n await this.set(key, result, {\n ttl: staleSeconds,\n staleAt: Date.now() + freshSeconds * 1000,\n tags: options.tags,\n });\n } catch (error) {\n this.logError(`SWR background refresh failed for ${parsedKey}`, error);\n await this.emit(\"error\", { key: parsedKey, error });\n } finally {\n if (this.swrRefreshes.get(parsedKey) === refresh) {\n this.swrRefreshes.delete(parsedKey);\n }\n }\n })();\n\n this.swrRefreshes.set(parsedKey, refresh);\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: get-then-remove, serialized per key in THIS\n * process. Drivers with a native primitive override it to be atomic across\n * servers (redis `GETDEL`, pg `DELETE … RETURNING`) or process-atomic\n * (memory, lru, mock).\n */\n public async pull(key: CacheKey): Promise<any | null> {\n return this.runSerialized(this.parseKey(key), async () => {\n // Events are emitted by get() and remove()\n const value = await this.get(key);\n\n if (value !== null) {\n await this.remove(key);\n }\n\n return value;\n });\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: read the value and write it back with the new ttl,\n * serialized per key in THIS process. Drivers with a native expiry command\n * or in-place metadata override it.\n */\n public async extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n const seconds = this.resolveExtendTtl(ttl);\n\n return this.runSerialized(this.parseKey(key), async () => {\n const value = await this.get(key);\n\n if (value === null) {\n return false;\n }\n\n await this.set(key, value, seconds);\n\n return true;\n });\n }\n\n /**\n * Resolve the `ttl` argument of `extend()` into seconds. `0` and `Infinity`\n * both mean \"no expiry\" and resolve to `Infinity`; negative numbers, NaN and\n * unparseable strings throw a `CacheConfigurationError`.\n */\n protected resolveExtendTtl(ttl: CacheTtl): number {\n const seconds = parseTtl(ttl);\n\n return seconds === 0 ? Infinity : seconds;\n }\n\n /**\n * {@inheritdoc}\n */\n public async forever(key: CacheKey, value: any): Promise<any> {\n // Event is emitted by set() method\n return this.set(key, value, Infinity);\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: read-add-write serialized per key in THIS process,\n * keeping the entry's deadline (a missing key starts from 0 with the driver\n * default TTL). Not atomic across servers: drivers with a native primitive\n * override it (redis `INCRBY`, pg single-statement upsert).\n *\n * The value and its deadline come from ONE read. Reading them separately\n * let a counter that expired in between be rewritten from its stale value\n * with no expiry at all (a login-throttle counter that then never resets).\n * The remaining TTL is rounded down, so repeated increments can never push\n * a window's deadline later.\n */\n public async increment(\n key: CacheKey,\n value: number = 1,\n options: { ttl?: CacheTtl } = {},\n ): Promise<number> {\n const ttl = options.ttl === undefined ? this.ttl : parseTtl(options.ttl);\n const parsedKey = this.parseKey(key);\n\n return this.runSerialized(parsedKey, async () => {\n const entry = await this.getEntry(key);\n const now = Date.now();\n const expiresAt = entry?.expiresAt;\n const live = entry ? expiresAt == null || expiresAt > now : false;\n const current = entry && live ? entry.data : null;\n const base = current === null || current === undefined ? 0 : current;\n\n if (typeof base !== \"number\") {\n throw new Error(\n `Cannot increment non-numeric value for key: ${maskEmailsInText(parsedKey)}`,\n );\n }\n\n const newValue = base + value;\n\n if (!live) {\n // missing, or expired since it was read: a fresh counter\n await this.set(key, newValue, { ttl });\n } else if (expiresAt == null || expiresAt === Infinity) {\n await this.set(key, newValue, { ttl: options.ttl === undefined ? Infinity : ttl });\n } else {\n await this.set(key, newValue, {\n ttl: Math.max(1, Math.floor((expiresAt - now) / 1000)),\n });\n }\n\n return newValue;\n });\n }\n\n /**\n * {@inheritdoc}\n */\n public async decrement(key: CacheKey, value: number = 1): Promise<number> {\n return this.increment(key, -value);\n }\n\n /**\n * {@inheritdoc}\n */\n public async many(keys: CacheKey[]): Promise<any[]> {\n return Promise.all(keys.map((key) => this.get(key)));\n }\n\n /**\n * {@inheritdoc}\n */\n public async setMany(items: Record<string, any>, ttl?: number): Promise<void> {\n await Promise.all(Object.entries(items).map(([key, value]) => this.set(key, value, ttl)));\n }\n\n /**\n * Log the operation\n */\n protected log(operation: CacheOperationType, key?: string | any) {\n // Connection failures and client errors are logged whether or not\n // operation logging is on.\n const alwaysLogged = operation === \"connectionFailed\" || operation === \"error\";\n\n if (!this.shouldLog && !alwaysLogged) return;\n\n if (typeof key === \"string\") {\n // this will be likely used with file cache driver as it will convert the dot to slash\n // to make it consistent and not to confuse developers we will output the key by making sure it's a dot\n // An email inside a key (an app's `user.<email>` key, say) is personal\n // data in a log line; key-based redaction cannot reach it, so mask it.\n key = maskEmailsInText(key.replace(/\\//g, \".\"));\n }\n\n if (operation === \"connectionFailed\") {\n log.fatal(`cache.${this.name}`, operation, key);\n\n if (!this.shouldLog) return;\n }\n\n if (operation == \"notFound\" || operation == \"expired\") {\n return log.info(\n \"cache.\" + this.name,\n operation,\n (key ? key + \" \" : \"\") + messages[operation],\n );\n }\n\n if (operation.endsWith(\"ed\")) {\n return log.success(\n \"cache.\" + this.name,\n operation,\n (key ? key + \" \" : \"\") + messages[operation],\n );\n }\n\n log.info(\"cache.\" + this.name, operation, (key ? key + \" \" : \"\") + messages[operation]);\n }\n\n /**\n * Log error message\n *\n * Never logs the raw `error` object — driver connection errors (Redis,\n * Postgres, ...) can carry the connection string, including the password,\n * in the message/cause. Only a redacted `{ message, code }` shape is\n * passed to the structured logger.\n */\n protected logError(message: string, error?: any) {\n // Error lines name the key (\"SWR background refresh failed for\n // user.alice@example.com\"), and they are written even with logging off,\n // so addresses are masked here as in `log()`.\n const maskedMessage = maskEmailsInText(message);\n\n if (error) {\n const info = safeErrorInfo(error);\n\n log.error(\"cache.\" + this.name, \"error\", maskedMessage, {\n ...info,\n message: maskEmailsInText(info.message),\n });\n } else {\n log.error(\"cache.\" + this.name, \"error\", maskedMessage);\n }\n }\n\n /**\n * Get the default TTL in seconds. Parses human-readable strings (`\"1h\"`, `\"30m\"`)\n * from driver options if present; falls back to `Infinity` when no default is set.\n */\n public get ttl() {\n if (this.options.ttl === undefined) {\n return Infinity;\n }\n\n return parseTtl(this.options.ttl);\n }\n\n /**\n * Get time to live value in milliseconds\n */\n public getExpiresAt(ttl: number = this.ttl) {\n if (ttl) {\n return new Date().getTime() + ttl * 1000;\n }\n }\n\n /**\n * Wrap a value with TTL and optional freshness metadata for backend\n * storage. `staleAt` persists alongside `expiresAt` when supplied — used\n * by the SWR flow to mark when the entry stops being fresh.\n */\n protected prepareDataForStorage(data: any, ttl?: number, staleAt?: number) {\n const preparedData: CacheData = {\n data,\n };\n\n if (ttl) {\n preparedData.ttl = ttl;\n preparedData.expiresAt = this.getExpiresAt(ttl);\n }\n\n if (staleAt !== undefined) {\n preparedData.staleAt = staleAt;\n }\n\n return preparedData;\n }\n\n /**\n * Parse fetched data from cache.\n *\n * Object values are deep-cloned so callers cannot mutate stored state; a\n * driver that just deserialized `data` (it is already a private copy)\n * passes `clone: false`.\n */\n protected async parseCachedData(key: string, data: CacheData, clone = true) {\n this.log(\"fetched\", key);\n\n if (data.expiresAt && data.expiresAt < Date.now()) {\n try {\n await this.removeParsed(key);\n } catch (error) {\n this.logError(`Failed to remove expired entry ${key}`, error);\n }\n\n return null;\n }\n\n const value = data.data;\n\n // Skip cloning for primitives (immutable types)\n if (value === null || value === undefined) {\n return value;\n }\n\n const type = typeof value;\n if (type === \"string\" || type === \"number\" || type === \"boolean\" || !clone) {\n return value;\n }\n\n // Deep clone objects/arrays to prevent cache mutation\n try {\n return structuredClone(value);\n } catch (error) {\n this.logError(\n `Failed to clone cached value for ${key}, typeof value: ${typeof value}`,\n error,\n );\n throw error;\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public async connect() {\n this.log(\"connecting\");\n this.log(\"connected\");\n await this.emit(\"connected\");\n }\n\n /**\n * {@inheritdoc}\n */\n public async disconnect() {\n this.log(\"disconnected\");\n await this.emit(\"disconnected\");\n }\n\n /**\n * Create a tagged cache instance for the given tags\n */\n public tags(tags: string[]): any {\n return new TaggedCache(tags, this);\n }\n\n /**\n * Emit `invalidated` on behalf of a {@link TaggedCache} created by this\n * driver, once per `invalidate()` call. Listeners cannot fail the\n * invalidation: `emit` isolates them.\n *\n * @internal\n */\n public async emitTagsInvalidated(data: {\n tags: string[];\n keys: string[];\n durationMs: number;\n }): Promise<void> {\n await this.emit(\"invalidated\", data);\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: read → transform → write, serialized per key in\n * THIS process only. Drivers that can offer cross-server atomicity (redis,\n * pg: compare-and-set with retries) override it.\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 // Chain each update onto the previous one for the same key so concurrent\n // callers are serialized end-to-end, not merely awakened together.\n return this.runSerialized(this.parseKey(key), async () => {\n const current = (await this.get(key)) as T | null;\n const result = await fn(current);\n\n if (result === null) {\n await this.remove(key);\n return null;\n }\n\n if (options.ttl !== undefined) {\n await this.set(key, result, { ttl: options.ttl });\n\n return result;\n }\n\n // No explicit TTL → preserve the existing entry's remaining lifetime\n // rather than resetting it to the driver default.\n const remainingTtl = await this.getRemainingTtl(key);\n\n if (remainingTtl !== undefined) {\n await this.set(key, result, { ttl: remainingTtl });\n } else {\n await this.set(key, result);\n }\n\n return result;\n });\n }\n\n /**\n * {@inheritdoc}\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 result = await this.update<T>(\n key,\n (current) => {\n const base = (current ?? {}) as T;\n return { ...base, ...partial } as T;\n },\n options,\n );\n\n return result as T;\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation: read-mutate-write array backed by the underlying\n * cache entry. Concrete drivers (e.g. Redis) override with native commands.\n */\n public list<T = any>(key: CacheKey): CacheListAccessor<T> {\n return new MemoryCacheList<T>(this, key);\n }\n\n /**\n * {@inheritdoc}\n *\n * Built on top of `set({ onConflict: \"create\" })` — Redis-native `SET … NX EX`\n * under the hood on Redis, emulated via key-existence check on other drivers.\n * The lock value is the resolved `owner` (defaults to `pid.<process.pid>`).\n *\n * Always releases in `finally`, even if `fn` throws — the thrown error\n * propagates to the caller unchanged, and a failed release is logged rather\n * than replacing `fn`'s result or error. The ttl must be finite and\n * positive; there is no renewal, so it must exceed the worst-case duration.\n */\n public async lock<T>(\n key: CacheKey,\n ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">,\n fn: () => Promise<T>,\n ): Promise<LockOutcome<T>> {\n const { ttl, owner } = this.normalizeLockOptions(ttlOrOptions);\n\n // A lock with no expiry stays held forever if its holder crashes, on every\n // server. Refuse it up front (parseTtl also rejects undefined / NaN).\n const ttlSeconds = parseTtl(ttl);\n\n if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {\n throw new CacheConfigurationError(\n `cache.lock() requires a finite, positive ttl (got ${String(ttl)}). The ttl must exceed the worst-case duration of the locked work.`,\n );\n }\n // The stored value is `<owner>#<token>`: the token makes it unique per\n // acquisition so release can compare-and-delete instead of deleting blindly.\n const lockValue = `${owner ?? `pid.${process.pid}`}#${randomUUID()}`;\n\n const setResult = (await this.set(key, lockValue, {\n onConflict: \"create\",\n ttl,\n })) as CacheSetResult | unknown;\n\n // `onConflict` drivers return CacheSetResult. Drivers that no-op on set\n // (e.g. the null driver) may return anything else — treat that as\n // \"acquired\" since there's nothing to collide with.\n const wasSet =\n typeof setResult === \"object\" && setResult !== null && \"wasSet\" in setResult\n ? (setResult as CacheSetResult).wasSet\n : true;\n\n if (!wasSet) {\n return { acquired: false };\n }\n\n try {\n const value = await fn();\n return { acquired: true, value };\n } finally {\n // Only delete our own lock — if the TTL expired and a successor\n // acquired the key, its value differs and it is left alone. A release\n // failure (e.g. a Redis blip) is logged, never allowed to replace fn's\n // outcome: the lock still expires by its TTL.\n try {\n await this.deleteIfEquals(key, lockValue);\n } catch (error) {\n this.logError(`lock release failed for ${this.parseKey(key)}`, error);\n }\n }\n }\n\n /**\n * Compare-and-delete: remove `key` only when its current value equals\n * `expected`. Returns whether a delete happened.\n *\n * This default is get-then-remove and is NOT atomic across processes; drivers\n * with a real primitive (memory, redis, pg) override it.\n */\n protected async deleteIfEquals(key: CacheKey, expected: unknown): Promise<boolean> {\n if ((await this.get(key)) !== expected) {\n return false;\n }\n\n await this.remove(key);\n\n return true;\n }\n\n /**\n * {@inheritdoc}\n *\n * Default implementation throws {@link CacheUnsupportedError}. Drivers that\n * support similarity retrieval (memory family, `pg`, `redis` w/ RediSearch)\n * override this with a real impl.\n */\n public async similar<T = any>(\n _vector: number[],\n _options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n throw new CacheUnsupportedError(\n `'${this.name}' driver does not support similarity retrieval. Use a memory driver, 'pg' (with pgvector), or 'redis' (with RediSearch).`,\n );\n }\n\n /**\n * Resolve the TTL-or-options arg of `lock` into a uniform shape.\n */\n protected normalizeLockOptions(ttlOrOptions: CacheTtl | Omit<LockOptions, \"driver\">): {\n ttl: CacheTtl;\n owner?: string;\n } {\n if (typeof ttlOrOptions === \"number\" || typeof ttlOrOptions === \"string\") {\n return { ttl: ttlOrOptions };\n }\n\n return { ttl: ttlOrOptions.ttl, owner: ttlOrOptions.owner };\n }\n}\n"],"mappings":";;;;;;;;;AAmEA,MAAM,WAAW;CACf,UAAU;CACV,SAAS;CACT,UAAU;CACV,SAAS;CACT,SAAS;CACT,QAAQ;CACR,UAAU;CACV,SAAS;CACT,UAAU;CACV,SAAS;CACT,SAAS;CACT,UAAU;CACV,YAAY;CACZ,WAAW;CACX,eAAe;CACf,cAA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;;;CASA,MAAgB,eAAe,KAAe,UAAqC;EACjF,IAAK,MAAM,KAAK,IAAI,GAAG,MAAO,UAC5B,OAAO;EAGT,MAAM,KAAK,OAAO,GAAG;EAErB,OAAO;CACT;;;;;;;;CASA,MAAa,QACX,SACA,UAC+B;EAC/B,MAAM,IAAI,sBACR,IAAI,KAAK,KAAK,yHAChB;CACF;;;;CAKA,AAAU,qBAAqB,cAG7B;EACA,IAAI,OAAO,iBAAiB,YAAY,OAAO,iBAAiB,UAC9D,OAAO,EAAE,KAAK,aAAa;EAG7B,OAAO;GAAE,KAAK,aAAa;GAAK,OAAO,aAAa;EAAM;CAC5D;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"clone-value.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/clone-value.ts"],"mappings":";;;;;;;AAMA,SAAgB,WAAc,OAAa;CACzC,IAAI,UAAU,QAAQ,UAAU,QAC9B,OAAO;CAGT,MAAM,OAAO,OAAO;CAEpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WACrD,OAAO;CAGT,OAAO,gBAAgB,KAAK;AAC9B"}
1
+ {"version":3,"file":"clone-value.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/clone-value.ts"],"sourcesContent":["/**\n * Clone non-primitive values so cached state can't be mutated through\n * references held by callers. Primitives are immutable and returned as-is.\n *\n * @internal Shared by the in-process drivers; not part of the public API.\n */\nexport function cloneValue<T>(value: T): T {\n if (value === null || value === undefined) {\n return value;\n }\n\n const type = typeof value;\n\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value;\n }\n\n return structuredClone(value);\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,WAAc,OAAa;CACzC,IAAI,UAAU,QAAQ,UAAU,QAC9B,OAAO;CAGT,MAAM,OAAO,OAAO;CAEpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WACrD,OAAO;CAGT,OAAO,gBAAgB,KAAK;AAC9B"}
@@ -1 +1 @@
1
- {"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SAAS;EAG3C,KAAK,IAAI,SAAS;EAGlB,MAAM,KAAK,KAAK,SAAS;CAC3B;;;;CAKA,MAAa,UAAU;EACrB,KAAK,IAAI,YAAY;EACrB,MAAM,qBAAqB,KAAK,SAAS;EACzC,KAAK,IAAI,WAAW;EACpB,MAAM,KAAK,KAAK,WAAW;CAC7B;AACF;;;;;AAMA,SAAS,eAAe,OAA2B;CACjD,OAAO,OAAO,MAAM,cAAc,YAAY,MAAM,aAAa,KAAK,IAAI;AAC5E;AAEA,SAAS,cAAc,OAAoC;CACzD,IAAI,OAAO,SAAS,UAAU,MAAM;AACtC;AAEA,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD"}
1
+ {"version":3,"file":"file-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/file-cache-driver.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport {\n atomicWriteJsonAsync,\n ensureDirectoryAsync,\n getJsonFileAsync,\n listDirectoriesAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport path from \"path\";\nimport type {\n CacheData,\n CacheDriver,\n CacheKey,\n CacheSetOptions,\n CacheSetResult,\n CacheTtl,\n FileCacheOptions,\n} from \"../types\";\nimport { CacheConfigurationError, CacheError, CacheUnsupportedError } from \"../types\";\nimport { BaseCacheDriver } from \"./base-cache-driver\";\n\n/**\n * How many times an exclusive write (or a compare-and-delete) retries while\n * another caller is removing the same entry.\n */\nconst EXCLUSIVE_ATTEMPTS = 50;\n\n/**\n * A removal guard older than this belongs to a process that died while\n * holding it (the guarded step takes a few milliseconds).\n */\nconst STALE_GUARD_MS = 10_000;\n\nexport class FileCacheDriver\n extends BaseCacheDriver<FileCacheDriver, FileCacheOptions>\n implements CacheDriver<FileCacheDriver, FileCacheOptions>\n{\n /**\n * {@inheritdoc}\n */\n public name = \"file\";\n\n /**\n * {@inheritdoc}\n */\n public setOptions(options: FileCacheOptions) {\n if (!options.directory) {\n throw new CacheConfigurationError(\n \"File driver requires 'directory' option to be configured.\",\n );\n }\n\n return super.setOptions(options);\n }\n\n /**\n * Get the cache directory\n */\n public get directory() {\n const directory = this.options.directory;\n\n if (typeof directory === \"function\") {\n return directory();\n }\n\n throw new CacheConfigurationError(\n \"Cache directory is not defined, please define it in the file driver options\",\n );\n }\n\n /**\n * Get file name\n */\n public get fileName() {\n const fileName = this.options.fileName;\n\n if (typeof fileName === \"function\") {\n return fileName();\n }\n\n return \"cache.json\";\n }\n\n /**\n * Map a parsed cache key (or namespace) to its on-disk directory.\n *\n * The key must become exactly one directory component: `%` and the path\n * separators are percent-encoded so a hostile key (`../../etc`,\n * `..\\\\..\\\\evil`) turns into an inert directory name instead of a path\n * traversal, while distinct keys can never collide after encoding. Dots are\n * left untouched — the `.`-delimited namespace scheme is purely logical and\n * only ever produces a single filesystem component here.\n */\n protected keyDirectory(parsedKey: string): string {\n // An empty key would resolve to the cache root — `remove(\"{}\")` must never\n // be able to wipe it.\n if (parsedKey === \"\") {\n throw new CacheConfigurationError(\"Cache key must not be empty.\");\n }\n\n return this.containedPath(this.encodeKeySegment(parsedKey));\n }\n\n /**\n * Percent-encode a parsed key into an inert, single-component directory\n * name. Dots are left untouched — see {@link keyDirectory}.\n */\n protected encodeKeySegment(parsedKey: string): string {\n return parsedKey.replace(/%/g, \"%25\").replace(/\\//g, \"%2F\").replace(/\\\\/g, \"%5C\");\n }\n\n /**\n * Reverse of {@link encodeKeySegment} — recovers the logical, dot-delimited\n * parsed key from an on-disk directory name. Used by {@link removeNamespace}\n * to test which sibling directories logically belong to a namespace, since\n * dotted keys (`ns.a`) are stored as sibling directories rather than nested\n * ones (see {@link keyDirectory}'s doc comment).\n */\n protected decodeKeySegment(encoded: string): string {\n return encoded.replace(/%2F/g, \"/\").replace(/%5C/g, \"\\\\\").replace(/%25/g, \"%\");\n }\n\n /**\n * Resolve `segment` against the cache root and throw when the result lands\n * outside it — the last line of defense against path traversal, independent\n * of how the key was encoded.\n */\n protected containedPath(segment: string): string {\n const base = path.resolve(this.directory);\n const resolved = path.resolve(base, segment);\n const relative = path.relative(base, resolved);\n\n if (relative === \"..\" || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n throw new CacheError(`Cache key resolves outside the cache directory: \"${segment}\"`);\n }\n\n return resolved;\n }\n\n /**\n * {@inheritdoc}\n *\n * Dotted keys (`ns.a`) are stored as sibling directories, not nested ones\n * (see {@link keyDirectory}) — a directory literally named `<namespace>`\n * rarely exists on its own. Namespace removal therefore has to scan the\n * cache root's immediate children and remove every directory whose\n * *logical* (decoded) name equals the namespace or starts with\n * `<namespace>.`, mirroring the `key = $1 OR key LIKE $2` boundary\n * semantics the `pg` driver already uses for the same contract.\n */\n public async removeNamespace(namespace: string) {\n const parsedNamespace = this.parseKey(namespace);\n\n this.log(\"clearing\", namespace);\n\n try {\n const root = this.containedPath(\"\");\n\n if (parsedNamespace === \"\") {\n await removeDirectoryAsync(root);\n this.log(\"cleared\", namespace);\n return this;\n }\n\n const prefix = `${parsedNamespace}.`;\n const entries = await listDirectoriesAsync(root).catch(() => [] as string[]);\n\n await Promise.all(\n entries.map(async (entryPath) => {\n const decoded = this.decodeKeySegment(path.basename(entryPath));\n\n if (decoded === parsedNamespace || decoded.startsWith(prefix)) {\n await removeDirectoryAsync(entryPath);\n }\n }),\n );\n\n this.log(\"cleared\", namespace);\n } catch (error) {\n //\n }\n\n return this;\n }\n\n /**\n * {@inheritdoc}\n *\n * `onConflict: \"create\"` is exclusive (temp file + hard link, so `lock()`\n * is safe across concurrent writers). `onConflict: \"update\"` is NOT atomic:\n * the existence probe and the write are separate steps.\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 \"'file' driver does not support similarity retrieval — use a memory driver, 'pg' (with pgvector), or 'redis' (with RediSearch).\",\n );\n }\n\n this.log(\"caching\", parsedKey);\n\n const existing =\n onConflict === \"upsert\" || onConflict === \"create\" ? null : await this.get(key);\n const exists = existing !== null;\n\n if (onConflict === \"update\" && !exists) {\n const result: CacheSetResult = { wasSet: false, existing: null };\n return result;\n }\n\n const data = this.prepareDataForStorage(value, ttl, staleAt);\n\n const fileDirectory = this.keyDirectory(parsedKey);\n\n await ensureDirectoryAsync(fileDirectory);\n\n const filePath = path.resolve(fileDirectory, this.fileName);\n\n if (onConflict === \"create\") {\n const conflict = await this.writeExclusive(filePath, data);\n\n if (conflict) {\n const result: CacheSetResult = { wasSet: false, existing: conflict.existing };\n return result;\n }\n } else {\n await atomicWriteJsonAsync(filePath, data);\n }\n\n if (tags && tags.length > 0) {\n await this.applyTags(key, tags);\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 const result: CacheSetResult = { wasSet: true, existing: null };\n return result;\n }\n\n return this;\n }\n\n /**\n * Create `filePath` only if it does not exist. Writes a temp file, then\n * hard-links it to the target (EEXIST = already present). An existing but\n * expired entry is removed under the key's removal guard (see\n * {@link withRemovalGuard}), so of several contenders only one can ever\n * win the retried link.\n *\n * Returns `null` when written, or `{ existing }` on conflict.\n */\n protected async writeExclusive(\n filePath: string,\n data: CacheData,\n ): Promise<{ existing: any } | null> {\n const tempPath = `${filePath}.${randomBytes(6).toString(\"hex\")}.tmp`;\n\n try {\n await fs.promises.writeFile(tempPath, JSON.stringify(data, null, 2));\n\n for (let attempt = 0; attempt < EXCLUSIVE_ATTEMPTS; attempt++) {\n try {\n await fs.promises.link(tempPath, filePath);\n return null;\n } catch (error: any) {\n if (error?.code !== \"EEXIST\") {\n throw error;\n }\n }\n\n const current = await this.readEntryFile(filePath);\n\n // Removed between the link and the read: try the link again.\n if (!current) continue;\n\n // Unreadable (corrupt) file: treat as held, never delete it.\n if (!current.entry) return { existing: null };\n\n if (!isExpiredEntry(current.entry)) {\n return { existing: current.entry.data ?? null };\n }\n\n const guarded = await this.withRemovalGuard(filePath, async () => {\n // Re-read inside the guard: only the expired file that was judged\n // is removed, never one written since.\n const latest = await this.readEntryFile(filePath);\n\n if (latest?.entry && latest.inode === current.inode && isExpiredEntry(latest.entry)) {\n await fs.promises.unlink(filePath).catch(ignoreMissing);\n }\n });\n\n // Another contender is removing it: give it a moment, then retry.\n if (!guarded) await delay(1);\n }\n\n return { existing: null };\n } finally {\n await fs.promises.unlink(tempPath).catch(() => undefined);\n }\n }\n\n /**\n * Run `task` while holding the key's removal guard: a `<file>.guard` file\n * created exclusively. Entry files are only ever created by an exclusive\n * link onto a missing path, so while every removal of a live or expired\n * entry by `writeExclusive` / `deleteIfEquals` happens under this guard, no\n * removal can delete an entry another writer has just created.\n *\n * Returns `false` (without running `task`) when another caller holds the\n * guard. A guard left behind by a crashed process is cleared once it is\n * older than {@link STALE_GUARD_MS}.\n */\n protected async withRemovalGuard(filePath: string, task: () => Promise<void>): Promise<boolean> {\n const guardPath = `${filePath}.guard`;\n let handle: FileHandle;\n\n try {\n handle = await fs.promises.open(guardPath, \"wx\");\n } catch (error: any) {\n // The key directory is gone, so is the entry: nothing to remove.\n if (error?.code === \"ENOENT\") return true;\n\n if (error?.code !== \"EEXIST\") throw error;\n\n await this.clearStaleGuard(guardPath);\n\n return false;\n }\n\n try {\n await handle.close();\n await task();\n\n return true;\n } finally {\n await fs.promises.unlink(guardPath).catch(() => undefined);\n }\n }\n\n /**\n * Remove a removal guard whose holder died (older than {@link STALE_GUARD_MS}).\n */\n protected async clearStaleGuard(guardPath: string): Promise<void> {\n try {\n const { mtimeMs } = await fs.promises.stat(guardPath);\n\n if (Date.now() - mtimeMs > STALE_GUARD_MS) {\n await fs.promises.unlink(guardPath).catch(ignoreMissing);\n }\n } catch (error: any) {\n if (error?.code !== \"ENOENT\") throw error;\n }\n }\n\n /**\n * Read an entry file together with its inode, so a later step can tell\n * whether the file at the same path is still the one that was read.\n * `undefined` when the file does not exist; `entry: undefined` when it\n * cannot be parsed.\n */\n protected async readEntryFile(\n filePath: string,\n ): Promise<{ entry: CacheData | undefined; inode: number } | undefined> {\n let handle: FileHandle;\n\n try {\n handle = await fs.promises.open(filePath, \"r\");\n } catch (error: any) {\n if (error?.code === \"ENOENT\") return undefined;\n\n throw error;\n }\n\n try {\n const { ino } = await handle.stat();\n const text = await handle.readFile(\"utf-8\");\n\n try {\n const entry = JSON.parse(text) as CacheData | null;\n\n return { entry: entry && typeof entry === \"object\" ? entry : undefined, inode: ino };\n } catch {\n return { entry: undefined, inode: ino };\n }\n } finally {\n await handle.close();\n }\n }\n\n /**\n * {@inheritdoc}\n *\n * Compare-and-delete under the key's removal guard, so a lock released just\n * as it expired never deletes a successor's lock.\n */\n protected async deleteIfEquals(key: CacheKey, expected: unknown): Promise<boolean> {\n const parsedKey = this.parseKey(key);\n const fileDirectory = this.keyDirectory(parsedKey);\n const filePath = path.resolve(fileDirectory, this.fileName);\n let deleted = false;\n\n for (let attempt = 0; attempt < EXCLUSIVE_ATTEMPTS; attempt++) {\n const guarded = await this.withRemovalGuard(filePath, async () => {\n const current = await this.readEntryFile(filePath);\n\n if (!current?.entry || isExpiredEntry(current.entry) || current.entry.data !== expected) {\n return;\n }\n\n await fs.promises.unlink(filePath).catch(ignoreMissing);\n deleted = true;\n });\n\n if (guarded) break;\n\n await delay(1);\n }\n\n if (!deleted) return false;\n\n // Drop the key directory when nothing else was written into it meanwhile.\n await fs.promises.rmdir(fileDirectory).catch(() => undefined);\n\n this.log(\"removed\", parsedKey);\n await this.emit(\"removed\", { key: parsedKey });\n\n return true;\n }\n\n /**\n * {@inheritdoc}\n *\n * File driver does not yet ship with a file-lock primitive, so concurrent\n * writers could clobber each other. Rather than ship an unsafe default, we\n * throw — consumers can fall back to memory/redis for `update` until a\n * proper file lock lands (tracked in `domains/cache/backlog.md`).\n */\n public async update(): Promise<never> {\n throw new CacheUnsupportedError(\n \"`update()` is not supported on the file driver. Use the memory or redis driver, or wait for the file-lock primitive (see domains/cache/backlog.md).\",\n );\n }\n\n /**\n * {@inheritdoc}\n */\n public async merge(): Promise<never> {\n throw new CacheUnsupportedError(\n \"`merge()` is not supported on the file driver. Use the memory or redis driver.\",\n );\n }\n\n /**\n * Read the raw {@link CacheData} wrapper from disk, including `staleAt`\n * metadata. Returns `null` for missing or expired files — `swr()`\n * consumes this to branch on freshness.\n */\n protected async getEntry(key: CacheKey): Promise<CacheData | null> {\n const parsedKey = this.parseKey(key);\n const fileDirectory = this.keyDirectory(parsedKey);\n\n try {\n const entry = (await getJsonFileAsync(path.resolve(fileDirectory, this.fileName))) as\n | CacheData\n | undefined;\n\n if (!entry) {\n return null;\n }\n\n // `Infinity` (no expiry) is written to JSON as `null`; `null <= now`\n // is true, so only a real deadline may count as expired.\n if (typeof entry.expiresAt === \"number\" && entry.expiresAt <= Date.now()) {\n return null;\n }\n\n return entry;\n } catch {\n return null;\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public async get(key: CacheKey) {\n const parsedKey = this.parseKey(key);\n\n this.log(\"fetching\", parsedKey);\n\n const fileDirectory = this.keyDirectory(parsedKey);\n\n let value: CacheData | undefined;\n\n try {\n value = (await getJsonFileAsync(path.resolve(fileDirectory, this.fileName))) as\n | CacheData\n | undefined;\n } catch {\n // Missing file (ENOENT) or corrupt JSON: a plain miss. Never remove the\n // directory here — it may be mid-write by another process.\n value = undefined;\n }\n\n if (value === undefined || value === null || typeof value !== \"object\") {\n this.log(\"notFound\", parsedKey);\n await this.emit(\"miss\", { key: parsedKey });\n return null;\n }\n\n // Only a successfully parsed but expired entry is removed (inside\n // parseCachedData). The value was just parsed from disk, so it is already\n // a private copy: no clone.\n const result = await this.parseCachedData(parsedKey, value, false);\n\n if (result === null) {\n await this.emit(\"miss\", { key: parsedKey });\n } else {\n await this.emit(\"hit\", { key: parsedKey, value: result });\n }\n\n return result;\n }\n\n /**\n * {@inheritdoc}\n */\n public async remove(key: CacheKey) {\n await this.removeParsed(this.parseKey(key));\n }\n\n /**\n * {@inheritdoc}\n */\n protected async removeParsed(parsedKey: string): Promise<void> {\n this.log(\"removing\", parsedKey);\n\n const fileDirectory = this.keyDirectory(parsedKey);\n\n try {\n await removeDirectoryAsync(fileDirectory);\n\n this.log(\"removed\", parsedKey);\n // Emit removed event\n await this.emit(\"removed\", { key: parsedKey });\n } catch (error) {\n //\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public async flush() {\n this.log(\"flushing\");\n\n if (this.options.globalPrefix) {\n await this.removeNamespace(\"\");\n } else {\n await removeDirectoryAsync(this.directory);\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 this.log(\"connecting\");\n await ensureDirectoryAsync(this.directory);\n this.log(\"connected\");\n await this.emit(\"connected\");\n }\n}\n\n/**\n * Whether a stored entry is past its deadline. `Infinity` (no expiry) is\n * written to JSON as `null`, so only a real number can be expired.\n */\nfunction isExpiredEntry(entry: CacheData): boolean {\n return typeof entry.expiresAt === \"number\" && entry.expiresAt <= Date.now();\n}\n\nfunction ignoreMissing(error: NodeJS.ErrnoException): void {\n if (error?.code !== \"ENOENT\") throw error;\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;;;;;;;;;;AA2BA,MAAM,qBAAqB;;;;;AAM3B,MAAM,iBAAiB;AAEvB,IAAa,kBAAb,cACU,gBAEV;;;cAIgB;;;;;CAKd,AAAO,WAAW,SAA2B;EAC3C,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,wBACR,2DACF;EAGF,OAAO,MAAM,WAAW,OAAO;CACjC;;;;CAKA,IAAW,YAAY;EACrB,MAAM,YAAY,KAAK,QAAQ;EAE/B,IAAI,OAAO,cAAc,YACvB,OA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A,AAAO,OAAO,QAAsB;EAClC,KAAK,KAAK,OAAO,MAAM;CACzB;;;;;;CAOA,AAAO,gBAAgB,WAAyB;EAC9C,IAAI,cAAc,IAAI;GACpB,KAAK,KAAK,MAAM;GAEhB;EACF;EAEA,MAAM,SAAS,YAAY;EAE3B,KAAK,MAAM,OAAO,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,GACpC,IAAI,QAAQ,aAAa,IAAI,WAAW,MAAM,GAC5C,KAAK,KAAK,OAAO,GAAG;CAG1B;;;;CAKA,AAAO,QAAc;EACnB,KAAK,KAAK,MAAM;CAClB;AACF"}
1
+ {"version":3,"file":"in-memory-tag-index.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/in-memory-tag-index.ts"],"sourcesContent":["/**\n * Tag index for the in-process drivers (memory, memoryExtended, lru, mock).\n *\n * Lives beside the driver's entry storage, never inside it: index sets are not\n * entries, so they are never subject to `maxSize` / LRU eviction or TTL\n * sweeps, and every operation is synchronous — concurrent tagged writes in one\n * process can never drop a member.\n *\n * Keys are the driver-parsed tag keys (`<prefix>.cache.tags.<tag>`); members\n * are the caller's normalized, un-prefixed cache keys.\n */\nexport class InMemoryTagIndex {\n protected readonly sets: Map<string, Set<string>> = new Map();\n\n /**\n * Add members to a tag set, creating it on first use.\n */\n public add(tagKey: string, members: readonly string[]): void {\n if (members.length === 0) {\n return;\n }\n\n let set = this.sets.get(tagKey);\n\n if (!set) {\n set = new Set();\n this.sets.set(tagKey, set);\n }\n\n for (const member of members) {\n set.add(member);\n }\n }\n\n /**\n * The members of a tag set (a copy; empty when the set does not exist).\n */\n public members(tagKey: string): string[] {\n return [...(this.sets.get(tagKey) ?? [])];\n }\n\n /**\n * Up to `count` members of a tag set from a random starting point, without\n * copying the whole set.\n */\n public sample(tagKey: string, count: number): string[] {\n const set = this.sets.get(tagKey);\n\n if (!set || count <= 0) {\n return [];\n }\n\n const skip = set.size > count ? Math.floor(Math.random() * (set.size - count + 1)) : 0;\n const picked: string[] = [];\n let index = 0;\n\n for (const member of set) {\n if (index++ < skip) continue;\n\n picked.push(member);\n\n if (picked.length >= count) break;\n }\n\n return picked;\n }\n\n /**\n * Remove members from a tag set; an emptied set is dropped.\n */\n public remove(tagKey: string, members: readonly string[]): void {\n const set = this.sets.get(tagKey);\n\n if (!set) {\n return;\n }\n\n for (const member of members) {\n set.delete(member);\n }\n\n if (set.size === 0) {\n this.sets.delete(tagKey);\n }\n }\n\n /**\n * Drop a whole tag set.\n */\n public delete(tagKey: string): void {\n this.sets.delete(tagKey);\n }\n\n /**\n * Drop every tag set whose key equals `namespace` or sits under\n * `namespace.` — the same rule the drivers use for entries. An empty\n * namespace clears everything.\n */\n public removeNamespace(namespace: string): void {\n if (namespace === \"\") {\n this.sets.clear();\n\n return;\n }\n\n const prefix = namespace + \".\";\n\n for (const key of [...this.sets.keys()]) {\n if (key === namespace || key.startsWith(prefix)) {\n this.sets.delete(key);\n }\n }\n }\n\n /**\n * Drop every tag set.\n */\n public clear(): void {\n this.sets.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAa,mBAAb,MAA8B;;8BACwB,IAAI,IAAI;;;;;CAK5D,AAAO,IAAI,QAAgB,SAAkC;EAC3D,IAAI,QAAQ,WAAW,GACrB;EAGF,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM;EAE9B,IAAI,CAAC,KAAK;GACR,sBAAM,IAAI,IAAI;GACd,KAAK,KAAK,IAAI,QAAQ,GAAG;EAC3B;EAEA,KAAK,MAAM,UAAU,SACnB,IAAI,IAAI,MAAM;CAElB;;;;CAKA,AAAO,QAAQ,QAA0B;EACvC,OAAO,CAAC,GAAI,KAAK,KAAK,IAAI,MAAM,KAAK,CAAC,CAAE;CAC1C;;;;;CAMA,AAAO,OAAO,QAAgB,OAAyB;EACrD,MAAM,MAAM,KAAK,KAAK,IAAI,MAAM;EAEhC,IAAI,CAAC,OAAO,SAAS,GACnB,OAAO,CAAC;EAGV,MAAM,OAAO,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,OAAO,QAAQ,EAAE,IAAI;EACrF,MAAM,SAAmB,CAAC;EAC1B,IAAI,QAAQ;EAEZ,KAAK,MAAM,UAAU,KAAK;GACxB,IAAI,UAAU,MAAM;GAEpB,OAAO,KAAK,MAAM;GAElB,IAAI,OAAO,UAAU,OAAO;EAC9B;EAEA,OAAO;CACT;;;;CAKA,AAAO,OAAO,QAAgB,SAAkC;EAC9D,MAAM,MAAM,KAAK,KAAK,IAAI,MAAM;EAEhC,IAAI,CAAC,KACH;EAGF,KAAK,MAAM,UAAU,SACnB,IAAI,OAAO,MAAM;EAGnB,IAAI,IAAI,SAAS,GACf,KAAK,KAAK,OAAO,MAAM;CAE3B;;;;CAKA,AAAO,OAAO,QAAsB;EAClC,KAAK,KAAK,OAAO,MAAM;CACzB;;;;;;CAOA,AAAO,gBAAgB,WAAyB;EAC9C,IAAI,cAAc,IAAI;GACpB,KAAK,KAAK,MAAM;GAEhB;EACF;EAEA,MAAM,SAAS,YAAY;EAE3B,KAAK,MAAM,OAAO,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,GACpC,IAAI,QAAQ,aAAa,IAAI,WAAW,MAAM,GAC5C,KAAK,KAAK,OAAO,GAAG;CAG1B;;;;CAKA,AAAO,QAAc;EACnB,KAAK,KAAK,MAAM;CAClB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"lru-memory-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/lru-memory-cache-driver.ts"],"mappings":";;;;;;;;AAoBA,IAAM,YAAN,MAAgB;CAcd,AAAO,YACL,AAAO,KACP,AAAO,OACP,KACA;EAHO;EACA;cAfuB;cACA;EAiB9B,IAAI,OAAO,QAAQ,UACjB,KAAK,YAAY,KAAK,IAAI,IAAI,MAAM;CAExC;CAEA,IAAW,YAAqB;EAC9B,OAAO,KAAK,cAAc,UAAa,KAAK,YAAY,KAAK,IAAI;CACnE;AACF;;;;;;;AAQA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,MAAM,WAAW;CACzB;AACF"}
1
+ {"version":3,"file":"lru-memory-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/lru-memory-cache-driver.ts"],"sourcesContent":["import { maskEmailsInText } from \"@warlock.js/logger\";\nimport type {\n CacheData,\n CacheDriver,\n CacheKey,\n CacheSetOptions,\n CacheSetResult,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheSwrOptions,\n CacheTtl,\n LRUMemoryCacheOptions,\n} from \"../types\";\nimport { cosineSimilarity, parseTtl } from \"../utils\";\nimport { BaseCacheDriver } from \"./base-cache-driver\";\nimport { cloneValue } from \"./clone-value\";\nimport { MemoryStructuresBackend } from \"../structures/memory-structures-backend\";\nimport type { CacheStructuresBackend, StructuresCapable } from \"../structures/types\";\nimport { InMemoryTagIndex } from \"./in-memory-tag-index\";\n\nclass CacheNode {\n public next: CacheNode | null = null;\n public prev: CacheNode | null = null;\n public expiresAt?: number;\n /**\n * Freshness deadline (ms timestamp) — populated by `swr()`. Within\n * `expiresAt > now > staleAt` the entry is \"stale-but-revalidatable.\"\n */\n public staleAt?: number;\n /**\n * Optional embedding vector — populated when the entry was written with\n * `set({ vector })`. Scanned by `similar()`.\n */\n public vector?: number[];\n public constructor(\n public key: string,\n public value: any,\n ttl?: number,\n ) {\n if (ttl && ttl !== Infinity) {\n this.expiresAt = Date.now() + ttl * 1000;\n }\n }\n\n public get isExpired(): boolean {\n return this.expiresAt !== undefined && this.expiresAt < Date.now();\n }\n}\n\n/**\n * LRU Memory Cache Driver\n * The concept of LRU is to remove the least recently used data\n * whenever the cache is full\n * The question that resides here is how to tell the cache is full?\n */\nexport class LRUMemoryCacheDriver\n extends BaseCacheDriver<LRUMemoryCacheDriver, LRUMemoryCacheOptions>\n implements CacheDriver<LRUMemoryCacheDriver, LRUMemoryCacheOptions>, StructuresCapable\n{\n /**\n * {@inheritdoc}\n */\n public name = \"lru\";\n\n /**\n * Cache map\n */\n protected cache: Map<string, CacheNode> = new Map();\n\n /**\n * Tag index, kept out of the LRU list so capacity pressure can never evict it.\n */\n protected tagIndex: InMemoryTagIndex = new InMemoryTagIndex();\n\n /**\n * Head of the cache\n */\n protected head: CacheNode = new CacheNode(\"\", null);\n\n /**\n * Tail of the cache\n */\n protected tail: CacheNode = new CacheNode(\"\", null);\n\n /**\n * Cleanup interval reference\n */\n protected cleanupInterval?: NodeJS.Timeout;\n\n /**\n * {@inheritdoc}\n */\n public constructor() {\n super();\n\n this.init();\n this.startCleanup();\n }\n\n /**\n * Initialize the cache\n */\n public init() {\n this.head.next = this.tail;\n this.tail.prev = this.head;\n }\n\n /**\n * Start the cleanup process for expired items\n */\n public startCleanup() {\n // Clear existing interval if any\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n }\n\n this.cleanupInterval = setInterval(async () => {\n const now = Date.now();\n const expiredKeys: string[] = [];\n\n for (const [key, node] of this.cache) {\n if (node.expiresAt && node.expiresAt <= now) {\n expiredKeys.push(key);\n }\n }\n\n for (const key of expiredKeys) {\n const node = this.cache.get(key);\n if (node) {\n this.removeNode(node);\n this.cache.delete(key);\n this.log(\"expired\", key);\n // Emit expired event\n await this.emit(\"expired\", { key });\n }\n }\n }, 1000);\n\n // do not block the process from exiting\n this.cleanupInterval.unref();\n }\n\n /**\n * {@inheritdoc}\n *\n * Clears every entry whose key starts with the parsed namespace (followed\n * by a dot) or equals it exactly. Called with an empty namespace while a\n * `globalPrefix` is configured, clears everything under the prefix — which\n * is how `flush()` scopes cleanup per tenant.\n */\n public async removeNamespace(namespace: string) {\n const parsedNamespace = this.parseKey(namespace);\n\n this.log(\"clearing\", parsedNamespace || \"(all)\");\n\n const removed: string[] = [];\n\n this.tagIndex.removeNamespace(parsedNamespace);\n\n if (parsedNamespace === \"\") {\n this.structureStore?.clear();\n for (const key of this.cache.keys()) {\n removed.push(key);\n }\n } else {\n const prefix = parsedNamespace + \".\";\n\n this.structureStore?.clearPrefix(prefix);\n\n for (const key of this.cache.keys()) {\n if (key === parsedNamespace || key.startsWith(prefix)) {\n removed.push(key);\n }\n }\n }\n\n for (const key of removed) {\n const node = this.cache.get(key);\n if (node) {\n this.removeNode(node);\n this.cache.delete(key);\n }\n await this.emit(\"removed\", { key });\n }\n\n this.log(\"cleared\", parsedNamespace || \"(all)\");\n\n return removed;\n }\n\n /**\n * Backing store of `cache.structures`, created on first use.\n */\n protected structureStore?: MemoryStructuresBackend;\n\n /**\n * {@inheritdoc}\n */\n public structuresBackend(): CacheStructuresBackend {\n this.structureStore ??= new MemoryStructuresBackend((key) => this.parseKey(key));\n\n return this.structureStore;\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 this.log(\"caching\", parsedKey);\n\n // For conditional writes, check existence via get() so expired entries\n // are treated as missing (get() handles expiry cleanup). The raw `cache.get`\n // node lookup would let stale entries block onConflict: \"create\".\n let existingNode = this.cache.get(parsedKey);\n if (existingNode && existingNode.isExpired) {\n this.removeNode(existingNode);\n this.cache.delete(parsedKey);\n existingNode = undefined;\n }\n\n const exists = Boolean(existingNode);\n\n if (onConflict === \"create\" && exists) {\n const result: CacheSetResult = {\n wasSet: false,\n existing: cloneValue(existingNode!.value),\n };\n return result;\n }\n\n if (onConflict === \"update\" && !exists) {\n const result: CacheSetResult = { wasSet: false, existing: null };\n return result;\n }\n\n if (existingNode) {\n existingNode.value = value;\n if (ttl && ttl !== Infinity) {\n existingNode.expiresAt = Date.now() + ttl * 1000;\n } else {\n existingNode.expiresAt = undefined;\n }\n existingNode.staleAt = staleAt;\n if (vector) {\n existingNode.vector = vector.slice();\n }\n\n this.moveHead(existingNode);\n } else {\n const newNode = new CacheNode(parsedKey, value, ttl);\n newNode.staleAt = staleAt;\n if (vector) {\n newNode.vector = vector.slice();\n }\n\n this.cache.set(parsedKey, newNode);\n\n this.addNode(newNode);\n if (this.cache.size > this.capacity) {\n this.removeTail();\n }\n }\n\n if (tags && tags.length > 0) {\n await this.applyTags(key, tags);\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 const result: CacheSetResult = { wasSet: true, existing: null };\n return result;\n }\n\n return this;\n }\n\n /**\n * Move the node to the head\n */\n protected moveHead(node: CacheNode) {\n this.removeNode(node);\n this.addNode(node);\n }\n\n /**\n * Remove the node from the cache\n */\n protected removeNode(node: CacheNode) {\n node.prev!.next = node.next;\n node.next!.prev = node.prev;\n }\n\n /**\n * Add the node to the head\n */\n protected addNode(node: CacheNode) {\n node.next = this.head.next;\n node.prev = this.head;\n this.head.next!.prev = node;\n this.head.next = node;\n }\n\n /**\n * Remove the tail node\n */\n protected removeTail() {\n const node = this.tail.prev!;\n\n this.removeNode(node);\n\n this.cache.delete(node.key);\n }\n\n /**\n * Read the raw {@link CacheData} wrapper, including `staleAt` metadata.\n * Returns `null` for missing or expired nodes — `swr()` consumes this\n * to branch on freshness without going through `get()`'s clone-and-emit\n * path.\n */\n protected async getEntry(key: CacheKey): Promise<CacheData | null> {\n const parsedKey = this.parseKey(key);\n const node = this.cache.get(parsedKey);\n\n if (!node || node.isExpired) {\n return null;\n }\n\n // A copy, as `get()` returns: `swr()` hands this value to the caller, and\n // a caller mutating it must not change the cached entry for everyone.\n return {\n data: cloneValue(node.value),\n expiresAt: node.expiresAt,\n staleAt: node.staleAt,\n };\n }\n\n /**\n * {@inheritdoc}\n *\n * This driver stores the written value by reference, so the callers of a\n * cold-miss fetch get a copy rather than the stored object itself.\n */\n protected async swrFetchAndStore<T>(\n key: CacheKey,\n options: CacheSwrOptions,\n callback: () => Promise<T>,\n freshSeconds: number,\n staleSeconds: number,\n ): Promise<T> {\n const result = await super.swrFetchAndStore(key, options, callback, freshSeconds, staleSeconds);\n\n return cloneValue(result);\n }\n\n /**\n * Live node for `parsedKey`, or `undefined` when missing / expired (an\n * expired node is unlinked). Synchronous.\n */\n protected liveNode(parsedKey: string): CacheNode | undefined {\n const node = this.cache.get(parsedKey);\n\n if (!node) {\n return undefined;\n }\n\n if (node.isExpired) {\n this.removeNode(node);\n this.cache.delete(parsedKey);\n\n return undefined;\n }\n\n return node;\n }\n\n /**\n * {@inheritdoc}\n *\n * Read, add and write run synchronously (no `await` in between), so\n * concurrent increments in this process never lose an update. An existing\n * node keeps its expiry; a missing key starts from 0 with the default TTL.\n */\n public async increment(\n key: CacheKey,\n value: number = 1,\n options: { ttl?: CacheTtl } = {},\n ): Promise<number> {\n const ttl = options.ttl === undefined ? this.ttl : parseTtl(options.ttl);\n const parsedKey = this.parseKey(key);\n const node = this.liveNode(parsedKey);\n const current = node ? node.value : 0;\n\n if (typeof current !== \"number\") {\n throw new Error(`Cannot increment non-numeric value for key: ${maskEmailsInText(parsedKey)}`);\n }\n\n const newValue = current + value;\n\n if (node) {\n node.value = newValue;\n if (\n options.ttl !== undefined &&\n !Number.isFinite(node.expiresAt) &&\n Number.isFinite(ttl) &&\n ttl > 0\n ) {\n node.expiresAt = Date.now() + ttl * 1000;\n }\n this.moveHead(node);\n } else {\n const newNode = new CacheNode(parsedKey, newValue, ttl);\n\n this.cache.set(parsedKey, newNode);\n this.addNode(newNode);\n\n if (this.cache.size > this.capacity) {\n this.removeTail();\n }\n }\n\n await this.emit(\"set\", { key: parsedKey, value: newValue, ttl });\n\n return newValue;\n }\n\n /**\n * {@inheritdoc}\n *\n * The deadline moves in place, synchronously.\n */\n public async extend(key: CacheKey, ttl: CacheTtl): Promise<boolean> {\n const seconds = this.resolveExtendTtl(ttl);\n const node = this.liveNode(this.parseKey(key));\n\n if (!node) {\n return false;\n }\n\n node.expiresAt = Number.isFinite(seconds) ? Date.now() + seconds * 1000 : undefined;\n this.moveHead(node);\n\n return true;\n }\n\n /**\n * {@inheritdoc}\n *\n * Read and unlink run synchronously, so a value is handed out exactly once\n * even when concurrent callers pull the same key.\n */\n public async pull(key: CacheKey): Promise<any | null> {\n const parsedKey = this.parseKey(key);\n const node = this.liveNode(parsedKey);\n\n if (!node) {\n await this.emit(\"miss\", { key: parsedKey });\n\n return null;\n }\n\n this.removeNode(node);\n this.cache.delete(parsedKey);\n\n const value =\n node.value !== null && typeof node.value === \"object\"\n ? structuredClone(node.value)\n : node.value;\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 public async get(key: CacheKey) {\n const parsedKey = this.parseKey(key);\n\n this.log(\"fetching\", parsedKey);\n\n const node = this.cache.get(parsedKey);\n\n if (!node) {\n this.log(\"notFound\", parsedKey);\n // Emit miss event\n await this.emit(\"miss\", { key: parsedKey });\n return null;\n }\n\n // Check if expired\n if (node.isExpired) {\n this.removeNode(node);\n this.cache.delete(parsedKey);\n this.log(\"expired\", parsedKey);\n // Emit expired event\n await this.emit(\"expired\", { key: parsedKey });\n // Also emit miss since we're returning null\n await this.emit(\"miss\", { key: parsedKey });\n return null;\n }\n\n this.moveHead(node);\n\n this.log(\"fetched\", parsedKey);\n\n const value = node.value;\n\n // Apply cloning for immutability protection\n if (value === null || value === undefined) {\n return value;\n }\n\n const type = typeof value;\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n // Emit hit event\n await this.emit(\"hit\", { key: parsedKey, value });\n return value;\n }\n\n try {\n const clonedValue = structuredClone(value);\n // Emit hit event\n await this.emit(\"hit\", { key: parsedKey, value: clonedValue });\n return clonedValue;\n } catch (error) {\n this.logError(`Failed to clone cached value for ${parsedKey}`, error);\n throw error;\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public async remove(key: CacheKey) {\n const parsedKey = this.parseKey(key);\n\n this.log(\"removing\", parsedKey);\n\n const node = this.cache.get(parsedKey);\n\n if (node) {\n this.removeNode(node);\n this.cache.delete(parsedKey);\n }\n\n this.log(\"removed\", parsedKey);\n\n // Emit removed event\n await this.emit(\"removed\", { key: parsedKey });\n }\n\n /**\n * {@inheritdoc}\n *\n * Synchronous in-process set, never evicted or expired with the entries.\n */\n public async tagAdd(tagKey: CacheKey, members: string[]): Promise<void> {\n this.tagIndex.add(this.parseKey(tagKey), members);\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagMembers(tagKey: CacheKey): Promise<string[]> {\n return this.tagIndex.members(this.parseKey(tagKey));\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagRemove(tagKey: CacheKey, members: string[]): Promise<void> {\n this.tagIndex.remove(this.parseKey(tagKey), members);\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagDelete(tagKey: CacheKey): Promise<void> {\n this.tagIndex.delete(this.parseKey(tagKey));\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagSample(tagKey: CacheKey, count: number): Promise<string[]> {\n return this.tagIndex.sample(this.parseKey(tagKey), count);\n }\n\n /**\n * {@inheritdoc}\n *\n * A synchronous lookup: no copy, no events, no recency or TTL change.\n */\n public async exists(key: CacheKey): Promise<boolean> {\n return this.liveNode(this.parseKey(key)) !== undefined;\n }\n\n /**\n * {@inheritdoc}\n *\n * When a `globalPrefix` is configured, `flush` scopes itself to that prefix\n * so multi-tenant caches don't accidentally wipe sibling tenants. Without\n * a prefix, clears everything.\n */\n public async flush() {\n this.log(\"flushing\");\n\n if (this.options.globalPrefix) {\n await this.removeNamespace(\"\");\n } else {\n this.cache.clear();\n this.tagIndex.clear();\n this.structureStore?.clear();\n this.init();\n }\n\n this.log(\"flushed\");\n\n await this.emit(\"flushed\");\n }\n\n /**\n * {@inheritdoc}\n *\n * Brute-force O(N) cosine similarity over every cached node that carries a\n * vector. Suitable for development and small in-memory knowledge bases —\n * not for production beyond ~10k entries.\n *\n * @warning Dev-only — O(N) per query.\n */\n public async similar<T = any>(\n vector: number[],\n options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n const tagFilter = await this.getKeysForTags(options.tags);\n\n const hits: CacheSimilarHit<T>[] = [];\n\n for (const [parsedKey, node] of this.cache) {\n if (!node.vector) continue;\n if (node.isExpired) continue;\n if (tagFilter && !tagFilter.has(parsedKey)) continue;\n\n const score = cosineSimilarity(vector, node.vector);\n\n if (options.threshold !== undefined && score < options.threshold) {\n continue;\n }\n\n // Clone object values to match get() semantics.\n let value: any = node.value;\n if (value !== null && value !== undefined) {\n const t = typeof value;\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n value = structuredClone(value);\n }\n }\n\n hits.push({ key: parsedKey, value, score });\n }\n\n hits.sort((a, b) => b.score - a.score);\n\n if (options.topK >= 0 && hits.length > options.topK) {\n hits.length = options.topK;\n }\n\n return hits;\n }\n\n /**\n * Get lru capacity\n */\n public get capacity() {\n return this.options.capacity || 1000;\n }\n\n /**\n * {@inheritdoc}\n */\n public async disconnect() {\n // Clear the cleanup interval to prevent memory leaks\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n\n await super.disconnect();\n }\n}\n"],"mappings":";;;;;;;;AAoBA,IAAM,YAAN,MAAgB;CAcd,AAAO,YACL,AAAO,KACP,AAAO,OACP,KACA;EAHO;EACA;cAfuB;cACA;EAiB9B,IAAI,OAAO,QAAQ,UACjB,KAAK,YAAY,KAAK,IAAI,IAAI,MAAM;CAExC;CAEA,IAAW,YAAqB;EAC9B,OAAO,KAAK,cAAc,UAAa,KAAK,YAAY,KAAK,IAAI;CACnE;AACF;;;;;;;AAQA,IAAa,uBAAb,cACU,gBAEV;;;;CAkCE,AAAO,cAAc;EACnB,MAAM;cA/BM;+BAK4B,IAAI,IAAI;kBAKX,IAAI,iBAAiB;cAKhC,IAAI,UAAU,IAAI,IAAI;cAKtB,IAAI,UAAU,IAAI,IAAI;EAahD,KAAK,KAAK;EACV,KAAK,aAAa;CACpB;;;;CAKA,AAAO,OAAO;EACZ,KAAK,KAAK,OAAO,KAAK;EACtB,KAAK,KAAK,OAAO,KAAK;CACxB;;;;CAKA,AAAO,eAAe;EAEp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;;;;;;;;;;CAYA,MAAa,QACX,QACA,SAC+B;EAC/B,MAAM,YAAY,MAAM,KAAK,eAAe,QAAQ,IAAI;EAExD,MAAM,OAA6B,CAAC;EAEpC,KAAK,MAAM,CAAC,WAAW,WAAW,CAAC,GAAG,KAAK,WAAW,GAAG;GACvD,IAAI,aAAa,CAAC,UAAU,IAAI,SAAS,GACvC;GAKF,MAAM,QAAQ,KAAK,SAAS,SAAS;GAErC,IAAI,CAAC,OACH;GAGF,MAAM,QAAa,WAAW,MAAM,IAAI;GAExC,MAAM,QAAQ,iBAAiB,QAAQ,MAAM;GAE7C,IAAI,QAAQ,cAAc,UAAa,QAAQ,QAAQ,WACrD;GAGF,KAAK,KAAK;IAAE,KAAK;IAAW;IAAO;GAAM,CAAC;EAC5C;EAEA,KAAK,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;EAErC,IAAI,QAAQ,QAAQ,KAAK,KAAK,SAAS,QAAQ,MAC7C,KAAK,SAAS,QAAQ;EAGxB,OAAO;CACT;;;;CAKA,MAAa,aAAa;EAExB,IAAI,KAAK,iBAAiB;GACxB,cAAc,KAAK,eAAe;GAClC,KAAK,kBAAkB;EACzB;EAEA,MAAM,MAAM,WAAW;CACzB;AACF"}
1
+ {"version":3,"file":"memory-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/memory-cache-driver.ts"],"sourcesContent":["import { maskEmailsInText } from \"@warlock.js/logger\";\nimport type {\n CacheData,\n CacheDriver,\n CacheKey,\n CacheSetOptions,\n CacheSetResult,\n CacheSimilarHit,\n CacheSimilarOptions,\n CacheTtl,\n MemoryCacheOptions,\n} from \"../types\";\nimport { cosineSimilarity, parseTtl } from \"../utils\";\nimport { BaseCacheDriver } from \"./base-cache-driver\";\nimport { MemoryStructuresBackend } from \"../structures/memory-structures-backend\";\nimport type { CacheStructuresBackend, StructuresCapable } from \"../structures/types\";\nimport { InMemoryTagIndex } from \"./in-memory-tag-index\";\n\n/**\n * Clone non-primitive values so cached state can't be mutated through\n * references held by callers. Primitives are immutable and returned as-is.\n */\nfunction cloneValue<T>(value: T): T {\n if (value === null || value === undefined) {\n return value;\n }\n\n const type = typeof value;\n\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value;\n }\n\n return structuredClone(value);\n}\n\n/**\n * Entries a memory driver keeps when `maxSize` is not configured. Past it the\n * least recently used entries are evicted, so request-derived keys cannot\n * grow the heap without bound.\n */\nconst DEFAULT_MAX_SIZE = 10_000;\n\nexport class MemoryCacheDriver\n extends BaseCacheDriver<MemoryCacheDriver, MemoryCacheOptions>\n implements CacheDriver<MemoryCacheDriver, MemoryCacheOptions>, StructuresCapable\n{\n /**\n * {@inheritdoc}\n */\n public name = \"memory\";\n\n /**\n * Flat storage keyed by the parsed key. Insertion order doubles as LRU\n * order (least recently used first) — accessed entries are deleted and\n * re-inserted.\n */\n protected entries: Map<string, CacheData> = new Map();\n\n /**\n * Read-only object view of the stored entries, keyed by parsed key.\n * Kept for introspection; the values are the live stored wrappers.\n */\n public get data(): Record<string, CacheData> {\n return Object.fromEntries(this.entries);\n }\n\n /**\n * Expiry records for entries with a FINITE ttl only (parsed key => expiresAt ms).\n * The sweep iterates just these.\n */\n protected expiry: Map<string, number> = new Map();\n\n /**\n * Cleanup interval reference\n */\n protected cleanupInterval?: NodeJS.Timeout;\n\n /**\n * Parallel vector index keyed by parsedKey. Populated by `set({ vector })`,\n * scanned by `similar()`. Lifetime mirrors the main entry — cleared on\n * `remove`, `flush`, expiry, namespace clear, overwrite without a vector,\n * and LRU eviction.\n */\n protected vectorIndex: Map<string, number[]> = new Map();\n\n /**\n * Tag index, kept apart from `entries`: never evicted by `maxSize`, never\n * swept by TTL, and updated synchronously.\n */\n protected tagIndex: InMemoryTagIndex = new InMemoryTagIndex();\n\n /**\n * {@inheritdoc}\n */\n public constructor() {\n super();\n\n this.startCleanup();\n }\n\n /**\n * Start the cleanup process for entries that carry a finite ttl\n */\n public startCleanup() {\n // Clear existing interval if any\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n }\n\n this.cleanupInterval = setInterval(async () => {\n const now = Date.now();\n const expiredKeys: string[] = [];\n\n for (const [key, expiresAt] of this.expiry) {\n if (expiresAt <= now) {\n expiredKeys.push(key);\n }\n }\n\n for (const key of expiredKeys) {\n // the entry may have been rewritten/slid since the snapshot\n const expiresAt = this.expiry.get(key);\n\n if (expiresAt === undefined || expiresAt > now) {\n continue;\n }\n\n this.dropEntry(key);\n\n this.log(\"expired\", key);\n // Emit expired event\n await this.emit(\"expired\", { key });\n }\n }, 1000);\n\n // do not block the process from exiting\n this.cleanupInterval.unref();\n }\n\n /**\n * Backing store of `cache.structures` (bloom, cuckoo, unique counter,\n * frequency), created on first use.\n */\n protected structureStore?: MemoryStructuresBackend;\n\n /**\n * {@inheritdoc}\n */\n public structuresBackend(): CacheStructuresBackend {\n this.structureStore ??= new MemoryStructuresBackend((key) => this.parseKey(key));\n\n return this.structureStore;\n }\n\n /**\n * Delete an entry and every side record (expiry, vector). Synchronous.\n */\n protected dropEntry(parsedKey: string) {\n this.entries.delete(parsedKey);\n this.expiry.delete(parsedKey);\n this.vectorIndex.delete(parsedKey);\n }\n\n /**\n * Raw, synchronous read of a live entry. An expired entry is deleted and\n * reported as missing. Never slides TTLs, never emits, never touches LRU order.\n */\n protected readLive(parsedKey: string): CacheData | undefined {\n const entry = this.entries.get(parsedKey);\n\n if (!entry) {\n return undefined;\n }\n\n if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) {\n this.dropEntry(parsedKey);\n return undefined;\n }\n\n return entry;\n }\n\n /**\n * The entry limit: `maxSize`, or 10,000 when it is not set. `Infinity`\n * (or `0`) means no limit.\n */\n protected get maxSize(): number {\n const configured = this.options?.maxSize;\n\n if (configured === undefined) return DEFAULT_MAX_SIZE;\n\n return configured > 0 ? configured : Infinity;\n }\n\n /**\n * Mark an entry as most recently used (not tracked without a limit).\n */\n protected touch(parsedKey: string, entry: CacheData) {\n if (this.maxSize === Infinity) return;\n\n this.entries.delete(parsedKey);\n this.entries.set(parsedKey, entry);\n }\n\n /**\n * When true, every live read slides the entry's expiration forward by its\n * ttl (the `memoryExtended` driver). Set in a subclass constructor rather\n * than redeclared, so subclasses stay structurally compatible with this\n * class (the `client` type relies on that).\n */\n protected slidingExpiration = false;\n\n /**\n * Invoked on a live read hit, before the value is returned. Runs only from\n * `get()` after the expiry check, so an expired entry is never resurrected,\n * and never from the internal existence check used by `onConflict`.\n */\n protected onRead(parsedKey: string, entry: CacheData) {\n if (!this.slidingExpiration) {\n return;\n }\n\n const rawTtl = entry.ttl ?? this.options.ttl;\n const ttl = rawTtl !== undefined ? parseTtl(rawTtl) : undefined;\n\n if (ttl && Number.isFinite(ttl)) {\n entry.expiresAt = this.getExpiresAt(ttl);\n this.expiry.set(parsedKey, entry.expiresAt as number);\n }\n }\n\n /**\n * {@inheritdoc}\n */\n public async removeNamespace(namespace: string) {\n this.log(\"clearing\", namespace);\n\n namespace = this.parseKey(namespace);\n\n this.tagIndex.removeNamespace(namespace);\n\n if (namespace === \"\") {\n this.structureStore?.clear();\n this.entries.clear();\n this.expiry.clear();\n this.vectorIndex.clear();\n } else {\n const prefix = namespace + \".\";\n\n this.structureStore?.clearPrefix(prefix);\n\n for (const key of [...this.entries.keys()]) {\n if (key === namespace || key.startsWith(prefix)) {\n this.dropEntry(key);\n }\n }\n }\n\n this.log(\"cleared\", namespace);\n\n return this;\n }\n\n /**\n * {@inheritdoc}\n *\n * The conditional check and the write run with no `await` in between, so\n * `onConflict` decisions are atomic within the process.\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 this.log(\"caching\", parsedKey);\n\n // expired entries count as missing (readLive deletes them)\n const existing =\n onConflict === \"create\" || onConflict === \"update\" ? this.readLive(parsedKey) : undefined;\n\n if (onConflict === \"create\" && existing) {\n const result: CacheSetResult = { wasSet: false, existing: cloneValue(existing.data) };\n return result;\n }\n\n if (onConflict === \"update\" && !existing) {\n const result: CacheSetResult = { wasSet: false, existing: null };\n return result;\n }\n\n const data = this.prepareDataForStorage(cloneValue(value), ttl, staleAt);\n\n // delete + set moves the key to the most-recent position\n this.entries.delete(parsedKey);\n this.entries.set(parsedKey, data);\n\n if (data.expiresAt !== undefined && Number.isFinite(data.expiresAt)) {\n this.expiry.set(parsedKey, data.expiresAt);\n } else {\n this.expiry.delete(parsedKey);\n }\n\n if (vector) {\n this.vectorIndex.set(parsedKey, vector.slice());\n } else {\n this.vectorIndex.delete(parsedKey);\n }\n\n this.enforceMaxSize(parsedKey);\n\n if (tags && tags.length > 0) {\n await this.applyTags(key, tags);\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 const result: CacheSetResult = { wasSet: true, existing: null };\n return result;\n }\n\n return this;\n }\n\n /**\n * {@inheritdoc}\n *\n * The check and the delete run synchronously (no `await` between them), so\n * the compare-and-delete is atomic within the process.\n */\n protected async deleteIfEquals(key: CacheKey, expected: unknown): Promise<boolean> {\n const parsedKey = this.parseKey(key);\n const entry = this.readLive(parsedKey);\n\n if (!entry || entry.data !== expected) {\n return false;\n }\n\n await this.remove(key);\n\n return true;\n }\n\n /**\n * {@inheritdoc}\n *\n * Read, add and write run synchronously (no `await` in between), so\n * concurrent increments in this process never lose an update. An existing\n * entry keeps its expiry; a missing key starts from 0 with the default TTL.\n */\n public async increment(\n key: CacheKey,\n value: number = 1,\n options: { ttl?: CacheTtl } = {},\n ): Promise<number> {\n const ttl = options.ttl === undefined ? this.ttl : parseTtl(options.ttl);\n const parsedKey = this.parseKey(key);\n const entry = this.readLive(parsedKey);\n const current = entry ? entry.data : 0;\n\n if (typeof current !== \"number\") {\n throw new Error(`Cannot increment non-numeric value for key: ${maskEmailsInText(parsedKey)}`);\n }\n\n const newValue = current + value;\n\n if (entry) {\n entry.data = newValue;\n if (\n options.ttl !== undefined &&\n !Number.isFinite(entry.expiresAt) &&\n Number.isFinite(ttl) &&\n ttl > 0\n ) {\n entry.ttl = ttl;\n entry.expiresAt = Date.now() + ttl * 1000;\n this.expiry.set(parsedKey, entry.expiresAt);\n }\n this.touch(parsedKey, entry);\n } else {\n const data = this.prepareDataForStorage(newValue, ttl);\n\n this.entries.set(parsedKey, data);\n\n if (data.expiresAt !== undefined && Number.isFinite(data.expiresAt)) {\n this.expiry.set(parsedKey, data.expiresAt);\n }\n\n this.enforceMaxSize(parsedKey);\n }\n\n await this.emit(\"set\", { key: parsedKey, value: newValue, ttl: entry?.ttl ?? ttl });\n\n return newValue;\n }\n\n /**\n * {@inheritdoc}\n *\n * The deadline moves in place, synchronously, so concurrent callers never\n * interleave with the read.\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 entry = this.readLive(parsedKey);\n\n if (!entry) {\n return false;\n }\n\n if (Number.isFinite(seconds)) {\n entry.ttl = seconds;\n entry.expiresAt = this.getExpiresAt(seconds);\n this.expiry.set(parsedKey, entry.expiresAt as number);\n } else {\n delete entry.ttl;\n delete entry.expiresAt;\n this.expiry.delete(parsedKey);\n }\n\n this.touch(parsedKey, entry);\n\n return true;\n }\n\n /**\n * {@inheritdoc}\n *\n * Read and delete run synchronously, so a value is handed out exactly once\n * even when concurrent callers pull the same key.\n */\n public async pull(key: CacheKey): Promise<any | null> {\n const parsedKey = this.parseKey(key);\n const entry = this.readLive(parsedKey);\n\n if (!entry) {\n await this.emit(\"miss\", { key: parsedKey });\n\n return null;\n }\n\n this.dropEntry(parsedKey);\n\n const value = cloneValue(entry.data);\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 public async get(key: CacheKey) {\n const parsedKey = this.parseKey(key);\n\n this.log(\"fetching\", parsedKey);\n\n const entry = this.readLive(parsedKey);\n\n if (!entry) {\n this.log(\"notFound\", parsedKey);\n // Emit miss event\n await this.emit(\"miss\", { key: parsedKey });\n return null;\n }\n\n this.onRead(parsedKey, entry);\n this.touch(parsedKey, entry);\n\n const result = await this.parseCachedData(parsedKey, entry);\n\n // Emit hit event\n await this.emit(\"hit\", { key: parsedKey, value: result });\n\n return result;\n }\n\n /**\n * Read the raw {@link CacheData} wrapper (cloned), including `staleAt` metadata.\n * Returns `null` for missing or expired entries so the SWR flow can branch\n * cleanly. Does not emit `hit`/`miss` events — that's `get()`'s job.\n */\n protected async getEntry(key: CacheKey): Promise<CacheData | null> {\n const entry = this.readLive(this.parseKey(key));\n\n if (!entry) {\n return null;\n }\n\n return { ...entry, data: cloneValue(entry.data) };\n }\n\n /**\n * {@inheritdoc}\n */\n public async remove(key: CacheKey) {\n const parsedKey = this.parseKey(key);\n\n this.log(\"removing\", parsedKey);\n\n this.dropEntry(parsedKey);\n\n this.log(\"removed\", parsedKey);\n\n // Emit removed event\n await this.emit(\"removed\", { key: parsedKey });\n }\n\n /**\n * {@inheritdoc}\n *\n * Synchronous in-process set — concurrent tagged writes never drop members.\n */\n public async tagAdd(tagKey: CacheKey, members: string[]): Promise<void> {\n this.tagIndex.add(this.parseKey(tagKey), members);\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagMembers(tagKey: CacheKey): Promise<string[]> {\n return this.tagIndex.members(this.parseKey(tagKey));\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagRemove(tagKey: CacheKey, members: string[]): Promise<void> {\n this.tagIndex.remove(this.parseKey(tagKey), members);\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagDelete(tagKey: CacheKey): Promise<void> {\n this.tagIndex.delete(this.parseKey(tagKey));\n }\n\n /**\n * {@inheritdoc}\n */\n public async tagSample(tagKey: CacheKey, count: number): Promise<string[]> {\n return this.tagIndex.sample(this.parseKey(tagKey), count);\n }\n\n /**\n * {@inheritdoc}\n *\n * A synchronous lookup: no copy, no events, no recency or TTL change.\n */\n public async exists(key: CacheKey): Promise<boolean> {\n return this.readLive(this.parseKey(key)) !== undefined;\n }\n\n /**\n * {@inheritdoc}\n */\n public async flush() {\n this.log(\"flushing\");\n if (this.options.globalPrefix) {\n await this.removeNamespace(\"\");\n } else {\n this.entries.clear();\n this.expiry.clear();\n this.vectorIndex.clear();\n this.tagIndex.clear();\n this.structureStore?.clear();\n }\n\n this.log(\"flushed\");\n\n // Emit flushed event\n await this.emit(\"flushed\");\n }\n\n /**\n * Evict least recently used entries (Map insertion order) until the size is\n * within `maxSize`. Never evicts `protectedKey` (the key just written).\n */\n protected enforceMaxSize(protectedKey: string) {\n const maxSize = this.maxSize;\n\n if (this.entries.size <= maxSize) {\n return;\n }\n\n // Iterate the live key view (deleting the current key during Map\n // iteration is safe): normally only the oldest key is touched, with no\n // copy of the key list.\n for (const lruKey of this.entries.keys()) {\n if (this.entries.size <= maxSize) {\n break;\n }\n\n if (lruKey === protectedKey) {\n continue;\n }\n\n this.log(\"removing\", lruKey);\n this.dropEntry(lruKey);\n this.log(\"removed\", lruKey);\n }\n }\n\n /**\n * {@inheritdoc}\n *\n * Brute-force O(N) cosine similarity over every entry that was written with\n * `set({ vector })`. Suitable for development and small in-memory knowledge\n * bases — not for production beyond ~10k entries. Use the `pg` driver\n * (with pgvector) or `redis` (with RediSearch) at scale.\n *\n * @warning Dev-only — O(N) per query.\n */\n public async similar<T = any>(\n vector: number[],\n options: CacheSimilarOptions,\n ): Promise<CacheSimilarHit<T>[]> {\n const tagFilter = await this.getKeysForTags(options.tags);\n\n const hits: CacheSimilarHit<T>[] = [];\n\n for (const [parsedKey, stored] of [...this.vectorIndex]) {\n if (tagFilter && !tagFilter.has(parsedKey)) {\n continue;\n }\n\n // Read the entry directly by its already-parsed key — this.get() would\n // parse it again and apply globalPrefix twice, missing every entry.\n const entry = this.readLive(parsedKey);\n\n if (!entry) {\n continue;\n }\n\n const value: any = cloneValue(entry.data);\n\n const score = cosineSimilarity(vector, stored);\n\n if (options.threshold !== undefined && score < options.threshold) {\n continue;\n }\n\n hits.push({ key: parsedKey, value, score });\n }\n\n hits.sort((a, b) => b.score - a.score);\n\n if (options.topK >= 0 && hits.length > options.topK) {\n hits.length = options.topK;\n }\n\n return hits;\n }\n\n /**\n * {@inheritdoc}\n */\n public async disconnect() {\n // Clear the cleanup interval to prevent memory leaks\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n\n await super.disconnect();\n }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,WAAc,OAAa;CAClC,IAAI,UAAU,QAAQ,UAAU,QAC9B,OAAO;CAGT,MAAM,OAAO,OAAO;CAEpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WACrD,OAAO;CAGT,OAAO,gBAAgB,KAAK;AAC9B;;;;;;AAOA,MAAM,mBAAmB;AAEzB,IAAa,oBAAb,cACU,gBAEV;;;;;CAiBE,IAAW,OAAkC;EAC3C,OAAO,OAAO,YAAY,KAAK,OAAO;CACxC;;;;CA8BA,AAAO,cAAc;EACnB,MAAM;cA9CM;iCAO8B,IAAI,IAAI;gCAcZ,IAAI,IAAI;qCAaD,IAAI,IAAI;kBAMhB,IAAI,iBAAiB;2BAyH9B;EAjH5B,KAAK,aAAa;CACpB;;;;CAKA,AAAO,eAAe;EAEpB,IAAI,KAAK,iBACP,cAAc,KAAK,eAAe;EAGpC,KAAK,kBAAkB,YAAY,YAAY;GAC7C,MAAM,MAAM,KAAK,IAAI;GACrB,MAAM,cAAwB,CAAC;GAE/B,KAAK,MAAM,CAAC,KAAK,cAAc,KAAK,QAClC,IAAI,aAAa,KACf,YAAY,KAAK,GAAG;GAIxB,KAAK,MAAM,OAAO,aAAa;IAE7B,MAAM,YAAY,KAAK,OAAO,IAAI,GAAG;IAErC,IAAI,cAAc,UAAa,YAAY,KACzC;IAGF,KAAK,UAAU,GAAG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AExB,IAAI,KAAK,iBAAiB;GACxB,cAAc,KAAK,eAAe;GAClC,KAAK,kBAAkB;EACzB;EAEA,MAAM,MAAM,WAAW;CACzB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"memory-extended-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/memory-extended-cache-driver.ts"],"mappings":";;;;;;;;;;AAUA,IAAa,4BAAb,cACU,kBAEV;CAME,AAAO,cAAc;EACnB,MAAM;cAHM;EAKZ,KAAK,oBAAoB;CAC3B;AACF"}
1
+ {"version":3,"file":"memory-extended-cache-driver.mjs","names":[],"sources":["../../../../../../../../packages/cache/src/drivers/memory-extended-cache-driver.ts"],"sourcesContent":["import type { CacheDriver, MemoryExtendedCacheOptions } from \"../types\";\nimport { MemoryCacheDriver } from \"./memory-cache-driver\";\n\n/**\n * Memory driver with a sliding ttl: every live read pushes the entry's\n * expiration forward by its ttl. The sliding itself lives in\n * `MemoryCacheDriver.onRead`, which checks expiry first, so an expired entry\n * is never resurrected and the internal `onConflict` existence check never\n * slides a held lock.\n */\nexport class MemoryExtendedCacheDriver\n extends MemoryCacheDriver\n implements CacheDriver<MemoryExtendedCacheDriver, MemoryExtendedCacheOptions>\n{\n /**\n * {@inheritdoc}\n */\n public name = \"memoryExtended\";\n\n public constructor() {\n super();\n\n this.slidingExpiration = true;\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAa,4BAAb,cACU,kBAEV;CAME,AAAO,cAAc;EACnB,MAAM;cAHM;EAKZ,KAAK,oBAAoB;CAC3B;AACF"}