@marianmeres/kv 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -5,7 +5,7 @@ Machine-friendly reference for AI agents working with this codebase.
5
5
  ## Quick Reference
6
6
 
7
7
  - **Stack**: TypeScript (erasable-only), Node LTS (`.node-version`), pnpm, `node:test`, Biome.
8
- - **Install**: `pnpm install` | **Test**: `pnpm test` (needs Postgres + Redis, see below) |
8
+ - **Install**: `pnpm install` | **Test**: `pnpm test` (needs Postgres + Redis; SQLite runs in memory) |
9
9
  **Check all**: `pnpm run ci` | **Build**: `pnpm run build`
10
10
  - **Published**: npm (`dist/`, built by `tsc`) and JSR (`src/` via `jsr.json`, for Deno consumers)
11
11
 
@@ -23,7 +23,8 @@ src/
23
23
  │ ├── abstract.ts — Base class + shared types
24
24
  │ ├── memory.ts — In-memory adapter
25
25
  │ ├── redis.ts — Redis adapter
26
- │ └── postgres.ts — PostgreSQL adapter
26
+ │ ├── postgres.ts — PostgreSQL adapter
27
+ │ └── sqlite.ts — SQLite adapter (`node:sqlite`)
27
28
  └── utils/
28
29
  └── sleep.ts — Sleep utility function
29
30
 
@@ -31,7 +32,8 @@ tests/
31
32
  ├── kv.test.ts — Main test file (node:test); every test runs against all adapters
32
33
  ├── _tests-runner.ts — Test harness: builds one client per adapter per test
33
34
  ├── _redis.ts — Redis test helper
34
- └── _pg.ts — PostgreSQL test helper
35
+ ├── _pg.ts — PostgreSQL test helper
36
+ └── _sqlite.ts — SQLite test helper (fresh `:memory:` database per test)
35
37
 
36
38
  dist/ — `tsc -p tsconfig.build.json` output; gitignored; the npm payload
