Elffuss BraidHub

utopia-ia/elffuss-code public

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