| 1 | // Censo EN EJECUCIÓN del nivel 2 (manual, con red): de las N extensiones más |
| 2 | // descargadas de Open VSX, las que traen código para navegador se instalan y |
| 3 | // arrancan de verdad, una a una, en el recinto real, con la baliza escuchando. |
| 4 | // |
| 5 | // node tests/x2_census.mjs [--top 500] [--pause 1500] [--out web/js/ext2/tested.json] |
| 6 | // node tests/x2_census.mjs --only ns.name,ns.name [--merge] |
| 7 | // --only re-runs just those; with --merge their entries replace the ones |
| 8 | // in the existing output (and the counts are recomputed); without it, |
| 9 | // nothing is written |
| 10 | // |
| 11 | // Por cada una: baja el .vsix y comprueba su SHA-256 (falla cerrado), lo |
| 12 | // guarda como lo haría una instalación (con sus lenguajes, para que Code |
| 13 | // reconozca sus ficheros), espera a que el recinto esté en marcha, abre |
| 14 | // entonces un documento de muestra por lenguaje que aporte, lanza |
| 15 | // onStartupFinished, «*» y los onCommand de sus comandos (solo activa: no |
| 16 | // ejecuta ningún comando) y anota: |
| 17 | // · si arranca, o el error con el que no arranca; |
| 18 | // · qué comandos y proveedores registra (por tipo), y los de fase 2; |
| 19 | // · si pone diagnósticos; |
| 20 | // · lo que no está soportado (el comando «type», llamadas sin servicio). |
| 21 | // Cualquier visita a la baliza es un fallo del recinto. Salida: tested.json |
| 22 | // (por id@versión) y un resumen con recuentos. Sin tiempos. |
| 23 | // Los manifiestos y los .vsix se guardan en tests/.cache/ para repetir sin red. |
| 24 | import fs from 'node:fs'; |
| 25 | import path from 'node:path'; |
| 26 | import { fileURLToPath } from 'node:url'; |
| 27 | import { chromium } from 'playwright'; |
| 28 | import { startServer } from './lib/x2-server.mjs'; |
| 29 | import { startBeacon } from './lib/beacon.mjs'; |
| 30 | import { fetchVsix, readCode, seedReal } from './lib/x2-vsix.mjs'; |
| 31 | import { readVsix, analyzeManifest } from '../web/js/ext/vsix.js'; |
| 32 | |
| 33 | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 34 | const REPO = path.resolve(HERE, '..'); |
| 35 | const API = 'https://open-vsx.org'; |
| 36 | const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; }; |
| 37 | const TOP = Number(arg('--top', 500)); |
| 38 | const PAUSE = Number(arg('--pause', 1500)); |
| 39 | const ONLY = arg('--only', '') ? new Set(arg('--only').toLowerCase().split(',')) : null; |
| 40 | const MERGE = process.argv.includes('--merge'); |
| 41 | const OUT = path.resolve(arg('--out', path.join(REPO, 'web/js/ext2/tested.json'))); |
| 42 | const CACHE = path.join(HERE, '.cache', 'census'); |
| 43 | fs.mkdirSync(CACHE, { recursive: true }); |
| 44 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 45 | async function until(fn, { timeout = 20000, every = 250 } = {}) { |
| 46 | const end = Date.now() + timeout; |
| 47 | let v; |
| 48 | while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); } |
| 49 | return v; |
| 50 | } |
| 51 | async function getJson(url) { |
| 52 | for (let attempt = 0; attempt < 3; attempt++) { |
| 53 | const r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-census' } }); |
| 54 | if (r.status === 429) { await sleep(10000 * (attempt + 1)); continue; } |
| 55 | if (!r.ok) throw Object.assign(new Error(`${url}: HTTP ${r.status}`), { status: r.status }); |
| 56 | return r.json(); |
| 57 | } |
| 58 | throw new Error('rate limited: ' + url); |
| 59 | } |
| 60 | |
| 61 | // ── 1. las N más descargadas ── |
| 62 | const listFile = path.join(CACHE, `top-${TOP}.json`); |
| 63 | let top; |
| 64 | if (fs.existsSync(listFile)) top = JSON.parse(fs.readFileSync(listFile, 'utf8')); |
| 65 | else { |
| 66 | top = []; |
| 67 | for (let off = 0; off < TOP; off += 100) { |
| 68 | const j = await getJson(`${API}/api/-/search?size=${Math.min(100, TOP - off)}&offset=${off}&sortBy=downloadCount&sortOrder=desc`); |
| 69 | top.push(...j.extensions.map((e, i) => ({ rank: off + i + 1, namespace: e.namespace, name: e.name, version: e.version, downloads: e.downloadCount }))); |
| 70 | await sleep(PAUSE); |
| 71 | } |
| 72 | fs.writeFileSync(listFile, JSON.stringify({ date: new Date().toISOString().slice(0, 10), list: top }, null, 1)); |
| 73 | top = JSON.parse(fs.readFileSync(listFile, 'utf8')); |
| 74 | } |
| 75 | const listDate = top.date; |
| 76 | top = top.list; |
| 77 | |
| 78 | // ── 2. sus package.json (4 a la vez, con pausa), en caché ── |
| 79 | // Las extensiones por plataforma pueden publicar una compilación «web» para |
| 80 | // el navegador: si existe, es la que cuenta (y la que se instalaría). |
| 81 | async function manifestOf(e) { |
| 82 | const file = path.join(CACHE, `${e.namespace}.${e.name}.json`); |
| 83 | if (fs.existsSync(file)) { |
| 84 | const c = JSON.parse(fs.readFileSync(file, 'utf8')); |
| 85 | if (c.variant || c.targetPlatform === 'universal') return c; |
| 86 | } |
| 87 | const base = `${API}/api/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.name)}`; |
| 88 | let meta = await getJson(base); |
| 89 | let variant = (meta.targetPlatform || 'universal') === 'universal' ? 'universal' : 'platform'; |
| 90 | if (variant === 'platform' && meta.downloads && meta.downloads.web) { |
| 91 | meta = await getJson(base + '/web'); |
| 92 | variant = 'web'; |
| 93 | } |
| 94 | const manifest = meta.files?.manifest ? await getJson(meta.files.manifest) : null; |
| 95 | const out = { version: meta.version, targetPlatform: meta.targetPlatform || 'universal', variant, license: meta.license || '', manifest }; |
| 96 | fs.writeFileSync(file, JSON.stringify(out)); |
| 97 | return out; |
| 98 | } |
| 99 | const withManifest = []; |
| 100 | for (let i = 0; i < top.length; i += 4) { |
| 101 | const batch = top.slice(i, i + 4); |
| 102 | const got = await Promise.all(batch.map(async e => { try { return { ...e, ...(await manifestOf(e)) }; } catch (err) { return { ...e, error: String(err.message || err) }; } })); |
| 103 | withManifest.push(...got); |
| 104 | if (got.some(g => !fs.existsSync(path.join(CACHE, `${g.namespace}.${g.name}.json`)))) await sleep(PAUSE); |
| 105 | } |
| 106 | const browserOnes = withManifest.filter(e => e.manifest && typeof e.manifest.browser === 'string' && (!ONLY || ONLY.has(`${e.namespace}.${e.name}`.toLowerCase()))); |
| 107 | console.log(`top ${TOP} (${listDate}): ${withManifest.filter(e => e.manifest).length} manifests read, ${withManifest.filter(e => e.manifest && typeof e.manifest.browser === 'string').length} with a browser entry`); |
| 108 | |
| 109 | // ── 3. en ejecución, una a una ── |
| 110 | const SAMPLES = { javascript: 'js', typescript: 'ts', json: 'json', jsonc: 'jsonc', markdown: 'md', html: 'html', css: 'css', scss: 'scss', less: 'less', python: 'py', |
| 111 | yaml: 'yaml', xml: 'xml', plaintext: 'txt', shellscript: 'sh', go: 'go', rust: 'rs', java: 'java', c: 'c', cpp: 'cpp', csharp: 'cs', php: 'php', ruby: 'rb', sql: 'sql', |
| 112 | toml: 'toml', ini: 'ini', dockerfile: 'Dockerfile', makefile: 'Makefile', vue: 'vue', svelte: 'svelte', javascriptreact: 'jsx', typescriptreact: 'tsx', lua: 'lua', dart: 'dart' }; |
| 113 | const SAMPLE_TEXT = 'hello world\n// TODO: check\nfoo bar\n'; |
| 114 | const srv = await startServer(); |
| 115 | const beacon = await startBeacon(); |
| 116 | const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] }); |
| 117 | const vendor = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8')); |
| 118 | const results = {}; |
| 119 | |
| 120 | for (const [k, e] of browserOnes.entries()) { |
| 121 | const id = `${e.namespace}.${e.name}`.toLowerCase(); |
| 122 | const key = `${id}@${e.version}`; |
| 123 | const r = { rank: e.rank, downloads: e.downloads }; |
| 124 | results[key] = r; |
| 125 | const a = analyzeManifest(e.manifest); |
| 126 | r.declarative = Object.fromEntries(Object.entries(a.applies).filter(([, n]) => n)); |
| 127 | r.workbench = Object.keys(e.manifest.contributes || {}).filter(c => ['views', 'viewsContainers', 'viewsWelcome', 'customEditors', 'notebooks', 'notebookRenderer', 'walkthroughs', 'debuggers', 'breakpoints', 'terminal', 'taskDefinitions', 'problemMatchers', 'authentication', 'chatParticipants', 'languageModelTools', 'mcpServerDefinitionProviders', 'resourceLabelFormatters'].includes(c)); |
| 128 | if (Array.isArray(e.manifest.enabledApiProposals) && e.manifest.enabledApiProposals.length) r.apiProposals = e.manifest.enabledApiProposals.length; |
| 129 | // (sin nombrar la plataforma: solo si es la compilación web o una por plataforma) |
| 130 | if (e.variant && e.variant !== 'universal') r.variant = e.variant; |
| 131 | let pkg, lv; |
| 132 | try { |
| 133 | const v = await fetchVsix({ namespace: e.namespace, name: e.name, version: e.version, targetPlatform: e.variant === 'web' ? 'web' : '' }); |
| 134 | pkg = await readCode(v.bytes); |
| 135 | lv = await readVsix(v.bytes).catch(() => null); |
| 136 | } catch (err) { |
| 137 | r.state = 'install-failed'; |
| 138 | // los topes de tamaño del nivel 2 (32 MiB por fichero, 64 MiB por extensión) |
| 139 | r.error = err?.code === 'big' ? (/descomprime demasiado/.test(err.message) ? 'over the 64 MiB limit for one extension' : 'a file over the 32 MiB limit') : String(err.message || err).slice(0, 300); |
| 140 | console.log(`${k + 1}/${browserOnes.length} ${key}: install failed (${r.error})`); |
| 141 | continue; |
| 142 | } |
| 143 | r.bytes = pkg.bytes; |
| 144 | const ctx = await browser.newContext(); |
| 145 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } }); |
| 146 | const page = await ctx.newPage(); |
| 147 | try { |
| 148 | await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' }); |
| 149 | const langs = lv?.languages || []; |
| 150 | const files = new Map([['sample.txt', SAMPLE_TEXT], ['sample.js', SAMPLE_TEXT]]); |
| 151 | for (const l of langs) { |
| 152 | const name = l.filenames?.[0] || (l.extensions?.[0] ? 'sample' + l.extensions[0] : null); |
| 153 | if (name && /^[\w.+-]{1,60}$/.test(name)) files.set(name, SAMPLE_TEXT); |
| 154 | } |
| 155 | for (const ev of Array.isArray(e.manifest.activationEvents) ? e.manifest.activationEvents : []) { |
| 156 | const m = /^onLanguage:(.+)$/.exec(ev); |
| 157 | if (m && SAMPLES[m[1]]) files.set(/^[A-Z]/.test(SAMPLES[m[1]]) ? SAMPLES[m[1]] : 'sample.' + SAMPLES[m[1]], SAMPLE_TEXT); |
| 158 | } |
| 159 | await page.evaluate(async files => { |
| 160 | const o = await navigator.storage.getDirectory(); |
| 161 | for (const [n, t] of files) { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); } |
| 162 | }, [...files]); |
| 163 | await seedReal(page, pkg, { languages: langs }); |
| 164 | await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 165 | await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 }); |
| 166 | // (una que el recinto rechaza —sustituye el tecleo— se queda fuera y, si era |
| 167 | // la única, el recinto se desmonta: eso es «no soportada», no un fallo) |
| 168 | const st = await until(() => page.evaluate(async id => { |
| 169 | const b = await import('/js/ext2/bridge.js'); |
| 170 | const s = b.state(); |
| 171 | return s.state === 'running' || s.state === 'error' || s.extensions.some(x => x.id === id && x.state === 'unsupported') ? s : null; |
| 172 | }, id), { timeout: 60000 }); |
| 173 | const refusedNow = st?.extensions?.find(x => x.id === id && x.state === 'unsupported'); |
| 174 | if (refusedNow) { r.state = 'unsupported'; r.unsupported = 'replaces typing'; r.error = (refusedNow.text || '').slice(0, 300); r.contributedCommands = (e.manifest.contributes?.commands || []).length; continue; } |
| 175 | if (st?.state !== 'running') { r.state = 'sandbox-error'; r.error = st?.error?.message || 'no start'; continue; } |
| 176 | // Los documentos de muestra se abren con el recinto YA en marcha, uno a |
| 177 | // uno, como los abriría alguien: cada uno llega a las extensiones y |
| 178 | // dispara su onLanguage. (Que las pestañas abiertas ANTES de arrancar |
| 179 | // también lleguen lo prueba tests/x2_ux.mjs, X11.) |
| 180 | for (const n of [...files.keys()].slice(0, 12)) await page.evaluate(async n => { await (await import('/js/ide.js')).openFile(n); }, n).catch(() => {}); |
| 181 | // Lo que la extensión le pregunte al usuario (avisos, diálogos, selectores, |
| 182 | // abrir direcciones) se contesta como lo haría alguien con prisa: cerrar o |
| 183 | // cancelar. Una extensión que espera esa respuesta para terminar de |
| 184 | // arrancar arranca igual, y se cuenta qué pidió. |
| 185 | await page.evaluate(() => { |
| 186 | const c = window.__x2asked = { toasts: 0, dialogs: 0, picks: 0, opens: 0 }; |
| 187 | setInterval(() => { |
| 188 | for (const x of document.querySelectorAll('#x2-toasts .x2-toast-close')) { c.toasts++; x.click(); } |
| 189 | for (const [sel, k] of [['#x2-dialog', 'dialogs'], ['#x2-pick', 'picks'], ['#x2-input', 'picks'], ['#x2-open', 'opens']]) { |
| 190 | const d = document.querySelector(sel); |
| 191 | if (!d) continue; |
| 192 | c[k]++; |
| 193 | // (los selectores escuchan en su campo; los diálogos, en el documento) |
| 194 | (d.querySelector('input') || d.querySelector('[role="dialog"]') || d).dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); |
| 195 | } |
| 196 | }, 300); |
| 197 | }); |
| 198 | const events = ['onStartupFinished', '*', ...((e.manifest.contributes?.commands || []).map(c => c && typeof c.command === 'string' ? 'onCommand:' + c.command : null).filter(Boolean).slice(0, 50))]; |
| 199 | await page.evaluate(async events => { const b = await import('/js/ext2/bridge.js'); for (const ev of events) b.activate(ev); }, events); |
| 200 | const ext = await until(async () => { |
| 201 | const s = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).state()); |
| 202 | const x = s.extensions.find(y => y.id === id); |
| 203 | return x && ['active', 'error', 'unsupported', 'stopped'].includes(x.state) ? x : null; |
| 204 | }, { timeout: 20000 }); |
| 205 | await sleep(2000); |
| 206 | const stats = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).stats()); |
| 207 | const finalState = (await page.evaluate(async () => (await import('/js/ext2/bridge.js')).state())).extensions.find(y => y.id === id); |
| 208 | r.state = finalState?.state === 'active' || ext?.state === 'active' ? 'active' : finalState?.state || 'not-activated'; |
| 209 | if (finalState?.text) r.error = finalState.text.slice(0, 300); |
| 210 | const xs = stats?.extensions?.[id]; |
| 211 | if (xs?.activationError) r.activation = 'failed'; |
| 212 | else if (xs && !xs.activated) r.activation = xs.started ? 'started, never finished' : 'no activation event fired'; |
| 213 | if (xs?.errors?.length && !r.error) r.error = xs.errors.join(' · ').slice(0, 300); |
| 214 | if (process.env.X2_CENSUS_DEBUG) console.log(' commands:', JSON.stringify(stats?.commands?.slice(0, 12)), 'status:', JSON.stringify(xs)); |
| 215 | r.commands = stats?.commands?.length || 0; |
| 216 | r.contributedCommands = (e.manifest.contributes?.commands || []).length; |
| 217 | r.providers = stats?.providers || {}; |
| 218 | if (stats && Object.keys(stats.later || {}).length) r.later = stats.later; |
| 219 | r.diagnostics = (stats?.markers || 0) > 0; |
| 220 | if (stats?.unsupported?.length || finalState?.state === 'unsupported') r.unsupported = 'replaces typing'; |
| 221 | const unsupportedCalls = (stats?.errors || []).filter(t => /not supported/.test(t)).map(t => (/Unsupported: ([\w$.]+)/.exec(t) || [])[1]).filter(Boolean); |
| 222 | if (unsupportedCalls.length) r.unsupportedCalls = [...new Set(unsupportedCalls)].slice(0, 10); |
| 223 | const otherErrors = (stats?.errors || []).filter(t => !/not supported/.test(t)); |
| 224 | if (otherErrors.length) r.sandboxErrors = otherErrors.length; |
| 225 | const asked = await page.evaluate(() => window.__x2asked || null).catch(() => null); |
| 226 | if (asked && Object.values(asked).some(Boolean)) r.askedUser = Object.fromEntries(Object.entries(asked).filter(([, n]) => n)); |
| 227 | } catch (err) { |
| 228 | r.state = r.state || 'census-error'; |
| 229 | r.error = String(err.message || err).slice(0, 300); |
| 230 | } finally { |
| 231 | await ctx.close().catch(() => {}); |
| 232 | const prov = Object.entries(r.providers || {}).map(([k2, n]) => `${k2}:${n}`).join(','); |
| 233 | console.log(`${k + 1}/${browserOnes.length} ${key}: ${r.state}${r.error ? ' (' + r.error.slice(0, 80) + ')' : ''} commands ${r.commands ?? '-'}/${r.contributedCommands ?? '-'} ${prov}`); |
| 234 | await sleep(PAUSE); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | await browser.close(); |
| 239 | const hits = beacon.hits.length; |
| 240 | await beacon.close(); |
| 241 | await srv.close(); |
| 242 | |
| 243 | // ── 4. resumen y tested.json ── |
| 244 | let merged = results; |
| 245 | let reruns = null; |
| 246 | if (ONLY && MERGE && fs.existsSync(OUT)) { |
| 247 | const prev = JSON.parse(fs.readFileSync(OUT, 'utf8')); |
| 248 | merged = { ...prev.results }; |
| 249 | for (const k of Object.keys(merged)) if (ONLY.has(k.split('@')[0])) delete merged[k]; |
| 250 | Object.assign(merged, results); |
| 251 | reruns = [...(prev.reruns || []), { date: new Date().toISOString().slice(0, 10), ids: Object.keys(results) }]; |
| 252 | } |
| 253 | const all = Object.values(merged); |
| 254 | const useful = x => x.state === 'active' && (x.commands > 0 || Object.keys(x.providers || {}).length > 0 || x.diagnostics); |
| 255 | const counts = { |
| 256 | topN: TOP, listDate, browserEntry: all.length, |
| 257 | installed: all.filter(x => x.state !== 'install-failed').length, |
| 258 | active: all.filter(x => x.state === 'active').length, |
| 259 | activeAndUseful: all.filter(useful).length, |
| 260 | activeNothingRegistered: all.filter(x => x.state === 'active' && !useful(x)).length, |
| 261 | error: all.filter(x => x.state === 'error').length, |
| 262 | notActivated: all.filter(x => ['installed', 'not-activated'].includes(x.state)).length, |
| 263 | unsupported: all.filter(x => x.state === 'unsupported' || x.unsupported).length, |
| 264 | installFailed: all.filter(x => x.state === 'install-failed').length, |
| 265 | sandboxOrCensusError: all.filter(x => ['sandbox-error', 'census-error'].includes(x.state)).length, |
| 266 | withWorkbenchContributions: all.filter(x => x.workbench?.length).length, |
| 267 | withFormatter: all.filter(x => x.state === 'active' && (x.providers?.format || x.providers?.formatRange)).length, |
| 268 | beaconHits: hits, |
| 269 | }; |
| 270 | const out = { |
| 271 | schema: 1, date: new Date().toISOString().slice(0, 10), vscode: vendor.vscode, library: vendor.library, buildId: vendor.buildId, |
| 272 | method: `Runtime census: the top ${TOP} Open VSX extensions by downloads (list of ${listDate}) that have a browser entry, each installed from its verified .vsix and started alone in the real sandbox; once the sandbox ran, one sample document per language was opened; activation events fired: those documents' languages, onStartupFinished, * and onCommand for each contributed command (no command was executed).`, |
| 273 | counts, ...(reruns ? { reruns } : {}), results: merged, |
| 274 | }; |
| 275 | if (!ONLY || MERGE) fs.writeFileSync(OUT, JSON.stringify(out, null, 1) + '\n'); |
| 276 | console.log('\n' + JSON.stringify(counts, null, 1)); |
| 277 | if (hits) console.log(`\n❌ the beacon recorded ${hits} hits: a sandbox leak`); |
| 278 | process.exit(hits ? 1 : 0); |