@open-mercato/cache-provider-sqlite 0.0.0-stage → 0.11.1-develop.8665.1.2455b2503c

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.
@@ -0,0 +1,2 @@
1
+ [build:cache-provider-sqlite] found 1 entry points
2
+ [build:cache-provider-sqlite] built successfully
package/build.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import { dirname } from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { buildPackage } from '../../scripts/build-package.mjs'
4
+
5
+ const packageDir = dirname(fileURLToPath(import.meta.url))
6
+
7
+ await buildPackage(packageDir, {
8
+ name: 'cache-provider-sqlite',
9
+ entryPoints: 'src/**/*.ts',
10
+ })
package/dist/index.js ADDED
@@ -0,0 +1,197 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { CacheDependencyUnavailableError } from "@open-mercato/cache-provider-kit/errors";
5
+ import { DEFAULT_SQLITE_CACHE_PATH } from "@open-mercato/cache-provider-kit/defaults";
6
+ import { matchCacheKeyPattern } from "@open-mercato/cache-provider-kit/patterns";
7
+ import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from "@open-mercato/cache-provider-kit/codec";
8
+ const sqliteRequire = createRequire(path.join(process.cwd(), "package.json"));
9
+ function createSqliteStrategy(dbPath, options) {
10
+ let db = null;
11
+ const defaultTtl = options?.defaultTtl;
12
+ const codec = resolveCacheCodecConfig(options);
13
+ const filePath = dbPath || process.env.CACHE_SQLITE_PATH || DEFAULT_SQLITE_CACHE_PATH;
14
+ async function getDb() {
15
+ if (db) return db;
16
+ try {
17
+ const imported = options?.databaseConstructor ?? sqliteRequire("better-sqlite3");
18
+ const Database = typeof imported === "function" ? imported : imported.default;
19
+ const dir = path.dirname(filePath);
20
+ if (!fs.existsSync(dir)) {
21
+ fs.mkdirSync(dir, { recursive: true });
22
+ }
23
+ db = new Database(filePath);
24
+ db.exec(`
25
+ PRAGMA journal_mode = WAL;
26
+ PRAGMA synchronous = NORMAL;
27
+ PRAGMA busy_timeout = 5000;
28
+ PRAGMA foreign_keys = ON;
29
+ `);
30
+ db.exec(`
31
+ CREATE TABLE IF NOT EXISTS cache_entries (
32
+ key TEXT PRIMARY KEY,
33
+ value TEXT NOT NULL,
34
+ expires_at INTEGER,
35
+ created_at INTEGER NOT NULL
36
+ );
37
+
38
+ CREATE TABLE IF NOT EXISTS cache_tags (
39
+ key TEXT NOT NULL,
40
+ tag TEXT NOT NULL,
41
+ PRIMARY KEY (key, tag),
42
+ FOREIGN KEY (key) REFERENCES cache_entries(key) ON DELETE CASCADE
43
+ );
44
+
45
+ CREATE INDEX IF NOT EXISTS idx_cache_tags_tag ON cache_tags(tag);
46
+ CREATE INDEX IF NOT EXISTS idx_cache_entries_expires_at ON cache_entries(expires_at);
47
+ `);
48
+ return db;
49
+ } catch (error) {
50
+ throw new CacheDependencyUnavailableError("sqlite", "better-sqlite3", error);
51
+ }
52
+ }
53
+ function isExpired(expiresAt) {
54
+ if (expiresAt === null) return false;
55
+ return Date.now() > expiresAt;
56
+ }
57
+ const get = async (key, options2) => {
58
+ const database = await getDb();
59
+ const stmt = database.prepare("SELECT value, expires_at FROM cache_entries WHERE key = ?");
60
+ const row = stmt.get(key);
61
+ if (!row) return null;
62
+ try {
63
+ const value = JSON.parse(decodeCacheText(row.value));
64
+ const expiresAt = row.expires_at;
65
+ if (isExpired(expiresAt)) {
66
+ if (options2?.returnExpired) {
67
+ return value;
68
+ }
69
+ await deleteKey(key);
70
+ return null;
71
+ }
72
+ return value;
73
+ } catch {
74
+ await deleteKey(key);
75
+ return null;
76
+ }
77
+ };
78
+ const set = async (key, value, options2) => {
79
+ const database = await getDb();
80
+ const ttl = options2?.ttl ?? defaultTtl;
81
+ const tags = options2?.tags || [];
82
+ const expiresAt = ttl ? Date.now() + ttl : null;
83
+ const createdAt = Date.now();
84
+ const serialized = encodeCacheText(JSON.stringify(value), codec);
85
+ database.transaction(() => {
86
+ database.prepare("DELETE FROM cache_tags WHERE key = ?").run(key);
87
+ database.prepare(`
88
+ INSERT OR REPLACE INTO cache_entries (key, value, expires_at, created_at)
89
+ VALUES (?, ?, ?, ?)
90
+ `).run(key, serialized, expiresAt, createdAt);
91
+ if (tags.length > 0) {
92
+ const insertTag = database.prepare("INSERT INTO cache_tags (key, tag) VALUES (?, ?)");
93
+ for (const tag of tags) {
94
+ insertTag.run(key, tag);
95
+ }
96
+ }
97
+ })();
98
+ };
99
+ const has = async (key) => {
100
+ const database = await getDb();
101
+ const stmt = database.prepare("SELECT expires_at FROM cache_entries WHERE key = ?");
102
+ const row = stmt.get(key);
103
+ if (!row) return false;
104
+ if (isExpired(row.expires_at)) {
105
+ await deleteKey(key);
106
+ return false;
107
+ }
108
+ return true;
109
+ };
110
+ const deleteKey = async (key) => {
111
+ const database = await getDb();
112
+ const result = database.transaction(() => {
113
+ database.prepare("DELETE FROM cache_tags WHERE key = ?").run(key);
114
+ const info = database.prepare("DELETE FROM cache_entries WHERE key = ?").run(key);
115
+ return info.changes > 0;
116
+ })();
117
+ return result;
118
+ };
119
+ const deleteByTags = async (tags) => {
120
+ const database = await getDb();
121
+ const placeholders = tags.map(() => "?").join(",");
122
+ const stmt = database.prepare(`
123
+ SELECT DISTINCT key FROM cache_tags WHERE tag IN (${placeholders})
124
+ `);
125
+ const rows = stmt.all(...tags);
126
+ let deleted = 0;
127
+ for (const row of rows) {
128
+ const success = await deleteKey(row.key);
129
+ if (success) deleted++;
130
+ }
131
+ return deleted;
132
+ };
133
+ const clear = async () => {
134
+ const database = await getDb();
135
+ const result = database.transaction(() => {
136
+ const countStmt = database.prepare("SELECT COUNT(*) as count FROM cache_entries");
137
+ const count = countStmt.get().count;
138
+ database.prepare("DELETE FROM cache_tags").run();
139
+ database.prepare("DELETE FROM cache_entries").run();
140
+ return count;
141
+ })();
142
+ return result;
143
+ };
144
+ const keys = async (pattern) => {
145
+ const database = await getDb();
146
+ const stmt = database.prepare("SELECT key FROM cache_entries");
147
+ const rows = stmt.all();
148
+ const allKeys = rows.map((row) => row.key);
149
+ if (!pattern) return allKeys;
150
+ return allKeys.filter((key) => matchCacheKeyPattern(key, pattern));
151
+ };
152
+ const stats = async () => {
153
+ const database = await getDb();
154
+ const sizeStmt = database.prepare("SELECT COUNT(*) as count FROM cache_entries");
155
+ const size = sizeStmt.get().count;
156
+ const now = Date.now();
157
+ const expiredStmt = database.prepare("SELECT COUNT(*) as count FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?");
158
+ const expired = expiredStmt.get(now).count;
159
+ return { size, expired };
160
+ };
161
+ const cleanup = async () => {
162
+ const database = await getDb();
163
+ const now = Date.now();
164
+ const result = database.transaction(() => {
165
+ const stmt = database.prepare("SELECT key FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?");
166
+ const rows = stmt.all(now);
167
+ for (const row of rows) {
168
+ database.prepare("DELETE FROM cache_tags WHERE key = ?").run(row.key);
169
+ }
170
+ const info = database.prepare("DELETE FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?").run(now);
171
+ return info.changes;
172
+ })();
173
+ return result;
174
+ };
175
+ const close = async () => {
176
+ if (db) {
177
+ db.close();
178
+ db = null;
179
+ }
180
+ };
181
+ return {
182
+ get,
183
+ set,
184
+ has,
185
+ delete: deleteKey,
186
+ deleteByTags,
187
+ clear,
188
+ keys,
189
+ stats,
190
+ cleanup,
191
+ close
192
+ };
193
+ }
194
+ export {
195
+ createSqliteStrategy
196
+ };
197
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["import type { CacheStrategy, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { CacheDependencyUnavailableError } from '@open-mercato/cache-provider-kit/errors'\nimport { DEFAULT_SQLITE_CACHE_PATH } from '@open-mercato/cache-provider-kit/defaults'\nimport { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'\nimport { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '@open-mercato/cache-provider-kit/codec'\nimport type { CacheCodecOptions } from '@open-mercato/cache-provider-kit/codec'\n\ntype SqliteStatement<TResult = unknown> = {\n get(...args: unknown[]): TResult | undefined\n all(...args: unknown[]): TResult[]\n run(...args: unknown[]): { changes: number }\n}\n\ntype SqliteTransaction<TResult = unknown> = () => TResult\n\ntype SqliteDatabase = {\n prepare<TResult = unknown>(sql: string): SqliteStatement<TResult>\n exec(sql: string): unknown\n transaction<TResult>(fn: () => TResult): SqliteTransaction<TResult>\n close(): void\n}\n\ntype SqliteConstructor = new (file: string) => SqliteDatabase\ntype SqliteModule = SqliteConstructor | { default: SqliteConstructor }\ntype SqliteStrategyOptions = { defaultTtl?: number; databaseConstructor?: SqliteConstructor } & CacheCodecOptions\n\nconst sqliteRequire = createRequire(path.join(process.cwd(), 'package.json'))\n\n/**\n * SQLite cache strategy with tag support\n * Persistent across process restarts, stored in a SQLite database file\n *\n * Uses two tables:\n * - cache_entries: stores cache data\n * - cache_tags: stores tag associations (many-to-many)\n */\nexport function createSqliteStrategy(dbPath?: string, options?: SqliteStrategyOptions): CacheStrategy {\n let db: SqliteDatabase | null = null\n const defaultTtl = options?.defaultTtl\n const codec = resolveCacheCodecConfig(options)\n const filePath = dbPath || process.env.CACHE_SQLITE_PATH || DEFAULT_SQLITE_CACHE_PATH\n\n async function getDb(): Promise<SqliteDatabase> {\n if (db) return db\n\n try {\n const imported = (options?.databaseConstructor ?? sqliteRequire('better-sqlite3')) as SqliteModule\n const Database = typeof imported === 'function' ? imported : imported.default\n\n // Ensure directory exists\n const dir = path.dirname(filePath)\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true })\n }\n\n db = new Database(filePath)\n\n db.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 5000;\n PRAGMA foreign_keys = ON;\n `)\n\n // Create tables\n db.exec(`\n CREATE TABLE IF NOT EXISTS cache_entries (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n expires_at INTEGER,\n created_at INTEGER NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS cache_tags (\n key TEXT NOT NULL,\n tag TEXT NOT NULL,\n PRIMARY KEY (key, tag),\n FOREIGN KEY (key) REFERENCES cache_entries(key) ON DELETE CASCADE\n );\n\n CREATE INDEX IF NOT EXISTS idx_cache_tags_tag ON cache_tags(tag);\n CREATE INDEX IF NOT EXISTS idx_cache_entries_expires_at ON cache_entries(expires_at);\n `)\n\n return db\n } catch (error) {\n throw new CacheDependencyUnavailableError('sqlite', 'better-sqlite3', error)\n }\n }\n\n function isExpired(expiresAt: number | null): boolean {\n if (expiresAt === null) return false\n return Date.now() > expiresAt\n }\n\n type EntryRow = { value: string | Buffer; expires_at: number | null }\n type ExpiresRow = { expires_at: number | null }\n type CountRow = { count: number }\n type KeyRow = { key: string }\n\n const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {\n const database = await getDb()\n\n const stmt = database.prepare('SELECT value, expires_at FROM cache_entries WHERE key = ?')\n const row = stmt.get(key) as EntryRow | undefined\n\n if (!row) return null\n\n try {\n const value = JSON.parse(decodeCacheText(row.value)) as CacheValue\n const expiresAt = row.expires_at\n\n if (isExpired(expiresAt)) {\n if (options?.returnExpired) {\n return value\n }\n // Clean up expired entry\n await deleteKey(key)\n return null\n }\n\n return value\n } catch {\n // Invalid JSON, remove it\n await deleteKey(key)\n return null\n }\n }\n\n const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {\n const database = await getDb()\n const ttl = options?.ttl ?? defaultTtl\n const tags = options?.tags || []\n const expiresAt = ttl ? Date.now() + ttl : null\n const createdAt = Date.now()\n\n const serialized = encodeCacheText(JSON.stringify(value), codec)\n\n database.transaction(() => {\n // Delete old tags\n database.prepare('DELETE FROM cache_tags WHERE key = ?').run(key)\n\n // Insert or replace cache entry\n database.prepare(`\n INSERT OR REPLACE INTO cache_entries (key, value, expires_at, created_at)\n VALUES (?, ?, ?, ?)\n `).run(key, serialized, expiresAt, createdAt)\n\n // Insert new tags\n if (tags.length > 0) {\n const insertTag = database.prepare('INSERT INTO cache_tags (key, tag) VALUES (?, ?)')\n for (const tag of tags) {\n insertTag.run(key, tag)\n }\n }\n })()\n }\n\n const has = async (key: string): Promise<boolean> => {\n const database = await getDb()\n\n const stmt = database.prepare('SELECT expires_at FROM cache_entries WHERE key = ?')\n const row = stmt.get(key) as ExpiresRow | undefined\n\n if (!row) return false\n\n if (isExpired(row.expires_at)) {\n await deleteKey(key)\n return false\n }\n\n return true\n }\n\n const deleteKey = async (key: string): Promise<boolean> => {\n const database = await getDb()\n\n const result = database.transaction(() => {\n database.prepare('DELETE FROM cache_tags WHERE key = ?').run(key)\n const info = database.prepare('DELETE FROM cache_entries WHERE key = ?').run(key)\n return info.changes > 0\n })()\n\n return result\n }\n\n const deleteByTags = async (tags: string[]): Promise<number> => {\n const database = await getDb()\n\n // Get all unique keys that have any of the specified tags\n const placeholders = tags.map(() => '?').join(',')\n const stmt = database.prepare(`\n SELECT DISTINCT key FROM cache_tags WHERE tag IN (${placeholders})\n `)\n const rows = stmt.all(...tags) as KeyRow[]\n\n let deleted = 0\n for (const row of rows) {\n const success = await deleteKey(row.key)\n if (success) deleted++\n }\n\n return deleted\n }\n\n const clear = async (): Promise<number> => {\n const database = await getDb()\n\n const result = database.transaction(() => {\n const countStmt = database.prepare('SELECT COUNT(*) as count FROM cache_entries')\n const count = (countStmt.get() as CountRow).count\n\n database.prepare('DELETE FROM cache_tags').run()\n database.prepare('DELETE FROM cache_entries').run()\n\n return count\n })()\n\n return result\n }\n\n const keys = async (pattern?: string): Promise<string[]> => {\n const database = await getDb()\n\n const stmt = database.prepare('SELECT key FROM cache_entries')\n const rows = stmt.all() as KeyRow[]\n\n const allKeys = rows.map((row) => row.key)\n\n if (!pattern) return allKeys\n\n return allKeys.filter((key: string) => matchCacheKeyPattern(key, pattern))\n }\n\n const stats = async (): Promise<{ size: number; expired: number }> => {\n const database = await getDb()\n\n const sizeStmt = database.prepare('SELECT COUNT(*) as count FROM cache_entries')\n const size = (sizeStmt.get() as CountRow).count\n\n const now = Date.now()\n const expiredStmt = database.prepare('SELECT COUNT(*) as count FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?')\n const expired = (expiredStmt.get(now) as CountRow).count\n\n return { size, expired }\n }\n\n const cleanup = async (): Promise<number> => {\n const database = await getDb()\n const now = Date.now()\n\n const result = database.transaction(() => {\n // Get keys to delete\n const stmt = database.prepare('SELECT key FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?')\n const rows = stmt.all(now) as KeyRow[]\n\n // Delete tags for expired keys\n for (const row of rows) {\n database.prepare('DELETE FROM cache_tags WHERE key = ?').run(row.key)\n }\n\n // Delete expired entries\n const info = database.prepare('DELETE FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?').run(now)\n return info.changes\n })()\n\n return result\n }\n\n const close = async (): Promise<void> => {\n if (db) {\n db.close()\n db = null\n }\n }\n\n return {\n get,\n set,\n has,\n delete: deleteKey,\n deleteByTags,\n clear,\n keys,\n stats,\n cleanup,\n close,\n }\n}\n"],
5
+ "mappings": "AACA,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AACjB,SAAS,uCAAuC;AAChD,SAAS,iCAAiC;AAC1C,SAAS,4BAA4B;AACrC,SAAS,iBAAiB,iBAAiB,+BAA+B;AAsB1E,MAAM,gBAAgB,cAAc,KAAK,KAAK,QAAQ,IAAI,GAAG,cAAc,CAAC;AAUrE,SAAS,qBAAqB,QAAiB,SAAgD;AACpG,MAAI,KAA4B;AAChC,QAAM,aAAa,SAAS;AAC5B,QAAM,QAAQ,wBAAwB,OAAO;AAC7C,QAAM,WAAW,UAAU,QAAQ,IAAI,qBAAqB;AAE5D,iBAAe,Q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AM,KAAK,IAAI;AAErB,UAAM,SAAS,SAAS,YAAY,MAAM;AAExC,YAAM,OAAO,SAAS,QAAQ,+EAA+E;AAC7G,YAAM,OAAO,KAAK,IAAI,GAAG;AAGzB,iBAAW,OAAO,MAAM;AACtB,iBAAS,QAAQ,sCAAsC,EAAE,IAAI,IAAI,GAAG;AAAA,MACtE;AAGA,YAAM,OAAO,SAAS,QAAQ,2EAA2E,EAAE,IAAI,GAAG;AAClH,aAAO,KAAK;AAAA,IACd,CAAC,EAAE;AAEH,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,YAA2B;AACvC,QAAI,IAAI;AACN,SAAG,MAAM;AACT,WAAK;AAAA,IACP;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
+ "names": ["options"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@open-mercato/cache-provider-sqlite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.11.1-develop.8665.1.2455b2503c",
4
+ "description": "Stock sqlite cache factory for Open Mercato",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "node build.mjs",
16
+ "watch": "node watch.mjs",
17
+ "typecheck": "tsc --noEmit"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "^26.4.0",
21
+ "typescript": "7.0.2"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/open-mercato/open-mercato",
29
+ "directory": "packages/cache-provider-sqlite"
30
+ },
31
+ "dependencies": {
32
+ "@open-mercato/cache-provider-kit": "0.11.1-develop.8665.1.2455b2503c",
33
+ "@types/better-sqlite3": "^7.6.13"
34
+ },
35
+ "peerDependencies": {
36
+ "better-sqlite3": ">=9.0.0"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "better-sqlite3": {
40
+ "optional": true
41
+ }
42
+ },
43
+ "stableVersion": "0.11.0"
6
44
  }
