@stacksjs/cache 0.75.250 → 0.75.253

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.
@@ -1,9 +1,12 @@
1
1
  import { CacheManager, MemoryDriver, RedisDriver } from '@stacksjs/ts-cache';
2
2
  import { SingleStoreCacheStore } from './singlestore';
3
+ import { SqliteCacheStore } from './sqlite';
3
4
  import type { CacheDriver, CacheStats } from '@stacksjs/types';
4
5
  import type { SingleStoreCacheOptions } from './singlestore';
6
+ import type { SqliteCacheOptions } from './sqlite';
5
7
  // Re-export the SingleStore store + its options for advanced usage
6
8
  export type { SingleStoreCacheOptions } from './singlestore';
9
+ export type { SqliteCacheOptions } from './sqlite';
7
10
  /**
8
11
  * Create a memory cache driver
9
12
  */
@@ -20,19 +23,31 @@ export declare function createRedisCache(options?: RedisOptions): CacheDriver;
20
23
  * The store implements {@link CacheBackend}, the surface `StacksCache` consumes.
21
24
  */
22
25
  export declare function createSingleStoreCache(options?: SingleStoreCacheOptions): CacheDriver;
26
+ /**
27
+ * Create a SQLite cache driver: entries in a table of a SQLite file, so they
28
+ * outlive the process (see ./sqlite). Same `StacksCache` façade as the others.
29
+ */
30
+ export declare function createSqliteCache(options?: SqliteCacheOptions): CacheDriver;
23
31
  /**
24
32
  * Create a cache driver based on the specified type
25
33
  */
26
34
  export declare function createCache(driver: 'memory', options?: MemoryOptions): CacheDriver;
27
35
  export declare function createCache(driver: 'redis', options?: RedisOptions): CacheDriver;
28
36
  export declare function createCache(driver: 'singlestore', options?: SingleStoreCacheOptions): CacheDriver;
37
+ export declare function createCache(driver: 'sqlite', options?: SqliteCacheOptions): CacheDriver;
29
38
  /**
30
- * Default memory cache instance
39
+ * The driver `config/cache.ts` selects, built from its options. Memory is
40
+ * the `memory` instance itself, so an app on the default changes nothing;
41
+ * the others get the configured `prefix` and `ttl` as their key prefix and
42
+ * default TTL.
31
43
  */
32
- export declare const memory: CacheDriver;
44
+ export declare function cacheFromConfig(settings?: CacheSettings | undefined): CacheDriver;
45
+ /** Forget the resolved driver (tests, or after changing the cache config). */
46
+ export declare function resetConfiguredCache(): void;
33
47
  /**
34
- * Default cache instance (memory)
48
+ * Default memory cache instance
35
49
  */
50
+ export declare const memory: CacheDriver;
36
51
  export declare const cache: CacheDriver;
