// Local-first storage: one IndexedDB database holding the Loro doc snapshots, // their incremental updates, content-addressed file blobs, sync cursors and // small metadata. Works identically in browsers and in the Tauri webviews. const DB_NAME = 'synapse'; const DOCS = 'docs'; const UPDATES = 'doc_updates'; const BLOBS = 'blobs'; const SYNC = 'sync_state'; const META = 'meta'; export interface StoredDoc { docId: string; snapshot: Uint8Array; savedAt: number; } export interface StoredUpdate { // Auto-incremented primary key; absent until stored. seq?: number; docId: string; bytes: Uint8Array; savedAt: number; } export interface StoredBlob { hash: string; // Raw bytes rather than a Blob: Uint8Array survives structured cloning in // every implementation (Blob round-trips break in test fakes). bytes: Uint8Array; mime: string; size: number; } export interface SyncState { // One row per transport + doc, e.g. "http:workspace". key: string; cursor?: number; lastPushedVV?: Uint8Array; lastSyncAt?: number; } let dbPromise: Promise | null = null; function openDb(): Promise { dbPromise ??= new Promise((resolve, reject) => { const req = indexedDB.open(DB_NAME, 1); req.onupgradeneeded = () => { const db = req.result; db.createObjectStore(DOCS, { keyPath: 'docId' }); const updates = db.createObjectStore(UPDATES, { keyPath: 'seq', autoIncrement: true }); updates.createIndex('docId', 'docId'); db.createObjectStore(BLOBS, { keyPath: 'hash' }); db.createObjectStore(SYNC, { keyPath: 'key' }); db.createObjectStore(META, { keyPath: 'key' }); }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); return dbPromise; } function asPromise(req: IDBRequest): Promise { return new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } async function inStore( store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest, ): Promise { const db = await openDb(); return asPromise(fn(db.transaction(store, mode).objectStore(store))); } export function getDoc(docId: string): Promise { return inStore(DOCS, 'readonly', (s) => s.get(docId) as IDBRequest); } export function appendUpdate(update: StoredUpdate): Promise { return inStore(UPDATES, 'readwrite', (s) => s.add(update) as IDBRequest); } export function updatesFor(docId: string): Promise { return inStore(UPDATES, 'readonly', (s) => s.index('docId').getAll(docId)) as Promise< StoredUpdate[] >; } // Compaction: replace the stored snapshot and drop the update rows it now // covers (seq <= upToSeq), atomically. export async function replaceDoc(doc: StoredDoc, upToSeq: number): Promise { const db = await openDb(); return new Promise((resolve, reject) => { const t = db.transaction([DOCS, UPDATES], 'readwrite'); t.objectStore(DOCS).put(doc); const cursorReq = t.objectStore(UPDATES).index('docId').openCursor(doc.docId); cursorReq.onsuccess = () => { const cursor = cursorReq.result; if (!cursor) return; const row = cursor.value as StoredUpdate; if ((row.seq ?? 0) <= upToSeq) cursor.delete(); cursor.continue(); }; t.oncomplete = () => resolve(); t.onerror = () => reject(t.error); }); } export function getBlob(hash: string): Promise { return inStore(BLOBS, 'readonly', (s) => s.get(hash) as IDBRequest); } export function putBlob(blob: StoredBlob): Promise { return inStore(BLOBS, 'readwrite', (s) => s.put(blob)); } export function getSyncState(key: string): Promise { return inStore(SYNC, 'readonly', (s) => s.get(key) as IDBRequest); } export function putSyncState(state: SyncState): Promise { return inStore(SYNC, 'readwrite', (s) => s.put(state)); } export async function getMeta(key: string): Promise { const row = await inStore( META, 'readonly', (s) => s.get(key) as IDBRequest<{ key: string; value: T } | undefined>, ); return row?.value; } export function setMeta(key: string, value: T): Promise { return inStore(META, 'readwrite', (s) => s.put({ key, value })); } // Every doc this database knows about: compacted snapshots plus docs that so // far only have update rows. Used by the file pack export. export async function listDocIds(): Promise { const ids = new Set(); const snapshotKeys = await inStore( DOCS, 'readonly', (s) => s.getAllKeys() as IDBRequest, ); for (const key of snapshotKeys) ids.add(String(key)); const updates = await inStore( UPDATES, 'readonly', (s) => s.getAll() as IDBRequest, ); for (const row of updates) ids.add(row.docId); return [...ids]; } export async function listBlobHashes(): Promise { const keys = await inStore(BLOBS, 'readonly', (s) => s.getAllKeys() as IDBRequest); return keys.map(String); } // Wipes every data store (docs, updates, blobs, sync cursors, meta) in one // transaction, keeping the schema. Used to reset the demo workspace before // re-importing a newer demo pack. export async function clearAll(): Promise { const db = await openDb(); await new Promise((resolve, reject) => { const tx = db.transaction([DOCS, UPDATES, BLOBS, SYNC, META], 'readwrite'); tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); for (const store of [DOCS, UPDATES, BLOBS, SYNC, META]) tx.objectStore(store).clear(); }); } // Tests swap the global indexedDB (fake-indexeddb) between cases; the cached // connection has to be dropped with it. export function resetDbForTests(): void { dbPromise = null; }