| 1 | // Caché persistente (IndexedDB) del análisis para el navegador, en tres capas: |
| 2 | // - 'files': entrada por fichero con clave `v|rel|size|mtime` → si el fichero |
| 3 | // no cambió, el re-escaneo reutiliza specs/defs/tokens sin releerlo. |
| 4 | // - 'snapshots': consolidado por commit de HEAD → sobrevive a checkouts y |
| 5 | // re-clones (donde cambian todos los mtime y la capa anterior falla). |
| 6 | // - 'handles': el FileSystemDirectoryHandle de la última carpeta, para poder |
| 7 | // reabrirla pidiendo el permiso de lectura nada más pulsar el botón. |
| 8 | const DB_NAME = 'vcc-analysis'; |
| 9 | const FILES = 'files'; |
| 10 | const SNAPSHOTS = 'snapshots'; |
| 11 | const HANDLES = 'handles'; |
| 12 | const MAX_ENTRIES = 400000; |
| 13 | const MAX_SNAPSHOTS = 4; |
| 14 | |
| 15 | function openDB() { |
| 16 | return new Promise((resolve, reject) => { |
| 17 | const req = indexedDB.open(DB_NAME, 2); |
| 18 | req.onupgradeneeded = () => { |
| 19 | const db = req.result; |
| 20 | if (!db.objectStoreNames.contains(FILES)) db.createObjectStore(FILES); |
| 21 | if (!db.objectStoreNames.contains(SNAPSHOTS)) db.createObjectStore(SNAPSHOTS); |
| 22 | if (!db.objectStoreNames.contains(HANDLES)) db.createObjectStore(HANDLES); |
| 23 | }; |
| 24 | req.onsuccess = () => resolve(req.result); |
| 25 | req.onerror = () => reject(req.error); |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | function get(store, key) { |
| 30 | return openDB().then(db => new Promise((resolve) => { |
| 31 | const req = db.transaction(store, 'readonly').objectStore(store).get(key); |
| 32 | req.onsuccess = () => resolve(req.result ?? null); |
| 33 | req.onerror = () => resolve(null); |
| 34 | })).catch(() => null); |
| 35 | } |
| 36 | |
| 37 | // carga toda la caché en memoria (una transacción es mucho más rápida que |
| 38 | // miles de lecturas individuales durante el escaneo) |
| 39 | export async function loadAnalysisCache() { |
| 40 | try { |
| 41 | const db = await openDB(); |
| 42 | return await new Promise((resolve) => { |
| 43 | const tx = db.transaction(FILES, 'readonly').objectStore(FILES); |
| 44 | const keysReq = tx.getAllKeys(); |
| 45 | const valsReq = tx.getAll(); |
| 46 | keysReq.onsuccess = () => { |
| 47 | valsReq.onsuccess = () => { |
| 48 | const map = new Map(); |
| 49 | keysReq.result.forEach((k, i) => map.set(k, valsReq.result[i])); |
| 50 | resolve(map); |
| 51 | }; |
| 52 | }; |
| 53 | keysReq.onerror = () => resolve(new Map()); |
| 54 | }); |
| 55 | } catch { |
| 56 | return new Map(); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // guarda entradas en bloque; se llama por lotes durante el análisis para que |
| 61 | // una ejecución interrumpida (memoria, cierre de pestaña) deje lo ya hecho |
| 62 | // persistido y la siguiente continúe desde ahí vía aciertos de caché |
| 63 | export async function saveAnalysisCache(newEntries) { |
| 64 | if (!newEntries.size) return; |
| 65 | try { |
| 66 | const db = await openDB(); |
| 67 | await new Promise((resolve, reject) => { |
| 68 | const tx = db.transaction(FILES, 'readwrite'); |
| 69 | const store = tx.objectStore(FILES); |
| 70 | let n = 0; |
| 71 | for (const [k, v] of newEntries) { |
| 72 | store.put(v, k); |
| 73 | if (++n >= MAX_ENTRIES) break; |
| 74 | } |
| 75 | tx.oncomplete = resolve; |
| 76 | tx.onerror = () => reject(tx.error); |
| 77 | }); |
| 78 | } catch { /* caché es solo una optimización */ } |
| 79 | } |
| 80 | |
| 81 | // ── snapshots por commit, en chunks (checkpoints) ────────────────────────── |
| 82 | // Cada checkpoint del análisis escribe un chunk pequeño bajo la clave |
| 83 | // `commit#seq` con valor { commit, when, files: { rel → { size, entry } } }. |
| 84 | // Escribir solo el delta evita el read-modify-write del snapshot completo en |
| 85 | // cada punto de control; al cargar se fusionan todos los chunks del commit. |
| 86 | |
| 87 | let chunkSeq = 0; |
| 88 | |
| 89 | function getAllSnapshotChunks() { |
| 90 | return openDB().then(db => new Promise((resolve) => { |
| 91 | const req = db.transaction(SNAPSHOTS, 'readonly').objectStore(SNAPSHOTS).getAll(); |
| 92 | req.onsuccess = () => resolve(req.result ?? []); |
| 93 | req.onerror = () => resolve([]); |
| 94 | })).catch(() => []); |
| 95 | } |
| 96 | |
| 97 | export async function loadSnapshot(commit) { |
| 98 | if (!commit) return null; |
| 99 | const chunks = (await getAllSnapshotChunks()).filter(s => s.commit === commit); |
| 100 | if (!chunks.length) return null; |
| 101 | chunks.sort((a, b) => a.when - b.when); |
| 102 | const files = {}; |
| 103 | for (const c of chunks) Object.assign(files, c.files); |
| 104 | return { commit, when: chunks[chunks.length - 1].when, files }; |
| 105 | } |
| 106 | |
| 107 | export async function latestSnapshot(excludeCommit) { |
| 108 | const all = (await getAllSnapshotChunks()).filter(s => s.commit !== excludeCommit); |
| 109 | if (!all.length) return null; |
| 110 | const best = all.reduce((a, b) => (b.when > a.when ? b : a)); |
| 111 | return loadSnapshot(best.commit); |
| 112 | } |
| 113 | |
| 114 | // checkpoint: persiste el delta analizado desde el último punto de control |
| 115 | export async function saveSnapshotChunk(commit, filesMap) { |
| 116 | if (!commit || !Object.keys(filesMap).length) return; |
| 117 | try { |
| 118 | const db = await openDB(); |
| 119 | await new Promise((resolve, reject) => { |
| 120 | const tx = db.transaction(SNAPSHOTS, 'readwrite'); |
| 121 | tx.objectStore(SNAPSHOTS).put( |
| 122 | { commit, when: Date.now(), files: filesMap }, |
| 123 | `${commit}#${Date.now()}-${chunkSeq++}`, |
| 124 | ); |
| 125 | tx.oncomplete = resolve; |
| 126 | tx.onerror = () => reject(tx.error); |
| 127 | }); |
| 128 | } catch { /* caché es solo una optimización */ } |
| 129 | } |
| 130 | |
| 131 | // compacta los chunks de un commit en uno y poda los commits más antiguos; |
| 132 | // se llama una vez al terminar el análisis, no en cada checkpoint |
| 133 | export async function pruneSnapshots(keepCommit) { |
| 134 | try { |
| 135 | const db = await openDB(); |
| 136 | const merged = keepCommit ? await loadSnapshot(keepCommit) : null; |
| 137 | await new Promise((resolve, reject) => { |
| 138 | const tx = db.transaction(SNAPSHOTS, 'readwrite'); |
| 139 | const store = tx.objectStore(SNAPSHOTS); |
| 140 | const keysReq = store.getAllKeys(); |
| 141 | const valsReq = store.getAll(); |
| 142 | keysReq.onsuccess = () => valsReq.onsuccess = () => { |
| 143 | const keys = keysReq.result ?? [], vals = valsReq.result ?? []; |
| 144 | // último `when` por commit → conservar los MAX_SNAPSHOTS más recientes |
| 145 | const newest = new Map(); |
| 146 | vals.forEach(v => newest.set(v.commit, Math.max(newest.get(v.commit) ?? 0, v.when))); |
| 147 | const keep = new Set([...newest.entries()] |
| 148 | .sort((a, b) => b[1] - a[1]).slice(0, MAX_SNAPSHOTS).map(([c]) => c)); |
| 149 | keys.forEach((k, i) => { |
| 150 | const c = vals[i].commit; |
| 151 | if (!keep.has(c) || (c === keepCommit && merged)) store.delete(k); |
| 152 | }); |
| 153 | if (merged && keep.has(keepCommit)) { |
| 154 | store.put(merged, `${keepCommit}#${Date.now()}-${chunkSeq++}`); |
| 155 | } |
| 156 | }; |
| 157 | tx.oncomplete = resolve; |
| 158 | tx.onerror = () => reject(tx.error); |
| 159 | }); |
| 160 | } catch { /* caché es solo una optimización */ } |
| 161 | } |
| 162 | |
| 163 | // ── handle persistente de la última carpeta ──────────────────────────────── |
| 164 | |
| 165 | export function loadSavedHandle() { |
| 166 | return get(HANDLES, 'last'); |
| 167 | } |
| 168 | |
| 169 | export async function saveHandle(handle) { |
| 170 | try { |
| 171 | const db = await openDB(); |
| 172 | await new Promise((resolve, reject) => { |
| 173 | const tx = db.transaction(HANDLES, 'readwrite'); |
| 174 | tx.objectStore(HANDLES).put(handle, 'last'); |
| 175 | tx.oncomplete = resolve; |
| 176 | tx.onerror = () => reject(tx.error); |
| 177 | }); |
| 178 | } catch { /* opcional */ } |
| 179 | } |