@wats/persistence 0.3.6

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WATS contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @wats/persistence
2
+
3
+ Experimental WATS persistence contracts and adapters.
4
+
5
+ Install:
6
+
7
+ ```bash
8
+ bun add @wats/persistence
9
+ npm i @wats/persistence
10
+ ```
11
+
12
+ Current scope:
13
+
14
+ - root persistence interfaces
15
+ - SQLite local-development adapter target
16
+ - forward-only migration runner
17
+ - redacted health diagnostics
18
+
19
+ SQLite is intended for local and single-instance testing. Postgres, service integration, conversation APIs, CLI thread navigation, and status UI wiring are tracked as follow-up WATS issues.
20
+
21
+ Docs: https://github.com/Switchbord/wats
22
+ License: MIT
@@ -0,0 +1,47 @@
1
+ export declare const CURRENT_SCHEMA_VERSION: 1;
2
+ export declare const REDACTED_SQLITE_LOCATION: "[REDACTED_SQLITE_DATABASE]";
3
+ export type PersistenceBackend = "sqlite" | "postgres";
4
+ export type PersistenceErrorCode = "invalid_options" | "invalid_filename" | "invalid_record" | "migration_failed" | "migration_checksum_mismatch" | "migration_lock_failed" | "store_closed";
5
+ export interface MigrationReport {
6
+ readonly currentVersion: number;
7
+ readonly appliedMigrations: readonly string[];
8
+ readonly alreadyCurrent: boolean;
9
+ }
10
+ export interface PersistenceHealth {
11
+ readonly ok: boolean;
12
+ readonly backend: PersistenceBackend;
13
+ readonly currentVersion: number;
14
+ readonly redactedLocation: string;
15
+ }
16
+ export interface WebhookEventRecordInput {
17
+ readonly eventKey: string;
18
+ readonly eventHash: string;
19
+ readonly receivedAt: string;
20
+ }
21
+ export type WebhookEventRecordResult = "recorded" | "duplicate";
22
+ export interface ServiceRequestLookupInput {
23
+ readonly idempotencyKey: string;
24
+ readonly requestHash: string;
25
+ }
26
+ export interface ServiceRequestRecordInput extends ServiceRequestLookupInput {
27
+ readonly responseJson: string;
28
+ readonly createdAt: string;
29
+ }
30
+ export type ServiceRequestLookupResult = null | "conflict" | {
31
+ readonly responseJson: string;
32
+ };
33
+ export interface PersistenceStore {
34
+ readonly backend: PersistenceBackend;
35
+ migrate(): Promise<MigrationReport>;
36
+ health(): Promise<PersistenceHealth>;
37
+ recordWebhookEvent(input: WebhookEventRecordInput): Promise<WebhookEventRecordResult>;
38
+ getServiceRequest(input: ServiceRequestLookupInput): Promise<ServiceRequestLookupResult>;
39
+ recordServiceRequest(input: ServiceRequestRecordInput): Promise<void>;
40
+ close(): Promise<void>;
41
+ }
42
+ export declare class PersistenceError extends Error {
43
+ readonly code: PersistenceErrorCode;
44
+ constructor(code: PersistenceErrorCode, message?: string, options?: ErrorOptions);
45
+ }
46
+ export { createSqlitePersistence } from "./sqlite";
47
+ export type { SqlitePersistenceOptions } from "./sqlite";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export const CURRENT_SCHEMA_VERSION = 1;
2
+ export const REDACTED_SQLITE_LOCATION = "[REDACTED_SQLITE_DATABASE]";
3
+
4
+ export class PersistenceError extends Error {
5
+ code;
6
+ constructor(code, message, options) {
7
+ super(message ?? code, options);
8
+ this.name = "PersistenceError";
9
+ this.code = code;
10
+ }
11
+ }
12
+ export { createSqlitePersistence } from "./sqlite";
@@ -0,0 +1,6 @@
1
+ import { type PersistenceStore } from "./index";
2
+ export interface SqlitePersistenceOptions {
3
+ readonly filename: string;
4
+ readonly readonly?: boolean;
5
+ }
6
+ export declare function createSqlitePersistence(options: SqlitePersistenceOptions): Promise<PersistenceStore>;
package/dist/sqlite.js ADDED
@@ -0,0 +1,301 @@
1
+ class SqlitePersistenceStore {
2
+ backend = "sqlite";
3
+ #database;
4
+ #closed = false;
5
+ constructor(database) {
6
+ this.#database = database;
7
+ }
8
+ async migrate() {
9
+ this.#assertOpen();
10
+ this.#database.exec("PRAGMA foreign_keys = ON");
11
+ this.#database.exec("PRAGMA busy_timeout = 5000");
12
+ this.#database.exec("PRAGMA journal_mode = WAL");
13
+ this.#database.run(`CREATE TABLE IF NOT EXISTS wats_persistence_lock (
14
+ id INTEGER PRIMARY KEY CHECK (id = 1),
15
+ holder TEXT NOT NULL,
16
+ acquired_at TEXT NOT NULL
17
+ )`);
18
+ this.#database.run(`CREATE TABLE IF NOT EXISTS wats_schema_migrations (
19
+ id TEXT PRIMARY KEY,
20
+ version INTEGER NOT NULL,
21
+ checksum TEXT NOT NULL,
22
+ applied_at TEXT NOT NULL
23
+ )`);
24
+ const holder = `wats-${Math.random().toString(36).slice(2)}`;
25
+ try {
26
+ this.#acquireLock(holder);
27
+ const applied = [];
28
+ this.#validateAppliedChecksums();
29
+ for (const migration of MIGRATIONS) {
30
+ const row = this.#migrationRow(migration.id);
31
+ if (row !== null)
32
+ continue;
33
+ this.#database.exec("BEGIN IMMEDIATE");
34
+ try {
35
+ for (const statement of migration.statements)
36
+ this.#database.run(statement);
37
+ this.#database.run("INSERT INTO wats_schema_migrations (id, version, checksum, applied_at) VALUES (?, ?, ?, ?)", migration.id, migration.version, migration.checksum, nowIso());
38
+ this.#database.exec("COMMIT");
39
+ applied.push(migration.id);
40
+ } catch (cause) {
41
+ this.#database.exec("ROLLBACK");
42
+ throw new PersistenceError("migration_failed", "SQLite migration failed.", { cause });
43
+ }
44
+ }
45
+ return Object.freeze({
46
+ currentVersion: CURRENT_SCHEMA_VERSION,
47
+ appliedMigrations: Object.freeze(applied.slice()),
48
+ alreadyCurrent: applied.length === 0
49
+ });
50
+ } finally {
51
+ this.#releaseLock(holder);
52
+ }
53
+ }
54
+ async health() {
55
+ this.#assertOpen();
56
+ const row = this.#database.query("SELECT COALESCE(MAX(version), 0) AS version FROM wats_schema_migrations").get();
57
+ return Object.freeze({
58
+ ok: true,
59
+ backend: "sqlite",
60
+ currentVersion: typeof row?.version === "number" ? row.version : 0,
61
+ redactedLocation: REDACTED_SQLITE_LOCATION
62
+ });
63
+ }
64
+ async recordWebhookEvent(input) {
65
+ this.#assertOpen();
66
+ const record = validateWebhookEventRecord(input);
67
+ try {
68
+ this.#database.run("INSERT INTO wats_webhook_events (event_key, event_hash, received_at) VALUES (?, ?, ?)", record.eventKey, record.eventHash, record.receivedAt);
69
+ return "recorded";
70
+ } catch (cause) {
71
+ const message = cause instanceof Error ? cause.message : String(cause);
72
+ if (/UNIQUE|constraint/i.test(message))
73
+ return "duplicate";
74
+ throw new PersistenceError("migration_failed", "SQLite webhook event record failed.", { cause });
75
+ }
76
+ }
77
+ async getServiceRequest(input) {
78
+ this.#assertOpen();
79
+ const lookup = validateServiceRequestLookup(input);
80
+ const row = this.#database.query("SELECT request_hash, response_json FROM wats_service_requests WHERE idempotency_key = ?").get(lookup.idempotencyKey);
81
+ if (row === null)
82
+ return null;
83
+ if (row.request_hash !== lookup.requestHash)
84
+ return "conflict";
85
+ return Object.freeze({ responseJson: row.response_json });
86
+ }
87
+ async recordServiceRequest(input) {
88
+ this.#assertOpen();
89
+ const record = validateServiceRequestRecord(input);
90
+ this.#database.run("INSERT OR IGNORE INTO wats_service_requests (idempotency_key, request_hash, response_json, created_at) VALUES (?, ?, ?, ?)", record.idempotencyKey, record.requestHash, record.responseJson, record.createdAt);
91
+ }
92
+ async close() {
93
+ if (this.#closed)
94
+ return;
95
+ this.#closed = true;
96
+ this.#database.close();
97
+ }
98
+ __unsafeTamperMigrationChecksumForTesting(id, checksum) {
99
+ this.#assertOpen();
100
+ this.#database.run("UPDATE wats_schema_migrations SET checksum = ? WHERE id = ?", checksum, id);
101
+ }
102
+ #assertOpen() {
103
+ if (this.#closed) {
104
+ throw new PersistenceError("store_closed", "Persistence store is closed.");
105
+ }
106
+ }
107
+ #acquireLock(holder) {
108
+ try {
109
+ this.#database.run("INSERT INTO wats_persistence_lock (id, holder, acquired_at) VALUES (?, ?, ?)", MIGRATION_LOCK_ID, holder, nowIso());
110
+ } catch (cause) {
111
+ throw new PersistenceError("migration_lock_failed", "SQLite migration lock is already held.", { cause });
112
+ }
113
+ }
114
+ #releaseLock(holder) {
115
+ try {
116
+ this.#database.run("DELETE FROM wats_persistence_lock WHERE id = ? AND holder = ?", MIGRATION_LOCK_ID, holder);
117
+ } catch {}
118
+ }
119
+ #migrationRow(id) {
120
+ return this.#database.query("SELECT id, version, checksum FROM wats_schema_migrations WHERE id = ?").get(id);
121
+ }
122
+ #validateAppliedChecksums() {
123
+ const rows = this.#database.query("SELECT id, version, checksum FROM wats_schema_migrations ORDER BY version ASC").all();
124
+ for (const row of rows) {
125
+ const expected = migrationById(row.id);
126
+ if (expected === undefined || expected.checksum !== row.checksum || expected.version !== row.version) {
127
+ throw new PersistenceError("migration_checksum_mismatch", "SQLite migration checksum mismatch.");
128
+ }
129
+ }
130
+ }
131
+ }
132
+ import {
133
+ CURRENT_SCHEMA_VERSION,
134
+ PersistenceError,
135
+ REDACTED_SQLITE_LOCATION
136
+ } from "./index";
137
+ const SQLITE_MEMORY = ":memory:";
138
+ const MAX_FILENAME_LENGTH = 4096;
139
+ const MIGRATION_LOCK_ID = 1;
140
+ const MIGRATIONS = Object.freeze([
141
+ {
142
+ id: "001_initial",
143
+ version: 1,
144
+ checksum: "sha256:wats-persistence-001-initial-v1",
145
+ statements: Object.freeze([
146
+ `CREATE TABLE IF NOT EXISTS wats_schema_migrations (
147
+ id TEXT PRIMARY KEY,
148
+ version INTEGER NOT NULL,
149
+ checksum TEXT NOT NULL,
150
+ applied_at TEXT NOT NULL
151
+ )`,
152
+ `CREATE TABLE IF NOT EXISTS wats_persistence_lock (
153
+ id INTEGER PRIMARY KEY CHECK (id = 1),
154
+ holder TEXT NOT NULL,
155
+ acquired_at TEXT NOT NULL
156
+ )`,
157
+ `CREATE TABLE IF NOT EXISTS wats_webhook_events (
158
+ event_key TEXT PRIMARY KEY,
159
+ event_hash TEXT NOT NULL,
160
+ received_at TEXT NOT NULL
161
+ )`,
162
+ `CREATE TABLE IF NOT EXISTS wats_service_requests (
163
+ idempotency_key TEXT PRIMARY KEY,
164
+ request_hash TEXT NOT NULL,
165
+ response_json TEXT NOT NULL,
166
+ created_at TEXT NOT NULL
167
+ )`,
168
+ `CREATE TABLE IF NOT EXISTS wats_outbox (
169
+ id TEXT PRIMARY KEY,
170
+ status TEXT NOT NULL,
171
+ attempts INTEGER NOT NULL,
172
+ next_attempt_at TEXT,
173
+ payload_hash TEXT NOT NULL,
174
+ created_at TEXT NOT NULL,
175
+ updated_at TEXT NOT NULL
176
+ )`
177
+ ])
178
+ }
179
+ ]);
180
+ function hasControlChars(value) {
181
+ return Array.from(value).some((char) => {
182
+ const code = char.codePointAt(0) ?? 0;
183
+ return code < 32 || code === 127;
184
+ });
185
+ }
186
+ function containsUnsafePathSegment(value) {
187
+ const lower = value.toLowerCase();
188
+ return value.includes("\\") || value.includes("?") || value.includes("#") || value.includes(":") || value.split("/").some((segment) => segment === ".." || segment === ".") || lower.includes("%2e%2e") || lower.includes("%252e%252e") || lower.includes("%2f") || lower.includes("%252f") || lower.includes("%5c") || lower.includes("%255c");
189
+ }
190
+ function looksTokenLike(value) {
191
+ const lower = value.toLowerCase();
192
+ return /(?:^|[^a-z])(token|secret|passwd|password|bearer|authorization|access[_-]?token)(?:[^a-z]|$)/u.test(lower);
193
+ }
194
+ function validateFilename(value) {
195
+ if (typeof value !== "string") {
196
+ throw new PersistenceError("invalid_filename", "SQLite filename must be a safe local path or :memory:.");
197
+ }
198
+ if (value === SQLITE_MEMORY)
199
+ return value;
200
+ if (value.trim().length === 0 || value.length > MAX_FILENAME_LENGTH || hasControlChars(value)) {
201
+ throw new PersistenceError("invalid_filename", "SQLite filename must be a safe local path or :memory:.");
202
+ }
203
+ if (containsUnsafePathSegment(value) || looksTokenLike(value)) {
204
+ throw new PersistenceError("invalid_filename", "SQLite filename must be a safe local path or :memory:.");
205
+ }
206
+ return value;
207
+ }
208
+ function isOptionsRecord(value) {
209
+ if (typeof value !== "object" || value === null || Array.isArray(value))
210
+ return false;
211
+ const prototype = Object.getPrototypeOf(value);
212
+ return prototype === null || prototype === Object.prototype;
213
+ }
214
+ function validateOptions(options) {
215
+ if (!isOptionsRecord(options)) {
216
+ throw new PersistenceError("invalid_options", "SQLite persistence options must be an object.");
217
+ }
218
+ const filename = validateFilename(options.filename);
219
+ const readonly = options.readonly;
220
+ if (readonly !== undefined && typeof readonly !== "boolean") {
221
+ throw new PersistenceError("invalid_options", "SQLite persistence readonly option must be boolean.");
222
+ }
223
+ return { filename, readonly: readonly ?? false };
224
+ }
225
+ function validateRecordInput(value, label) {
226
+ if (!isOptionsRecord(value)) {
227
+ throw new PersistenceError("invalid_record", `${label} must be an object.`);
228
+ }
229
+ return value;
230
+ }
231
+ function validateRecordString(value, label) {
232
+ if (typeof value !== "string" || value.trim().length === 0 || value.length > 1024 || hasControlChars(value)) {
233
+ throw new PersistenceError("invalid_record", `${label} must be a safe non-empty string.`);
234
+ }
235
+ return value;
236
+ }
237
+ function validateTimestamp(value, label) {
238
+ const raw = validateRecordString(value, label);
239
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(raw)) {
240
+ throw new PersistenceError("invalid_record", `${label} must be an ISO timestamp.`);
241
+ }
242
+ const normalized = new Date(raw).toISOString();
243
+ if (normalized !== raw) {
244
+ throw new PersistenceError("invalid_record", `${label} must be an ISO timestamp.`);
245
+ }
246
+ return raw;
247
+ }
248
+ function validateWebhookEventRecord(input) {
249
+ const record = validateRecordInput(input, "webhook event record");
250
+ return Object.freeze({
251
+ eventKey: validateRecordString(record.eventKey, "eventKey"),
252
+ eventHash: validateRecordString(record.eventHash, "eventHash"),
253
+ receivedAt: validateTimestamp(record.receivedAt, "receivedAt")
254
+ });
255
+ }
256
+ function validateServiceRequestLookup(input) {
257
+ const record = validateRecordInput(input, "service request lookup");
258
+ return Object.freeze({
259
+ idempotencyKey: validateRecordString(record.idempotencyKey, "idempotencyKey"),
260
+ requestHash: validateRecordString(record.requestHash, "requestHash")
261
+ });
262
+ }
263
+ function validateServiceRequestRecord(input) {
264
+ const record = validateRecordInput(input, "service request record");
265
+ const responseJson = validateRecordString(record.responseJson, "responseJson");
266
+ try {
267
+ JSON.parse(responseJson);
268
+ } catch (cause) {
269
+ throw new PersistenceError("invalid_record", "responseJson must be valid JSON.", { cause });
270
+ }
271
+ return Object.freeze({
272
+ idempotencyKey: validateRecordString(record.idempotencyKey, "idempotencyKey"),
273
+ requestHash: validateRecordString(record.requestHash, "requestHash"),
274
+ responseJson,
275
+ createdAt: validateTimestamp(record.createdAt, "createdAt")
276
+ });
277
+ }
278
+ function nowIso() {
279
+ return new Date().toISOString();
280
+ }
281
+ function migrationById(id) {
282
+ return MIGRATIONS.find((migration) => migration.id === id);
283
+ }
284
+ async function loadBunSqlite() {
285
+ try {
286
+ const specifier = "bun:sqlite";
287
+ return await import("bun:sqlite");
288
+ } catch (cause) {
289
+ throw new PersistenceError("migration_failed", "SQLite persistence requires Bun sqlite support.", { cause });
290
+ }
291
+ }
292
+ export async function createSqlitePersistence(options) {
293
+ const { filename, readonly } = validateOptions(options);
294
+ const sqlite = await loadBunSqlite();
295
+ try {
296
+ const database = new sqlite.Database(filename, { readonly, create: !readonly });
297
+ return new SqlitePersistenceStore(database);
298
+ } catch (cause) {
299
+ throw new PersistenceError("migration_failed", "SQLite database could not be opened.", { cause });
300
+ }
301
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@wats/persistence",
3
+ "version": "0.3.6",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./sqlite": {
15
+ "types": "./dist/sqlite.d.ts",
16
+ "import": "./dist/sqlite.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/Switchbord/wats.git",
30
+ "directory": "packages/persistence"
31
+ },
32
+ "homepage": "https://github.com/Switchbord/wats#readme",
33
+ "bugs": {
34
+ "url": "https://github.com/Switchbord/wats/issues"
35
+ },
36
+ "keywords": [
37
+ "whatsapp",
38
+ "whatsapp-cloud-api",
39
+ "sqlite",
40
+ "persistence",
41
+ "wats"
42
+ ]
43
+ }