Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : src/lib/client/offline.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/note-spboucher-ai11 * Project Website : https://note.spboucher.ai12 * Created : 2026-11-1713 * Last Modified : 2026-11-1914 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243"use client";44/**45 * file: src/lib/client/offline.ts46 * description: device-local store (IndexedDB "note-local"). Version 2 (SP Note Next Generation, offline-first):47 * drafts — the unsaved state of a page being edited (title/content + the server version it was based on);48 * outbox — quick captures not yet confirmed, each with its idempotency key;49 * pages — the local replica: every page of the workspace, content included, as GET /api/sync delivers them;50 * tasks — the replica of the tasks table (GET /api/sync?kinds=task);51 * attachments — attachment metadata (never the files themselves);52 * journal — ordered mutation journal (create / rename / move / pin / archive / trash / tags / tasks / queued uploads);53 * blobs — images added offline, waiting to be uploaded (bounded, see IMAGE_MAX / BLOBS_MAX in journal-core.ts);54 * meta — sync cursor, last sync time, conflicts, integrity report.55 * Retention: a queue entry is deleted as soon as the server confirms it; drafts and captures older than 30 days are purged at startup;56 * EVERYTHING is erased by "Lock this device" / sign-out everywhere (wipeLocalData). It is NOT encrypted: a key readable by the same57 * JavaScript would add nothing against XSS or someone holding the unlocked device, so the protection is the device lock + the wipe.58 * A session that merely expires does not erase drafts (that would lose text); they are replayed after the next sign-in.59 * Nothing private is ever put in the HTTP cache (see public/sw.js): this database is the only offline store.60 * author: Simon-Pierre Boucher — contact@spboucher.ai61 */62const DB = "note-local", VERSION = 2, RETENTION_MS = 30 * 86_400_000;63export interface Draft { pageId: string; baseVersion: number; patch: Record<string, unknown>; updatedAt: number }64export interface OutboxItem { id: string; kind: "capture"; body: { kind: string; text?: string; url?: string }; files?: File[]; uploadedIds?: string[]; createdAt: number; attempts: number; lastError?: string }65export type StoreName = "drafts" | "outbox" | "pages" | "tasks" | "attachments" | "journal" | "blobs" | "meta";66export const STORES: StoreName[] = ["drafts", "outbox", "pages", "tasks", "attachments", "journal", "blobs", "meta"];6768let dbp: Promise<IDBDatabase> | null = null;69function open(): Promise<IDBDatabase> {70 if (typeof indexedDB === "undefined") return Promise.reject(new Error("IndexedDB unavailable"));71 if (!dbp) dbp = new Promise((resolve, reject) => {72 const r = indexedDB.open(DB, VERSION);73 r.onupgradeneeded = () => {74 const d = r.result; const has = (n: string) => d.objectStoreNames.contains(n);75 if (!has("drafts")) d.createObjectStore("drafts", { keyPath: "pageId" });76 if (!has("outbox")) d.createObjectStore("outbox", { keyPath: "id" });77 if (!has("pages")) d.createObjectStore("pages", { keyPath: "id" });78 if (!has("tasks")) d.createObjectStore("tasks", { keyPath: "id" });79 if (!has("attachments")) d.createObjectStore("attachments", { keyPath: "id" });80 if (!has("journal")) d.createObjectStore("journal", { keyPath: "seq", autoIncrement: true });81 if (!has("blobs")) d.createObjectStore("blobs", { keyPath: "id" });82 if (!has("meta")) d.createObjectStore("meta", { keyPath: "k" });83 };84 r.onsuccess = () => { const d = r.result; d.onversionchange = () => { d.close(); dbp = null; }; resolve(d); };85 r.onerror = () => { dbp = null; reject(r.error); }; r.onblocked = () => { dbp = null; reject(new Error("blocked")); };86 });87 return dbp;88}89function tx<T>(store: StoreName, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T> | void): Promise<T | undefined> {90 return open().then((d) => new Promise<T | undefined>((resolve, reject) => { const t = d.transaction(store, mode); const req = fn(t.objectStore(store)); t.oncomplete = () => resolve(req ? (req as IDBRequest<T>).result : undefined); t.onerror = () => reject(t.error); t.onabort = () => reject(t.error); }));91}92const notify = () => { if (typeof window !== "undefined") window.dispatchEvent(new CustomEvent("note:local-changed")); };9394// ── generic helpers used by the replica and the journal (they reject when IndexedDB is unavailable; callers decide) ──95export const idbGet = <T>(store: StoreName, key: IDBValidKey) => tx<T>(store, "readonly", (s) => s.get(key));96export const idbAll = <T>(store: StoreName) => tx<T[]>(store, "readonly", (s) => s.getAll()).then((r) => r ?? []);97export const idbCount = (store: StoreName) => tx<number>(store, "readonly", (s) => s.count()).then((r) => r ?? 0);98export const idbPut = <T>(store: StoreName, value: T) => tx<IDBValidKey>(store, "readwrite", (s) => s.put(value));99export const idbDelete = (store: StoreName, key: IDBValidKey) => tx(store, "readwrite", (s) => { s.delete(key); });100/** Several writes in ONE transaction (all or nothing): rows to put, keys to delete. */101export const idbBatch = (store: StoreName, puts: unknown[], deletes: IDBValidKey[] = []) => tx(store, "readwrite", (s) => { for (const v of puts) s.put(v); for (const k of deletes) s.delete(k); });102export const idbClear = (store: StoreName) => tx(store, "readwrite", (s) => { s.clear(); });103export const getMeta = <T>(k: string) => idbGet<{ k: string; v: T }>("meta", k).then((r) => r?.v).catch(() => undefined);104export const setMeta = (k: string, v: unknown) => idbPut("meta", { k, v }).then(() => {}).catch(() => {});105export const deleteMeta = (k: string) => idbDelete("meta", k).catch(() => {});106107export const getDraft = (pageId: string) => tx<Draft>("drafts", "readonly", (s) => s.get(pageId)).catch(() => undefined);108export const putDraft = (d: Draft) => tx("drafts", "readwrite", (s) => s.put(d)).then(notify).catch(() => { /* private mode / quota: the in-memory copy still exists */ });109export const deleteDraft = (pageId: string) => tx("drafts", "readwrite", (s) => s.delete(pageId)).then(notify).catch(() => {});110export const listDrafts = () => tx<Draft[]>("drafts", "readonly", (s) => s.getAll()).then((r) => r ?? []).catch(() => [] as Draft[]);111export const listOutbox = () => tx<OutboxItem[]>("outbox", "readonly", (s) => s.getAll()).then((r) => (r ?? []).sort((a, b) => a.createdAt - b.createdAt)).catch(() => [] as OutboxItem[]);112export const putOutbox = (i: OutboxItem) => tx("outbox", "readwrite", (s) => s.put(i)).then(notify);113export const deleteOutbox = (id: string) => tx("outbox", "readwrite", (s) => s.delete(id)).then(notify).catch(() => {});114115/** Startup hygiene: drop anything older than the retention period. (The replica is not aged out: it is refreshed by every sync.) */116export async function purgeExpired() {117 const now = Date.now();118 for (const d of await listDrafts()) if (now - d.updatedAt > RETENTION_MS) await deleteDraft(d.pageId);119 for (const o of await listOutbox()) if (now - o.createdAt > RETENTION_MS) await deleteOutbox(o.id);120}121/** Lock / sign-out: erase every private byte this app left on the device (replica, journal, queued images, drafts, outbox, legacy localStorage copies, runtime caches). */122export async function wipeLocalData() {123 try { const d = await open(); const names = STORES.filter((n) => d.objectStoreNames.contains(n)); await new Promise<void>((res) => { const t = d.transaction(names, "readwrite"); for (const n of names) t.objectStore(n).clear(); t.oncomplete = () => res(); t.onerror = () => res(); t.onabort = () => res(); }); } catch { /* nothing stored */ }124 try { for (const k of Object.keys(localStorage)) if (k.startsWith("note-pending-") || k.startsWith("note-draft-") || k.startsWith("note-search") || k === "note-recent-searches" || k === "note-sync-state") localStorage.removeItem(k); } catch { /* storage disabled */ }125 try { sessionStorage.clear(); } catch { /* ignore */ }126 try { if (typeof caches !== "undefined") for (const k of await caches.keys()) if (k.startsWith("note-rt-")) await caches.delete(k); } catch { /* ignore */ }127 notify(); if (typeof window !== "undefined") window.dispatchEvent(new CustomEvent("note:journal-changed"));128}129