| 1 | // Nivel 2 dentro del host de extensiones (js/ext/host.js): encender y apagar |
| 2 | // el código de una extensión, leer y guardar sus ficheros al instalarla con su |
| 3 | // código, sus ajustes y su formateador por lenguaje, y el puente con el |
| 4 | // recinto (bridge.js). host.js solo lo importa cuando hace falta: alguna |
| 5 | // extensión con su código encendido, o el usuario pide algo de esto. Quien solo |
| 6 | // usa temas, gramáticas y snippets no baja nada de aquí. |
| 7 | import * as store from '../ext/store.js'; |
| 8 | |
| 9 | // TODOS los ficheros del paquete bajo extension/, en bytes, para entregarlos al |
| 10 | // recinto al encenderla. Fuera node_modules/** y los *.map, y ninguna ruta que |
| 11 | // salga del paquete. Topes contados sobre lo que sale al descomprimir: 32 MiB |
| 12 | // por fichero y 64 MiB por extensión. La página nunca ejecuta estos bytes. |
| 13 | export const RAW_MAX_ENTRY = 32 << 20, RAW_MAX_TOTAL = 64 << 20; |
| 14 | export async function readVsixRaw(bytes, { maxEntry = RAW_MAX_ENTRY, maxTotal = RAW_MAX_TOTAL } = {}) { |
| 15 | const { openZip } = await import('../ext/unzip.js'); |
| 16 | const zip = openZip(bytes, { maxEntry, maxTotal }); |
| 17 | const files = new Map(); |
| 18 | let total = 0; |
| 19 | for (const name of zip.names) { |
| 20 | if (!name.startsWith('extension/')) continue; |
| 21 | const rel = name.slice('extension/'.length); |
| 22 | if (!rel || /(^|\/)node_modules\//.test(rel) || /\.map$/i.test(rel)) continue; |
| 23 | if (rel.startsWith('/') || rel.split('/').some(s => s === '..' || s === '.' || s === '')) continue; |
| 24 | const data = await zip.read(name); |
| 25 | total += data.length; |
| 26 | files.set(rel, data); |
| 27 | } |
| 28 | return { files, bytes: total }; |
| 29 | } |
| 30 | // La entrada `browser` del manifiesto como fichero del paquete |
| 31 | // («./dist/web/extension» → «dist/web/extension.js»), o null si no está. |
| 32 | export function browserEntry(manifest, names) { |
| 33 | if (!manifest || typeof manifest.browser !== 'string') return null; |
| 34 | const base = manifest.browser.replace(/^\.\//, '').replace(/\\/g, '/'); |
| 35 | for (const c of [base, base + '.js', base + '/index.js']) if (names.has(c)) return c; |
| 36 | return null; |
| 37 | } |
| 38 | |
| 39 | // [[ruta, ArrayBuffer]] del código guardado de una extensión |
| 40 | export async function readCode(rec) { |
| 41 | const paths = Array.isArray(rec?.code?.files) ? rec.code.files : []; |
| 42 | const vals = await store.getFiles(paths.map(p => store.codeKey(rec.id, rec.version, p))); |
| 43 | return paths.map((p, i) => { |
| 44 | const v = vals[i]; |
| 45 | if (v === undefined) throw Object.assign(new Error('falta ' + p), { code: 'missing' }); |
| 46 | const buf = v instanceof ArrayBuffer ? v.slice(0) : ArrayBuffer.isView(v) ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : new TextEncoder().encode(String(v)).buffer; |
| 47 | return [p, buf]; |
| 48 | }); |
| 49 | } |
| 50 | |
| 51 | // Antes de encender el código de una extensión: el diálogo de consentimiento |
| 52 | // del panel (qué verá, que no tiene red, cuánto se baja). |
| 53 | async function confirmaTamano({ runtimeBytes, extensionBytes, name, rec }) { |
| 54 | const { consent } = await import('./manage.js'); |
| 55 | return (await consent({ name, publisher: rec?.publisher, version: rec?.version, license: rec?.license, runtime: { bytes: runtimeBytes }, extensionBytes, mode: 'run' })) === 'code'; |
| 56 | } |
| 57 | |
| 58 | const PARADO = { state: 'stopped', extensions: [], commands: [] }; |
| 59 | |
| 60 | // h: lo que host.js comparte (ver allí): monaco, exts(), recarga(), emit(), |
| 61 | // paused, sinCodigo, listeners (los del panel) y uiTheme() |
| 62 | const KIND = { vs: 'light', 'hc-black': 'hc', 'hc-light': 'hc-light' }; |
| 63 | const kindOf = uiTheme => KIND[uiTheme] || 'dark'; // claro, oscuro o contraste |
| 64 | export function attach(h) { |
| 65 | let puente = null, cargando = null; |
| 66 | const corren = () => (h.paused || h.sinCodigo ? [] : h.exts().filter(e => e.enabled && e.runs)); |
| 67 | |
| 68 | // Con alguna extensión con su código encendido, el recinto arranca (en |
| 69 | // paralelo: ide.js crea el editor después y el puente lo espera); sin |
| 70 | // ninguna, se desmonta. La lista se lee al sincronizar, no al pedirlo: dos |
| 71 | // cambios seguidos (instalar dos, encender y apagar) no pueden dejar el |
| 72 | // recinto con una lista vieja. |
| 73 | function sync() { |
| 74 | if (!corren().length && !puente && !cargando) return; |
| 75 | (async () => { |
| 76 | cargando ??= import('./bridge.js').then(m => { |
| 77 | m.onChange(() => { for (const f of h.listeners) { try { f(); } catch { /* — */ } } }); |
| 78 | return m; |
| 79 | }); |
| 80 | puente = await cargando; |
| 81 | puente.setTheme(kindOf(h.uiTheme())); |
| 82 | await puente.sync({ monaco: h.monaco, records: corren(), readCode }); |
| 83 | h.emit(); |
| 84 | })().catch(e => console.warn('[elffuss-ext] nivel 2:', e?.message || e)); |
| 85 | } |
| 86 | |
| 87 | // Instalar con su código (el usuario ya aceptó): los bytes del paquete por |
| 88 | // ruta, la entrada `browser`, encendida salvo que estuviera apagada antes, y |
| 89 | // sus ajustes y su formateador si ya los tenía (una actualización). |
| 90 | async function codeFiles(v, bytes, previo) { |
| 91 | if (typeof v.manifest.browser !== 'string') throw Object.assign(new Error('sin código para navegador'), { code: 'nocode' }); |
| 92 | const raw = await readVsixRaw(bytes); |
| 93 | const entry = browserEntry(v.manifest, raw.files); |
| 94 | if (!entry) throw Object.assign(new Error('la entrada browser no está en el paquete'), { code: 'noentry' }); |
| 95 | const files = new Map(); |
| 96 | for (const [p, data] of raw.files) files.set(store.codeKey(v.id, v.version, p), data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)); |
| 97 | return { |
| 98 | files, |
| 99 | fields: { |
| 100 | code: { entry, files: [...raw.files.keys()], bytes: raw.bytes, manifest: v.manifest }, |
| 101 | runs: previo?.code ? !!previo.runs : true, |
| 102 | settings: previo?.settings || {}, formatter: previo?.formatter || {}, |
| 103 | }, |
| 104 | }; |
| 105 | } |
| 106 | |
| 107 | // Encender el código: la primera vez enseña cuánto se va a bajar ANTES de |
| 108 | // bajar nada; cancelar no cambia nada. |
| 109 | async function setRuns(id, on, { confirm = confirmaTamano } = {}) { |
| 110 | const rec = h.exts().find(e => e.id === id); |
| 111 | if (!rec) throw Object.assign(new Error('no instalada: ' + id), { code: 'missing' }); |
| 112 | if (on) { |
| 113 | if (typeof rec.code?.manifest?.browser !== 'string') throw Object.assign(new Error('sin código para navegador'), { code: 'nocode' }); |
| 114 | const { runtimeInfo } = await import('./vendor.js'); |
| 115 | const info = await runtimeInfo(); |
| 116 | if (!info.available) throw Object.assign(new Error('nivel 2 no disponible: ' + info.reason), { code: 'x2-' + info.reason }); |
| 117 | if (!info.cached && !(await confirm({ runtimeBytes: info.bytes, extensionBytes: rec.code.bytes || 0, name: rec.displayName || rec.id, id, rec }))) return false; |
| 118 | } |
| 119 | await store.update(id, r => { r.runs = !!on; }); |
| 120 | await h.recarga(); |
| 121 | return true; |
| 122 | } |
| 123 | |
| 124 | // Ajustes (validados por el panel contra lo que la extensión declara) y |
| 125 | // formateador por lenguaje: se aplican sin recargar. |
| 126 | async function setSettings(id, settings) { |
| 127 | if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw Object.assign(new Error('los ajustes son un objeto JSON'), { code: 'settings' }); |
| 128 | await store.update(id, r => { r.settings = structuredClone(settings); }, { mirror: false }); |
| 129 | await h.recarga(); |
| 130 | } |
| 131 | async function setFormatter(id, lang, choice) { |
| 132 | const rec = h.exts().find(e => e.id === id); |
| 133 | if (!rec || typeof lang !== 'string' || !['extension', 'builtin'].includes(choice)) return; |
| 134 | await store.update(id, r => { r.formatter = { ...(r.formatter || {}), [lang]: choice }; }, { mirror: false }); |
| 135 | await h.recarga(); |
| 136 | } |
| 137 | |
| 138 | // ¿está disponible el nivel 2 aquí? (navegador, sitio, interruptor) y su tamaño |
| 139 | const runtime = async () => (h.paused || h.sinCodigo ? { available: false, reason: 'url' } : (await import('./vendor.js')).runtimeInfo()); |
| 140 | |
| 141 | return { |
| 142 | sync, codeFiles, setRuns, setSettings, setFormatter, runtime, |
| 143 | setTheme: uiTheme => puente?.setTheme(kindOf(uiTheme)), |
| 144 | state: () => (puente ? puente.state() : PARADO), |
| 145 | commands: () => (puente ? puente.commands() : []), |
| 146 | }; |
| 147 | } |