Elffuss BraidHub

utopia-ia/elffuss-code public

Level 2 smoke against production: x2_live_prod

The same real extensions as x2_live (sort-lines and Prettier, pinned) run on the
published Code, with the sandbox checked by frame origin instead of a local
beacon: only its two documents are requested from the sandbox site, its frames
request nothing elsewhere, and the bundle comes from the build the served
manifest names. Hosts come from X2_CODE and X2_SANDBOX; it fails, never skips,
when either is missing or not https, so it cannot pass against a local server.
Not part of run-modes.sh.
Changeset011bd456b23abed71e1f9e6e57927c501776672a98cce54b638177282d81ff60
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-13 12:36 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-13 12:36 +02:00
Parentseeafa8b53e66

Browse the files at this changeset

1 file changed

added tests/x2_live_prod.mjs +119 −0
@@ -0,0 +1,119 @@
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.
13+import { chromium } from 'playwright';
14+import { fetchVsix, readCode, seedReal, PINNED } from './lib/x2-vsix.mjs';
15+
16+let fails = 0;
17+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
18+const sleep = ms => new Promise(r => setTimeout(r, ms));
19+async 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+
26+const pkgs = [];
27+for (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+}
31+ok('SHA-256 de los dos .vsix coincide con la publicada y con la fijada', pkgs.length === 2);
32+
33+const need = (k) => {
34+ const v = process.env[k];
35+ let u = null; try { u = new URL(v); } catch { /* sin valor o no es una URL */ }
36+ 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); }
37+ return u;
38+};
39+const CODE = need('X2_CODE'), SANDBOX = need('X2_SANDBOX');
40+const srv = { codeOrigin: CODE.origin };
41+const reqs = [];
42+const browser = await chromium.launch();
43+const ctx = await browser.newContext();
44+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
45+const page = await ctx.newPage();
46+ctx.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 {} });
47+const errors = [], x2log = [];
48+page.on('console', m => { if (m.text().includes('[x2]')) x2log.push(m.text().slice(0, 600)); });
49+page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(JSON.stringify({ name: e.name, message: e.message, stack: String(e.stack || '').slice(0, 400) })); });
50+await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
51+await page.evaluate(async () => {
52+ const o = await navigator.storage.getDirectory();
53+ 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(); };
54+ await w('fruits.txt', 'pear\napple\nfig\nbanana\ncherry\ndate\n');
55+ await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
56+});
57+for (const pkg of pkgs) await seedReal(page, pkg);
58+const since = reqs.length;
59+await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
60+await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
61+const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
62+const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
63+const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
64+
65+await open('fruits.txt');
66+const st = await until(async () => { const s = await state(); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 });
67+ok('el recinto arranca con las dos extensiones', st?.state === 'running', JSON.stringify(st?.error));
68+
69+// sort-lines: su comando, desde las entradas de la paleta de Code
70+const entries = await until(async () => { const c = (await state()).commands; return c.some(e => e.id === 'sortLines.sortLines') ? c : null; });
71+ok('sort-lines aporta sus comandos a la paleta', !!entries && entries.length >= 10, entries ? entries.length + ' commands' : 'none');
72+await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 6, endColumn: 5 }); ed.focus(); });
73+await sleep(300);
74+await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().find(e => e.id === 'sortLines.sortLines').run());
75+ok('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()));
76+
77+// Prettier: Format Document
78+await open('ugly.js');
79+await until(async () => (await state()).extensions.find(e => e.id === 'esbenp.prettier-vscode')?.state === 'active', { timeout: 60000 });
80+let formatted = null;
81+for (let i = 0; i < 20 && !formatted; i++) {
82+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
83+ formatted = await until(async () => { const v = await value(); return v === 'const x = { a: 1, b: [1, 2, 3] };\n' ? v : null; }, { timeout: 1500 });
84+}
85+ok('Format Document con Prettier', !!formatted, JSON.stringify(await value()));
86+
87+// sus ajustes llegan al recinto: sin punto y coma
88+await page.evaluate(async () => {
89+ const store = await import('/js/ext/store.js');
90+ const rec = await store.get('esbenp.prettier-vscode');
91+ rec.settings = { 'prettier.semi': false };
92+ await store.put(rec, new Map());
93+ const host = await (await import('/js/ide.js')).loadExt();
94+ await host.setEnabled('esbenp.prettier-vscode', true);
95+});
96+await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('const y = {a:1}\n'));
97+let semi = null;
98+for (let i = 0; i < 20 && !semi; i++) {
99+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
100+ semi = await until(async () => { const v = await value(); return v === 'const y = { a: 1 }\n' ? v : null; }, { timeout: 1500 });
101+}
102+ok('los ajustes de la extensión llegan («prettier.semi»: false)', !!semi, JSON.stringify(await value()));
103+
104+await sleep(1000);
105+const after = reqs.slice(since);
106+const sandboxDocs = [...new Set(after.filter(r => r.host === SANDBOX.host).map(r => r.path))];
107+ok(`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(' '));
108+const fromSandbox = [...new Set(after.filter(r => r.frameHost === SANDBOX.host && r.host !== '' && r.host !== SANDBOX.host).map(r => r.host + r.path))];
109+ok('los marcos del recinto no piden nada a ningún otro sitio', fromSandbox.length === 0, fromSandbox.slice(0, 5).join(' '));
110+const buildId = await page.evaluate(async () => (await (await fetch('/js/ext2/vendor-manifest.json', { cache: 'no-store' })).json()).buildId).catch(() => null);
111+const vendor = [...new Set(after.filter(r => r.path.startsWith('/vendor/x2/')).map(r => r.host + r.path))];
112+ok(`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(' '));
113+ok('sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | '));
114+const sandboxErrors = x2log.filter(t => /unhandled|uncaught/.test(t));
115+if (sandboxErrors.length) console.log('errores dentro del recinto (registro de la página):\n' + sandboxErrors.slice(0, 8).join('\n'));
116+
117+await browser.close();
118+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
119+process.exit(fails ? 1 : 0);