| 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. |
| 5 | import { openZip } from './unzip.js'; |
| 6 | import { parseJsonc, parsePlist } from './formats.js'; |
| 7 | import { loadTheme, joinPath } from './themes.js'; |
| 8 | import { normalizeSnippets } from './snippets.js'; |
| 9 | import { sanitizeGrammar, ambitoValido } from './grammars.js'; |
| 10 | import { nestedRepetition, unsafeConfigRegexes } from './languages.js'; |
| 11 | |
| 12 | export 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». |
| 17 | const 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). |
| 26 | export 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 => ({ |
| 43 | id: l.id, config: typeof l.configuration === 'string', |
| 44 | name: Array.isArray(l.aliases) && typeof l.aliases[0] === 'string' ? l.aliases[0] : undefined, |
| 45 | extensions: Array.isArray(l.extensions) ? l.extensions.filter(x => typeof x === 'string') : [], |
| 46 | })); |
| 47 | // para el veredicto en lenguaje llano (verdict.js): de qué va, qué partes |
| 48 | // necesitan su código y si ese código podría correr en un navegador |
| 49 | const categories = Array.isArray(pkg?.categories) ? pkg.categories.filter(x => typeof x === 'string') : []; |
| 50 | const sizes = {}; |
| 51 | for (const k of Object.keys(c)) sizes[k] = Array.isArray(c[k]) ? c[k].length : c[k] && typeof c[k] === 'object' ? Object.keys(c[k]).length : 1; |
| 52 | const webviews = Object.values(c.views && typeof c.views === 'object' ? c.views : {}).some(v => Array.isArray(v) && v.some(x => x?.type === 'webview')); |
| 53 | const themeLabels = arr('themes').map(t => (typeof t?.label === 'string' ? t.label : typeof t?.id === 'string' ? t.id : null)).filter(Boolean); |
| 54 | return { |
| 55 | applies, ignored, hasCode, pack, snippetLangs, languages, grammarLangs, languageList, any: Object.values(applies).some(Boolean), |
| 56 | categories, sizes, webviews, browserEntry: typeof pkg?.browser === 'string', themeLabels, |
| 57 | }; |
| 58 | } |
| 59 | |
| 60 | // %clave% → texto de package.nls(.<idioma>).json, en todo el manifiesto. |
| 61 | export function resolveNls(pkg, nls) { |
| 62 | const msg = v => (typeof v === 'string' ? v : v && typeof v.message === 'string' ? v.message : null); |
| 63 | const walk = v => { |
| 64 | if (typeof v === 'string') { |
| 65 | const m = /^%([^%\s]+)%$/.exec(v); |
| 66 | return m && msg(nls?.[m[1]]) != null ? msg(nls[m[1]]) : v; |
| 67 | } |
| 68 | if (Array.isArray(v)) return v.map(walk); |
| 69 | // «__proto__» (propia, de JSON.parse) asignada cambiaría el prototipo de `o` |
| 70 | if (v && typeof v === 'object') { const o = {}; for (const [k, x] of Object.entries(v)) if (k !== '__proto__') o[k] = walk(x); return o; } |
| 71 | return v; |
| 72 | }; |
| 73 | return walk(pkg); |
| 74 | } |
| 75 | |
| 76 | const strs = v => (Array.isArray(v) ? v.filter(x => typeof x === 'string') : []); |
| 77 | const mapaStr = v => { |
| 78 | if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined; |
| 79 | const o = {}; |
| 80 | for (const [k, x] of Object.entries(v)) if (typeof x === 'string') o[k] = x; |
| 81 | return o; |
| 82 | }; |
| 83 | |
| 84 | // Un fallo de una contribución suelta: qué era, cómo se llama y por qué (un |
| 85 | // código que el panel traduce; `detail` es el mensaje técnico, de apoyo). |
| 86 | function aviso(kind, name, e, extra = {}) { |
| 87 | const code = e?.code || (e instanceof SyntaxError ? 'json' : ''); |
| 88 | return { kind, name: String(name ?? '').slice(0, 200), code, detail: String(e?.message ?? e ?? '').slice(0, 300), ...extra }; |
| 89 | } |
| 90 | |
| 91 | // Lee el paquete entero. Los fallos de una contribución suelta van a |
| 92 | // `warnings` y no tumban la instalación del resto. |
| 93 | export async function readVsix(bytes, { lang = 'en' } = {}) { |
| 94 | const zip = openZip(bytes); |
| 95 | const dec = new TextDecoder(); |
| 96 | const readText = async p => { |
| 97 | if (!p.startsWith('extension/')) throw Object.assign(new Error('ruta fuera de la extensión: ' + p), { code: 'outside' }); |
| 98 | return dec.decode(await zip.read(p)); |
| 99 | }; |
| 100 | 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' }); |
| 101 | let pkg; |
| 102 | try { pkg = parseJsonc(await readText('extension/package.json')); } |
| 103 | catch (e) { throw e?.code ? e : Object.assign(new Error(e?.message || String(e)), { code: 'badmanifest' }); } |
| 104 | if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) throw Object.assign(new Error('package.json no es un objeto'), { code: 'badmanifest' }); |
| 105 | let nls = {}; |
| 106 | for (const f of ['extension/package.nls.json', `extension/package.nls.${lang}.json`]) { |
| 107 | if (zip.has(f)) { try { nls = { ...nls, ...parseJsonc(await readText(f)) }; } catch { /* traducción rota: se queda la clave */ } } |
| 108 | } |
| 109 | pkg = resolveNls(pkg, nls); |
| 110 | if (typeof pkg.name !== 'string' || typeof pkg.publisher !== 'string' || !pkg.name || !pkg.publisher) { |
| 111 | throw Object.assign(new Error('package.json sin name/publisher'), { code: 'noname' }); |
| 112 | } |
| 113 | |
| 114 | const warnings = []; |
| 115 | const ruta = p => joinPath('extension', String(p)); |
| 116 | const c = pkg.contributes && typeof pkg.contributes === 'object' ? pkg.contributes : {}; |
| 117 | |
| 118 | const themes = []; |
| 119 | for (const [i, t] of (Array.isArray(c.themes) ? c.themes : []).entries()) { |
| 120 | if (!t || typeof t.path !== 'string') continue; |
| 121 | try { |
| 122 | const data = await loadTheme(ruta(t.path), readText, { label: t.label || t.id || t.path, uiTheme: t.uiTheme }); |
| 123 | themes.push({ index: i, id: typeof t.id === 'string' ? t.id : '', label: data.label, uiTheme: data.uiTheme, path: ruta(t.path), data }); |
| 124 | } catch (e) { warnings.push(aviso('theme', t.label || t.id || t.path, e)); } |
| 125 | } |
| 126 | |
| 127 | const grammars = []; |
| 128 | for (const g of Array.isArray(c.grammars) ? c.grammars : []) { |
| 129 | if (!g || typeof g.path !== 'string' || typeof g.scopeName !== 'string') continue; |
| 130 | try { |
| 131 | if (!ambitoValido(g.scopeName)) throw Object.assign(new Error('scopeName no válido: ' + g.scopeName), { code: 'scope' }); |
| 132 | const p = ruta(g.path); |
| 133 | const text = await readText(p); |
| 134 | const leida = /\.json$/i.test(p) ? parseJsonc(text) : parsePlist(text); |
| 135 | if (!leida || typeof leida !== 'object' || !Array.isArray(leida.patterns) && !leida.injectionSelector) throw Object.assign(new Error('no parece una gramática TextMate'), { code: 'notgrammar' }); |
| 136 | // sin nombres que lleven al motor fuera de la gramática (grammars.js) |
| 137 | const data = sanitizeGrammar(leida); |
| 138 | grammars.push({ |
| 139 | path: p, scopeName: g.scopeName, data, |
| 140 | language: typeof g.language === 'string' ? g.language : undefined, |
| 141 | embeddedLanguages: mapaStr(g.embeddedLanguages), tokenTypes: mapaStr(g.tokenTypes), |
| 142 | injectTo: strs(g.injectTo), balancedBracketScopes: Array.isArray(g.balancedBracketScopes) ? strs(g.balancedBracketScopes) : undefined, |
| 143 | unbalancedBracketScopes: Array.isArray(g.unbalancedBracketScopes) ? strs(g.unbalancedBracketScopes) : undefined, |
| 144 | }); |
| 145 | } catch (e) { warnings.push(aviso('grammar', g.scopeName, e)); } |
| 146 | } |
| 147 | |
| 148 | const snippets = []; |
| 149 | const porRuta = new Map(); |
| 150 | for (const s of Array.isArray(c.snippets) ? c.snippets : []) { |
| 151 | if (!s || typeof s.path !== 'string' || typeof s.language !== 'string') continue; |
| 152 | try { |
| 153 | const p = ruta(s.path); |
| 154 | if (!porRuta.has(p)) porRuta.set(p, normalizeSnippets(parseJsonc(await readText(p)))); |
| 155 | if (porRuta.get(p).length) snippets.push({ language: s.language, path: p, data: porRuta.get(p) }); |
| 156 | } catch (e) { warnings.push(aviso('snippets', s.path, e)); } |
| 157 | } |
| 158 | |
| 159 | // Las expresiones de un lenguaje (firstLine y las del language-configuration) |
| 160 | // con repetición anidada se descartan: podrían congelar la pestaña. Aquí |
| 161 | // solo se avisa; languages.js las descarta también al aplicarlas. |
| 162 | const languages = []; |
| 163 | for (const l of Array.isArray(c.languages) ? c.languages : []) { |
| 164 | if (!l || typeof l.id !== 'string' || !l.id) continue; |
| 165 | let firstLine = typeof l.firstLine === 'string' && l.firstLine ? l.firstLine : undefined; |
| 166 | if (firstLine && nestedRepetition(firstLine)) { warnings.push(aviso('regex', l.id, { code: 'nested', message: firstLine }, { where: 'firstLine' })); firstLine = undefined; } |
| 167 | const entry = { |
| 168 | id: l.id, aliases: strs(l.aliases), extensions: strs(l.extensions), filenames: strs(l.filenames), |
| 169 | filenamePatterns: strs(l.filenamePatterns), mimetypes: strs(l.mimetypes), |
| 170 | firstLine, configPath: null, config: null, |
| 171 | }; |
| 172 | if (typeof l.configuration === 'string') { |
| 173 | try { |
| 174 | entry.configPath = ruta(l.configuration); |
| 175 | entry.config = parseJsonc(await readText(entry.configPath)); |
| 176 | // (solo cuenta si el lenguaje es nuevo: la de uno de serie no se aplica) |
| 177 | for (const src of unsafeConfigRegexes(entry.config)) warnings.push(aviso('regex', l.id, { code: 'nested', message: src }, { where: 'config' })); |
| 178 | } catch (e) { warnings.push(aviso('config', l.id, e)); entry.configPath = null; entry.config = null; } |
| 179 | } |
| 180 | languages.push(entry); |
| 181 | } |
| 182 | |
| 183 | // licencia: la que diga «SEE LICENSE IN x» o el LICENSE* de la raíz |
| 184 | let licenseText = ''; |
| 185 | const ref = /^SEE LICEN[SC]E IN (.+)$/i.exec(String(pkg.license || ''))?.[1]?.trim(); |
| 186 | const candidatas = [ref && ruta(ref), ...zip.names.filter(n => /^extension\/licen[sc]e(\.[\w-]+|-[\w.-]+)?$/i.test(n))].filter(Boolean); |
| 187 | for (const f of candidatas) { |
| 188 | if (!zip.has(f)) continue; |
| 189 | try { licenseText = (await readText(f)).slice(0, 200_000); break; } catch { /* siguiente */ } |
| 190 | } |
| 191 | |
| 192 | return { |
| 193 | manifest: pkg, |
| 194 | publisher: pkg.publisher, name: pkg.name, version: String(pkg.version || '0.0.0'), |
| 195 | id: `${pkg.publisher}.${pkg.name}`.toLowerCase(), |
| 196 | displayName: typeof pkg.displayName === 'string' ? pkg.displayName : pkg.name, |
| 197 | description: typeof pkg.description === 'string' ? pkg.description : '', |
| 198 | license: typeof pkg.license === 'string' ? pkg.license : '', |
| 199 | licenseText, themes, grammars, snippets, languages, warnings, |
| 200 | analysis: analyzeManifest(pkg), |
| 201 | }; |
| 202 | } |