Elffuss BraidHub

utopia-ia/elffuss-code public

22eb75f6760e · 10.7 KiBRawPermalink
1// Un .vsix (zip) → lo que Elffuss Code sabe aplicar: temas, gramáticas,
2// snippets y lenguajes. NUNCA se lee, importa ni evalúa JavaScript del
3// paquete: `main` y `browser` se ignoran y solo se descomprimen el manifiesto,
4// sus traducciones, la licencia y los ficheros que citan esas contribuciones.
5import { openZip } from './unzip.js';
6import { parseJsonc, parsePlist } from './formats.js';
7import { loadTheme, joinPath } from './themes.js';
8import { normalizeSnippets } from './snippets.js';
9import { sanitizeGrammar, ambitoValido } from './grammars.js';
10import { nestedRepetition, unsafeConfigRegexes } from './languages.js';
11
12export const SUPPORTED = ['themes', 'grammars', 'snippets', 'languages'];
13
14// Contribuciones que solo tienen sentido con el código de la extensión
15// corriendo (haría falta un host de extensiones). El resto de las que no se
16// aplican son declarativas: «todavía no».
17const NEEDS_CODE = new Set([
18 'commands', 'menus', 'submenus', 'keybindings', 'views', 'viewsContainers', 'viewsWelcome', 'debuggers',
19 'breakpoints', 'taskDefinitions', 'customEditors', 'notebooks', 'notebookRenderer', 'authentication',
20 'walkthroughs', 'terminal', 'codeActions', 'configuration', 'typescriptServerPlugins', 'chatParticipants',
21 'languageModelTools', 'mcpServerDefinitionProviders', 'remoteHelp', 'resourceLabelFormatters', 'statusBarItems',
22]);
23
24// Lo que una extensión aplicaría aquí y lo que no, a partir de su package.json
25// (sirve igual con el manifiesto que publica Open VSX que con el del .vsix).
26export function analyzeManifest(pkg) {
27 const c = pkg && typeof pkg.contributes === 'object' && pkg.contributes ? pkg.contributes : {};
28 const arr = k => (Array.isArray(c[k]) ? c[k] : []);
29 const applies = { themes: arr('themes').length, grammars: arr('grammars').length, snippets: arr('snippets').length, languages: arr('languages').length };
30 const ignored = [];
31 for (const k of Object.keys(c)) {
32 if (SUPPORTED.includes(k)) continue;
33 ignored.push({ key: k, why: NEEDS_CODE.has(k) ? 'code' : 'later' });
34 }
35 const hasCode = typeof pkg?.main === 'string' || typeof pkg?.browser === 'string';
36 const pack = Array.isArray(pkg?.extensionPack) ? pkg.extensionPack.filter(x => typeof x === 'string') : [];
37 const snippetLangs = [...new Set(arr('snippets').map(s => s?.language).filter(x => typeof x === 'string'))];
38 const languages = [...new Set([...arr('languages').map(l => l?.id), ...arr('grammars').map(g => g?.language)].filter(x => typeof x === 'string'))];
39 // para decir qué NO se aplicaría aunque se instale (panel.js): el lenguaje
40 // de cada gramática y si cada lenguaje trae configuración
41 const grammarLangs = arr('grammars').map(g => (typeof g?.language === 'string' ? g.language : null));
42 const languageList = arr('languages').filter(l => typeof l?.id === 'string' && l.id).map(l => ({ id: l.id, config: typeof l.configuration === 'string' }));
43 return { applies, ignored, hasCode, pack, snippetLangs, languages, grammarLangs, languageList, any: Object.values(applies).some(Boolean) };
44}
45
46// %clave% → texto de package.nls(.<idioma>).json, en todo el manifiesto.
47export function resolveNls(pkg, nls) {
48 const msg = v => (typeof v === 'string' ? v : v && typeof v.message === 'string' ? v.message : null);
49 const walk = v => {
50 if (typeof v === 'string') {
51 const m = /^%([^%\s]+)%$/.exec(v);
52 return m && msg(nls?.[m[1]]) != null ? msg(nls[m[1]]) : v;
53 }
54 if (Array.isArray(v)) return v.map(walk);
55 // «__proto__» (propia, de JSON.parse) asignada cambiaría el prototipo de `o`
56 if (v && typeof v === 'object') { const o = {}; for (const [k, x] of Object.entries(v)) if (k !== '__proto__') o[k] = walk(x); return o; }
57 return v;
58 };
59 return walk(pkg);
60}
61
62const strs = v => (Array.isArray(v) ? v.filter(x => typeof x === 'string') : []);
63const mapaStr = v => {
64 if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined;
65 const o = {};
66 for (const [k, x] of Object.entries(v)) if (typeof x === 'string') o[k] = x;
67 return o;
68};
69
70// Un fallo de una contribución suelta: qué era, cómo se llama y por qué (un
71// código que el panel traduce; `detail` es el mensaje técnico, de apoyo).
72function aviso(kind, name, e, extra = {}) {
73 const code = e?.code || (e instanceof SyntaxError ? 'json' : '');
74 return { kind, name: String(name ?? '').slice(0, 200), code, detail: String(e?.message ?? e ?? '').slice(0, 300), ...extra };
75}
76
77// Lee el paquete entero. Los fallos de una contribución suelta van a
78// `warnings` y no tumban la instalación del resto.
79export async function readVsix(bytes, { lang = 'en' } = {}) {
80 const zip = openZip(bytes);
81 const dec = new TextDecoder();
82 const readText = async p => {
83 if (!p.startsWith('extension/')) throw Object.assign(new Error('ruta fuera de la extensión: ' + p), { code: 'outside' });
84 return dec.decode(await zip.read(p));
85 };
86 if (!zip.has('extension/package.json')) throw Object.assign(new Error('no es una extensión de VS Code (falta extension/package.json)'), { code: 'notvsix' });
87 let pkg;
88 try { pkg = parseJsonc(await readText('extension/package.json')); }
89 catch (e) { throw e?.code ? e : Object.assign(new Error(e?.message || String(e)), { code: 'badmanifest' }); }
90 if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) throw Object.assign(new Error('package.json no es un objeto'), { code: 'badmanifest' });
91 let nls = {};
92 for (const f of ['extension/package.nls.json', `extension/package.nls.${lang}.json`]) {
93 if (zip.has(f)) { try { nls = { ...nls, ...parseJsonc(await readText(f)) }; } catch { /* traducción rota: se queda la clave */ } }
94 }
95 pkg = resolveNls(pkg, nls);
96 if (typeof pkg.name !== 'string' || typeof pkg.publisher !== 'string' || !pkg.name || !pkg.publisher) {
97 throw Object.assign(new Error('package.json sin name/publisher'), { code: 'noname' });
98 }
99
100 const warnings = [];
101 const ruta = p => joinPath('extension', String(p));
102 const c = pkg.contributes && typeof pkg.contributes === 'object' ? pkg.contributes : {};
103
104 const themes = [];
105 for (const [i, t] of (Array.isArray(c.themes) ? c.themes : []).entries()) {
106 if (!t || typeof t.path !== 'string') continue;
107 try {
108 const data = await loadTheme(ruta(t.path), readText, { label: t.label || t.id || t.path, uiTheme: t.uiTheme });
109 themes.push({ index: i, id: typeof t.id === 'string' ? t.id : '', label: data.label, uiTheme: data.uiTheme, path: ruta(t.path), data });
110 } catch (e) { warnings.push(aviso('theme', t.label || t.id || t.path, e)); }
111 }
112
113 const grammars = [];
114 for (const g of Array.isArray(c.grammars) ? c.grammars : []) {
115 if (!g || typeof g.path !== 'string' || typeof g.scopeName !== 'string') continue;
116 try {
117 if (!ambitoValido(g.scopeName)) throw Object.assign(new Error('scopeName no válido: ' + g.scopeName), { code: 'scope' });
118 const p = ruta(g.path);
119 const text = await readText(p);
120 const leida = /\.json$/i.test(p) ? parseJsonc(text) : parsePlist(text);
121 if (!leida || typeof leida !== 'object' || !Array.isArray(leida.patterns) && !leida.injectionSelector) throw Object.assign(new Error('no parece una gramática TextMate'), { code: 'notgrammar' });
122 // sin nombres que lleven al motor fuera de la gramática (grammars.js)
123 const data = sanitizeGrammar(leida);
124 grammars.push({
125 path: p, scopeName: g.scopeName, data,
126 language: typeof g.language === 'string' ? g.language : undefined,
127 embeddedLanguages: mapaStr(g.embeddedLanguages), tokenTypes: mapaStr(g.tokenTypes),
128 injectTo: strs(g.injectTo), balancedBracketScopes: Array.isArray(g.balancedBracketScopes) ? strs(g.balancedBracketScopes) : undefined,
129 unbalancedBracketScopes: Array.isArray(g.unbalancedBracketScopes) ? strs(g.unbalancedBracketScopes) : undefined,
130 });
131 } catch (e) { warnings.push(aviso('grammar', g.scopeName, e)); }
132 }
133
134 const snippets = [];
135 const porRuta = new Map();
136 for (const s of Array.isArray(c.snippets) ? c.snippets : []) {
137 if (!s || typeof s.path !== 'string' || typeof s.language !== 'string') continue;
138 try {
139 const p = ruta(s.path);
140 if (!porRuta.has(p)) porRuta.set(p, normalizeSnippets(parseJsonc(await readText(p))));
141 if (porRuta.get(p).length) snippets.push({ language: s.language, path: p, data: porRuta.get(p) });
142 } catch (e) { warnings.push(aviso('snippets', s.path, e)); }
143 }
144
145 // Las expresiones de un lenguaje (firstLine y las del language-configuration)
146 // con repetición anidada se descartan: podrían congelar la pestaña. Aquí
147 // solo se avisa; languages.js las descarta también al aplicarlas.
148 const languages = [];
149 for (const l of Array.isArray(c.languages) ? c.languages : []) {
150 if (!l || typeof l.id !== 'string' || !l.id) continue;
151 let firstLine = typeof l.firstLine === 'string' && l.firstLine ? l.firstLine : undefined;
152 if (firstLine && nestedRepetition(firstLine)) { warnings.push(aviso('regex', l.id, { code: 'nested', message: firstLine }, { where: 'firstLine' })); firstLine = undefined; }
153 const entry = {
154 id: l.id, aliases: strs(l.aliases), extensions: strs(l.extensions), filenames: strs(l.filenames),
155 filenamePatterns: strs(l.filenamePatterns), mimetypes: strs(l.mimetypes),
156 firstLine, configPath: null, config: null,
157 };
158 if (typeof l.configuration === 'string') {
159 try {
160 entry.configPath = ruta(l.configuration);
161 entry.config = parseJsonc(await readText(entry.configPath));
162 // (solo cuenta si el lenguaje es nuevo: la de uno de serie no se aplica)
163 for (const src of unsafeConfigRegexes(entry.config)) warnings.push(aviso('regex', l.id, { code: 'nested', message: src }, { where: 'config' }));
164 } catch (e) { warnings.push(aviso('config', l.id, e)); entry.configPath = null; entry.config = null; }
165 }
166 languages.push(entry);
167 }
168
169 // licencia: la que diga «SEE LICENSE IN x» o el LICENSE* de la raíz
170 let licenseText = '';
171 const ref = /^SEE LICEN[SC]E IN (.+)$/i.exec(String(pkg.license || ''))?.[1]?.trim();
172 const candidatas = [ref && ruta(ref), ...zip.names.filter(n => /^extension\/licen[sc]e(\.[\w-]+|-[\w.-]+)?$/i.test(n))].filter(Boolean);
173 for (const f of candidatas) {
174 if (!zip.has(f)) continue;
175 try { licenseText = (await readText(f)).slice(0, 200_000); break; } catch { /* siguiente */ }
176 }
177
178 return {
179 manifest: pkg,
180 publisher: pkg.publisher, name: pkg.name, version: String(pkg.version || '0.0.0'),
181 id: `${pkg.publisher}.${pkg.name}`.toLowerCase(),
182 displayName: typeof pkg.displayName === 'string' ? pkg.displayName : pkg.name,
183 description: typeof pkg.description === 'string' ? pkg.description : '',
184 license: typeof pkg.license === 'string' ? pkg.license : '',
185 licenseText, themes, grammars, snippets, languages, warnings,
186 analysis: analyzeManifest(pkg),
187 };
188}