Elffuss BraidHub

kikocis/VibeCodeViewer public

main · 12.0 KiBRawPermalink
1// Escáner en navegador con la File System Access API (Chrome/Edge).
2// Produce el mismo formato compacto que scan.mjs:
3// dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes, ignorado?]
4//
5// El escaneo del árbol es completo y sin límite; el análisis de contenidos
6// (modo Blast) se devuelve como `runAnalysis`, una pasada perezosa por lotes
7// que se ejecuta con la ciudad ya cargada, prioriza los ficheros clave y
8// persiste cada lote, de modo que una ejecución interrumpida continúa donde
9// se quedó.
10import { IgnoreStack, IGNORE_FILES } from './ignore.js';
11import { isCodeownersFile, isPackageMeta, parseCodeowners, parsePackageMeta } from './ownership.js';
12import { parseGitIndex, gitStatusOf, readHeadCommit } from './gitIndex.js';
13import { isAnalyzable, extractRefs, resolveAll } from './codeLinks.js';
14import { stripCommentsAndStrings, extractDefs, extractTokens, buildSymbolLinks, isIndexable, INDEX_VERSION } from './codeIndex.js';
15import {
16 loadAnalysisCache, saveAnalysisCache,
17 loadSnapshot, latestSnapshot, saveSnapshotChunk, pruneSnapshots,
18 loadSavedHandle, saveHandle,
19} from './analysisCache.js';
20import { priorityScore } from './filePriority.js';
21import { t } from './i18n.js';
22
23const SKIP = new Set(['.git', '.hg', '.svn', '.cache', '__pycache__', 'node_modules', '.DS_Store']);
24// presupuesto del análisis de código (modo Blast): solo la lectura de
25// contenidos tiene tope, y se gasta por orden de prioridad
26const ANALYZE_MAX_FILES = 20000;
27const ANALYZE_MAX_BYTES = 48 * 1024 * 1024;
28// tamaño de lote: tras cada lote se escribe un checkpoint (caché de ficheros
29// + chunk de snapshot del commit), de modo que un análisis interrumpido
30// continúa desde el último punto de control
31const BATCH_FILES = 1500;
32const BATCH_BYTES = 8 * 1024 * 1024;
33// el refresco de enlaces (resolveAll + buildSymbolLinks sobre lo acumulado)
34// es caro y síncrono: se hace cada REFRESH_FILES analizados, no por lote
35const REFRESH_FILES = 6000;
36// cesión periódica del hilo dentro del lote para no congelar el render
37const YIELD_EVERY = 100;
38
39export function canPickFolder() {
40 return typeof window.showDirectoryPicker === 'function';
41}
42
43// pide el permiso de lectura dentro del gesto de usuario: en carpetas grandes
44// el primer acceso diferido retrasaba el prompt varios segundos
45async function ensureReadPermission(handle) {
46 if (await handle.queryPermission?.({ mode: 'read' }) === 'granted') return true;
47 return (await handle.requestPermission?.({ mode: 'read' })) === 'granted';
48}
49
50export async function pickAndScanFolder(onProgress) {
51 const handle = await window.showDirectoryPicker();
52 if (!await ensureReadPermission(handle)) throw Object.assign(new Error('permiso denegado'), { name: 'AbortError' });
53 saveHandle(handle); // para poder reabrir sin picker la próxima vez
54 return scanHandle(handle, onProgress);
55}
56
57// nombre de la última carpeta abierta (o null), para el botón "Reabrir"
58export async function savedFolderName() {
59 const h = await loadSavedHandle();
60 return h?.name ?? null;
61}
62
63export async function reopenLastFolder(onProgress) {
64 const handle = await loadSavedHandle();
65 if (!handle) return null;
66 if (!await ensureReadPermission(handle)) return null;
67 return scanHandle(handle, onProgress);
68}
69
70async function scanHandle(handle, onProgress) {
71 let count = 0;
72 const stack = new IgnoreStack();
73 const ownerRules = [];
74 const refsMap = {}, fileRels = [], dirRels = [];
75 const defsMap = {}, tokensMap = {};
76 // candidatos a análisis: se recogen durante el paseo y se leen después,
77 // por lotes y ordenados por prioridad (ver filePriority.js)
78 const candidates = [];
79 // rel → { size, entry } pendiente de consolidar en el snapshot del commit;
80 // se vacía en cada checkpoint (cada chunk escribe solo el delta)
81 let pendingUsed = {};
82 // la caché se carga en paralelo con el índice git y el commit de HEAD
83 const cachePromise = loadAnalysisCache();
84 const newCacheEntries = new Map();
85 let cacheHits = 0, snapHits = 0;
86
87 // estado git aproximado: parsea .git/index (sin binario git en el navegador)
88 let gitIndex = null, headCommit = null;
89 try {
90 const gh = await handle.getDirectoryHandle('.git');
91 const fh = await gh.getFileHandle('index');
92 gitIndex = parseGitIndex(await (await fh.getFile()).arrayBuffer());
93 headCommit = await readHeadCommit(gh);
94 } catch { /* sin .git */ }
95 const gitMap = gitIndex ? {} : null;
96
97 // capas de reutilización: caché por mtime + snapshots por commit. El
98 // snapshot del commit actual vale tal cual (aunque el mtime haya cambiado
99 // por un checkout o re-clone); el de otro commit solo para ficheros
100 // trackeados cuyo tamaño coincide con el índice git.
101 const analysisCache = await cachePromise;
102 const snap = headCommit ? await loadSnapshot(headCommit) : null;
103 const donor = gitIndex ? await latestSnapshot(headCommit) : null;
104
105 function applyEntry(rel, size, entry, consolidate = true) {
106 if (entry.specs?.length) refsMap[rel] = entry.specs;
107 if (entry.defs?.length) defsMap[rel] = entry.defs;
108 if (entry.tokens?.length) tokensMap[rel] = entry.tokens;
109 // lo que ya vive en el snapshot del commit actual no se reescribe
110 if (consolidate) pendingUsed[rel] = { size, entry };
111 }
112
113 function snapshotEntry(rel, size) {
114 const s = snap?.files[rel];
115 if (s && s.size === size) return { entry: s.entry, fromCurrent: true };
116 const d = donor?.files[rel];
117 if (d && d.size === size && gitIndex?.get(rel)?.size === size) {
118 return { entry: d.entry, fromCurrent: false };
119 }
120 return null;
121 }
122
123 async function walk(h, rel, forced) {
124 const dirs = [], files = [];
125 for await (const e of h.values()) {
126 (e.kind === 'directory' ? dirs : files).push(e);
127 }
128 dirs.sort((a, b) => a.name.localeCompare(b.name));
129 files.sort((a, b) => a.name.localeCompare(b.name));
130
131 let pushed = 0;
132 for (const f of files) {
133 const isIgn = IGNORE_FILES.includes(f.name);
134 const isOwn = !rel.includes('.git') && (isCodeownersFile(f.name) || isPackageMeta(f.name));
135 if (!isIgn && !isOwn) continue;
136 try {
137 const txt = await (await f.getFile()).text();
138 if (isIgn) { stack.push(rel, txt.split('\n')); pushed++; }
139 if (isOwn) {
140 if (isCodeownersFile(f.name)) ownerRules.push(...parseCodeowners(txt));
141 else {
142 const rule = parsePackageMeta(txt, rel);
143 if (rule) ownerRules.push(rule);
144 }
145 }
146 } catch { /* ignorar */ }
147 }
148
149 const outFiles = [], outDirs = [];
150 for (const f of files) {
151 const childRel = rel ? `${rel}/${f.name}` : f.name;
152 let file = null, size = 0;
153 try { file = await f.getFile(); size = file.size; } catch { /* ignorar */ }
154 const ign = forced || stack.ignored(childRel, false);
155 outFiles.push(ign ? [f.name, size, 1] : [f.name, size]);
156 fileRels.push(childRel);
157 count++;
158 if (count % 200 === 0) onProgress?.(t('progress.files', { count }));
159 if (!file || childRel.startsWith('.git/')) continue;
160 // estado git aproximado (limpio → sin entrada)
161 if (gitMap && !ign) {
162 const st = gitStatusOf(gitIndex, childRel, size, file.lastModified);
163 if (st) gitMap[childRel] = [st, 0, 0];
164 }
165 // relaciones de código + índice de símbolos (con caché y presupuesto)
166 const wantRefs = isAnalyzable(f.name, size);
167 const wantIndex = isIndexable(f.name, size);
168 if (wantRefs || wantIndex) {
169 const key = `v${INDEX_VERSION}|${childRel}|${size}|${file.lastModified}`;
170 const hit = analysisCache.get(key);
171 const se = hit ? { entry: hit, fromCurrent: false } : snapshotEntry(childRel, size);
172 if (se) {
173 hit ? cacheHits++ : snapHits++;
174 // lo recuperado del snapshot se reescribe con la clave mtime actual
175 // para que el próximo escaneo acierte por la vía rápida
176 newCacheEntries.set(key, se.entry);
177 applyEntry(childRel, size, se.entry, !se.fromCurrent);
178 } else {
179 candidates.push({
180 file, key, rel: childRel, name: f.name, size, wantRefs, wantIndex,
181 score: priorityScore(childRel, f.name, size),
182 });
183 }
184 }
185 }
186 for (const d of dirs) {
187 if (SKIP.has(d.name)) continue;
188 const childRel = rel ? `${rel}/${d.name}` : d.name;
189 if (childRel === '.git/objects') continue; // ruido binario sin interés
190 const ign = forced || stack.ignored(childRel, true);
191 dirRels.push(childRel);
192 outDirs.push(await walk(d, childRel, ign));
193 }
194 while (pushed--) stack.pop();
195 return [h.name, outDirs, outFiles];
196 }
197
198 const tree = await walk(handle, '', false);
199 // lo recuperado de caché/snapshot se persiste ya: el primer meta queda
200 // consolidado aunque el análisis perezoso no llegue a ejecutarse
201 await saveAnalysisCache(newCacheEntries);
202 newCacheEntries.clear();
203 // la caché en memoria ya no se consulta más: liberarla antes del análisis
204 // (en repos grandes puede ocupar cientos de MB)
205 analysisCache.clear();
206 console.info(`[fsScan] ${count} ficheros · caché: ${cacheHits} hits, snapshot: ${snapHits} · pendientes de análisis: ${candidates.length}`);
207
208 const buildMeta = () => ({
209 links: resolveAll(refsMap, fileRels, dirRels),
210 codeIndex: { version: INDEX_VERSION, defs: defsMap, symLinks: buildSymbolLinks(defsMap, tokensMap) },
211 });
212
213 // ── análisis perezoso por lotes (se lanza con la ciudad ya cargada) ──────
214 candidates.sort((a, b) => b.score - a.score);
215 const total = Math.min(candidates.length, ANALYZE_MAX_FILES);
216
217 async function runAnalysis({ onBatch, onProgress: onTick, isCancelled } = {}) {
218 let analyzed = 0, analyzedBytes = 0, batchBytes = 0;
219 let checkpoints = 0, lastRefresh = 0;
220
221 // checkpoint: persiste la caché del lote y el chunk de snapshot (delta);
222 // si la pestaña muere aquí en adelante, la próxima ejecución parte de esto
223 async function checkpoint() {
224 await saveAnalysisCache(newCacheEntries);
225 newCacheEntries.clear();
226 if (headCommit) await saveSnapshotChunk(headCommit, pendingUsed);
227 pendingUsed = {};
228 batchBytes = 0;
229 checkpoints++;
230 onTick?.(t('progress.analysisCheckpoint', { analyzed, total, checkpoints }));
231 }
232
233 for (const c of candidates) {
234 if (analyzed >= ANALYZE_MAX_FILES || analyzedBytes >= ANALYZE_MAX_BYTES) break;
235 if (isCancelled?.()) break;
236 try {
237 analyzed++;
238 analyzedBytes += c.size;
239 batchBytes += c.size;
240 const text = await c.file.text();
241 const entry = {};
242 if (c.wantRefs) {
243 const specs = extractRefs(c.name, text);
244 if (specs.length) entry.specs = specs;
245 }
246 if (c.wantIndex) {
247 const clean = stripCommentsAndStrings(text, c.name);
248 const defs = extractDefs(c.name, clean);
249 const tokens = [...extractTokens(clean)];
250 if (defs.length) entry.defs = defs;
251 if (tokens.length) entry.tokens = tokens;
252 }
253 applyEntry(c.rel, c.size, entry);
254 newCacheEntries.set(c.key, entry);
255 } catch { /* ignorar */ }
256 // ceder el hilo con regularidad: el render no se congela dentro del lote
257 if (analyzed % YIELD_EVERY === 0) await new Promise(r => setTimeout(r, 0));
258 if (newCacheEntries.size >= BATCH_FILES || batchBytes >= BATCH_BYTES) {
259 await checkpoint();
260 // el refresco de enlaces es lo caro: solo cada REFRESH_FILES, no por lote
261 if (analyzed - lastRefresh >= REFRESH_FILES) {
262 lastRefresh = analyzed;
263 onBatch?.(buildMeta());
264 await new Promise(r => setTimeout(r, 0));
265 }
266 }
267 }
268 await checkpoint();
269 if (headCommit) await pruneSnapshots(headCommit);
270 if (analyzed) onBatch?.(buildMeta());
271 console.info(`[fsScan] análisis perezoso: ${analyzed}/${total} ficheros · ${checkpoints} checkpoints`);
272 return { analyzed, total };
273 }
274
275 return {
276 tree,
277 meta: {
278 git: gitMap, // aproximado desde .git/index (sin +/− líneas)
279 owners: ownerRules,
280 ...buildMeta(), // enlaces ya consolidados desde caché/snapshot
281 },
282 pending: total,
283 runAnalysis,
284 };
285}