Elffuss BraidHub

utopia-ia/elffuss-code public

main · 8.2 KiBRawPermalink
1// Nivel 2 en PRODUCCIÓN: humo después de cada despliegue de Code. Es x2_live
2// (sort-lines 1.12.0 y Prettier 12.4.0, versión y SHA-256 fijadas) contra el
3// sitio publicado, sin servidor ni baliza propios: en su lugar comprueba, por el
4// origen de cada marco, que del recinto solo se piden sus dos documentos y que
5// los marcos del recinto no piden nada a ningún otro sitio.
6//
7// X2_CODE=https://code.elffuss.com X2_SANDBOX=https://x2.utopiaia.com node tests/x2_live_prod.mjs
8//
9// Falla (no se salta) si falta alguna de las dos variables o si no son https:
10// contra un servidor local daría por bueno algo que no es producción. Escribe
11// solo en el perfil temporal del propio navegador de la prueba. No va en
12// run-modes.sh, que corre contra el árbol local.
13import { chromium } from 'playwright';
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 // Exit 2, no 0: es un humo de producción que se encadena tras un despliegue,
30 // y un «no se ha podido mirar» que sale con 0 se lee como «producción bien».
31 catch (e) { console.log(`⏭️ NOT RUN x2_live_prod — ${p.namespace}.${p.name}@${p.version}: ${e.message} (exit 2: NOT verified)`); process.exit(2); }
32}
33ok('SHA-256 de los dos .vsix coincide con la publicada y con la fijada', pkgs.length === 2);
34
35const need = (k) => {
36 const v = process.env[k];
37 let u = null; try { u = new URL(v); } catch { /* sin valor o no es una URL */ }
38 if (!u || u.protocol !== 'https:') { console.log(`❌ ${k} tiene que ser una URL https de producción (es ${JSON.stringify(v ?? null)})`); process.exit(1); }
39 return u;
40};
41const CODE = need('X2_CODE'), SANDBOX = need('X2_SANDBOX');
42const srv = { codeOrigin: CODE.origin };
43const reqs = [];
44const browser = await chromium.launch();
45const ctx = await browser.newContext();
46await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
47const page = await ctx.newPage();
48ctx.on('request', r => { try { const u = new URL(r.url()); let fo = ''; try { fo = new URL(r.frame().url()).host; } catch {} reqs.push({ host: u.host, path: u.pathname, frameHost: fo }); } catch {} });
49const errors = [], x2log = [];
50page.on('console', m => { if (m.text().includes('[x2]')) x2log.push(m.text().slice(0, 600)); });
51page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(JSON.stringify({ name: e.name, message: e.message, stack: String(e.stack || '').slice(0, 400) })); });
52await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
53await page.evaluate(async () => {
54 const o = await navigator.storage.getDirectory();
55 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(); };
56 await w('fruits.txt', 'pear\napple\nfig\nbanana\ncherry\ndate\n');
57 await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
58});
59for (const pkg of pkgs) await seedReal(page, pkg);
60const since = reqs.length;
61await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
62await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
63const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
64const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
65const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
66
67await open('fruits.txt');
68const st = await until(async () => { const s = await state(); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 });
69ok('el recinto arranca con las dos extensiones', st?.state === 'running', JSON.stringify(st?.error));
70
71// sort-lines: su comando, desde las entradas de la paleta de Code
72const entries = await until(async () => { const c = (await state()).commands; return c.some(e => e.id === 'sortLines.sortLines') ? c : null; });
73ok('sort-lines aporta sus comandos a la paleta', !!entries && entries.length >= 10, entries ? entries.length + ' commands' : 'none');
74await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 6, endColumn: 5 }); ed.focus(); });
75await sleep(300);
76await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().find(e => e.id === 'sortLines.sortLines').run());
77ok('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()));
78
79// Prettier: Format Document
80await open('ugly.js');
81await until(async () => (await state()).extensions.find(e => e.id === 'esbenp.prettier-vscode')?.state === 'active', { timeout: 60000 });
82let formatted = null;
83for (let i = 0; i < 20 && !formatted; i++) {
84 await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
85 formatted = await until(async () => { const v = await value(); return v === 'const x = { a: 1, b: [1, 2, 3] };\n' ? v : null; }, { timeout: 1500 });
86}
87ok('Format Document con Prettier', !!formatted, JSON.stringify(await value()));
88
89// sus ajustes llegan al recinto: sin punto y coma
90await page.evaluate(async () => {
91 const store = await import('/js/ext/store.js');
92 const rec = await store.get('esbenp.prettier-vscode');
93 rec.settings = { 'prettier.semi': false };
94 await store.put(rec, new Map());
95 const host = await (await import('/js/ide.js')).loadExt();
96 await host.setEnabled('esbenp.prettier-vscode', true);
97});
98await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('const y = {a:1}\n'));
99let semi = null;
100for (let i = 0; i < 20 && !semi; i++) {
101 await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
102 semi = await until(async () => { const v = await value(); return v === 'const y = { a: 1 }\n' ? v : null; }, { timeout: 1500 });
103}
104ok('los ajustes de la extensión llegan («prettier.semi»: false)', !!semi, JSON.stringify(await value()));
105
106await sleep(1000);
107const after = reqs.slice(since);
108const sandboxDocs = [...new Set(after.filter(r => r.host === SANDBOX.host).map(r => r.path))];
109ok(`del recinto (${SANDBOX.host}) solo sus dos documentos`, sandboxDocs.length > 0 && sandboxDocs.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sandboxDocs.join(' '));
110const fromSandbox = [...new Set(after.filter(r => r.frameHost === SANDBOX.host && r.host !== '' && r.host !== SANDBOX.host).map(r => r.host + r.path))];
111ok('los marcos del recinto no piden nada a ningún otro sitio', fromSandbox.length === 0, fromSandbox.slice(0, 5).join(' '));
112const buildId = await page.evaluate(async () => (await (await fetch('/js/ext2/vendor-manifest.json', { cache: 'no-store' })).json()).buildId).catch(() => null);
113const vendor = [...new Set(after.filter(r => r.path.startsWith('/vendor/x2/')).map(r => r.host + r.path))];
114ok(`el bundle llega desde ${CODE.host}/vendor/x2/${buildId}/`, !!buildId && vendor.length >= 1 && vendor.every(u => u.startsWith(`${CODE.host}/vendor/x2/${buildId}/`)), vendor.join(' '));
115ok('sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | '));
116const sandboxErrors = x2log.filter(t => /unhandled|uncaught/.test(t));
117if (sandboxErrors.length) console.log('errores dentro del recinto (registro de la página):\n' + sandboxErrors.slice(0, 8).join('\n'));
118
119await browser.close();
120console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
121process.exit(fails ? 1 : 0);