| 1 | // IndexedDB mínima: stores clave→valor. |
| 2 | const NAME = 'elffuss-code', VERSION = 2; |
| 3 | const STORES = ['kv', 'apps', 'tasks', 'vault', 'fs', 'memory']; |
| 4 | let dbPromise = null; |
| 5 | |
| 6 | function open() { |
| 7 | if (dbPromise) return dbPromise; |
| 8 | dbPromise = new Promise((resolve, reject) => { |
| 9 | const req = indexedDB.open(NAME, VERSION); |
| 10 | req.onupgradeneeded = () => { |
| 11 | for (const s of STORES) |
| 12 | if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s); |
| 13 | }; |
| 14 | req.onsuccess = () => resolve(req.result); |
| 15 | req.onerror = () => reject(req.error); |
| 16 | }); |
| 17 | return dbPromise; |
| 18 | } |
| 19 | |
| 20 | function tx(store, mode, fn) { |
| 21 | return open().then(db => new Promise((resolve, reject) => { |
| 22 | const req = fn(db.transaction(store, mode).objectStore(store)); |
| 23 | req.onsuccess = () => resolve(req.result); |
| 24 | req.onerror = () => reject(req.error); |
| 25 | })); |
| 26 | } |
| 27 | |
| 28 | // Quien necesite saber que algo se escribió (el espacio de trabajo, que copia |
| 29 | // conversaciones y skills a tu disco con «Guardar solo») se apunta aquí. Un |
| 30 | // fallo de quien escucha nunca rompe la escritura. |
| 31 | const oyentes = []; |
| 32 | export function onWrite(fn) { |
| 33 | oyentes.push(fn); |
| 34 | return () => { const i = oyentes.indexOf(fn); if (i >= 0) oyentes.splice(i, 1); }; |
| 35 | } |
| 36 | const avisa = (store, key) => (r) => { for (const f of oyentes) { try { f(store, key); } catch { /* */ } } return r; }; |
| 37 | |
| 38 | export const get = (store, key) => tx(store, 'readonly', s => s.get(key)); |
| 39 | export const set = (store, key, val) => tx(store, 'readwrite', s => s.put(val, key)).then(avisa(store, key)); |
| 40 | export const del = (store, key) => tx(store, 'readwrite', s => s.delete(key)).then(avisa(store, key)); |
| 41 | export const keys = (store) => tx(store, 'readonly', s => s.getAllKeys()); |
| 42 | export const all = (store) => tx(store, 'readonly', s => s.getAll()); |