Elffuss BraidHub

utopia-ia/elffuss-code public

main · 6.8 KiBRawPermalink
1// Nivel 2 con extensiones REALES de Open VSX (punto de control de B1):
2// Tyriar.sort-lines 1.12.0 (un comando) y esbenp.prettier-vscode 12.4.0 (un
3// formateador), con versión y SHA-256 fijadas, corriendo en el recinto.
4//
5// node tests/x2_live.mjs
6//
7// Necesita red la primera vez (luego usa tests/.cache/vsix/); sin red y sin
8// caché, NOT RUN. Comprueba: el comando de sort-lines desde las entradas de
9// la paleta de Code, Format Document con Prettier (y que sus ajustes llegan),
10// la baliza a 0 y que del recinto solo se piden sus dos documentos.
11import { chromium } from 'playwright';
12import { startServer } from './lib/x2-server.mjs';
13import { startBeacon } from './lib/beacon.mjs';
14import { fetchVsix, readCode, seedReal, PINNED } from './lib/x2-vsix.mjs';
15
16let fails = 0;
17const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
18const sleep = ms => new Promise(r => setTimeout(r, ms));
19async function until(fn, { timeout = 30000, every = 200 } = {}) {
20 const end = Date.now() + timeout;
21 let v;
22 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
23 return v;
24}
25
26const pkgs = [];
27for (const p of PINNED) {
28 try { pkgs.push(await readCode((await fetchVsix({ ...p, offline: process.env.X2_OFFLINE === '1' })).bytes)); }
29 catch (e) { console.log(`⏭️ NOT RUN x2_live — ${p.namespace}.${p.name}@${p.version}: ${e.message}`); process.exit(0); }
30}
31ok('SHA-256 de los dos .vsix coincide con la publicada y con la fijada', pkgs.length === 2);
32
33const srv = await startServer();
34const beacon = await startBeacon();
35const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
36const ctx = await browser.newContext();
37await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
38const page = await ctx.newPage();
39const errors = [], x2log = [];
40page.on('console', m => { if (m.text().includes('[x2]')) x2log.push(m.text().slice(0, 600)); });
41page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(JSON.stringify({ name: e.name, message: e.message, stack: String(e.stack || '').slice(0, 400) })); });
42await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
43await page.evaluate(async () => {
44 const o = await navigator.storage.getDirectory();
45 const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
46 await w('fruits.txt', 'pear\napple\nfig\nbanana\ncherry\ndate\n');
47 await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
48});
49for (const pkg of pkgs) await seedReal(page, pkg);
50const since = srv.requests.length;
51await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
52await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
53const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
54const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
55const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
56
57await open('fruits.txt');
58const st = await until(async () => { const s = await state(); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 });
59ok('el recinto arranca con las dos extensiones', st?.state === 'running', JSON.stringify(st?.error));
60
61// sort-lines: su comando, desde las entradas de la paleta de Code
62const entries = await until(async () => { const c = (await state()).commands; return c.some(e => e.id === 'sortLines.sortLines') ? c : null; });
63ok('sort-lines aporta sus comandos a la paleta', !!entries && entries.length >= 10, entries ? entries.length + ' commands' : 'none');
64await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 6, endColumn: 5 }); ed.focus(); });
65await sleep(300);
66await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().find(e => e.id === 'sortLines.sortLines').run());
67ok('Sort Lines (Tyriar.sort-lines) ordena el texto en el editor de Code', !!(await until(async () => (await value()) === 'apple\nbanana\ncherry\ndate\nfig\npear\n')), JSON.stringify(await value()));
68
69// Prettier: Format Document
70await open('ugly.js');
71await until(async () => (await state()).extensions.find(e => e.id === 'esbenp.prettier-vscode')?.state === 'active', { timeout: 60000 });
72let formatted = null;
73for (let i = 0; i < 20 && !formatted; i++) {
74 await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
75 formatted = await until(async () => { const v = await value(); return v === 'const x = { a: 1, b: [1, 2, 3] };\n' ? v : null; }, { timeout: 1500 });
76}
77ok('Format Document con Prettier', !!formatted, JSON.stringify(await value()));
78
79// sus ajustes llegan al recinto: sin punto y coma
80await page.evaluate(async () => {
81 const store = await import('/js/ext/store.js');
82 const rec = await store.get('esbenp.prettier-vscode');
83 rec.settings = { 'prettier.semi': false };
84 await store.put(rec, new Map());
85 const host = await (await import('/js/ide.js')).loadExt();
86 await host.setEnabled('esbenp.prettier-vscode', true);
87});
88await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('const y = {a:1}\n'));
89let semi = null;
90for (let i = 0; i < 20 && !semi; i++) {
91 await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
92 semi = await until(async () => { const v = await value(); return v === 'const y = { a: 1 }\n' ? v : null; }, { timeout: 1500 });
93}
94ok('los ajustes de la extensión llegan («prettier.semi»: false)', !!semi, JSON.stringify(await value()));
95
96await sleep(1000);
97ok('baliza: 0 visitas', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
98const sandboxReqs = [...new Set(srv.requests.slice(since).filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
99ok('del recinto solo sus dos documentos', sandboxReqs.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sandboxReqs.join(' '));
100ok('sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | '));
101const sandboxErrors = x2log.filter(t => /unhandled|uncaught/.test(t));
102if (sandboxErrors.length) console.log('errores dentro del recinto (registro de la página):\n' + sandboxErrors.slice(0, 8).join('\n'));
103
104await browser.close();
105await beacon.close();
106await srv.close();
107console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
108process.exit(fails ? 1 : 0);