37
52
  /**
38
53
  * Memory cache options
@@ -58,6 +73,17 @@ export declare interface RedisOptions {
58
73
  stdTTL?: number
59
74
  prefix?: string
60
75
  }
76
+ /** What `config/cache.ts` holds, as far as choosing a driver goes. */
77
+ export declare interface CacheSettings {
78
+ driver?: 'memory' | 'redis' | 'singlestore' | 'sqlite'
79
+ prefix?: string
80
+ ttl?: number
81
+ drivers?: {
82
+ redis?: RedisOptions
83
+ singlestore?: SingleStoreCacheOptions
84
+ sqlite?: SqliteCacheOptions
85
+ }
86
+ }
61
87
  /**
62
88
  * Stacks Cache Wrapper
63
89
  *
@@ -129,7 +155,42 @@ export declare class TaggedCache {
129
155
  has(key: string): Promise<boolean>;
130
156
  flush(): Promise<number>;
131
157
  }
158
+ /**
159
+ * Default cache instance: the driver `config/cache.ts` selects.
160
+ *
161
+ * It used to be the memory instance whatever the config said, so an app that
162
+ * chose `driver: 'redis'` - or `'sqlite'`, to keep entries across deploys -
163
+ * still lost every entry on a restart and kept one cache per worker. Resolved
164
+ * on first use, so importing the package opens no connection. A plain object
165
+ * with a method per operation, so it can be spied on like any other.
166
+ */
167
+ declare class ConfiguredCache implements CacheDriver {
168
+ get<T>(key: string): Promise<T | undefined>;
169
+ mget<T>(keys: string[]): Promise<Record<string, T>>;
170
+ set<T>(key: string, value: T, ttl?: number): Promise<boolean>;
171
+ mset<T>(entries: Array<{ key: string, value: T, ttl?: number }>): Promise<boolean>;
172
+ setForever<T>(key: string, value: T): Promise<boolean>;
173
+ getOrSet<T>(key: string, fetcher: () => T | Promise<T>, ttl?: number): Promise<T>;
174
+ del(keys: string | string[]): Promise<number>;
175
+ has(key: string): Promise<boolean>;
176
+ missing(key: string): Promise<boolean>;
177
+ remove(key: string): Promise<void>;
178
+ deleteMany(keys: string[]): Promise<number>;
179
+ clear(): Promise<void>;
180
+ flush(): Promise<void>;
181
+ keys(pattern?: string): Promise<string[]>;
182
+ getTtl(key: string): Promise<number | undefined>;
183
+ ttl(key: string, ttl: number): Promise<boolean>;
184
+ take<T>(key: string): Promise<T | undefined>;
185
+ remember<T>(key: string, ttl: number, callback: () => T | Promise<T>): Promise<T>;
186
+ rememberForever<T>(key: string, callback: () => T | Promise<T>): Promise<T>;
187
+ getStats(): Promise<CacheStats>;
188
+ close(): Promise<void>;
189
+ disconnect(): Promise<void>;
190
+ tags(tags: readonly string[]): TaggedCache;
191
+ }
132
192
  export { SingleStoreCacheStore } from './singlestore';
193
+ export { SqliteCacheStore } from './sqlite';
133
194
  // Re-export ts-cache utilities for advanced usage
