| 1 | // Formatting with a real web extension: Prettier in Code. |
| 2 | // |
| 3 | // node tests/x2_format.mjs (own server; without the pinned .vsix in |
| 4 | // tests/.cache and no network: NOT RUN) |
| 5 | // |
| 6 | // esbenp.prettier-vscode 12.4.0 (pinned, SHA-256 checked) is installed with its |
| 7 | // code through Code's own install path for a .vsix file. |
| 8 | // |
| 9 | // F1 before it, Format Document uses Monaco's built-in formatter (the |
| 10 | // reference for F6 and F7) |
| 11 | // F2 Format Document with Prettier: `const x = {a:1,b:[1,2,3]}` becomes |
| 12 | // `const x = { a: 1, b: [1, 2, 3] };` |
| 13 | // F3 one undo step brings the text back; the tab shows unsaved changes; |
| 14 | // Cmd+S writes the formatted file to the project |
| 15 | // F4 Shift+Alt+F formats too |
| 16 | // F5 {"prettier.semi": false} in its settings changes the output |
| 17 | // F6 "built-in" as the formatter for javascript: Monaco formats again; |
| 18 | // back to Prettier |
| 19 | // F7 its code turned off: the sandbox stops and the built-in formatter is |
| 20 | // back; turned on again: Prettier formats |
| 21 | // F8 a race with an agent write: the extension's edit computed on the old |
| 22 | // text is discarded, the status bar says so, the agent's text stays, and |
| 23 | // the next format works on the new text |
| 24 | // F9 the beacon gets nothing, the sandbox site only its two documents, no |
| 25 | // page errors |
| 26 | import { chromium } from 'playwright'; |
| 27 | import { startServer } from './lib/x2-server.mjs'; |
| 28 | import { startBeacon } from './lib/beacon.mjs'; |
| 29 | import { fetchVsix, PINNED } from './lib/x2-vsix.mjs'; |
| 30 | |
| 31 | let fails = 0; |
| 32 | const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; }; |
| 33 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 34 | async function until(fn, { timeout = 20000, every = 150 } = {}) { |
| 35 | const end = Date.now() + timeout; |
| 36 | let v; |
| 37 | while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); } |
| 38 | return v; |
| 39 | } |
| 40 | const MOD = process.platform === 'darwin' ? 'Meta' : 'Control'; |
| 41 | |
| 42 | let prettier; |
| 43 | try { prettier = (await fetchVsix({ ...PINNED.find(p => p.name === 'prettier-vscode'), offline: process.env.X2_OFFLINE === '1' })).bytes; } |
| 44 | catch (e) { console.log(`⏭️ NOT RUN x2_format — esbenp.prettier-vscode@12.4.0: ${e.message}`); process.exit(0); } |
| 45 | |
| 46 | const UGLY = 'const x = {a:1,b:[1,2,3]}\n'; |
| 47 | const PRETTY = 'const x = { a: 1, b: [1, 2, 3] };\n'; |
| 48 | const NOSEMI = 'const x = { a: 1, b: [1, 2, 3] }\n'; |
| 49 | // un fichero largo: a Prettier le cuesta más que al agente escribir encima |
| 50 | const BIG = Array.from({ length: 1500 }, (_, i) => `const v${i} = {k:${i},list:[${i},${i + 1}]}`).join('\n') + '\n'; |
| 51 | |
| 52 | const srv = await startServer(); |
| 53 | const beacon = await startBeacon(); |
| 54 | const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] }); |
| 55 | const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } }); |
| 56 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } }); |
| 57 | const page = await ctx.newPage(); |
| 58 | const errors = []; |
| 59 | page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); }); |
| 60 | await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' }); |
| 61 | await page.evaluate(async ({ UGLY, BIG }) => { |
| 62 | const o = await navigator.storage.getDirectory(); |
| 63 | 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(); }; |
| 64 | await w('ugly.js', UGLY); |
| 65 | await w('big.js', BIG); |
| 66 | }, { UGLY, BIG }); |
| 67 | await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 68 | await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 }); |
| 69 | |
| 70 | const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p); |
| 71 | const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue()); |
| 72 | const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v); |
| 73 | const readOpfs = name => page.evaluate(async n => { const o = await navigator.storage.getDirectory(); return (await (await o.getFileHandle(n)).getFile()).text(); }, name); |
| 74 | const dirty = () => page.evaluate(() => document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty') || false); |
| 75 | const focusEditor = async () => { await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); await sleep(100); }; |
| 76 | const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); }); |
| 77 | const host = fn => page.evaluate(fn); |
| 78 | const bridgeState = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state()); |
| 79 | // formatea hasta obtener `want` (la primera vez Prettier carga sus analizadores) |
| 80 | async function formatsTo(want, tries = 20) { |
| 81 | for (let i = 0; i < tries; i++) { |
| 82 | await formatDoc(); |
| 83 | if (await until(async () => (await value()) === want, { timeout: 1500 })) return true; |
| 84 | } |
| 85 | return false; |
| 86 | } |
| 87 | |
| 88 | // ── F1: la referencia, sin extensiones ── |
| 89 | await open('ugly.js'); |
| 90 | // (el formateador de serie necesita su worker listo: se reintenta) |
| 91 | let builtin = null; |
| 92 | for (let i = 0; i < 20 && !builtin; i++) { |
| 93 | await formatDoc(); |
| 94 | builtin = await until(async () => { const v = await value(); return v !== UGLY ? v : null; }, { timeout: 1500 }); |
| 95 | } |
| 96 | ok('F1 with no extension, Format Document uses Monaco’s built-in formatter', builtin === NOSEMI, JSON.stringify(builtin)); |
| 97 | await setValue(UGLY); |
| 98 | |
| 99 | // ── instalar Prettier con su código ── |
| 100 | const id = await page.evaluate(async b64 => { |
| 101 | const bin = atob(b64); |
| 102 | const u8 = new Uint8Array(bin.length); |
| 103 | for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i); |
| 104 | const h = await (await import('/js/ide.js')).loadExt(); |
| 105 | return (await h.install(new File([u8], 'prettier.vsix'), { withCode: true })).id; |
| 106 | }, Buffer.from(prettier).toString('base64')); |
| 107 | const active = await until(async () => { const s = await bridgeState(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active' ? s : null; }, { timeout: 90000 }); |
| 108 | ok('Prettier installed with its code, running in the sandbox', !!active, JSON.stringify((await bridgeState()).extensions.map(e => [e.id, e.state, e.text]))); |
| 109 | |
| 110 | // ── F2–F3 ── |
| 111 | await page.keyboard.press(`${MOD}+KeyS`); |
| 112 | await until(async () => !(await dirty())); |
| 113 | ok('F2 Format Document with Prettier', await formatsTo(PRETTY), JSON.stringify(await value())); |
| 114 | ok('F3 the tab shows unsaved changes', !!(await until(() => dirty()))); |
| 115 | await focusEditor(); |
| 116 | await page.keyboard.press(`${MOD}+KeyZ`); |
| 117 | ok('F3 one undo step brings the text back', !!(await until(async () => (await value()) === UGLY)), JSON.stringify(await value())); |
| 118 | await page.keyboard.press(`${MOD}+Shift+KeyZ`); |
| 119 | await until(async () => (await value()) === PRETTY); |
| 120 | await page.keyboard.press(`${MOD}+KeyS`); |
| 121 | ok('F3 Cmd+S writes the formatted file to the project', !!(await until(async () => (await readOpfs('ugly.js')) === PRETTY && !(await dirty()))), JSON.stringify(await readOpfs('ugly.js'))); |
| 122 | |
| 123 | // ── F4: Shift+Alt+F ── |
| 124 | await setValue(UGLY); |
| 125 | let viaKeys = false; |
| 126 | for (let i = 0; i < 10 && !viaKeys; i++) { |
| 127 | await focusEditor(); |
| 128 | await page.keyboard.press('Shift+Alt+KeyF'); |
| 129 | viaKeys = !!(await until(async () => (await value()) === PRETTY, { timeout: 1500 })); |
| 130 | } |
| 131 | ok('F4 Shift+Alt+F formats with Prettier', viaKeys, JSON.stringify(await value())); |
| 132 | |
| 133 | // ── F5: sus ajustes ── |
| 134 | await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setSettings('esbenp.prettier-vscode', { 'prettier.semi': false }); }); |
| 135 | await setValue(UGLY); |
| 136 | ok('F5 {"prettier.semi": false} changes the output', await formatsTo(NOSEMI), JSON.stringify(await value())); |
| 137 | await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setSettings('esbenp.prettier-vscode', {}); }); |
| 138 | await setValue(UGLY); |
| 139 | ok('F5 and without it, the semicolons come back', await formatsTo(PRETTY), JSON.stringify(await value())); |
| 140 | |
| 141 | // ── F6: el formateador de serie para javascript, y vuelta ── |
| 142 | await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setFormatter('esbenp.prettier-vscode', 'javascript', 'builtin'); }); |
| 143 | await setValue(UGLY); |
| 144 | await sleep(500); |
| 145 | await formatDoc(); |
| 146 | ok('F6 "built-in" for javascript: Monaco formats, as with no extension', !!(await until(async () => (await value()) === builtin, { timeout: 8000 })), JSON.stringify(await value())); |
| 147 | await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setFormatter('esbenp.prettier-vscode', 'javascript', 'extension'); }); |
| 148 | await setValue(UGLY); |
| 149 | ok('F6 back to Prettier', await formatsTo(PRETTY), JSON.stringify(await value())); |
| 150 | |
| 151 | // ── F7: su código apagado y encendido ── |
| 152 | await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns('esbenp.prettier-vscode', false); }); |
| 153 | const off = await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')), { timeout: 15000 }); |
| 154 | await setValue(UGLY); |
| 155 | await sleep(300); |
| 156 | await formatDoc(); |
| 157 | ok('F7 its code off: the sandbox is gone and the built-in formatter is back', !!off && !!(await until(async () => (await value()) === builtin, { timeout: 8000 })), JSON.stringify(await value())); |
| 158 | await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns('esbenp.prettier-vscode', true, { confirm: async () => true }); }); |
| 159 | await until(async () => { const s = await bridgeState(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active'; }, { timeout: 90000 }); |
| 160 | await setValue(UGLY); |
| 161 | ok('F7 on again: Prettier formats', await formatsTo(PRETTY), JSON.stringify(await value())); |
| 162 | |
| 163 | // ── F8: carrera con una escritura del agente ── |
| 164 | // Para que la carrera sea la que importa (el cambio de la extensión llega a la |
| 165 | // página DESPUÉS de que el fichero cambiara), la página se queda ocupada justo |
| 166 | // tras pedir el formateo: el recinto (otro sitio, otro proceso) formatea y |
| 167 | // manda su cambio mientras tanto, y el agente escribe antes de que la página |
| 168 | // lo lea. Sin esa pausa, el propio VS Code del recinto suele tirar el cambio |
| 169 | // viejo, que también es seguro pero no prueba la comprobación de la página. |
| 170 | await open('big.js'); |
| 171 | await sleep(500); |
| 172 | const agentText = BIG.replace('const v0 =', 'const fromAgent ='); |
| 173 | await page.evaluate(async t => { |
| 174 | document.getElementById('statusbar').textContent = ''; |
| 175 | const bridge = await import('/js/ext2/bridge.js'); |
| 176 | window.__race = bridge.runCommand('prettier.forceFormatDocument'); // Prettier, sobre el texto de ahora |
| 177 | const end = Date.now() + 3000; |
| 178 | while (Date.now() < end) { /* la página, ocupada; el recinto, no */ } |
| 179 | window.monaco.editor.getEditors()[0].getModel().setValue(t); // lo que hace una escritura del agente al fichero abierto |
| 180 | }, agentText); |
| 181 | await page.evaluate(async t => { await (await import('/js/tools/code.js')).write({ path: 'big.js', content: t }); }, agentText); |
| 182 | await page.evaluate(() => window.__race); |
| 183 | const said = await until(() => page.evaluate(() => { const t = document.getElementById('statusbar').textContent; return /discarded because the file changed meanwhile/.test(t) ? t : null; }), { timeout: 15000 }); |
| 184 | await sleep(800); |
| 185 | ok('F8 the edit Prettier computed on the old text is discarded, and the status bar says so', !!said && (await value()) === agentText, JSON.stringify({ said, v: (await value()).slice(0, 60) })); |
| 186 | ok('F8 the agent’s text is in the project', (await readOpfs('big.js')) === agentText); |
| 187 | await open('ugly.js'); |
| 188 | await setValue('const y = {b:2}\n'); |
| 189 | ok('F8 the next format works', await formatsTo('const y = { b: 2 };\n'), JSON.stringify(await value())); |
| 190 | |
| 191 | // ── F9: privacidad ── |
| 192 | const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))]; |
| 193 | ok('F9 the sandbox site was asked only for its two documents', sbx.length > 0 && sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' ')); |
| 194 | ok('F9 beacon: 0 hits', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3))); |
| 195 | ok('F9 no page errors', errors.length === 0, errors.slice(0, 3).join(' | ')); |
| 196 | |
| 197 | await browser.close(); |
| 198 | await beacon.close(); |
| 199 | await srv.close(); |
| 200 | console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed'); |
| 201 | process.exit(fails ? 1 : 0); |