package/src/index.ts ADDED
@@ -0,0 +1,292 @@
1
+ import type { CacheStrategy, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'
2
+ import fs from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import path from 'node:path'
5
+ import { CacheDependencyUnavailableError } from '@open-mercato/cache-provider-kit/errors'
6
+ import { DEFAULT_SQLITE_CACHE_PATH } from '@open-mercato/cache-provider-kit/defaults'
7
+ import { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'
8
+ import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '@open-mercato/cache-provider-kit/codec'
9
+ import type { CacheCodecOptions } from '@open-mercato/cache-provider-kit/codec'
10
+
11
+ type SqliteStatement<TResult = unknown> = {
12
+ get(...args: unknown[]): TResult | undefined
13
+ all(...args: unknown[]): TResult[]
14
+ run(...args: unknown[]): { changes: number }
15
+ }
16
+
17
+ type SqliteTransaction<TResult = unknown> = () => TResult
18
+
19
+ type SqliteDatabase = {
20
+ prepare<TResult = unknown>(sql: string): SqliteStatement<TResult>
21
+ exec(sql: string): unknown
22
+ transaction<TResult>(fn: () => TResult): SqliteTransaction<TResult>
23
+ close(): void
24
+ }
25
+
26
+ type SqliteConstructor = new (file: string) => SqliteDatabase
27
+ type SqliteModule = SqliteConstructor | { default: SqliteConstructor }
28
+ type SqliteStrategyOptions = { defaultTtl?: number; databaseConstructor?: SqliteConstructor } & CacheCodecOptions
29
+
30
+ const sqliteRequire = createRequire(path.join(process.cwd(), 'package.json'))
31
+
32
+ /**
33
+ * SQLite cache strategy with tag support
34
+ * Persistent across process restarts, stored in a SQLite database file
35
+ *
36
+ * Uses two tables:
37
+ * - cache_entries: stores cache data
38
+ * - cache_tags: stores tag associations (many-to-many)
39
+ */
40
+ export function createSqliteStrategy(dbPath?: string, options?: SqliteStrategyOptions): CacheStrategy {
41
+ let db: SqliteDatabase | null = null
42
+ const defaultTtl = options?.defaultTtl
43
+ const codec = resolveCacheCodecConfig(options)
44
+ const filePath = dbPath || process.env.CACHE_SQLITE_PATH || DEFAULT_SQLITE_CACHE_PATH
45
+
46
+ async function getDb(): Promise<SqliteDatabase> {
47
+ if (db) return db
48
+
49
+ try {
50
+ const imported = (options?.databaseConstructor ?? sqliteRequire('better-sqlite3')) as SqliteModule
51
+ const Database = typeof imported === 'function' ? imported : imported.default
52
+
53
+ // Ensure directory exists
54
+ const dir = path.dirname(filePath)
55
+ if (!fs.existsSync(dir)) {
56
+ fs.mkdirSync(dir, { recursive: true })
57
+ }
58
+
59
+ db = new Database(filePath)
60
+
61
+ db.exec(`
62
+ PRAGMA journal_mode = WAL;
63
+ PRAGMA synchronous = NORMAL;
64
+ PRAGMA busy_timeout = 5000;
65
+ PRAGMA foreign_keys = ON;
66
+ `)
67
+
68
+ // Create tables
69
+ db.exec(`
70
+ CREATE TABLE IF NOT EXISTS cache_entries (
71
+ key TEXT PRIMARY KEY,
72
+ value TEXT NOT NULL,
73
+ expires_at INTEGER,
74
+ created_at INTEGER NOT NULL
75
+ );
76
+
77
+ CREATE TABLE IF NOT EXISTS cache_tags (
78
+ key TEXT NOT NULL,
79
+ tag TEXT NOT NULL,
80
+ PRIMARY KEY (key, tag),
81
+ FOREIGN KEY (key) REFERENCES cache_entries(key) ON DELETE CASCADE
82
+ );
83
+
84
+ CREATE INDEX IF NOT EXISTS idx_cache_tags_tag ON cache_tags(tag);
85
+ CREATE INDEX IF NOT EXISTS idx_cache_entries_expires_at ON cache_entries(expires_at);
86
+ `)
87
+
88
+ return db
89
+ } catch (error) {
90
+ throw new CacheDependencyUnavailableError('sqlite', 'better-sqlite3', error)
91
+ }
92
+ }
93
+
94
+ function isExpired(expiresAt: number | null): boolean {
95
+ if (expiresAt === null) return false
96
+ return Date.now() > expiresAt
97
+ }
98
+
99
+ type EntryRow = { value: string | Buffer; expires_at: number | null }
100
+ type ExpiresRow = { expires_at: number | null }
101
+ type CountRow = { count: number }
102
+ type KeyRow = { key: string }
103
+
104
+ const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {
105
+ const database = await getDb()
106
+
107
+ const stmt = database.prepare('SELECT value, expires_at FROM cache_entries WHERE key = ?')
108
+ const row = stmt.get(key) as EntryRow | undefined
109
+
110
+ if (!row) return null
111
+
112
+ try {
113
+ const value = JSON.parse(decodeCacheText(row.value)) as CacheValue
114
+ const expiresAt = row.expires_at
115
+
116
+ if (isExpired(expiresAt)) {
117
+ if (options?.returnExpired) {
118
+ return value
119
+ }
120
+ // Clean up expired entry
121
+ await deleteKey(key)
122
+ return null
123
+ }
124
+
125
+ return value
126
+ } catch {
127
+ // Invalid JSON, remove it
128
+ await deleteKey(key)
129
+ return null
130
+ }
131
+ }
132
+
133
+ const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {
134
+ const database = await getDb()
135
+ const ttl = options?.ttl ?? defaultTtl
136
+ const tags = options?.tags || []
137
+ const expiresAt = ttl ? Date.now() + ttl : null
138
+ const createdAt = Date.now()
139
+
140
+ const serialized = encodeCacheText(JSON.stringify(value), codec)
141
+
142
+ database.transaction(() => {
143
+ // Delete old tags
144
+ database.prepare('DELETE FROM cache_tags WHERE key = ?').run(key)
145
+
146
+ // Insert or replace cache entry
147
+ database.prepare(`
148
+ INSERT OR REPLACE INTO cache_entries (key, value, expires_at, created_at)
149
+ VALUES (?, ?, ?, ?)
150
+ `).run(key, serialized, expiresAt, createdAt)
151
+
152
+ // Insert new tags
153
+ if (tags.length > 0) {
154
+ const insertTag = database.prepare('INSERT INTO cache_tags (key, tag) VALUES (?, ?)')
155
+ for (const tag of tags) {
156
+ insertTag.run(key, tag)
157
+ }
158
+ }
159
+ })()
160
+ }
161
+
162
+ const has = async (key: string): Promise<boolean> => {
163
+ const database = await getDb()
164
+
165
+ const stmt = database.prepare('SELECT expires_at FROM cache_entries WHERE key = ?')
166
+ const row = stmt.get(key) as ExpiresRow | undefined
167
+
168
+ if (!row) return false
169
+
170
+ if (isExpired(row.expires_at)) {
171
+ await deleteKey(key)
172
+ return false
173
+ }
174
+
175
+ return true
176
+ }
177
+
178
+ const deleteKey = async (key: string): Promise<boolean> => {
179
+ const database = await getDb()
180
+
181
+ const result = database.transaction(() => {
182
+ database.prepare('DELETE FROM cache_tags WHERE key = ?').run(key)
183
+ const info = database.prepare('DELETE FROM cache_entries WHERE key = ?').run(key)
184
+ return info.changes > 0
185
+ })()
186
+
187
+ return result
188
+ }
189
+
190
+ const deleteByTags = async (tags: string[]): Promise<number> => {
191
+ const database = await getDb()
192
+
193
+ // Get all unique keys that have any of the specified tags
194
+ const placeholders = tags.map(() => '?').join(',')
195
+ const stmt = database.prepare(`
196
+ SELECT DISTINCT key FROM cache_tags WHERE tag IN (${placeholders})
197
+ `)
198
+ const rows = stmt.all(...tags) as KeyRow[]
199
+
200
+ let deleted = 0
201
+ for (const row of rows) {
202
+ const success = await deleteKey(row.key)
203
+ if (success) deleted++
204
+ }
205
+
206
+ return deleted
207
+ }
208
+
209
+ const clear = async (): Promise<number> => {
210
+ const database = await getDb()
211
+
212
+ const result = database.transaction(() => {
213
+ const countStmt = database.prepare('SELECT COUNT(*) as count FROM cache_entries')
214
+ const count = (countStmt.get() as CountRow).count
215
+
216
+ database.prepare('DELETE FROM cache_tags').run()
217
+ database.prepare('DELETE FROM cache_entries').run()
218
+
219
+ return count
220
+ })()
221
+
222
+ return result
223
+ }
224
+
225
+ const keys = async (pattern?: string): Promise<string[]> => {
226
+ const database = await getDb()
227
+
228
+ const stmt = database.prepare('SELECT key FROM cache_entries')
229
+ const rows = stmt.all() as KeyRow[]
230
+
231
+ const allKeys = rows.map((row) => row.key)
232
+
233
+ if (!pattern) return allKeys
234
+
235
+ return allKeys.filter((key: string) => matchCacheKeyPattern(key, pattern))
236
+ }
237
+
238
+ const stats = async (): Promise<{ size: number; expired: number }> => {
239
+ const database = await getDb()
240
+
241
+ const sizeStmt = database.prepare('SELECT COUNT(*) as count FROM cache_entries')
242
+ const size = (sizeStmt.get() as CountRow).count
243
+
244
+ const now = Date.now()
245
+ const expiredStmt = database.prepare('SELECT COUNT(*) as count FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?')
246
+ const expired = (expiredStmt.get(now) as CountRow).count
247
+
248
+ return { size, expired }
249
+ }
250
+
251
+ const cleanup = async (): Promise<number> => {
252
+ const database = await getDb()
253
+ const now = Date.now()
254
+
255
+ const result = database.transaction(() => {
256
+ // Get keys to delete
257
+ const stmt = database.prepare('SELECT key FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?')
258
+ const rows = stmt.all(now) as KeyRow[]
259
+
260
+ // Delete tags for expired keys
261
+ for (const row of rows) {
262
+ database.prepare('DELETE FROM cache_tags WHERE key = ?').run(row.key)
263
+ }
264
+
265
+ // Delete expired entries
266
+ const info = database.prepare('DELETE FROM cache_entries WHERE expires_at IS NOT NULL AND expires_at < ?').run(now)
267
+ return info.changes
268
+ })()
269
+
270
+ return result
271
+ }
272
+
273
+ const close = async (): Promise<void> => {
274
+ if (db) {
275
+ db.close()
276
+ db = null
277
+ }
278
+ }
279
+
280
+ return {
281
+ get,
282
+ set,
283
+ has,
284
+ delete: deleteKey,
285
+ deleteByTags,
286
+ clear,
287
+ keys,
288
+ stats,
289
+ cleanup,
290
+ close,
291
+ }
292
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "../../tsconfig.base.json",
4
+ "compilerOptions": {
5
+ "noEmit": true,
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src/**/*"],
9
+ "exclude": ["node_modules", "dist", "**/__tests__/**"]
10
+ }
package/watch.mjs ADDED
@@ -0,0 +1,6 @@
1
+ import { watch } from '../../scripts/watch.mjs'
2
+ import { dirname } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const __dirname = dirname(fileURLToPath(import.meta.url))
6
+ watch(__dirname)
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.