134
195
  export {
135
196
  CacheManager,
@@ -0,0 +1,31 @@
1
+ import { EventEmitter } from 'node:events';
2
+ export declare interface SqliteCacheOptions {
3
+ path?: string
4
+ table?: string
5
+ prefix?: string
6
+ stdTTL?: number
7
+ }
8
+ declare interface CacheStatsShape {
9
+ hits: number
10
+ misses: number
11
+ keys: number
12
+ ksize: number
13
+ vsize: number
14
+ }
15
+ export declare class SqliteCacheStore extends EventEmitter {
16
+ constructor(options?: SqliteCacheOptions);
17
+ get<T>(key: string): Promise<T | undefined>;
18
+ mget<T>(keys: string[]): Promise<Record<string, T>>;
19
+ set<T>(key: string, value: T, ttl?: number): Promise<boolean>;
20
+ mset<T>(entries: Array<{ key: string, value: T, ttl?: number }>): Promise<boolean>;
21
+ fetch<T>(key: string, fn: () => T | Promise<T>, ttl?: number): Promise<T>;
22
+ del(keys: string | string[]): Promise<number>;
23
+ has(key: string): Promise<boolean>;
24
+ flush(): Promise<void>;
25
+ keys(pattern?: string): Promise<string[]>;
26
+ getTtl(key: string): Promise<number | undefined>;
27
+ ttl(key: string, ttl: number): Promise<boolean>;
28
+ take<T>(key: string): Promise<T | undefined>;
29
+ getStats(): Promise<CacheStatsShape>;
30
+ close(): Promise<void>;
31
+ }
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{createCache as f}from"@stacksjs/ts-cache";import{EventEmitter as T}from"events";var{SQL:w}=globalThis.Bun;function b(e){return`\`${e.replace(/`/g,"``")}\``}class g extends T{sql;table;qualified;prefix;stdTTL;ready=null;hits=0;misses=0;constructor(e={}){super();let{host:t="127.0.0.1",port:r=3306,username:i="root",password:s="",database:o="stacks",table:c="stacks_cache",ssl:h=!1}=e;this.table=c,this.qualified=b(c),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let u=s?`${i}:${encodeURIComponent(s)}`:i,d=h?"?ssl=true":"";this.sql=new w(`mysql://${u}@${t}:${r}/${o}${d}`)}async ensureReady(){if(!this.ready)this.ready=this.sql.unsafe(`CREATE ROWSTORE TABLE IF NOT EXISTS ${this.qualified} ( cache_key VARCHAR(255) NOT NULL, value LONGTEXT NOT NULL, expires_at BIGINT NULL, PRIMARY KEY (cache_key) )`).then(()=>{return});await this.ready}k(e){return this.prefix?`${this.prefix}:${e}`:e}nowMs(){return Date.now()}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return this.nowMs()+t*1000}async get(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r){this.misses++;return}if(r.expires_at!=null&&r.expires_at<=this.nowMs()){await this.del(e),this.misses++;return}return this.hits++,JSON.parse(r.value)}async mget(e){let t={};for(let r of e){let i=await this.get(r);if(i!==void 0)t[r]=i}return t}async set(e,t,r){await this.ensureReady();let i=this.expiryFor(r);return await this.sql.unsafe(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value), expires_at = VALUES(expires_at)`,[this.k(e),JSON.stringify(t),i]),!0}async mset(e){for(let t of e)await this.set(t.key,t.value,t.ttl);return!0}async fetch(e,t,r){let i=await this.get(e);if(i!==void 0)return i;let s=await t();return await this.set(e,s,r),s}async del(e){await this.ensureReady();let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", "),s=(await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`,t.map((o)=>this.k(o)))).affectedRows;return typeof s==="number"?s:t.length}async has(e){return await this.get(e)!==void 0}async flush(){if(await this.ensureReady(),this.prefix)await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ?`,[`${this.prefix}:%`]);else await this.sql.unsafe(`TRUNCATE TABLE ${this.qualified}`)}async keys(e){await this.ensureReady();let t=`${this.prefix?`${this.prefix}:`:""}${e?e.replace(/\*/g,"%"):"%"}`,r=await this.sql.unsafe(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? AND (expires_at IS NULL OR expires_at > ?)`,[t,this.nowMs()]),i=this.prefix?this.prefix.length+1:0;return r.map((s)=>i?s.cache_key.slice(i):s.cache_key)}async getTtl(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r)return;return r.expires_at==null?0:r.expires_at}async ttl(e,t){await this.ensureReady();let r=this.expiryFor(t);if(((await this.sql.unsafe(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`,[r,this.k(e)])).affectedRows??0)>0)return!0;let s=await this.sql.unsafe(`SELECT 1 FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]);return Array.isArray(s)&&s.length>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){await this.ensureReady();let e=await this.sql.unsafe(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`,[this.nowMs()]);return{hits:this.hits,misses:this.misses,keys:Number(e[0]?.n??0),ksize:0,vsize:0}}async close(){await this.sql.end()}}import{CacheManager as K,MemoryDriver as U,RedisDriver as W}from"@stacksjs/ts-cache";import{CacheAsidePattern as H,MultiLevelPattern as z,RefreshAheadPattern as G,WriteThroughPattern as V,BatchOperations as X,CacheInvalidation as j,CacheLock as J,CircuitBreaker as Y,memoize as Q,RateLimiter as Z}from"@stacksjs/ts-cache";class n{manager;inflight=new Map;inflightTimeoutMs;constructor(e,t={}){this.manager=e,this.inflightTimeoutMs=t.inflightTimeoutMs??30000}async get(e){return await this.manager.get(e)}async mget(e){return await this.manager.mget(e)}async set(e,t,r){return await this.manager.set(e,t,r)}async mset(e){return await this.manager.mset(e)}async setForever(e,t){return await this.manager.set(e,t,0)}async getOrSet(e,t,r){let i=await this.manager.get(e);if(i!==void 0)return i;let s=this.inflight.get(e);if(s)return await s;let c=(async()=>{let l=await t();return await this.manager.set(e,l,r),this.manager.emit("fetch",e,l,r),l})(),h=this.inflightTimeoutMs,u,d=new Promise((l,p)=>{u=setTimeout(()=>{p(Error(`[cache] getOrSet('${e}') timed out after ${h}ms`))},h)}),m=Promise.race([c,d]),y=()=>{if(clearTimeout(u),this.inflight.get(e)===m)this.inflight.delete(e)};return m.then(y,y),this.inflight.set(e,m),await m}async remember(e,t,r){return await this.getOrSet(e,r,t)}async rememberForever(e,t){return this.getOrSet(e,t,0)}async del(e){return await this.manager.del(e)}async has(e){return await this.manager.has(e)}async missing(e){return!await this.manager.has(e)}async remove(e){await this.manager.del(e)}async deleteMany(e){return await this.manager.del(e)}async clear(){await this.manager.flush()}async flush(){await this.manager.flush()}async keys(e){return await this.manager.keys(e)}async getTtl(e){return await this.manager.getTtl(e)}async ttl(e,t){return await this.manager.ttl(e,t)}async take(e){return await this.manager.take(e)}async getStats(){let e=await this.manager.getStats(),t=e.hits+e.misses;return{hits:e.hits,misses:e.misses,keys:e.keys,size:e.ksize+e.vsize,hitRate:t>0?e.hits/t:0}}async close(){await this.manager.close()}async disconnect(){await this.manager.close()}get cacheManager(){return this.manager}tags(e){return new a(this,e)}}class a{cache;tags;static TAG_PREFIX="__stacks_tag__:";static flushLocks=new Map;constructor(e,t){this.cache=e;this.tags=t;if(!t||t.length===0)throw Error("cache.tags(...) requires at least one tag")}tagKey(e){return`${a.TAG_PREFIX}${e}`}async indexKey(e){for(let t of this.tags){let r=this.tagKey(t),i=await this.cache.get(r)??[],s=new Set(i);if(!s.has(e))s.add(e),await this.cache.setForever(r,[...s])}}async put(e,t,r){let i=await this.cache.set(e,t,r);if(i)await this.indexKey(e);return i}async set(e,t,r){return this.put(e,t,r)}async setForever(e,t){let r=await this.cache.setForever(e,t);if(r)await this.indexKey(e);return r}async remember(e,t,r){let i=await this.cache.remember(e,t,r);return await this.indexKey(e),i}async rememberForever(e,t){let r=await this.cache.rememberForever(e,t);return await this.indexKey(e),r}async get(e){return this.cache.get(e)}async has(e){return this.cache.has(e)}async flush(){let e=0;for(let t of this.tags){let r=this.tagKey(t),i=a.flushLocks.get(r),s=i?i.catch(()=>0).then(()=>this.doFlushOne(r)):this.doFlushOne(r);a.flushLocks.set(r,s);try{e+=await s}finally{if(a.flushLocks.get(r)===s)a.flushLocks.delete(r)}}return e}async doFlushOne(e){let t=await this.cache.get(e)??[],r=0;if(t.length>0)r=await this.cache.del(t);return await this.cache.del(e),r}}function v(e={}){let t=f({driver:"memory",stdTTL:e.stdTTL??0,checkPeriod:e.checkPeriod??600,maxKeys:e.maxKeys??-1,useClones:e.useClones??!0,prefix:e.prefix});return new n(t)}function P(e={}){let t=f({driver:"redis",url:e.url,host:e.host??"localhost",port:e.port??6379,password:e.password,database:e.database??0,tls:e.tls??!1,stdTTL:e.stdTTL??0,prefix:e.prefix});return new n(t)}function x(e={}){let t=new g(e);return new n(t)}function q(e,t){if(e==="redis")return P(t);if(e==="singlestore")return x(t);return v(t)}var S=f({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),E=new n(S),F=E;function ee(e,t){let r=Object.keys(t).sort().map((i)=>{let s=t[i];if(typeof s==="number"&&!Number.isFinite(s))throw RangeError("Cache key numbers must be finite");if(s!==void 0&&s!==null&&!["string","number","boolean"].includes(typeof s))throw TypeError("Invalid cache key value");return[i,s===void 0?["undefined"]:s]});return JSON.stringify([e,r])}export{X as BatchOperations,H as CacheAsidePattern,j as CacheInvalidation,J as CacheLock,K as CacheManager,Y as CircuitBreaker,U as MemoryDriver,z as MultiLevelPattern,Z as RateLimiter,W as RedisDriver,G as RefreshAheadPattern,g as SingleStoreCacheStore,n as StacksCache,a as TaggedCache,V as WriteThroughPattern,F as cache,ee as cacheKey,q as createCache,v as createMemoryCache,P as createRedisCache,x as createSingleStoreCache,Q as memoize,E as memory};
2
+ import{config as D,overridesReady as N}from"@stacksjs/config";import{createCache as v}from"@stacksjs/ts-cache";import{EventEmitter as k}from"events";var{SQL:O}=globalThis.Bun;function L(e){return`\`${e.replace(/`/g,"``")}\``}class f extends k{sql;table;qualified;prefix;stdTTL;ready=null;hits=0;misses=0;constructor(e={}){super();let{host:t="127.0.0.1",port:r=3306,username:s="root",password:i="",database:u="stacks",table:h="stacks_cache",ssl:l=!1}=e;this.table=h,this.qualified=L(h),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let m=i?`${s}:${encodeURIComponent(i)}`:s,T=l?"?ssl=true":"";this.sql=new O(`mysql://${m}@${t}:${r}/${u}${T}`)}async ensureReady(){if(!this.ready)this.ready=this.sql.unsafe(`CREATE ROWSTORE TABLE IF NOT EXISTS ${this.qualified} ( cache_key VARCHAR(255) NOT NULL, value LONGTEXT NOT NULL, expires_at BIGINT NULL, PRIMARY KEY (cache_key) )`).then(()=>{return});await this.ready}k(e){return this.prefix?`${this.prefix}:${e}`:e}nowMs(){return Date.now()}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return this.nowMs()+t*1000}async get(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r){this.misses++;return}if(r.expires_at!=null&&r.expires_at<=this.nowMs()){await this.del(e),this.misses++;return}return this.hits++,JSON.parse(r.value)}async mget(e){let t={};for(let r of e){let s=await this.get(r);if(s!==void 0)t[r]=s}return t}async set(e,t,r){await this.ensureReady();let s=this.expiryFor(r);return await this.sql.unsafe(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value), expires_at = VALUES(expires_at)`,[this.k(e),JSON.stringify(t),s]),!0}async mset(e){for(let t of e)await this.set(t.key,t.value,t.ttl);return!0}async fetch(e,t,r){let s=await this.get(e);if(s!==void 0)return s;let i=await t();return await this.set(e,i,r),i}async del(e){await this.ensureReady();let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", "),i=(await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`,t.map((u)=>this.k(u)))).affectedRows;return typeof i==="number"?i:t.length}async has(e){return await this.get(e)!==void 0}async flush(){if(await this.ensureReady(),this.prefix)await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ?`,[`${this.prefix}:%`]);else await this.sql.unsafe(`TRUNCATE TABLE ${this.qualified}`)}async keys(e){await this.ensureReady();let t=`${this.prefix?`${this.prefix}:`:""}${e?e.replace(/\*/g,"%"):"%"}`,r=await this.sql.unsafe(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? AND (expires_at IS NULL OR expires_at > ?)`,[t,this.nowMs()]),s=this.prefix?this.prefix.length+1:0;return r.map((i)=>s?i.cache_key.slice(s):i.cache_key)}async getTtl(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r)return;return r.expires_at==null?0:r.expires_at}async ttl(e,t){await this.ensureReady();let r=this.expiryFor(t);if(((await this.sql.unsafe(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`,[r,this.k(e)])).affectedRows??0)>0)return!0;let i=await this.sql.unsafe(`SELECT 1 FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]);return Array.isArray(i)&&i.length>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){await this.ensureReady();let e=await this.sql.unsafe(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`,[this.nowMs()]);return{hits:this.hits,misses:this.misses,keys:Number(e[0]?.n??0),ksize:0,vsize:0}}async close(){await this.sql.end()}}import{Database as _}from"bun:sqlite";import{EventEmitter as q}from"events";import{mkdirSync as A}from"fs";import{dirname as M}from"path";function F(e){return`"${e.replace(/"/g,'""')}"`}function y(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`).replace(/\*/g,"%")}class p extends q{db;qualified;prefix;stdTTL;hits=0;misses=0;constructor(e={}){super();let t=e.path??"storage/framework/cache/cache.sqlite";if(t!==":memory:"&&!t.startsWith("file:"))A(M(t),{recursive:!0});if(this.db=new _(t,{create:!0}),this.db.run("PRAGMA busy_timeout = 5000"),t!==":memory:")this.db.run("PRAGMA journal_mode = WAL");this.qualified=F(e.table??"stacks_cache"),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0,this.db.run(`CREATE TABLE IF NOT EXISTS ${this.qualified} (cache_key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER NULL)`)}k(e){return this.prefix?`${this.prefix}:${e}`:e}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return Date.now()+t*1000}async get(e){let t=this.db.query(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ?`).get(this.k(e));if(!t){this.misses++;return}if(t.expires_at!=null&&t.expires_at<=Date.now()){this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key = ?`).run(this.k(e)),this.misses++;return}return this.hits++,JSON.parse(t.value)}async mget(e){let t={};for(let r of e){let s=await this.get(r);if(s!==void 0)t[r]=s}return t}async set(e,t,r){return this.db.query(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(cache_key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`).run(this.k(e),JSON.stringify(t),this.expiryFor(r)),!0}async mset(e){return this.db.transaction(()=>{for(let t of e)this.db.query(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(cache_key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`).run(this.k(t.key),JSON.stringify(t.value),this.expiryFor(t.ttl))})(),!0}async fetch(e,t,r){let s=await this.get(e);if(s!==void 0)return s;let i=await t();return await this.set(e,i,r),i}async del(e){let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", ");return this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`).run(...t.map((s)=>this.k(s))).changes}async has(e){return await this.get(e)!==void 0}async flush(){if(this.prefix)this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ? ESCAPE '\\'`).run(`${y(this.prefix)}:%`);else this.db.run(`DELETE FROM ${this.qualified}`)}async keys(e){let t=`${this.prefix?`${y(this.prefix)}:`:""}${e?y(e):"%"}`,r=this.db.query(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)`).all(t,Date.now()),s=this.prefix?this.prefix.length+1:0;return r.map((i)=>s?i.cache_key.slice(s):i.cache_key)}async getTtl(e){let t=this.db.query(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ?`).get(this.k(e));if(!t)return;return t.expires_at==null?0:t.expires_at}async ttl(e,t){return this.db.query(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`).run(this.expiryFor(t),this.k(e)).changes>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){let e=this.db.query(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`).get(Date.now());return{hits:this.hits,misses:this.misses,keys:Number(e?.n??0),ksize:0,vsize:0}}async close(){this.db.close()}}import{CacheManager as he,MemoryDriver as le,RedisDriver as me}from"@stacksjs/ts-cache";import{CacheAsidePattern as ge,MultiLevelPattern as fe,RefreshAheadPattern as pe,WriteThroughPattern as Te,BatchOperations as ye,CacheInvalidation as be,CacheLock as ve,CircuitBreaker as we,memoize as xe,RateLimiter as Pe}from"@stacksjs/ts-cache";class o{manager;inflight=new Map;inflightTimeoutMs;constructor(e,t={}){this.manager=e,this.inflightTimeoutMs=t.inflightTimeoutMs??30000}async get(e){return await this.manager.get(e)}async mget(e){return await this.manager.mget(e)}async set(e,t,r){return await this.manager.set(e,t,r)}async mset(e){return await this.manager.mset(e)}async setForever(e,t){return await this.manager.set(e,t,0)}async getOrSet(e,t,r){let s=await this.manager.get(e);if(s!==void 0)return s;let i=this.inflight.get(e);if(i)return await i;let h=(async()=>{let g=await t();return await this.manager.set(e,g,r),this.manager.emit("fetch",e,g,r),g})(),l=this.inflightTimeoutMs,m,T=new Promise((g,R)=>{m=setTimeout(()=>{R(Error(`[cache] getOrSet('${e}') timed out after ${l}ms`))},l)}),d=Promise.race([h,T]),w=()=>{if(clearTimeout(m),this.inflight.get(e)===d)this.inflight.delete(e)};return d.then(w,w),this.inflight.set(e,d),await d}async remember(e,t,r){return await this.getOrSet(e,r,t)}async rememberForever(e,t){return this.getOrSet(e,t,0)}async del(e){return await this.manager.del(e)}async has(e){return await this.manager.has(e)}async missing(e){return!await this.manager.has(e)}async remove(e){await this.manager.del(e)}async deleteMany(e){return await this.manager.del(e)}async clear(){await this.manager.flush()}async flush(){await this.manager.flush()}async keys(e){return await this.manager.keys(e)}async getTtl(e){return await this.manager.getTtl(e)}async ttl(e,t){return await this.manager.ttl(e,t)}async take(e){return await this.manager.take(e)}async getStats(){let e=await this.manager.getStats(),t=e.hits+e.misses;return{hits:e.hits,misses:e.misses,keys:e.keys,size:e.ksize+e.vsize,hitRate:t>0?e.hits/t:0}}async close(){await this.manager.close()}async disconnect(){await this.manager.close()}get cacheManager(){return this.manager}tags(e){return new a(this,e)}}class a{cache;tags;static TAG_PREFIX="__stacks_tag__:";static flushLocks=new Map;constructor(e,t){this.cache=e;this.tags=t;if(!t||t.length===0)throw Error("cache.tags(...) requires at least one tag")}tagKey(e){return`${a.TAG_PREFIX}${e}`}async indexKey(e){for(let t of this.tags){let r=this.tagKey(t),s=await this.cache.get(r)??[],i=new Set(s);if(!i.has(e))i.add(e),await this.cache.setForever(r,[...i])}}async put(e,t,r){let s=await this.cache.set(e,t,r);if(s)await this.indexKey(e);return s}async set(e,t,r){return this.put(e,t,r)}async setForever(e,t){let r=await this.cache.setForever(e,t);if(r)await this.indexKey(e);return r}async remember(e,t,r){let s=await this.cache.remember(e,t,r);return await this.indexKey(e),s}async rememberForever(e,t){let r=await this.cache.rememberForever(e,t);return await this.indexKey(e),r}async get(e){return this.cache.get(e)}async has(e){return this.cache.has(e)}async flush(){let e=0;for(let t of this.tags){let r=this.tagKey(t),s=a.flushLocks.get(r),i=s?s.catch(()=>0).then(()=>this.doFlushOne(r)):this.doFlushOne(r);a.flushLocks.set(r,i);try{e+=await i}finally{if(a.flushLocks.get(r)===i)a.flushLocks.delete(r)}}return e}async doFlushOne(e){let t=await this.cache.get(e)??[],r=0;if(t.length>0)r=await this.cache.del(t);return await this.cache.del(e),r}}function I(e={}){let t=v({driver:"memory",stdTTL:e.stdTTL??0,checkPeriod:e.checkPeriod??600,maxKeys:e.maxKeys??-1,useClones:e.useClones??!0,prefix:e.prefix});return new o(t)}function x(e={}){let t=v({driver:"redis",url:e.url,host:e.host??"localhost",port:e.port??6379,password:e.password,database:e.database??0,tls:e.tls??!1,stdTTL:e.stdTTL??0,prefix:e.prefix});return new o(t)}function P(e={}){let t=new f(e);return new o(t)}function E(e={}){return new o(new p(e))}function se(e,t){if(e==="redis")return x(t);if(e==="singlestore")return P(t);if(e==="sqlite")return E(t);return I(t)}var U=v({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),S=new o(U);function K(e=D.cache){let t={prefix:e?.prefix,stdTTL:e?.ttl};switch(e?.driver){case"redis":return x({...e.drivers?.redis,...t});case"singlestore":return P({...e.drivers?.singlestore,...t});case"sqlite":return E({...e.drivers?.sqlite,...t});default:return S}}var c=null,b=!1;Promise.resolve(N).then(()=>{b=!0},()=>{b=!0});function ie(){c=null}function n(){if(c)return c;if(!b)return S;return c=K(),c}class C{get(e){return n().get(e)}mget(e){return n().mget(e)}set(e,t,r){return n().set(e,t,r)}mset(e){return n().mset(e)}setForever(e,t){return n().setForever(e,t)}getOrSet(e,t,r){return n().getOrSet(e,t,r)}del(e){return n().del(e)}has(e){return n().has(e)}missing(e){return n().missing(e)}remove(e){return n().remove(e)}deleteMany(e){return n().deleteMany(e)}clear(){return n().clear()}flush(){return n().flush()}keys(e){return n().keys(e)}getTtl(e){return n().getTtl(e)}ttl(e,t){return n().ttl(e,t)}take(e){return n().take(e)}remember(e,t,r){return n().remember(e,t,r)}rememberForever(e,t){return n().rememberForever(e,t)}getStats(){return n().getStats()}close(){return n().close()}disconnect(){return n().disconnect()}tags(e){return n().tags(e)}}var ne=new C;function Ee(e,t){let r=Object.keys(t).sort().map((s)=>{let i=t[s];if(typeof i==="number"&&!Number.isFinite(i))throw RangeError("Cache key numbers must be finite");if(i!==void 0&&i!==null&&!["string","number","boolean"].includes(typeof i))throw TypeError("Invalid cache key value");return[s,i===void 0?["undefined"]:i]});return JSON.stringify([e,r])}export{ye as BatchOperations,ge as CacheAsidePattern,be as CacheInvalidation,ve as CacheLock,he as CacheManager,we as CircuitBreaker,le as MemoryDriver,fe as MultiLevelPattern,Pe as RateLimiter,me as RedisDriver,pe as RefreshAheadPattern,f as SingleStoreCacheStore,p as SqliteCacheStore,o as StacksCache,a as TaggedCache,Te as WriteThroughPattern,ne as cache,K as cacheFromConfig,Ee as cacheKey,se as createCache,I as createMemoryCache,x as createRedisCache,P as createSingleStoreCache,E as createSqliteCache,xe as memoize,S as memory,ie as resetConfiguredCache};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/cache",
3
3
  "type": "module",
4
- "version": "0.75.250",
4
+ "version": "0.75.253",
5
5
  "description": "Caching the Stacks way.",
6
6
  "author": "Chris Breuer",
7
7
  "contributors": [
@@ -59,9 +59,7 @@
59
59
  "prepublishOnly": "bun run build"
60
60
  },
61
61
  "dependencies": {
62
+ "@stacksjs/config": "0.75.253",
62
63
  "@stacksjs/ts-cache": "^0.1.7"
63
- },
64
- "devDependencies": {
65
- "@stacksjs/config": "0.75.250"
66
64
  }
67
65
  }