src/state.js
Commit 01f96e7. All files · Download the tarball.
// State lives in one D1 row (a small JSON document), so each check costs one read and at most one write.
import { STATE_VERSION } from "./detect.js";
const SCHEMA = "CREATE TABLE IF NOT EXISTS tripwire_state (id INTEGER PRIMARY KEY CHECK (id = 1), v TEXT NOT NULL, updated_at TEXT NOT NULL)";
export async function loadState(db) {
await db.prepare(SCHEMA).run();
const row = await db.prepare("SELECT v FROM tripwire_state WHERE id = 1").first();
if (!row || !row.v) return null;
try {
const s = JSON.parse(row.v);
return s && s.v === STATE_VERSION ? s : null;
} catch { return null; }
}
export async function saveState(db, state, now) {
await db.prepare("INSERT INTO tripwire_state (id, v, updated_at) VALUES (1, ?1, ?2) ON CONFLICT(id) DO UPDATE SET v = excluded.v, updated_at = excluded.updated_at")
.bind(JSON.stringify(state), new Date(now).toISOString()).run();
}