import { createHash } from "node:crypto"; import { openSiteDatabase } from "./site-database"; function openImages() { const db = openSiteDatabase(); try { db.exec(`CREATE TABLE IF NOT EXISTS document_images ( id TEXT PRIMARY KEY, bytes BLOB NOT NULL )`); return db; } catch (error) { db.close(); throw error; } } export function saveDocumentImage(bytes: Buffer) { const id = createHash("sha256").update(bytes).digest("hex"); const db = openImages(); try { db.prepare("INSERT INTO document_images (id, bytes) VALUES (?, ?) ON CONFLICT(id) DO NOTHING").run(id, bytes); return id; } finally { db.close(); } } export function readDocumentImage(id: string) { const db = openImages(); try { const row = db.prepare("SELECT bytes FROM document_images WHERE id = ?").get(id) as | { bytes: Uint8Array } | undefined; return row ? Buffer.from(row.bytes) : undefined; } finally { db.close(); } }