Elffuss BraidHub

utopia-ia/elffuss-code public

main · 19.7 KiBRawPermalink
1// Life of real web extensions in Code, against the live Open VSX.
2//
3// node tests/x2_lifecycle.mjs
4// needs the network; offline (or X2_OFFLINE=1) it is NOT RUN, and
5// tests/x2_manager.mjs runs the same panel flows on the cached packages
6//
7// Everything goes through the Extensions panel and Code's own requests to
8// open-vsx.org (metadata, the published SHA-256, the .vsix). Only the search
9// listing is pinned, so the versions under test stay fixed: Tyriar.sort-lines
10// 1.9.1 and 1.12.0, esbenp.prettier-vscode 12.3.0 and 12.4.0.
11//
12// L0 sort-lines 1.9.1 declares a browser entry its package does not
13// contain: running its code is refused, and nothing is left installed
14// L1 sort-lines 1.12.0, search and detail: what will work, before installing
15// L2 "Install and run its code…": Cancel downloads nothing
16// L3 accept: Code's page downloads it, checks the published SHA-256
17// (pinned too) and starts its code
18// L4 its command runs from the panel and sorts the open file
19// L5 code off and on again without a reload
20// L6 Prettier 12.3.0 the same way; Format Document uses it
21// L7 update to 12.4.0 from the result row: still with its code, still on,
22// with the pinned SHA-256, the old version's files gone, and it formats
23// L8 disabling the extension stops its code (the built-in formatter is
24// back); enabling it brings Prettier back
25// L9 after a reload both are back, running, with what they did
26// L10 uninstall both: no files left in IndexedDB, no sandbox, nothing in kv
27// L11 only Code's page talked to Open VSX; the sandbox site was asked only
28// for its two documents; no page errors
29import { chromium } from 'playwright';
30import { startServer } from './lib/x2-server.mjs';
31import { PINNED, fetchVsix } from './lib/x2-vsix.mjs';
32
33let fails = 0;
34const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
35const sleep = ms => new Promise(r => setTimeout(r, ms));
36async function until(fn, { timeout = 30000, every = 200 } = {}) {
37 const end = Date.now() + timeout;
38 let v;
39 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
40 return v;
41}
42const API = 'https://open-vsx.org';
43
44// ── ¿hay Open VSX? ──
45const live = {};
46try {
47 if (process.env.X2_OFFLINE === '1') throw new Error('X2_OFFLINE=1');
48 for (const [ns, name, v] of [['Tyriar', 'sort-lines', '1.9.1'], ['Tyriar', 'sort-lines', '1.12.0'], ['esbenp', 'prettier-vscode', '12.3.0'], ['esbenp', 'prettier-vscode', '12.4.0']]) {
49 const r = await fetch(`${API}/api/${ns}/${name}/${v}`, { signal: AbortSignal.timeout(20000), headers: { 'User-Agent': 'elffuss-code-tests' } });
50 if (!r.ok) throw new Error(`${ns}.${name}@${v}: HTTP ${r.status}`);
51 const j = await r.json();
52 if (!j.files?.download || !j.files?.sha256) throw new Error(`${ns}.${name}@${v}: no download or no published SHA-256`);
53 live[`${ns}.${name}@${v}`.toLowerCase()] = j;
54 }
55} catch (e) {
56 console.log(`⏭️ NOT RUN x2_lifecycle — Open VSX not reachable (${e.message}); tests/x2_manager.mjs runs these flows on the cached packages`);
57 process.exit(0);
58}
59const pinnedSha = Object.fromEntries(PINNED.map(p => [`${p.namespace}.${p.name}@${p.version}`.toLowerCase(), p.sha256]));
60
61const srv = await startServer();
62const browser = await chromium.launch();
63const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
64await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
65// solo la lista de la búsqueda va fijada; lo demás sale a Open VSX de verdad
66let sortVersion = '1.9.1', prettierVersion = '12.3.0';
67const listing = () => [
68 { namespace: 'Tyriar', name: 'sort-lines', version: sortVersion, displayName: 'Sort lines', description: 'Sorts lines of text', downloadCount: 1000, verified: true, files: {} },
69 { namespace: 'esbenp', name: 'prettier-vscode', version: prettierVersion, displayName: 'Prettier - Code formatter', description: 'Code formatter using prettier', downloadCount: 1000, verified: true, files: {} },
70];
71await ctx.route(`${API}/api/-/search**`, route => {
72 const q = (new URL(route.request().url()).searchParams.get('query') || '').toLowerCase();
73 const hits = listing().filter(x => !q || `${x.namespace} ${x.name} ${x.displayName}`.toLowerCase().includes(q));
74 return route.fulfill({ status: 200, headers: { 'access-control-allow-origin': '*', 'content-type': 'application/json' }, body: JSON.stringify({ totalSize: hits.length, offset: 0, extensions: hits }) });
75});
76const page = await ctx.newPage();
77const errors = [];
78page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
79page.on('dialog', d => d.accept()); // confirmar desinstalar
80const outside = []; // peticiones fuera de Code y del CDN de Monaco
81ctx.on('request', r => {
82 let u;
83 try { u = new URL(r.url()); } catch { return; }
84 if (!/^https?:$/.test(u.protocol) || u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === 'cdn.jsdelivr.net') return;
85 let frame = '';
86 let parent = '';
87 try { frame = r.frame()?.url() || ''; parent = r.frame()?.parentFrame()?.url() || ''; } catch { frame = '(worker)'; }
88 outside.push({ url: u.origin + u.pathname, frame, parent, method: r.method() });
89});
90
91await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
92await page.evaluate(async () => {
93 const o = await navigator.storage.getDirectory();
94 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(); };
95 await w('fruits.txt', 'pear\napple\nfig\n');
96 await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
97});
98const openIde = async () => {
99 await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
100 await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
101};
102await openIde();
103const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
104const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
105const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
106const selectAll = () => page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; const m = ed.getModel(); ed.setSelection(m.getFullModelRange()); });
107const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
108const panel = async () => { await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); }); await until(() => page.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel'))); };
109const row = id => page.locator(`#ext-results .ext-row[data-id="${id}"]`);
110const installed = id => page.locator(`#ext-installed .ext-row[data-id="${id}"]`);
111const search = async q => { await page.fill('#ext-q', q); await page.press('#ext-q', 'Enter'); };
112const codeState = id => page.evaluate(id => document.querySelector(`#ext-installed .ext-row[data-id="${id}"] .ext-x2-state`)?.textContent || null, id);
113const record = id => page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const r = h.list().find(e => e.id === id); return r ? { version: r.version, verified: r.verified, sha256: r.sha256, code: !!r.code, runs: !!r.runs, enabled: r.enabled } : null; }, id);
114const idbKeys = prefix => page.evaluate(prefix => new Promise((res, rej) => {
115 const r = indexedDB.open('elffuss-code-ext', 1);
116 r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => String(k).startsWith(prefix)).length); r.result.close(); }; q.onerror = () => rej(q.error); };
117 r.onerror = () => rej(r.error);
118}), prefix);
119const READY = s => s === 'running' || s === 'ready (starts when first used)';
120// (un HEAD solo mira lo que pesa, para el consentimiento: no es una descarga)
121const downloads = () => outside.filter(o => /\.vsix$/.test(o.url) && o.method !== 'HEAD').map(o => o.url.split('/').pop());
122const sizeLookups = () => outside.filter(o => /\.vsix$/.test(o.url) && o.method === 'HEAD').map(o => o.url.split('/').pop());
123const SORT = 'tyriar.sort-lines', PRETTIER = 'esbenp.prettier-vscode';
124async function sortFromPanel(text, want) {
125 await open('fruits.txt');
126 await setValue(text);
127 await selectAll();
128 await panel();
129 await installed(SORT).locator('[data-k="cmd:sortLines.sortLines"]').click();
130 return until(async () => (await value()) === want);
131}
132async function formatsTo(want, tries = 20) {
133 for (let i = 0; i < tries; i++) {
134 await formatDoc();
135 if (await until(async () => (await value()) === want, { timeout: 1500 })) return true;
136 }
137 return false;
138}
139
140// ── L0: una versión cuyo paquete no trae su entrada para el navegador ──
141await panel();
142await search('sort-lines');
143await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
144await row('Tyriar.sort-lines').locator('.ext-name').click();
145await until(async () => (await row('Tyriar.sort-lines').locator('.ext-install-code').count()) === 1);
146await row('Tyriar.sort-lines').locator('.ext-install-code').click();
147await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
148await page.click('#x2-consent button:has-text("Install and run code")');
149const refused = await until(async () => { const t = await page.textContent('#ext-msg'); return /browser entry is not in the package/i.test(t) ? t : null; }, { timeout: 120000 });
150ok('L0 sort-lines 1.9.1 declares a browser entry its package lacks: its code is refused, nothing is installed', !!refused && !(await record(SORT)) && (await idbKeys(SORT + '@')) === 0, String(refused || await page.textContent('#ext-msg')));
151
152// ── L1 ──
153sortVersion = '1.12.0';
154await openIde();
155await panel();
156await search('sort-lines');
157await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
158await row('Tyriar.sort-lines').locator('.ext-name').click();
159const det = await until(async () => { const t = await row('Tyriar.sort-lines').locator('.ext-detail').innerText(); return /Runs in Code’s sandbox/.test(t) ? t : null; });
160ok('L1 the detail says what will work, before installing', !!det && /No internet; sees only the files you open/.test(det), det);
161
162// ── L2 ──
163const before = downloads().length;
164await row('Tyriar.sort-lines').locator('.ext-install-code').click();
165const consentText = await until(() => page.evaluate(() => document.querySelector('#x2-consent [role="dialog"]')?.textContent || null));
166await page.keyboard.press('Escape');
167await sleep(800);
168ok('L2 Cancel in the consent dialog: nothing downloaded, nothing installed', downloads().length === before && !(await record(SORT)), JSON.stringify(downloads()));
169// (aquí la petición HEAD pasa por la intercepción de Playwright, que fija la
170// búsqueda, y Open VSX le contesta 403: el diálogo dice entonces que la baja al
171// aceptar. Sin intercepción, como en un navegador de verdad, se ve abajo, L2b)
172ok('L2 …the dialog opened at once and asked Open VSX for its size (a HEAD request), before anything was downloaded', sizeLookups().includes('Tyriar.sort-lines-1.12.0.vsix')
173 && /This extension: (checking its size|\d+\.\d MB|downloaded from Open VSX when you accept)/.test(consentText || ''), JSON.stringify({ heads: sizeLookups(), text: String(consentText).slice(-160) }));
174{
175 const ctx2 = await browser.newContext();
176 await ctx2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
177 const p2 = await ctx2.newPage();
178 await p2.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
179 const size = await p2.evaluate(async () => {
180 const ovsx = await import('/js/ext/openvsx.js');
181 return (await import('/js/ext2/manage.js')).downloadSize(await ovsx.metadata('Tyriar', 'sort-lines', '1.12.0'));
182 }).catch(e => String(e.message || e));
183 const pinned = PINNED.find(x => x.name === 'sort-lines');
184 const want = (await fetchVsix({ ...pinned, offline: true }).catch(() => null))?.bytes?.length;
185 ok('L2b in a browser without interception, the size the consent shows comes from Open VSX itself (HEAD) and is the pinned package’s', !!want && size === want, JSON.stringify({ size, want }));
186 await ctx2.close();
187}
188
189// ── L3 ──
190await row('Tyriar.sort-lines').locator('.ext-install-code').click();
191await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
192await page.click('#x2-consent button:has-text("Install and run code")');
193const st1 = await until(async () => { const s = await codeState(SORT); return READY(s) ? s : null; }, { timeout: 120000 });
194const r1 = await record(SORT);
195ok('L3 accepted: Code downloaded 1.12.0 from Open VSX, checked the published SHA-256 (the pinned one) and runs its code', !!st1 && r1?.version === '1.12.0' && r1.verified && r1.code && r1.runs
196 && r1.sha256 === pinnedSha['tyriar.sort-lines@1.12.0'] && downloads().includes('Tyriar.sort-lines-1.12.0.vsix') && outside.some(o => o.url.endsWith('Tyriar.sort-lines-1.12.0.sha256')), JSON.stringify({ st1, r1, d: downloads() }));
197
198// ── L4 ──
199ok('L4 its command runs from the panel and sorts the open file', !!(await sortFromPanel('pear\napple\nfig', 'apple\nfig\npear')), JSON.stringify(await value()));
200
201// ── L5: apagar y encender su código ──
202await panel();
203await installed(SORT).locator('[data-k="x2run"]').click();
204ok('L5 code off: the extension stays installed, the sandbox goes away', !!(await until(async () => (await codeState(SORT)) === 'off'))
205 && !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')))));
206await installed(SORT).locator('[data-k="x2run"]').click();
207ok('L5 code on again, no reload and no second consent (the runtime is cached)', !!(await until(async () => READY(await codeState(SORT)), { timeout: 60000 }))
208 && !(await page.evaluate(() => !!document.querySelector('#x2-consent'))));
209ok('L5 …and the command works', !!(await sortFromPanel('d\nc', 'c\nd')), JSON.stringify(await value()));
210
211// ── L6: Prettier 12.3.0 ──
212await panel();
213await search('prettier');
214await until(async () => (await row('esbenp.prettier-vscode').count()) === 1);
215await row('esbenp.prettier-vscode').locator('.ext-name').click();
216await until(async () => (await row('esbenp.prettier-vscode').locator('.ext-install-code').count()) === 1);
217await row('esbenp.prettier-vscode').locator('.ext-install-code').click();
218await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
219await page.click('#x2-consent button:has-text("Install and run code")');
220await until(async () => (await codeState(PRETTIER)) === 'running', { timeout: 120000 });
221const r3 = await record(PRETTIER);
222ok('L6 Prettier 12.3.0 installed with its code, the published SHA-256 checked', r3?.version === '12.3.0' && r3.verified && r3.code && r3.runs, JSON.stringify(r3));
223await open('ugly.js');
224await setValue('const x = {a:1,b:[1,2,3]}\n');
225ok('L6 Format Document uses Prettier', await formatsTo('const x = { a: 1, b: [1, 2, 3] };\n'), JSON.stringify(await value()));
226
227// ── L7: actualizar a 12.4.0 ──
228prettierVersion = '12.4.0';
229await panel();
230await search('prettier');
231const upd = row('esbenp.prettier-vscode').locator('.ext-install');
232await until(async () => /Update to 12\.4\.0/.test(await upd.textContent()));
233await upd.click();
234const r4 = await until(async () => { const r = await record(PRETTIER); return r?.version === '12.4.0' ? r : null; }, { timeout: 120000 });
235ok('L7 updated to 12.4.0 with its code, still on, with the pinned SHA-256', !!r4 && r4.verified && r4.code && r4.runs && r4.sha256 === pinnedSha['esbenp.prettier-vscode@12.4.0'], JSON.stringify(r4));
236ok('L7 the old version’s files are gone', (await idbKeys(PRETTIER + '@12.3.0/')) === 0);
237await until(async () => (await codeState(PRETTIER)) === 'running', { timeout: 60000 });
238await open('ugly.js');
239await setValue('const z = {c:3}\n');
240ok('L7 …and the new version formats', await formatsTo('const z = { c: 3 };\n'), JSON.stringify(await value()));
241
242// ── L8: desactivar la extensión entera, y volver ──
243await panel();
244await installed(PRETTIER).locator('.ext-toggle').click();
245await until(async () => (await record(PRETTIER))?.enabled === false);
246await open('ugly.js');
247await setValue('const x = {a:1}\n');
248await sleep(800);
249await formatDoc();
250ok('L8 disabled: its code stops and the built-in formatter is back', !!(await until(async () => (await value()) === 'const x = { a: 1 }\n', { timeout: 10000 })), JSON.stringify(await value()));
251await panel();
252await installed(PRETTIER).locator('.ext-toggle').click();
253await until(async () => (await record(PRETTIER))?.enabled === true && (await codeState(PRETTIER)) === 'running', { timeout: 60000 });
254await open('ugly.js');
255await setValue('const x = {a:1}\n');
256ok('L8 enabled again: Prettier formats', await formatsTo('const x = { a: 1 };\n'), JSON.stringify(await value()));
257
258// ── L9: recargar ──
259await openIde();
260await open('ugly.js');
261await setValue('const y = {b:2}\n');
262ok('L9 after a reload Prettier runs and formats', await formatsTo('const y = { b: 2 };\n', 40), JSON.stringify(await value()));
263await panel();
264await until(async () => READY(await codeState(SORT)), { timeout: 60000 });
265ok('L9 …and sort-lines is back too', !!(await sortFromPanel('z\ny', 'y\nz')), JSON.stringify(await value()));
266
267// ── L10: desinstalar ──
268await panel();
269await installed(SORT).locator('.ext-uninstall').click();
270ok('L10 sort-lines uninstalled: no row, no files', !!(await until(async () => (await installed(SORT).count()) === 0)) && (await idbKeys(SORT + '@')) === 0);
271ok('L10 the sandbox stays while Prettier runs', await page.evaluate(() => !!document.getElementById('x2-sandbox')));
272await installed(PRETTIER).locator('.ext-uninstall').click();
273await until(async () => (await installed(PRETTIER).count()) === 0);
274const mirror = await page.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'));
275ok('L10 Prettier uninstalled: no files, no sandbox, nothing in kv', (await idbKeys(PRETTIER + '@')) === 0 && !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox'))))
276 && Array.isArray(mirror) && !mirror.length, JSON.stringify(mirror));
277
278// ── L11: privacidad ──
279const vsx = outside.filter(o => o.url.startsWith(API) || /openvsx|eclipsecontent/.test(o.url));
280const notPage = vsx.filter(o => !o.frame.startsWith(srv.codeOrigin));
281ok('L11 only Code’s page talked to Open VSX (no request from the sandbox)', vsx.length > 0 && notPage.length === 0, JSON.stringify(notPage.slice(0, 3)));
282// Code's own model store: the hidden iframe of the shared broker
283// (js/runtime/model-broker.js) that Code's page opens, not level 2
284const broker = o => o.url === 'https://models.elffuss.com/' && o.frame === '' && o.parent.startsWith(srv.codeOrigin) && o.method === 'GET';
285const strangers = outside.filter(o => !vsx.includes(o) && !broker(o));
286ok('L11 and nobody talked to anything else', strangers.length === 0, JSON.stringify(strangers.slice(0, 3)));
287const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
288ok('L11 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(' '));
289ok('L11 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
290
291await browser.close();
292await srv.close();
293console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
294process.exit(fails ? 1 : 0);