| 1 | // Host de extensiones de VS Code — nivel 1: solo contribuciones declarativas |
| 2 | // (temas de color, gramáticas TextMate, snippets y configuración de lenguajes). |
| 3 | // NINGÚN JavaScript de una extensión se ejecuta aquí. |
| 4 | // |
| 5 | // ide.js lo carga solo si hay alguna extensión activa (o un tema elegido) y el |
| 6 | // panel lo carga al abrirse: sin extensiones, el arranque de Code no cambia. |
| 7 | // Cada cambio (instalar, activar, desactivar, desinstalar) deshace lo aplicado |
| 8 | // y lo vuelve a aplicar desde cero, de uno en uno: más simple y sin restos. |
| 9 | // Las gramáticas solo se rehacen si su lista cambia. |
| 10 | import * as store from './store.js'; |
| 11 | import { BASES, builtinTheme, toMonacoTheme, toTextMateTheme, chromeCss, themeIdFor } from './themes.js'; |
| 12 | import { registerSnippets } from './snippets.js'; |
| 13 | import { toLanguageConfiguration, matchLanguage } from './languages.js'; |
| 14 | import { Grammars } from './grammars.js'; |
| 15 | import { uiLang } from '../i18n.js'; |
| 16 | |
| 17 | export const THEME_PREF = 'elffusscode.theme'; |
| 18 | let instancia = null; |
| 19 | |
| 20 | export function init(monaco, opts = {}) { |
| 21 | instancia ??= crear(monaco, opts).catch(e => { instancia = null; throw e; }); |
| 22 | return instancia; |
| 23 | } |
| 24 | |
| 25 | async function crear(monaco, { onLanguagesChanged = () => {} } = {}) { |
| 26 | const paused = /[?&]noext\b/.test(location.search); |
| 27 | const builtin = new Set(monaco.languages.getLanguages().map(l => l.id)); |
| 28 | const registrados = new Set(); // lenguajes que registramos (Monaco no permite quitarlos) |
| 29 | const listeners = new Set(); |
| 30 | let exts = []; |
| 31 | let aplicado = []; // disposables de lo aplicado |
| 32 | let langContribs = []; |
| 33 | let themeIndex = new Map(); // id de tema → { key, label, uiTheme, ext, extName } |
| 34 | let pref = leePref(); |
| 35 | let actual = 'vs-dark', monacoId = 'vs-dark'; |
| 36 | let estilo = null; |
| 37 | let firmaGramaticas = '[]'; |
| 38 | let cola = Promise.resolve(); // los cambios se aplican de uno en uno |
| 39 | |
| 40 | const grammars = new Grammars(monaco, { |
| 41 | loadFile: store.getFile, |
| 42 | builtin, |
| 43 | // la primera gramática enciende el motor: el tema se redefine con el mapa |
| 44 | // de colores de TextMate antes de pintar ningún token |
| 45 | onActivate: () => aplicaTema(actual), |
| 46 | }); |
| 47 | |
| 48 | function leePref() { try { return localStorage.getItem(THEME_PREF) || 'vs-dark'; } catch { return 'vs-dark'; } } |
| 49 | function guardaPref(id) { |
| 50 | pref = id; |
| 51 | try { if (id === 'vs-dark') localStorage.removeItem(THEME_PREF); else localStorage.setItem(THEME_PREF, id); } catch { /* sin almacenamiento */ } |
| 52 | } |
| 53 | |
| 54 | function pintaCromo(tema, id) { |
| 55 | if (!estilo) { estilo = document.createElement('style'); estilo.id = 'ext-theme-chrome'; document.head.appendChild(estilo); } |
| 56 | estilo.textContent = id === 'vs-dark' ? '' : chromeCss(tema); |
| 57 | } |
| 58 | |
| 59 | let turnoTema = 0; |
| 60 | async function aplicaTema(id, { guardar = false } = {}) { |
| 61 | const turno = ++turnoTema; |
| 62 | let elegido = id, tema = null; |
| 63 | if (themeIndex.has(id)) { |
| 64 | tema = await store.getFile(themeIndex.get(id).key).catch(() => null); |
| 65 | if (!tema) elegido = 'vs-dark'; |
| 66 | } else if (!BASES.includes(id)) elegido = 'vs-dark'; |
| 67 | // flechas rápidas en el selector: solo cuenta la última petición |
| 68 | if (turno !== turnoTema) return actual; |
| 69 | tema ??= builtinTheme(elegido); |
| 70 | const encoded = grammars.setTheme(toTextMateTheme(tema)); |
| 71 | let mid = elegido; |
| 72 | if (!tema.builtin) monaco.editor.defineTheme(elegido, toMonacoTheme(tema, encoded)); |
| 73 | else if (encoded) { |
| 74 | mid = 'elffuss-tm-' + elegido; |
| 75 | monaco.editor.defineTheme(mid, { base: elegido, inherit: true, rules: [], colors: {}, encodedTokensColors: encoded }); |
| 76 | } |
| 77 | monaco.editor.setTheme(mid); |
| 78 | actual = elegido; |
| 79 | monacoId = mid; |
| 80 | pintaCromo(tema, elegido); |
| 81 | if (guardar) guardaPref(elegido); |
| 82 | return elegido; |
| 83 | } |
| 84 | |
| 85 | async function reaplica() { |
| 86 | for (const d of aplicado) { try { d.dispose(); } catch { /* ya fuera */ } } |
| 87 | aplicado = []; |
| 88 | const activas = paused ? [] : exts.filter(e => e.enabled); |
| 89 | |
| 90 | langContribs = []; |
| 91 | for (const e of activas) { |
| 92 | for (const l of e.languages || []) { |
| 93 | langContribs.push(l); |
| 94 | if (builtin.has(l.id)) continue; // los de serie conservan su configuración |
| 95 | if (!registrados.has(l.id)) { |
| 96 | monaco.languages.register({ id: l.id, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, firstLine: l.firstLine, aliases: l.aliases, mimetypes: l.mimetypes }); |
| 97 | registrados.add(l.id); |
| 98 | } |
| 99 | if (l.configKey) { |
| 100 | const conf = await store.getFile(l.configKey).catch(() => null); |
| 101 | if (conf) aplicado.push(monaco.languages.setLanguageConfiguration(l.id, toLanguageConfiguration(conf, monaco))); |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | const porLang = new Map(); |
| 107 | for (const e of activas) { |
| 108 | for (const s of e.snippets || []) { |
| 109 | if (!porLang.has(s.language)) porLang.set(s.language, []); |
| 110 | porLang.get(s.language).push({ key: s.key, ext: e.displayName }); |
| 111 | } |
| 112 | } |
| 113 | for (const [lang, fuentes] of porLang) { |
| 114 | const cargar = async () => (await Promise.all(fuentes.map(async f => ((await store.getFile(f.key)) || []).map(s => ({ ...s, ext: f.ext }))))).flat(); |
| 115 | aplicado.push(registerSnippets(monaco, lang, cargar, s => s.ext)); |
| 116 | } |
| 117 | |
| 118 | // las gramáticas solo se rehacen si cambian: un tema nuevo no obliga a |
| 119 | // recompilarlas ni a repintar los ficheros con gramática |
| 120 | const gramaticas = activas.flatMap(e => (e.grammars || []).map(g => ({ ...g, ext: e.id }))); |
| 121 | const firma = JSON.stringify(gramaticas.map(g => [g.key, g.language, g.scopeName])); |
| 122 | if (firma !== firmaGramaticas) { firmaGramaticas = firma; grammars.configure(gramaticas); } |
| 123 | |
| 124 | themeIndex = new Map(); |
| 125 | for (const e of activas) for (const t of e.themes || []) themeIndex.set(t.themeId, { ...t, ext: e.id, extName: e.displayName }); |
| 126 | await aplicaTema(pref); |
| 127 | } |
| 128 | |
| 129 | const emit = () => { |
| 130 | for (const f of listeners) { try { f(); } catch { /* un oyente roto no para al resto */ } } |
| 131 | try { onLanguagesChanged(); } catch { /* — */ } |
| 132 | }; |
| 133 | function recarga() { |
| 134 | const r = cola.then(async () => { exts = await store.list(); await reaplica(); }); |
| 135 | cola = r.catch(() => {}); |
| 136 | return r.then(emit); |
| 137 | } |
| 138 | |
| 139 | // ── arranque ── |
| 140 | try { await store.reconcile(); } catch (e) { console.warn('[elffuss-ext] no pude ordenar las extensiones guardadas:', e?.message || e); } |
| 141 | exts = await store.list().catch(() => []); |
| 142 | await reaplica(); |
| 143 | |
| 144 | const quitaTemasDe = id => { if (themeIndex.get(pref)?.ext === id) guardaPref('vs-dark'); }; |
| 145 | |
| 146 | async function install(src, { onProgress, confirmLarge, signal } = {}) { |
| 147 | let bytes, sha256, verified = false, source = 'file', meta = null; |
| 148 | const ovsx = await import('./openvsx.js'); |
| 149 | if (src instanceof Blob) { |
| 150 | bytes = new Uint8Array(await src.arrayBuffer()); |
| 151 | sha256 = await ovsx.sha256Hex(bytes); |
| 152 | } else { |
| 153 | meta = await ovsx.metadata(src.namespace, src.name, src.version || '', { signal }); |
| 154 | ({ bytes, sha256, verified } = await ovsx.download(meta, { onProgress, confirmLarge, signal })); |
| 155 | source = 'open-vsx'; |
| 156 | } |
| 157 | const { readVsix } = await import('./vsix.js'); |
| 158 | const v = await readVsix(bytes, { lang: uiLang() }); |
| 159 | if (meta && v.id !== `${meta.namespace}.${meta.name}`.toLowerCase()) throw new Error(`el paquete dice ser ${v.id}, no ${meta.namespace}.${meta.name}`); |
| 160 | if (!v.themes.length && !v.grammars.length && !v.snippets.length && !v.languages.length) { |
| 161 | const e = new Error('nothing-applies'); e.code = 'nothing'; throw e; |
| 162 | } |
| 163 | const previo = exts.find(e => e.id === v.id); |
| 164 | const usados = new Set(exts.filter(e => e.id !== v.id).flatMap(e => (e.themes || []).map(t => t.themeId))); |
| 165 | const files = new Map(); |
| 166 | const k = p => store.fileKey(v.id, v.version, p); |
| 167 | const rec = { |
| 168 | id: v.id, publisher: v.publisher, name: v.name, version: v.version, |
| 169 | displayName: v.displayName, description: v.description.slice(0, 500), |
| 170 | license: (meta?.license || v.license || '').slice(0, 200), sha256, verified, source, size: bytes.length, |
| 171 | installedAt: previo?.installedAt || Date.now(), enabled: previo ? previo.enabled : true, |
| 172 | hasCode: v.analysis.hasCode, ignored: v.analysis.ignored, pack: v.analysis.pack, warnings: v.warnings.slice(0, 20), |
| 173 | themes: v.themes.map(t => { const key = k('theme/' + t.index); files.set(key, t.data); return { key, label: t.label, uiTheme: t.uiTheme, themeId: themeIdFor(v.id, t, t.index, usados) }; }), |
| 174 | grammars: v.grammars.map(g => { |
| 175 | const key = k(g.path); files.set(key, g.data); |
| 176 | return { key, scopeName: g.scopeName, language: g.language, embeddedLanguages: g.embeddedLanguages, tokenTypes: g.tokenTypes, injectTo: g.injectTo, balancedBracketScopes: g.balancedBracketScopes, unbalancedBracketScopes: g.unbalancedBracketScopes }; |
| 177 | }), |
| 178 | snippets: v.snippets.map(s => { const key = k(s.path); files.set(key, s.data); return { key, language: s.language, count: s.data.length }; }), |
| 179 | languages: v.languages.map(l => { |
| 180 | let configKey = null; |
| 181 | if (l.config) { configKey = k(l.configPath); files.set(configKey, l.config); } |
| 182 | return { id: l.id, aliases: l.aliases, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, firstLine: l.firstLine, mimetypes: l.mimetypes, configKey }; |
| 183 | }), |
| 184 | licenseKey: null, |
| 185 | }; |
| 186 | if (v.licenseText) { rec.licenseKey = k('LICENSE'); files.set(rec.licenseKey, v.licenseText); } |
| 187 | await store.put(rec, files); |
| 188 | await recarga(); |
| 189 | return rec; |
| 190 | } |
| 191 | |
| 192 | async function setEnabled(id, on) { |
| 193 | if (!on) quitaTemasDe(id); |
| 194 | await store.setEnabled(id, on); |
| 195 | await recarga(); |
| 196 | } |
| 197 | async function uninstall(id) { |
| 198 | quitaTemasDe(id); |
| 199 | await store.remove(id); |
| 200 | await recarga(); |
| 201 | } |
| 202 | |
| 203 | const nombresSerie = { 'vs-dark': 'builtinDark', vs: 'builtinLight', 'hc-black': 'builtinHc', 'hc-light': 'builtinHcLight' }; |
| 204 | return { |
| 205 | paused, |
| 206 | list: () => exts.map(e => ({ ...e })), |
| 207 | onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); }, |
| 208 | install, setEnabled, uninstall, |
| 209 | licenseText: async id => { const e = exts.find(x => x.id === id); return e?.licenseKey ? (await store.getFile(e.licenseKey)) || '' : ''; }, |
| 210 | themes: () => [ |
| 211 | ...BASES.map(id => ({ id, builtin: true, labelKey: nombresSerie[id], uiTheme: id })), |
| 212 | ...[...themeIndex].map(([id, t]) => ({ id, label: t.label, uiTheme: t.uiTheme, ext: t.ext, extName: t.extName })), |
| 213 | ], |
| 214 | currentTheme: () => actual, |
| 215 | themeId: () => monacoId, |
| 216 | setTheme: id => aplicaTema(id, { guardar: true }), |
| 217 | previewTheme: id => aplicaTema(id), |
| 218 | languageForPath: (path, primeraLinea = null) => (paused ? null : matchLanguage(langContribs, path, primeraLinea)), |
| 219 | prepareLanguage: async lang => (paused || !grammars.hasGrammarFor(lang) ? false : grammars.prepare(lang)), |
| 220 | skippedGrammars: () => grammars.skipped.map(g => ({ ext: g.ext, language: g.language, scopeName: g.scopeName })), |
| 221 | }; |
| 222 | } |