37
39
  ```
@@ -57,14 +59,17 @@ dist/ — `tsc -p tsconfig.build.json` output; gitignored; the
57
59
  7. TTL is in seconds; stored as absolute `Date` internally.
58
60
  8. Pattern matching: Redis-style (`*` = any chars, `?` = single char). All other characters — including `.`, `(`, `[`, `%`, `_` — are matched **literally**.
59
61
  9. TTL resolution: `options.ttl ?? defaultTtl`; `0` or negative disables expiration for that call (explicitly overrides `defaultTtl`).
60
- 10. All pattern-to-regex / pattern-to-LIKE conversion lives in `abstract.ts` — use `_globToRegex()`, `_resolveTtl()`, `_normalizePairs()`; do not re-implement per-adapter.
62
+ 10. Shared helpers live in `abstract.ts` — use `_globToRegex()`, `_resolveTtl()`, `_normalizePairs()`; do not re-implement per-adapter. The SQL adapters keep their own pattern escaping next to the SQL that uses it: Postgres `#likePattern` (LIKE, `ESCAPE '\'`), SQLite `#globPattern` (GLOB — case-sensitive, unlike SQLite's LIKE; `[` → `[[]`). Both escape the namespace as a literal prefix.
61
63
  11. Postgres `transaction()` must pin a single connection via `pool.connect()`; every nested query uses that client, not `this.options.db`.
62
- 12. Redis adapter owns the connection iff `initialize()` opened it (`#weOpened` flag).
64
+ 12. Redis adapter owns the connection iff `initialize()` opened it (`#weOpened` flag). The Postgres and SQLite adapters never close the `db` they were given.
63
65
  13. Key validation lives in `_withNs()` — enforced when `options.validateKeys !== false`. Reject empty strings, keys with `\0`, and total `namespace + key` length > 512.
64
66
  14. `ttl()` returns `TtlResult = { state: "missing" | "no-ttl" | "expires"; at? }` — discriminated union, not `Date | null | false`.
65
- 15. `incr`/`decr`/`getSet`/`cas`/`setIfAbsent` must be atomic: Redis = Lua or NX; Postgres = UPSERT/UPDATE with RETURNING; Memory = plain read-modify-write (single-threaded).
66
- 16. Non-numeric `incr`/`decr` target throws `TypeError("KV value is not a number")`. In Postgres, detect via error code `22P02`.
67
- 17. `keysIter` must clean up on early consumer break — PG releases its server-side cursor in the generator's `finally`.
67
+ 15. `incr`/`decr`/`getSet`/`cas`/`setIfAbsent` must be atomic: Redis = Lua or NX; Postgres = UPSERT/UPDATE with RETURNING; SQLite = a single UPSERT/UPDATE (`setIfAbsent`, `cas`) or a read-modify-write inside `#atomic()` (`getSet`, `incr`/`decr`); Memory = plain read-modify-write (single-threaded).
68
+ 16. Non-numeric `incr`/`decr` target throws `TypeError("KV value is not a number")`. In Postgres, detect via error code `22P02`; SQLite checks `typeof` in JS, like Memory.
69
+ 17. `keysIter` must clean up on early consumer break — PG releases its server-side cursor in the generator's `finally`. SQLite pages by keyset (`key > last`), so nothing stays open between yields.
70
+ 18. SQLite: `src/` imports `node:sqlite` **type-only** — the caller passes the `DatabaseSync`. A runtime import would make every consumer of the package load `node:sqlite`.
71
+ 19. SQLite multi-statement operations go through `#atomic()`: `BEGIN IMMEDIATE`, or a savepoint when `db.isTransaction` (the caller's transaction on the same handle). The callback must stay synchronous — an `await` inside would let other work join the transaction.
72
+ 20. SQLite stores `value` as JSON text and `expires_at` as epoch ms (INTEGER), compared against a bound `Date.now()` — never SQLite's own clock. Read counts/integers through `Number()` (a handle opened with `readBigInts` returns bigints).
68
73
 
69
74
  ## Before Making Changes
70
75
 
@@ -74,11 +79,12 @@ dist/ — `tsc -p tsconfig.build.json` output; gitignored; the
74
79
 
75
80
  ## Supported Adapters
76
81
 
77
- | Adapter | Type String | Required Options | Limitations |
78
- | ---------- | ------------ | --------------------- | ------------------------------------------------------------------ |
79
- | Memory | `"memory"` | None | Not persisted |
80
- | Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
81
- | PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | `tableName` limited to `[A-Za-z0-9_]` + optional `schema.` prefix |
82
+ | Adapter | Type String | Required Options | Limitations |
83
+ | ---------- | ------------ | --------------------- | --------------------------------------------------------------------------- |
84
+ | Memory | `"memory"` | None | Not persisted |
85
+ | Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
86
+ | PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | `tableName` limited to `[A-Za-z0-9_]` + optional `schema.` prefix |
87
+ | SQLite | `"sqlite"` | `db` (`DatabaseSync`) | `tableName` limited to `[A-Za-z0-9_]`, no schema prefix; synchronous driver |
82
88
 
83
89
  ## Core API
84
90
 
@@ -168,7 +174,8 @@ human action.
168
174
 
169
175
  ## Test Environment Variables
170
176
 
171
- Every test runs against all three adapters, so tests need a live Postgres and Redis. Put
177
+ Every test runs against all four adapters, so tests need a live Postgres and Redis (SQLite
178
+ uses a fresh `:memory:` database per test and needs nothing). Put
172
179
  these in `.env` (see `.env.example`); CI provides them via service containers
173
180
  (`.github/workflows/ci.yml`). The harness deletes **every key** in the Redis DB before each
174
181
  test — use a scratch DB.
package/API.md CHANGED
@@ -31,11 +31,11 @@ function createKVClient<T extends keyof KnownTypes>(
31
31
 
32
32
  **Parameters:**
33
33
 
34
- | Parameter | Type | Default | Description |
35
- | ----------- | ----------------------------------- | ---------- | -------------------------------------------------------------------- |
36
- | `namespace` | `string` | `""` | Key prefix applied to all operations. Must end with `:` or be empty. |
37
- | `type` | `"memory" \| "redis" \| "postgres"` | `"memory"` | The storage backend to use. |
38
- | `options` | `Partial<AdapterOptions>` | `{}` | Adapter-specific configuration options. |
34
+ | Parameter | Type | Default | Description |
35
+ | ----------- | ----------------------------------------------- | ---------- | -------------------------------------------------------------------- |
36
+ | `namespace` | `string` | `""` | Key prefix applied to all operations. Must end with `:` or be empty. |
37
+ | `type` | `"memory" \| "redis" \| "postgres" \| "sqlite"` | `"memory"` | The storage backend to use. |
38
+ | `options` | `Partial<AdapterOptions>` | `{}` | Adapter-specific configuration options. |
39
39
 
40
40
  **Returns:** A configured adapter instance. Call `initialize()` before use.
41
41
 
@@ -64,6 +64,11 @@ import pg from "pg";
64
64
  const pool = new pg.Pool({ connectionString: "..." });
65
65
  const postgres = createKVClient("myapp:", "postgres", { db: pool });
66
66
  await postgres.initialize();
67
+
68
+ // SQLite storage (node:sqlite ships with Node)
69
+ import { DatabaseSync } from "node:sqlite";
70
+ const sqlite = createKVClient("myapp:", "sqlite", { db: new DatabaseSync("kv.db") });
71
+ await sqlite.initialize();
67
72
  ```
68
73
 
69
74
  ---
@@ -98,9 +103,9 @@ destroy(hard?: boolean): Promise<void>
98
103
 
99
104
  **Parameters:**
100
105
 
101
- | Parameter | Type | Default | Description |
102
- | --------- | --------- | ------- | ---------------------------------------------------------------------- |
103
- | `hard` | `boolean` | `false` | If `true`, performs a hard cleanup (e.g., drops tables in PostgreSQL). |
106
+ | Parameter | Type | Default | Description |
107
+ | --------- | --------- | ------- | --------------------------------------------------------------------------------- |
108
+ | `hard` | `boolean` | `false` | If `true`, performs a hard cleanup (e.g., drops tables in PostgreSQL and SQLite). |
104
109
 
105
110
  ---
106
111
 
@@ -116,7 +121,7 @@ info(): AdapterInfo
116
121
 
117
122
  ```typescript
118
123
  const info = client.info();
119
- console.log(info.type); // "redis", "postgres", or "memory"
124
+ console.log(info.type); // "redis", "postgres", "sqlite", or "memory"
120
125
  ```
121
126
 
122
127
  ---
@@ -453,6 +458,7 @@ Ordering is not guaranteed across adapters — use `keys()` if you need sorted o
453
458
  **Per-adapter behavior:**
454
459
  - Redis: wraps `SCAN` (non-blocking).
455
460
  - PostgreSQL: uses a server-side cursor (`DECLARE CURSOR`) inside a short transaction. Early break releases the cursor and commits.
461
+ - SQLite: keyset pages of 500 keys (`key > last ORDER BY key`). Nothing stays open between pages, so an early break has nothing to release.
456
462
  - Memory: yields from the internal `Map`.
457
463
 
458
464
  **Example:**
@@ -581,8 +587,9 @@ Atomicity per adapter:
581
587
  | Memory | ✓ | Single-threaded by nature |
582
588
  | Redis | ✓ | Uses `MULTI`/`EXEC` |
583
589
  | PostgreSQL | ✓ | Pins a single connection for `BEGIN`/…/`COMMIT`, even on a `pg.Pool` |
590
+ | SQLite | ✓ | `BEGIN IMMEDIATE`; a savepoint inside a caller-opened transaction |
584
591
 
585
- Per-operation `options.ttl` is honored by **all** adapters (Redis, PostgreSQL, Memory).
592
+ Per-operation `options.ttl` is honored by **all** adapters (Redis, PostgreSQL, SQLite, Memory).
586
593
 
587
594
  **Parameters:**
588
595
 
@@ -627,7 +634,7 @@ Information about the adapter instance.
627
634
  ```typescript
628
635
  interface AdapterInfo {
629
636
  /** The adapter type identifier. */
630
- type: string; // "redis" | "postgres" | "memory"
637
+ type: string; // "redis" | "postgres" | "sqlite" | "memory"
631
638
  }
632
639
  ```
633
640
 
@@ -777,6 +784,56 @@ interface AdapterPostgresOptions extends AdapterAbstractOptions {
777
784
 
778
785
  ---
779
786
 
787
+ ### `AdapterSqliteOptions`
788
+
789
+ ```typescript
790
+ interface AdapterSqliteOptions extends AdapterAbstractOptions {
791
+ /**
792
+ * An open `node:sqlite` database, e.g. `new DatabaseSync("kv.db")`. The caller owns
793
+ * it: `destroy()` never closes it, so one handle can be shared across adapters.
794
+ */
795
+ db: DatabaseSync;
796
+ /**
797
+ * Name of the table to use for storing key-value pairs.
798
+ * The table will be created automatically if it doesn't exist.
799
+ * Must match `^[A-Za-z_][A-Za-z0-9_]*$` (no `schema.` prefix).
800
+ * @default "__kv"
801
+ */
802
+ tableName: string;
803
+ /**
804
+ * Interval in seconds for automatic cleanup of expired keys.
805
+ * Set to 0 to disable automatic cleanup.
806
+ */
807
+ ttlCleanupIntervalSec: number;
808
+ }
809
+ ```
810
+
811
+ **Connection ownership:** the adapter never opens, closes or reconfigures the handle — it
812
+ sets no pragmas. For several processes on one file, open it with a busy timeout
813
+ (`new DatabaseSync(path, { timeout: 5000 })`) so a locked write waits instead of failing,
814
+ and consider `PRAGMA journal_mode = WAL`.
815
+
816
+ **Atomicity:** `setIfAbsent`, `cas`, `expire` and `set` are single statements.
817
+ `getSet`, `incr`/`decr`, `setMultiple`, `clear` and `transaction` run in `BEGIN IMMEDIATE`,
818
+ which takes the write lock up front, so they stay atomic against other connections and
819
+ processes. Called inside a transaction you opened on the same handle (`db.isTransaction`),
820
+ they use a savepoint instead: their own failure rolls back only themselves, and your
821
+ `COMMIT`/`ROLLBACK` decides the rest.
822
+
823
+ **Synchronous driver:** `node:sqlite` blocks the event loop for the duration of each call.
824
+ Every method still returns a Promise, like the other adapters.
825
+
826
+ **Pattern matching** uses SQLite `GLOB`, which is case-sensitive and uses the primary-key
827
+ index for a literal prefix. `[` is escaped, so `keys()` / `clear()` follow the same
828
+ literal-except-`*`/`?` rules as every adapter.
829
+
830
+ **Table Schema:**
831
+ - `key` (TEXT) - Primary key
832
+ - `value` (TEXT) - Stored value as JSON text
833
+ - `expires_at` (INTEGER) - Expiration time as epoch milliseconds; `NULL` = no expiration
834
+
835
+ ---
836
+
780
837
  ## Utility Functions
781
838
 
782
839
  ### `sleep(timeout, __timeout_ref__?)`
package/README.md CHANGED
@@ -7,6 +7,7 @@
7
7
  Key-value storage abstraction layer with support for multiple backend adapters:
8
8
  - redis
9
9
  - postgresql
10
+ - sqlite (`node:sqlite`)
10
11
  - memory
11
12
 
12
13
  The API is inspired by the Redis API.
@@ -18,8 +19,8 @@ npm install @marianmeres/kv # or pnpm add
18
19
  deno add jsr:@marianmeres/kv # Deno
19
20
  ```
20
21
 
21
- The `redis` and `postgres` adapters take a client you create yourself (`redis`, `pg`).
22
- Requires Node >= 24.12.
22
+ The `redis`, `postgres` and `sqlite` adapters take a client you create yourself (`redis`,
23
+ `pg`, or a `node:sqlite` `DatabaseSync`, which ships with Node). Requires Node >= 24.12.
23
24
 
24
25
  ## Usage
25
26
 
@@ -32,7 +33,7 @@ const client = createKVClient("my-app-namespace:");
32
33
  // Or specify a different adapter type
33
34
  const redisClient = createKVClient(
34
35
  "my-app-namespace:",
35
- "redis", // 'redis' | 'postgres' | 'memory'
36
+ "redis", // 'redis' | 'postgres' | 'sqlite' | 'memory'
36
37
  { db: myRedisClient }, // adapter-specific options
37
38
  );
38
39
 
@@ -97,20 +98,20 @@ type TtlResult =
97
98
 
98
99
  ## Adapter Feature Matrix
99
100
 
100
- | Feature | Memory | Redis | PostgreSQL |
101
- | --------------------------------------------------------- | :-----------------: | :--------------------: | :--------------: |
102
- | Persistent | ✗ | ✓ | ✓ |
103
- | TTL on `set()` | ✓ | ✓ | ✓ |
104
- | `ttl()` → `expires`/`no-ttl`/`missing` | ✓ | ✓ | ✓ |
105
- | `expire()` | ✓ | ✓ | ✓ |
106
- | Atomic `setIfAbsent` / `incr` / `decr` / `cas` / `getSet` | ✓ | ✓ (Lua) | ✓ (UPSERT) |
107
- | Sorted `keys()` | ✓ | ✓ | ✓ |
108
- | Streaming `keysIter()` | ✓ | ✓ (SCAN) | ✓ (cursor) |
109
- | Per-pair TTL in `setMultiple` | ✓ | ✓ | ✓ |
110
- | Atomic `transaction()` | ✓ (single-threaded) | ✓ (MULTI) | ✓ (BEGIN/COMMIT) |
111
- | `delete()` returns real existed-flag | ✓ | ✓ | ✓ |
112
- | Background TTL cleanup | optional | native (Redis does it) | optional |
113
- | `keys()` / `clear()` | ✓ | ✓ (non-cluster only) | ✓ |
101
+ | Feature | Memory | Redis | PostgreSQL | SQLite |
102
+ | --------------------------------------------------------- | :-----------------: | :--------------------: | :--------------: | :-----------------------: |
103
+ | Persistent | ✗ | ✓ | ✓ | ✓ (file database) |
104
+ | TTL on `set()` | ✓ | ✓ | ✓ | ✓ |
105
+ | `ttl()` → `expires`/`no-ttl`/`missing` | ✓ | ✓ | ✓ | ✓ |
106
+ | `expire()` | ✓ | ✓ | ✓ | ✓ |
107
+ | Atomic `setIfAbsent` / `incr` / `decr` / `cas` / `getSet` | ✓ | ✓ (Lua) | ✓ (UPSERT) | ✓ (UPSERT / IMMEDIATE tx) |
108
+ | Sorted `keys()` | ✓ | ✓ | ✓ | ✓ |
109
+ | Streaming `keysIter()` | ✓ | ✓ (SCAN) | ✓ (cursor) | ✓ (keyset paging) |
110
+ | Per-pair TTL in `setMultiple` | ✓ | ✓ | ✓ | ✓ |
111
+ | Atomic `transaction()` | ✓ (single-threaded) | ✓ (MULTI) | ✓ (BEGIN/COMMIT) | ✓ (BEGIN IMMEDIATE) |
112
+ | `delete()` returns real existed-flag | ✓ | ✓ | ✓ | ✓ |
113
+ | Background TTL cleanup | optional | native (Redis does it) | optional | optional |
114
+ | `keys()` / `clear()` | ✓ | ✓ (non-cluster only) | ✓ | ✓ |
114
115
 
115
116
  ## Adapter-Specific Limitations
116
117
 
@@ -127,6 +128,31 @@ type TtlResult =
127
128
  - `transaction()` pins a single connection from the Pool for the whole BEGIN/…/COMMIT block — safe to call against a `pg.Pool`.
128
129
  - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option.
129
130
 
131
+ ### SQLite
132
+
133
+ ```typescript
134
+ import { DatabaseSync } from "node:sqlite";
135
+
136
+ const client = createKVClient("my-app-namespace:", "sqlite", {
137
+ db: new DatabaseSync("kv.db"),
138
+ });
139
+ ```
140
+
141
+ - Takes an open `node:sqlite` `DatabaseSync` and never closes it — the handle is yours,
142
+ and can be shared with your own tables or other adapters.
143
+ - Creates a table (default: `__kv`). `tableName` must match `^[A-Za-z_][A-Za-z0-9_]*$` — no
144
+ `schema.` prefix.
145
+ - `node:sqlite` is synchronous: each call blocks the event loop while it runs.
146
+ - Multi-statement operations (`getSet`, `incr`/`decr`, `setMultiple`, `clear`,
147
+ `transaction`) run in `BEGIN IMMEDIATE`. Called inside a transaction you opened on the
148
+ same handle, they use a savepoint instead, so your `COMMIT`/`ROLLBACK` decides.
149
+ - The adapter does not touch connection settings. For several processes on one file,
150
+ open it with a busy timeout (`new DatabaseSync(path, { timeout: 5000 })`) and consider
151
+ `PRAGMA journal_mode = WAL`.
152
+ - `cas()` compares the stored JSON text, so object key order matters (as with Memory and
153
+ Redis; PostgreSQL compares `jsonb`, which ignores key order).
154
+ - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option.
155
+
130
156
  ### Memory
131
157
 
132
158
  - Data is not persisted (in-memory only).
@@ -214,10 +240,10 @@ For complete API documentation including all methods, types, and adapter-specifi
214
240
  Node LTS (`.node-version`), pnpm, Biome, `node:test`. The source is erasable-only
215
241
  TypeScript that Node runs directly; `dist/` is built only for publishing.
216
242
 
217
- Every test runs against all three adapters, so `pnpm test` needs a running PostgreSQL and
218
- Redis. Copy `.env.example` to `.env` and fill in the connection details. Redis keys in the
219
- target database are deleted before each test, so point it at a scratch database (the
220
- default is `/13`).
243
+ Every test runs against all four adapters, so `pnpm test` needs a running PostgreSQL and
244
+ Redis (SQLite runs in memory, nothing to set up). Copy `.env.example` to `.env` and fill
245
+ in the connection details. Redis keys in the target database are deleted before each
246
+ test, so point it at a scratch database (the default is `/13`).
221
247
 
222
248
  | Command | Does |
223
249
  | ----------------------------------- | -------------------------------------------------- |
@@ -15,7 +15,7 @@ export interface SetOptions extends Record<string, any> {
15
15
  * Information about the adapter instance.
16
16
  */
17
17
  export interface AdapterInfo {
18
- /** The adapter type identifier (e.g., "redis", "postgres", "memory"). */
18
+ /** The adapter type identifier (e.g., "redis", "postgres", "sqlite", "memory"). */
19
19
  type: string;
20
20
  }
21
21
  /**
@@ -323,7 +323,7 @@ export declare abstract class AdapterAbstract {
323
323
  /**
324
324
  * Retrieves multiple values in a single batch operation.
325
325
  *
326
- * More efficient than multiple individual `get` calls, especially for Redis and PostgreSQL.
326
+ * More efficient than multiple individual `get` calls, especially for Redis, PostgreSQL and SQLite.
327
327
  *
328
328
  * @param keys - An array of keys to retrieve.
329
329
  * @returns A promise that resolves to an object mapping keys to their values.
@@ -339,7 +339,7 @@ export declare abstract class AdapterAbstract {
339
339
  /**
340
340
  * Executes multiple operations within a single transaction.
341
341
  *
342
- * For adapters that support it (Redis, PostgreSQL), operations are atomic.
342
+ * For adapters that support it (Redis, PostgreSQL, SQLite), operations are atomic.
343
343
  * For memory, operations are executed sequentially.
344
344
  *
345
345
  * @param operations - An array of operations to execute.
@@ -393,7 +393,7 @@ export declare abstract class AdapterAbstract {
393
393
  * @example
394
394
  * ```typescript
395
395
  * const info = client.info();
396
- * console.log(info.type); // "redis", "postgres", or "memory"
396
+ * console.log(info.type); // "redis", "postgres", "sqlite", or "memory"
397
397
  * ```
398
398
  */
399
399
  info(): AdapterInfo;
@@ -302,7 +302,7 @@ export class AdapterAbstract {
302
302
  /**
303
303
  * Retrieves multiple values in a single batch operation.
304
304
  *
305
- * More efficient than multiple individual `get` calls, especially for Redis and PostgreSQL.
305
+ * More efficient than multiple individual `get` calls, especially for Redis, PostgreSQL and SQLite.
306
306
  *
307
307
  * @param keys - An array of keys to retrieve.
308
308
  * @returns A promise that resolves to an object mapping keys to their values.
@@ -320,7 +320,7 @@ export class AdapterAbstract {
320
320
  /**
321
321
  * Executes multiple operations within a single transaction.
322
322
  *
323
- * For adapters that support it (Redis, PostgreSQL), operations are atomic.
323
+ * For adapters that support it (Redis, PostgreSQL, SQLite), operations are atomic.
324
324
  * For memory, operations are executed sequentially.
325
325
  *
326
326
  * @param operations - An array of operations to execute.
@@ -380,7 +380,7 @@ export class AdapterAbstract {
380
380
  * @example
381
381
  * ```typescript
382
382
  * const info = client.info();
383
- * console.log(info.type); // "redis", "postgres", or "memory"
383
+ * console.log(info.type); // "redis", "postgres", "sqlite", or "memory"
384
384
  * ```
385
385
  */
386
386
  info() {
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * SQLite key-value storage adapter implementation (`node:sqlite`).
5
+ */
6
+ import type { DatabaseSync } from "node:sqlite";
7
+ import { AdapterAbstract, type AdapterAbstractOptions, type Operation, type SetMultipleEntry, type SetOptions, type TtlResult } from "./abstract.ts";
8
+ /**
9
+ * Configuration options for the SQLite KV adapter.
10
+ */
11
+ export interface AdapterSqliteOptions extends AdapterAbstractOptions {
12
+ /**
13
+ * An open `node:sqlite` database, e.g. `new DatabaseSync("kv.db")`. The caller owns
14
+ * it: `destroy()` never closes it, so one handle can be shared across adapters.
15
+ */
16
+ db: DatabaseSync;
17
+ /**
18
+ * Name of the table to use for storing key-value pairs.
19
+ * The table will be created automatically if it doesn't exist.
20
+ * Only word characters are allowed (no `schema.` prefix).
21
+ * @default "__kv"
22
+ */
23
+ tableName: string;
24
+ /**
25
+ * Interval in seconds for automatic cleanup of expired keys.
26
+ * Set to 0 to disable automatic cleanup.
27
+ */
28
+ ttlCleanupIntervalSec: number;
29
+ }
30
+ /**
31
+ * SQLite key-value storage adapter.
32
+ *
33
+ * Provides persistent key-value storage on a `node:sqlite` database: values are JSON
34
+ * text, expirations are epoch milliseconds. Automatically creates the required table
35
+ * and index on initialization.
36
+ *
37
+ * @remarks
38
+ * - `node:sqlite` is synchronous, so every operation blocks the event loop for its
39
+ * duration (typically microseconds) and nothing else on the handle interleaves.
40
+ * - Multi-statement operations run in `BEGIN IMMEDIATE`, so they stay atomic against
41
+ * other connections and processes on the same file. Inside a transaction the caller
42
+ * already opened on the same handle, they use a savepoint instead.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * import { DatabaseSync } from "node:sqlite";
47
+ *
48
+ * const client = createKVClient("myapp:", "sqlite", {
49
+ * db: new DatabaseSync("kv.db"),
50
+ * });
51
+ * await client.initialize();
52
+ * await client.set("session:abc", { userId: 123 }, { ttl: 3600 });
53
+ * ```
54
+ */
55
+ export declare class AdapterSqlite extends AdapterAbstract {
56
+ #private;
57
+ _type: string;
58
+ readonly options: AdapterSqliteOptions;
59
+ constructor(namespace?: string, options?: Partial<AdapterSqliteOptions>);
60
+ /** @inheritdoc */
61
+ initialize(): Promise<void>;
62
+ /** @inheritdoc */
63
+ destroy(hard?: boolean): Promise<void>;
64
+ /** @inheritdoc */
65
+ set(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
66
+ /** @inheritdoc */
67
+ setIfAbsent(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
68
+ /** @inheritdoc */
69
+ getSet(key: string, value: any, options?: Partial<SetOptions>): Promise<any>;
70
+ /** @inheritdoc */
71
+ incr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
72
+ /** @inheritdoc */
73
+ decr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
74
+ /** @inheritdoc */
75
+ cas(key: string, expected: any, next: any, options?: Partial<SetOptions>): Promise<boolean>;
76
+ /** @inheritdoc */
77
+ get(key: string): Promise<any>;
78
+ /** @inheritdoc */
79
+ delete(key: string): Promise<boolean>;
80
+ /** @inheritdoc */
81
+ exists(key: string): Promise<boolean>;
82
+ /** @inheritdoc */
83
+ keys(pattern: string): Promise<string[]>;
84
+ /** @inheritdoc */
85
+ keysIter(pattern: string): AsyncIterable<string>;
86
+ /** @inheritdoc */
87
+ clear(pattern: string): Promise<number>;
88
+ /** @inheritdoc */
89
+ setMultiple(entries: readonly SetMultipleEntry[], options?: Partial<SetOptions>): Promise<boolean[]>;
90
+ /** @inheritdoc */
91
+ getMultiple(keys: string[]): Promise<Record<string, any>>;
92
+ /** @inheritdoc */
93
+ expire(key: string, ttl: number): Promise<boolean>;
94
+ /** @inheritdoc */
95
+ ttl(key: string): Promise<TtlResult>;
96
+ /** @inheritdoc */
97
+ transaction(operations: Operation[]): Promise<any[]>;
98
+ __debug_dump(): Promise<Record<string, {
99
+ value: any;
100
+ ttl: Date | null;
101
+ }>>;
102
+ }
@@ -0,0 +1,410 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * SQLite key-value storage adapter implementation (`node:sqlite`).
5
+ */
6
+ import { createClog } from "@marianmeres/clog";
7
+ import { AdapterAbstract, } from "./abstract.js";
8
+ /** Rows fetched per page by {@link AdapterSqlite.keysIter}. */
9
+ const KEYS_ITER_PAGE = 500;
10
+ /** A row is live when it has no expiry or expires after the bound `now` (epoch ms). */
11
+ const LIVE = "(expires_at IS NULL OR expires_at > ?)";
12
+ /**
13
+ * SQLite key-value storage adapter.
14
+ *
15
+ * Provides persistent key-value storage on a `node:sqlite` database: values are JSON
16
+ * text, expirations are epoch milliseconds. Automatically creates the required table
17
+ * and index on initialization.
18
+ *
19
+ * @remarks
20
+ * - `node:sqlite` is synchronous, so every operation blocks the event loop for its
21
+ * duration (typically microseconds) and nothing else on the handle interleaves.
22
+ * - Multi-statement operations run in `BEGIN IMMEDIATE`, so they stay atomic against
23
+ * other connections and processes on the same file. Inside a transaction the caller
24
+ * already opened on the same handle, they use a savepoint instead.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * import { DatabaseSync } from "node:sqlite";
29
+ *
30
+ * const client = createKVClient("myapp:", "sqlite", {
31
+ * db: new DatabaseSync("kv.db"),
32
+ * });
33
+ * await client.initialize();
34
+ * await client.set("session:abc", { userId: 123 }, { ttl: 3600 });
35
+ * ```
36
+ */
37
+ export class AdapterSqlite extends AdapterAbstract {
38
+ _type = "sqlite";
39
+ options = {
40
+ defaultTtl: 0, // no ttl by default
41
+ logger: createClog("KV/sqlite"),
42
+ db: null, // will be set in constructor via options merge
43
+ tableName: "__kv",
44
+ ttlCleanupIntervalSec: 0,
45
+ validateKeys: true,
46
+ };
47
+ #cleanupTimer;
48
+ /** Prepared statements by SQL text — a small, fixed set per adapter. */
49
+ #statements = new Map();
50
+ constructor(namespace = "", options = {}) {
51
+ super(namespace);
52
+ this.options = Object.freeze({ ...this.options, ...(options || {}) });
53
+ if (!this.options.db) {
54
+ throw new Error("Missing sqlite database instance");
55
+ }
56
+ // tableName is spliced into SQL verbatim, so guard against surprises.
57
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(this.options.tableName)) {
58
+ throw new Error(`Invalid tableName "${this.options.tableName}". Only word characters are allowed.`);
59
+ }
60
+ }
61
+ #stmt(sql) {
62
+ let stmt = this.#statements.get(sql);
63
+ if (!stmt) {
64
+ stmt = this.options.db.prepare(sql);
65
+ this.#statements.set(sql, stmt);
66
+ }
67
+ return stmt;
68
+ }
69
+ #expiresAt(ttl) {
70
+ return ttl ? Math.round(Date.now() + ttl * 1000) : null;
71
+ }
72
+ /**
73
+ * Runs `fn` as one unit: `BEGIN IMMEDIATE` takes the write lock up front, so no other
74
+ * connection can write between its statements. Inside a transaction the caller opened
75
+ * on this handle, a savepoint keeps `fn` all-or-nothing without committing theirs.
76
+ * `fn` must stay synchronous — an `await` inside would let other work join the
77
+ * transaction.
78
+ */
79
+ #atomic(fn) {
80
+ const { db, logger } = this.options;
81
+ const [begin, commit, rollback] = db.isTransaction
82
+ ? ["SAVEPOINT kv_atomic", "RELEASE kv_atomic", "ROLLBACK TO kv_atomic"]
83
+ : ["BEGIN IMMEDIATE", "COMMIT", "ROLLBACK"];
84
+ db.exec(begin);
85
+ try {
86
+ const result = fn();
87
+ db.exec(commit);
88
+ return result;
89
+ }
90
+ catch (err) {
91
+ try {
92
+ db.exec(rollback);
93
+ // a savepoint survives ROLLBACK TO; release it to leave the caller's
94
+ // transaction exactly as it was
95
+ if (begin.startsWith("SAVEPOINT"))
96
+ db.exec(commit);
97
+ }
98
+ catch (rollbackErr) {
99
+ logger?.error?.(`Rollback failed: ${rollbackErr}`);
100
+ }
101
+ throw err;
102
+ }
103
+ }
104
+ /** @inheritdoc */
105
+ async initialize() {
106
+ const { db, tableName } = this.options;
107
+ db.exec(`
108
+ CREATE TABLE IF NOT EXISTS ${tableName} (
109
+ key TEXT NOT NULL PRIMARY KEY,
110
+ value TEXT NOT NULL,
111
+ expires_at INTEGER
112
+ )
113
+ `);
114
+ db.exec(`
115
+ CREATE INDEX IF NOT EXISTS idx_${tableName}_expires_at
116
+ ON ${tableName} (expires_at)
117
+ WHERE expires_at IS NOT NULL
118
+ `);
119
+ this._initialized = true;
120
+ this.#maybeTTLCleanup();
121
+ }
122
+ /** @inheritdoc */
123
+ async destroy(hard) {
124
+ // stop the timer first so a pending tick cannot fire during DROP
125
+ clearTimeout(this.#cleanupTimer);
126
+ this.#cleanupTimer = undefined;
127
+ this.#statements.clear();
128
+ if (hard) {
129
+ const { db, tableName } = this.options;
130
+ db.exec(`DROP TABLE IF EXISTS ${tableName}`);
131
+ }
132
+ this._initialized = false;
133
+ }
134
+ #maybeTTLCleanup() {
135
+ clearTimeout(this.#cleanupTimer); // safety
136
+ if (this.options.ttlCleanupIntervalSec) {
137
+ const { tableName, logger } = this.options;
138
+ // do the cleanup now
139
+ try {
140
+ this.#stmt(`DELETE FROM ${tableName}
141
+ WHERE expires_at IS NOT NULL AND expires_at <= ?`).run(Date.now());
142
+ }
143
+ catch (err) {
144
+ logger?.error?.(`TTL cleanup error: ${err}`);
145
+ }
146
+ // schedule next...
147
+ this.#cleanupTimer = setTimeout(this.#maybeTTLCleanup.bind(this), this.options.ttlCleanupIntervalSec * 1000);
148
+ }
149
+ }
150
+ /**
151
+ * Convert a Redis-style glob to an SQLite GLOB pattern. GLOB already reads `*` and `?`
152
+ * as wildcards; its one other metacharacter, `[`, is made literal as `[[]`. Unlike
153
+ * LIKE, GLOB is case-sensitive and can use the primary-key index for a literal prefix.
154
+ */
155
+ #globPattern(pattern) {
156
+ return pattern.replace(/\[/g, "[[]");
157
+ }
158
+ #withNsGlob(pattern) {
159
+ // namespace is a literal prefix — its own `*`/`?`/`[` must be escaped too
160
+ const ns = this.namespace.replace(/[*?[]/g, "[$&]");
161
+ return ns + this.#globPattern(pattern);
162
+ }
163
+ #upsertSql() {
164
+ return `INSERT INTO ${this.options.tableName} (key, value, expires_at)
165
+ VALUES (?, ?, ?)
166
+ ON CONFLICT (key) DO UPDATE SET
167
+ value = excluded.value,
168
+ expires_at = excluded.expires_at`;
169
+ }
170
+ #set(key, value, options = {}) {
171
+ this._assertInitialized();
172
+ this.#stmt(this.#upsertSql()).run(this._withNs(key), JSON.stringify(value ?? null), this.#expiresAt(this._resolveTtl(options)));
173
+ return true;
174
+ }
175
+ /** @inheritdoc */
176
+ async set(key, value, options = {}) {
177
+ return this.#set(key, value, options);
178
+ }
179
+ /** @inheritdoc */
180
+ async setIfAbsent(key, value, options = {}) {
181
+ this._assertInitialized();
182
+ const nsKey = this._withNs(key);
183
+ // INSERT on new keys; UPDATE only when the existing row is expired.
184
+ // (Live keys stay untouched — the hallmark of setIfAbsent.)
185
+ const { changes } = this.#stmt(`${this.#upsertSql()}
186
+ WHERE expires_at IS NOT NULL AND expires_at <= ?`).run(nsKey, JSON.stringify(value ?? null), this.#expiresAt(this._resolveTtl(options)), Date.now());
187
+ return Number(changes) > 0;
188
+ }
189
+ /** @inheritdoc */
190
+ async getSet(key, value, options = {}) {
191
+ this._assertInitialized();
192
+ return this.#atomic(() => {
193
+ const previous = this.#get(key);
194
+ this.#set(key, value, options);
195
+ return previous;
196
+ });
197
+ }
198
+ #incrBy(key, delta, options = {}) {
199
+ this._assertInitialized();
200
+ const nsKey = this._withNs(key);
201
+ const { tableName } = this.options;
202
+ // Read-modify-write in JS, so the arithmetic is exactly the memory adapter's.
203
+ return this.#atomic(() => {
204
+ const row = this.#stmt(`SELECT value FROM ${tableName} WHERE key = ? AND ${LIVE}`).get(nsKey, Date.now());
205
+ // - New key OR expired key: value = delta, expires_at = $ttl
206
+ // - Live key: value = old + delta, preserve existing expires_at
207
+ if (!row) {
208
+ this.#stmt(this.#upsertSql()).run(nsKey, JSON.stringify(delta), this.#expiresAt(this._resolveTtl(options)));
209
+ return delta;
210
+ }
211
+ const current = JSON.parse(row.value);
212
+ if (typeof current !== "number") {
213
+ throw new TypeError("KV value is not a number");
214
+ }
215
+ const next = current + delta;
216
+ this.#stmt(`UPDATE ${tableName} SET value = ? WHERE key = ?`).run(JSON.stringify(next), nsKey);
217
+ return next;
218
+ });
219
+ }
220
+ /** @inheritdoc */
221
+ async incr(key, by = 1, options = {}) {
222
+ return this.#incrBy(key, by, options);
223
+ }
224
+ /** @inheritdoc */
225
+ async decr(key, by = 1, options = {}) {
226
+ return this.#incrBy(key, -by, options);
227
+ }
228
+ /** @inheritdoc */
229
+ async cas(key, expected, next, options = {}) {
230
+ this._assertInitialized();
231
+ const nsKey = this._withNs(key);
232
+ const { tableName } = this.options;
233
+ const hasTtl = options.ttl !== undefined;
234
+ // Stored values are `JSON.stringify` output, so comparing the text is comparing
235
+ // the values — with the memory and Redis adapters' key-order sensitivity.
236
+ const params = [JSON.stringify(next ?? null)];
237
+ if (hasTtl)
238
+ params.push(this.#expiresAt(this._resolveTtl(options)));
239
+ params.push(nsKey, JSON.stringify(expected ?? null), Date.now());
240
+ const { changes } = this.#stmt(`UPDATE ${tableName}
241
+ SET value = ?${hasTtl ? ", expires_at = ?" : ""}
242
+ WHERE key = ? AND value = ? AND ${LIVE}`).run(...params);
243
+ return Number(changes) > 0;
244
+ }
245
+ #get(key) {
246
+ this._assertInitialized();
247
+ const row = this.#stmt(`SELECT value FROM ${this.options.tableName} WHERE key = ? AND ${LIVE}`).get(this._withNs(key), Date.now());
248
+ return row ? JSON.parse(row.value) : null;
249
+ }
250
+ /** @inheritdoc */
251
+ async get(key) {
252
+ return this.#get(key);
253
+ }
254
+ #delete(key) {
255
+ this._assertInitialized();
256
+ const { changes } = this.#stmt(`DELETE FROM ${this.options.tableName} WHERE key = ?`).run(this._withNs(key));
257
+ return Number(changes) > 0;
258
+ }
259
+ /** @inheritdoc */
260
+ async delete(key) {
261
+ return this.#delete(key);
262
+ }
263
+ /** @inheritdoc */
264
+ async exists(key) {
265
+ this._assertInitialized();
266
+ const row = this.#stmt(`SELECT 1 FROM ${this.options.tableName} WHERE key = ? AND ${LIVE}`).get(this._withNs(key), Date.now());
267
+ return row !== undefined;
268
+ }
269
+ /** @inheritdoc */
270
+ async keys(pattern) {
271
+ this._assertInitialized();
272
+ const rows = this.#stmt(`SELECT key FROM ${this.options.tableName}
273
+ WHERE key GLOB ? AND ${LIVE}
274
+ ORDER BY key`).all(this.#withNsGlob(pattern), Date.now());
275
+ return rows.map((row) => this._withoutNs(row.key)).toSorted();
276
+ }
277
+ /** @inheritdoc */
278
+ async *keysIter(pattern) {
279
+ this._assertInitialized();
280
+ const { tableName } = this.options;
281
+ const glob = this.#withNsGlob(pattern);
282
+ // Keyset pages instead of one open statement: nothing is left open (no read
283
+ // snapshot held) while the consumer awaits between yields, and an early break
284
+ // leaves nothing to release.
285
+ let after;
286
+ while (true) {
287
+ const rows = (after === undefined
288
+ ? this.#stmt(`SELECT key FROM ${tableName}
289
+ WHERE key GLOB ? AND ${LIVE}
290
+ ORDER BY key LIMIT ${KEYS_ITER_PAGE}`).all(glob, Date.now())
291
+ : this.#stmt(`SELECT key FROM ${tableName}
292
+ WHERE key GLOB ? AND key > ? AND ${LIVE}
293
+ ORDER BY key LIMIT ${KEYS_ITER_PAGE}`).all(glob, after, Date.now()));
294
+ for (const row of rows) {
295
+ yield this._withoutNs(row.key);
296
+ }
297
+ if (rows.length < KEYS_ITER_PAGE)
298
+ return;
299
+ after = rows[rows.length - 1].key;
300
+ }
301
+ }
302
+ /** @inheritdoc */
303
+ async clear(pattern) {
304
+ this._assertInitialized();
305
+ const { tableName } = this.options;
306
+ const glob = this.#withNsGlob(pattern);
307
+ const now = Date.now();
308
+ return this.#atomic(() => {
309
+ const { changes } = this.#stmt(`DELETE FROM ${tableName} WHERE key GLOB ? AND ${LIVE}`).run(glob, now);
310
+ // expired rows under the pattern are already invisible; drop them too, but
311
+ // don't count them
312
+ this.#stmt(`DELETE FROM ${tableName}
313
+ WHERE key GLOB ? AND expires_at IS NOT NULL AND expires_at <= ?`).run(glob, now);
314
+ return Number(changes);
315
+ });
316
+ }
317
+ /** @inheritdoc */
318
+ async setMultiple(entries, options = {}) {
319
+ this._assertInitialized();
320
+ if (entries.length === 0)
321
+ return [];
322
+ // validate every key before writing any
323
+ const rows = this._normalizePairs(entries).map(({ key, value, ttl }) => [
324
+ this._withNs(key),
325
+ JSON.stringify(value ?? null),
326
+ this.#expiresAt(this._resolveTtl({ ttl: ttl ?? options.ttl })),
327
+ ]);
328
+ // one transaction: all-or-nothing, and a single commit instead of one per row
329
+ this.#atomic(() => {
330
+ const upsert = this.#stmt(this.#upsertSql());
331
+ for (const params of rows)
332
+ upsert.run(...params);
333
+ });
334
+ return rows.map(() => true);
335
+ }
336
+ /** @inheritdoc */
337
+ async getMultiple(keys) {
338
+ this._assertInitialized();
339
+ if (keys.length === 0)
340
+ return {};
341
+ // one JSON-array parameter instead of N placeholders: no bound-variable limit,
342
+ // and a single cached statement for every batch size
343
+ const rows = this.#stmt(`SELECT key, value FROM ${this.options.tableName}
344
+ WHERE key IN (SELECT j.value FROM json_each(?) AS j) AND ${LIVE}`).all(JSON.stringify(keys.map((k) => this._withNs(k))), Date.now());
345
+ const found = Object.create(null);
346
+ for (const row of rows) {
347
+ found[this._withoutNs(row.key)] = JSON.parse(row.value);
348
+ }
349
+ // preserve explicit null / false / 0 / "" — missing keys become null
350
+ const resultMap = {};
351
+ for (const key of keys) {
352
+ resultMap[key] = key in found ? found[key] : null;
353
+ }
354
+ return resultMap;
355
+ }
356
+ /** @inheritdoc */
357
+ async expire(key, ttl) {
358
+ this._assertInitialized();
359
+ const { changes } = this.#stmt(`UPDATE ${this.options.tableName}
360
+ SET expires_at = ?
361
+ WHERE key = ? AND ${LIVE}`).run(Math.round(Date.now() + ttl * 1000), this._withNs(key), Date.now());
362
+ return Number(changes) > 0;
363
+ }
364
+ /** @inheritdoc */
365
+ async ttl(key) {
366
+ this._assertInitialized();
367
+ const row = this.#stmt(`SELECT expires_at FROM ${this.options.tableName} WHERE key = ?`).get(this._withNs(key));
368
+ if (!row)
369
+ return { state: "missing" };
370
+ if (row.expires_at === null)
371
+ return { state: "no-ttl" };
372
+ // expired-but-not-yet-cleaned counts as missing (matches get() filter)
373
+ const at = new Date(Number(row.expires_at));
374
+ if (at.valueOf() <= Date.now())
375
+ return { state: "missing" };
376
+ return { state: "expires", at };
377
+ }
378
+ /** @inheritdoc */
379
+ async transaction(operations) {
380
+ this._assertInitialized();
381
+ return this.#atomic(() => {
382
+ const results = [];
383
+ for (const op of operations) {
384
+ switch (op.type) {
385
+ case "set":
386
+ results.push(this.#set(op.key, op.value, op.options || {}));
387
+ break;
388
+ case "get":
389
+ results.push(this.#get(op.key));
390
+ break;
391
+ case "delete":
392
+ results.push(this.#delete(op.key));
393
+ break;
394
+ }
395
+ }
396
+ return results;
397
+ });
398
+ }
399
+ async __debug_dump() {
400
+ this._assertInitialized();
401
+ const rows = this.#stmt(`SELECT key, value, expires_at FROM ${this.options.tableName} WHERE key GLOB ?`).all(this.#withNsGlob("*"));
402
+ return rows.reduce((m, row) => {
403
+ m[this._withoutNs(row.key)] = {
404
+ value: JSON.parse(row.value),
405
+ ttl: row.expires_at === null ? null : new Date(Number(row.expires_at)),
406
+ };
407
+ return m;
408
+ }, {});
409
+ }
410
+ }
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * - **memory** - In-memory storage (default, not persisted)
8
8
  * - **redis** - Redis server
9
9
  * - **postgres** - PostgreSQL database
10
+ * - **sqlite** - SQLite database (`node:sqlite`)
10
11
  *
11
12
  * @example
12
13
  * ```typescript
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@
7
7
  * - **memory** - In-memory storage (default, not persisted)
8
8
  * - **redis** - Redis server
9
9
  * - **postgres** - PostgreSQL database
10
+ * - **sqlite** - SQLite database (`node:sqlite`)
10
11
  *
11
12
  * @example
12
13
  * ```typescript
package/dist/kv.d.ts CHANGED
@@ -9,11 +9,13 @@
9
9
  import { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.ts";
10
10
  import { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.ts";
11
11
  import { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.ts";
12
+ import { AdapterSqlite, type AdapterSqliteOptions } from "./adapter/sqlite.ts";
12
13
  export type { AdapterAbstractOptions, AdapterInfo, Operation, SetMultipleEntry, SetOptions, TtlResult, } from "./adapter/abstract.ts";
13
14
  export { AdapterAbstract } from "./adapter/abstract.ts";
14
15
  export { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.ts";
15
16
  export { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.ts";
16
17
  export { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.ts";
18
+ export { AdapterSqlite, type AdapterSqliteOptions } from "./adapter/sqlite.ts";
17
19
  export { sleep } from "./utils/sleep.ts";
18
20
  /**
19
21
  * Type mapping for all supported KV adapter types.
@@ -32,6 +34,10 @@ interface KnownTypes {
32
34
  options: AdapterRedisOptions;
33
35
  adapter: AdapterRedis;
34
36
  };
37
+ sqlite: {
38
+ options: AdapterSqliteOptions;
39
+ adapter: AdapterSqlite;
40
+ };
35
41
  }
36
42
  /**
37
43
  * Factory function to create a KV client with the specified adapter type.
@@ -47,6 +53,7 @@ interface KnownTypes {
47
53
  * - `"memory"` - In-memory storage (default, not persisted)
48
54
  * - `"redis"` - Redis server (requires `db` option with Redis client)
49
55
  * - `"postgres"` - PostgreSQL database (requires `db` option with pg client/pool)
56
+ * - `"sqlite"` - SQLite database (requires `db` option with a `node:sqlite` `DatabaseSync`)
50
57
  * @param options - Adapter-specific configuration options.
51
58
  *
52
59
  * @returns A configured adapter instance. Call `initialize()` before use.
@@ -72,6 +79,11 @@ interface KnownTypes {
72
79
  * const pool = new pg.Pool({ connectionString: '...' });
73
80
  * const postgres = createKVClient("myapp:", "postgres", { db: pool });
74
81
  * await postgres.initialize();
82
+ *
83
+ * // SQLite storage
84
+ * import { DatabaseSync } from 'node:sqlite';
85
+ * const sqlite = createKVClient("myapp:", "sqlite", { db: new DatabaseSync("kv.db") });
86
+ * await sqlite.initialize();
75
87
  * ```
76
88
  */
77
89
  export declare function createKVClient<T extends keyof KnownTypes>(namespace?: string, type?: T, options?: Partial<KnownTypes[T]["options"]>): KnownTypes[T]["adapter"];
package/dist/kv.js CHANGED
@@ -9,10 +9,12 @@
9
9
  import { AdapterMemory } from "./adapter/memory.js";
10
10
  import { AdapterPostgres } from "./adapter/postgres.js";
11
11
  import { AdapterRedis } from "./adapter/redis.js";
12
+ import { AdapterSqlite } from "./adapter/sqlite.js";
12
13
  export { AdapterAbstract } from "./adapter/abstract.js";
13
14
  export { AdapterMemory } from "./adapter/memory.js";
14
15
  export { AdapterPostgres } from "./adapter/postgres.js";
15
16
  export { AdapterRedis } from "./adapter/redis.js";
17
+ export { AdapterSqlite } from "./adapter/sqlite.js";
16
18
  export { sleep } from "./utils/sleep.js";
17
19
  /**
18
20
  * Factory function to create a KV client with the specified adapter type.
@@ -28,6 +30,7 @@ export { sleep } from "./utils/sleep.js";
28
30
  * - `"memory"` - In-memory storage (default, not persisted)
29
31
  * - `"redis"` - Redis server (requires `db` option with Redis client)
30
32
  * - `"postgres"` - PostgreSQL database (requires `db` option with pg client/pool)
33
+ * - `"sqlite"` - SQLite database (requires `db` option with a `node:sqlite` `DatabaseSync`)
31
34
  * @param options - Adapter-specific configuration options.
32
35
  *
33
36
  * @returns A configured adapter instance. Call `initialize()` before use.
@@ -53,6 +56,11 @@ export { sleep } from "./utils/sleep.js";
53
56
  * const pool = new pg.Pool({ connectionString: '...' });
54
57
  * const postgres = createKVClient("myapp:", "postgres", { db: pool });
55
58
  * await postgres.initialize();
59
+ *
60
+ * // SQLite storage
61
+ * import { DatabaseSync } from 'node:sqlite';
62
+ * const sqlite = createKVClient("myapp:", "sqlite", { db: new DatabaseSync("kv.db") });
63
+ * await sqlite.initialize();
56
64
  * ```
57
65
  */
58
66
  export function createKVClient(namespace = "", type = "memory", options = {}) {
@@ -63,6 +71,8 @@ export function createKVClient(namespace = "", type = "memory", options = {}) {
63
71
  return new AdapterPostgres(namespace, options);
64
72
  if (type === "redis")
65
73
  return new AdapterRedis(namespace, options);
74
+ if (type === "sqlite")
75
+ return new AdapterSqlite(namespace, options);
66
76
  //
67
77
  throw new TypeError(`Unsupported KV client type "${type}"`);
68
78
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@marianmeres/kv",
3
- "version": "3.0.0",
4
- "description": "Key-value storage abstraction with a unified, Redis-inspired API over memory, Redis and PostgreSQL backends.",
3
+ "version": "3.1.0",
4
+ "description": "Key-value storage abstraction with a unified, Redis-inspired API over memory, Redis, PostgreSQL and SQLite backends.",
5
5
  "license": "MIT",
6
6
  "author": "Marian Meres",
7
7
  "type": "module",
@@ -37,19 +37,20 @@
37
37
  "redis",
38
38
  "postgres",
39
39
  "postgresql",
40
+ "sqlite",
40
41
  "cache",
41
42
  "ttl",
42
43
  "storage"
43
44
  ],
44
45
  "dependencies": {
45
- "@marianmeres/clog": "^3.21.0",
46
- "@types/pg": "^8.20.0",
47
- "pg": "^8.21.0",
48
- "redis": "^6.0.0"
46
+ "@marianmeres/clog": "^3.23.0",
47
+ "@types/pg": "^8.23.1",
48
+ "pg": "^8.23.1",
49
+ "redis": "^6.3.1"
49
50
  },
50
51
  "devDependencies": {
51
- "@biomejs/biome": "^2.6.3",
52
- "@types/node": "^26.6.5",
52
+ "@biomejs/biome": "^2.6.4",
53
+ "@types/node": "^26.6.6",
53
54
  "typescript": "^7.0.2"
54
55
  },
55
56
  "scripts": {