Elffuss BraidHub

kikocis/VibeCodeViewer public

26da0d5e2201 · 4.4 KiBRawPermalink
1// Análisis estático ligero de relaciones entre ficheros para el modo Blast:
2// imports/exports/require/include/source/url(...) → enlaces fichero→fichero
3// o fichero→carpeta. Compartido por scan.mjs y fsScan.js.
4
5const SRC_EXT = /\.(m?js|cjs|jsx|tsx?|css|html?|py|c|cc|cpp|h|hpp|sh|vue|svelte)$/i;
6export const MAX_SRC_BYTES = 400 * 1024;
7
8export function isAnalyzable(name, size) {
9 return size > 0 && size <= MAX_SRC_BYTES && SRC_EXT.test(name);
10}
11
12// extrae las "specs" crudas referenciadas desde un fichero
13export function extractRefs(name, text) {
14 const specs = new Set();
15 const add = (s) => {
16 if (!s) return;
17 s = s.split(/[?#]/)[0].trim();
18 if (s && !/^(https?:|\/\/|data:|mailto:|about:)/.test(s)) specs.add(s);
19 };
20 const scan = (re) => { for (const m of text.matchAll(re)) add(m[1]); };
21 const n = name.toLowerCase();
22
23 if (/\.(m?js|cjs|jsx|tsx?|vue|svelte|html?)$/.test(n)) {
24 scan(/import\s+(?:[\s\S]*?from\s*)?['"]([^'"]+)['"]/g);
25 scan(/export\s+[^;'"]*?from\s*['"]([^'"]+)['"]/g);
26 scan(/require\s*\(\s*['"]([^'"]+)['"]/g);
27 scan(/import\s*\(\s*['"]([^'"]+)['"]/g);
28 }
29 if (/\.(html?|vue|svelte)$/.test(n)) scan(/(?:src|href)\s*=\s*["']([^"']+)["']/g);
30 if (/\.css$/.test(n)) {
31 scan(/@import\s+(?:url\(\s*)?['"]?([^'")\s]+)/g);
32 scan(/url\(\s*['"]?([^'")\s]+)/g);
33 }
34 if (/\.py$/.test(n)) {
35 for (const m of text.matchAll(/^\s*from\s+([\w.]+)\s+import/gm)) add(m[1].replace(/\./g, '/'));
36 for (const m of text.matchAll(/^\s*import\s+([\w.]+)/gm)) add(m[1].replace(/\./g, '/'));
37 }
38 if (/\.(c|cc|cpp|h|hpp)$/.test(n)) scan(/#include\s*["<]([^">]+)[">]/g);
39 if (/\.sh$/.test(n)) scan(/(?:^|\s)(?:source|\.)\s+(\S+\.\w+)/gm);
40 return [...specs];
41}
42
43const RESOLVE_EXTS = ['', '.js', '.mjs', '.ts', '.tsx', '.jsx', '.css', '.html', '.py', '.h', '.hpp', '.sh', '.json'];
44
45function normalize(parts) {
46 const out = [];
47 for (const p of parts) {
48 if (!p || p === '.') continue;
49 if (p === '..') { if (!out.length) return null; out.pop(); }
50 else out.push(p);
51 }
52 return out.join('/');
53}
54
55// resuelve las specs contra el conjunto de ficheros/carpetas del árbol.
56// refs: { relFichero: [spec, …] } → { relFichero: ['F:rel'|'D:rel', …] }
57export function resolveAll(refs, fileRels, dirRels) {
58 const files = new Set(fileRels);
59 const dirs = new Set(dirRels);
60 // índice por nombre para specs sueltas ('three' → three.module.js)
61 const byName = new Map();
62 for (const rel of fileRels) {
63 const base = rel.split('/').pop();
64 const stem = base.replace(/\.[^.]+$/, '');
65 for (const k of new Set([base, stem, stem.split('.')[0]])) {
66 if (!byName.has(k)) byName.set(k, []);
67 byName.get(k).push(rel);
68 }
69 }
70 const tryResolve = (cand) => {
71 for (const e of RESOLVE_EXTS) if (files.has(cand + e)) return 'F:' + cand + e;
72 for (const e of RESOLVE_EXTS) if (e && files.has(`${cand}/index${e}`)) return `F:${cand}/index${e}`;
73 if (dirs.has(cand)) return 'D:' + cand;
74 return null;
75 };
76
77 const links = {};
78 for (const [src, specs] of Object.entries(refs)) {
79 const dir = src.split('/').slice(0, -1);
80 const out = new Set();
81 for (const spec of specs) {
82 let hit = null;
83 if (spec.startsWith('.')) {
84 const p = normalize([...dir, ...spec.split('/')]);
85 if (p != null) hit = tryResolve(p);
86 } else if (spec.startsWith('/')) {
87 hit = tryResolve(spec.slice(1));
88 } else {
89 // ruta implícita relativa, luego anclada a la raíz
90 const p = normalize([...dir, ...spec.split('/')]);
91 hit = (p != null && tryResolve(p)) || tryResolve(spec);
92 if (!hit && spec.includes('/')) {
93 // spec de paquete ('three/addons/x.js'): sufijo único en el árbol.
94 // Se buscan candidatos por nombre de fichero en vez de filtrar el
95 // árbol entero: con cientos de miles de ficheros y miles de specs
96 // sin resolver, el filtro lineal congelaba el análisis.
97 const tail = spec.split('/').slice(1).join('/');
98 const cand = tail ? byName.get(tail.split('/').pop()) ?? [] : [];
99 const m = cand.filter(f => f.endsWith('/' + tail));
100 if (m.length === 1) hit = 'F:' + m[0];
101 }
102 if (!hit && !spec.includes('/')) {
103 // nombre suelto único en todo el árbol
104 const m = byName.get(spec);
105 if (m && m.length === 1) hit = 'F:' + m[0];
106 }
107 }
108 if (hit && hit !== 'F:' + src) out.add(hit);
109 }
110 if (out.size) links[src] = [...out];
111 }
112 return links;
113}