| 1 | // Extensiones instaladas, en su PROPIA base IndexedDB (elffuss-code-ext): así |
| 2 | // db.js no sube de versión y otra pestaña abierta con la versión vieja no |
| 3 | // bloquea la actualización. Nada de OPFS: con ?test-opfs la raíz de OPFS ES el |
| 4 | // proyecto, y los ficheros de las extensiones aparecerían en el árbol y para |
| 5 | // el agente. |
| 6 | // |
| 7 | // ext id → registro (versión, sha256, licencia, activa, contribuciones…) |
| 8 | // files "id@versión/ruta" → contenido ya parseado (tema, gramática…) |
| 9 | // "id@versión/code/ruta" → bytes del código (nivel 2, js/ext2/host2.js) |
| 10 | // meta marcas internas |
| 11 | // |
| 12 | // La lista [{id, version, enabled, runs}] se refleja en kv «extensions» de la |
| 13 | // base principal, que es lo que ven el inventario y la copia del espacio de |
| 14 | // trabajo. |
| 15 | import * as maindb from '../db.js'; |
| 16 | |
| 17 | const NAME = 'elffuss-code-ext', VERSION = 1; |
| 18 | const MIRROR = 'extensions'; |
| 19 | let dbp = null; |
| 20 | |
| 21 | function open() { |
| 22 | dbp ??= new Promise((resolve, reject) => { |
| 23 | const req = indexedDB.open(NAME, VERSION); |
| 24 | req.onupgradeneeded = () => { |
| 25 | for (const s of ['ext', 'files', 'meta']) if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s); |
| 26 | }; |
| 27 | req.onsuccess = () => { |
| 28 | const db = req.result; |
| 29 | db.onversionchange = () => { db.close(); dbp = null; }; // no bloquear una versión futura |
| 30 | resolve(db); |
| 31 | }; |
| 32 | req.onerror = () => { dbp = null; reject(req.error); }; |
| 33 | req.onblocked = () => { dbp = null; reject(Object.assign(new Error('base de extensiones bloqueada por otra pestaña'), { code: 'blocked' })); }; |
| 34 | }); |
| 35 | return dbp; |
| 36 | } |
| 37 | const done = req => new Promise((res, rej) => { req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); }); |
| 38 | const txDone = tx => new Promise((res, rej) => { tx.oncomplete = () => res(); tx.onerror = () => rej(tx.error); tx.onabort = () => rej(tx.error || new Error('transacción abortada')); }); |
| 39 | |
| 40 | export const fileKey = (id, version, path) => `${id}@${version}/${path}`; |
| 41 | export const codeKey = (id, version, path) => `${id}@${version}/code/${path}`; |
| 42 | |
| 43 | export async function list() { |
| 44 | const db = await open(); |
| 45 | const recs = await done(db.transaction('ext').objectStore('ext').getAll()); |
| 46 | return recs.sort((a, b) => (a.installedAt || 0) - (b.installedAt || 0)); |
| 47 | } |
| 48 | export async function get(id) { return done((await open()).transaction('ext').objectStore('ext').get(id)); } |
| 49 | export async function getFile(key) { return done((await open()).transaction('files').objectStore('files').get(key)); } |
| 50 | |
| 51 | // Instala/reemplaza en UNA transacción: registro + ficheros nuevos, y fuera |
| 52 | // los de la versión anterior. |
| 53 | export async function put(rec, files) { |
| 54 | const db = await open(); |
| 55 | const tx = db.transaction(['ext', 'files'], 'readwrite'); |
| 56 | const prev = await done(tx.objectStore('ext').get(rec.id)); |
| 57 | if (prev && prev.version !== rec.version) tx.objectStore('files').delete(rango(`${prev.id}@${prev.version}/`)); |
| 58 | for (const [k, v] of files) tx.objectStore('files').put(v, k); |
| 59 | tx.objectStore('ext').put(rec, rec.id); |
| 60 | await txDone(tx); |
| 61 | await writeMirror(); |
| 62 | } |
| 63 | |
| 64 | const rango = prefijo => IDBKeyRange.bound(prefijo, prefijo + ''); |
| 65 | |
| 66 | export async function remove(id) { |
| 67 | const db = await open(); |
| 68 | const tx = db.transaction(['ext', 'files'], 'readwrite'); |
| 69 | tx.objectStore('files').delete(rango(`${id}@`)); |
| 70 | tx.objectStore('ext').delete(id); |
| 71 | await txDone(tx); |
| 72 | await writeMirror(); |
| 73 | } |
| 74 | |
| 75 | export async function getFiles(keys) { |
| 76 | const st = (await open()).transaction('files').objectStore('files'); |
| 77 | return Promise.all(keys.map(k => done(st.get(k)))); |
| 78 | } |
| 79 | |
| 80 | // Caché de cosas pequeñas de Open VSX (p. ej. lo que se sabe de un manifiesto |
| 81 | // por id@versión, para el filtro «Funciona en Code»). |
| 82 | export async function getMeta(key) { return done((await open()).transaction('meta').objectStore('meta').get('cache:' + key)); } |
| 83 | export async function setMeta(key, value) { |
| 84 | const db = await open(); |
| 85 | const tx = db.transaction('meta', 'readwrite'); |
| 86 | tx.objectStore('meta').put(value, 'cache:' + key); |
| 87 | await txDone(tx); |
| 88 | } |
| 89 | |
| 90 | // Cambia un registro en una transacción (`cambia(rec)` lo modifica). |
| 91 | export async function update(id, cambia, { mirror = true } = {}) { |
| 92 | const db = await open(); |
| 93 | const tx = db.transaction('ext', 'readwrite'); |
| 94 | const rec = await done(tx.objectStore('ext').get(id)); |
| 95 | if (!rec) throw new Error('no instalada: ' + id); |
| 96 | cambia(rec); |
| 97 | tx.objectStore('ext').put(rec, id); |
| 98 | await txDone(tx); |
| 99 | if (mirror) await writeMirror(); |
| 100 | return rec; |
| 101 | } |
| 102 | export const setEnabled = (id, enabled) => update(id, r => { r.enabled = !!enabled; }); |
| 103 | |
| 104 | async function writeMirror() { |
| 105 | const recs = await list(); |
| 106 | await maindb.set('kv', MIRROR, recs.map(r => ({ id: r.id, version: r.version, enabled: !!r.enabled, runs: !!r.runs }))); |
| 107 | const db = await open(); |
| 108 | const tx = db.transaction('meta', 'readwrite'); |
| 109 | tx.objectStore('meta').put(true, 'mirrored'); |
| 110 | await txDone(tx); |
| 111 | } |
| 112 | |
| 113 | // Al arrancar: la lista de kv «extensions» manda. Si alguien la borró (copia |
| 114 | // del espacio de trabajo → «borrar»), se borran también las extensiones; si |
| 115 | // nunca llegó a escribirse, se escribe ahora. Y fuera los ficheros huérfanos |
| 116 | // (de versiones viejas o de instalaciones a medias). |
| 117 | export async function reconcile() { |
| 118 | let espejo; |
| 119 | try { espejo = await maindb.get('kv', MIRROR); } catch { return; } // sin lectura fiable no se toca nada |
| 120 | const db = await open(); |
| 121 | const yaEscrito = await done(db.transaction('meta').objectStore('meta').get('mirrored')); |
| 122 | let recs = await list(); |
| 123 | if (Array.isArray(espejo)) { |
| 124 | const enLista = new Map(espejo.filter(e => e && e.id).map(e => [e.id, e])); |
| 125 | for (const r of recs) if (!enLista.has(r.id)) await remove(r.id); |
| 126 | } else if (espejo == null && yaEscrito) { |
| 127 | for (const r of recs) await remove(r.id); |
| 128 | } |
| 129 | recs = await list(); |
| 130 | const vivos = new Set(recs.map(r => `${r.id}@${r.version}/`)); |
| 131 | const tx = db.transaction('files', 'readwrite'); |
| 132 | const keys = await done(tx.objectStore('files').getAllKeys()); |
| 133 | let huerfanos = 0; |
| 134 | for (const k of keys) { |
| 135 | const i = String(k).indexOf('/'); |
| 136 | if (!vivos.has(String(k).slice(0, i + 1))) { tx.objectStore('files').delete(k); huerfanos++; } |
| 137 | } |
| 138 | await txDone(tx); |
| 139 | await writeMirror(); |
| 140 | return { huerfanos }; |
| 141 | } |