| 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 | // 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 | } |
| 33 | ok('SHA-256 de los dos .vsix coincide con la publicada y con la fijada', pkgs.length === 2); |
| 34 | |
| 35 | const 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 | }; |
| 41 | const CODE = need('X2_CODE'), SANDBOX = need('X2_SANDBOX'); |
| 42 | const srv = { codeOrigin: CODE.origin }; |
| 43 | const reqs = []; |
| 44 | const browser = await chromium.launch(); |
| 45 | const ctx = await browser.newContext(); |
| 46 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } }); |
| 47 | const page = await ctx.newPage(); |
| 48 | 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 {} }); |
| 49 | const errors = [], x2log = []; |
| 50 | page.on('console', m => { if (m.text().includes('[x2]')) x2log.push(m.text().slice(0, 600)); }); |
| 51 | 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) })); }); |
| 52 | await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' }); |
| 53 | await 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 | }); |
| 59 | for (const pkg of pkgs) await seedReal(page, pkg); |
| 60 | const since = reqs.length; |
| 61 | await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 62 | await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 }); |
| 63 | const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p); |
| 64 | const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue()); |
| 65 | const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state()); |
| 66 | |
| 67 | await open('fruits.txt'); |
| 68 | const st = await until(async () => { const s = await state(); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 }); |
| 69 | ok('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 |
| 72 | const entries = await until(async () => { const c = (await state()).commands; return c.some(e => e.id === 'sortLines.sortLines') ? c : null; }); |
| 73 | ok('sort-lines aporta sus comandos a la paleta', !!entries && entries.length >= 10, entries ? entries.length + ' commands' : 'none'); |
| 74 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 6, endColumn: 5 }); ed.focus(); }); |
| 75 | await sleep(300); |
| 76 | await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().find(e => e.id === 'sortLines.sortLines').run()); |
| 77 | 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())); |
| 78 | |
| 79 | // Prettier: Format Document |
| 80 | await open('ugly.js'); |
| 81 | await until(async () => (await state()).extensions.find(e => e.id === 'esbenp.prettier-vscode')?.state === 'active', { timeout: 60000 }); |
| 82 | let formatted = null; |
| 83 | for (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 | } |
| 87 | ok('Format Document con Prettier', !!formatted, JSON.stringify(await value())); |
| 88 | |
| 89 | // sus ajustes llegan al recinto: sin punto y coma |
| 90 | await 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 | }); |
| 98 | await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('const y = {a:1}\n')); |
| 99 | let semi = null; |
| 100 | for (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 | } |
| 104 | ok('los ajustes de la extensión llegan («prettier.semi»: false)', !!semi, JSON.stringify(await value())); |
| 105 | |
| 106 | await sleep(1000); |
| 107 | const after = reqs.slice(since); |
| 108 | const sandboxDocs = [...new Set(after.filter(r => r.host === SANDBOX.host).map(r => r.path))]; |
| 109 | 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(' ')); |
| 110 | const fromSandbox = [...new Set(after.filter(r => r.frameHost === SANDBOX.host && r.host !== '' && r.host !== SANDBOX.host).map(r => r.host + r.path))]; |
| 111 | ok('los marcos del recinto no piden nada a ningún otro sitio', fromSandbox.length === 0, fromSandbox.slice(0, 5).join(' ')); |
| 112 | const buildId = await page.evaluate(async () => (await (await fetch('/js/ext2/vendor-manifest.json', { cache: 'no-store' })).json()).buildId).catch(() => null); |
| 113 | const vendor = [...new Set(after.filter(r => r.path.startsWith('/vendor/x2/')).map(r => r.host + r.path))]; |
| 114 | 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(' ')); |
| 115 | ok('sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | ')); |
| 116 | const sandboxErrors = x2log.filter(t => /unhandled|uncaught/.test(t)); |
| 117 | if (sandboxErrors.length) console.log('errores dentro del recinto (registro de la página):\n' + sandboxErrors.slice(0, 8).join('\n')); |
| 118 | |
| 119 | await browser.close(); |
| 120 | console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed'); |
| 121 | process.exit(fails ? 1 : 0); |