Elffuss BraidHub

utopia-ia/elffuss-code public

2df00d521f0c · 15.1 KiBRawPermalink
1// What people who never turn on an extension's code download, compared with
2// Code's main before level 2 (84cc38b, which has level 1), and what turning it
3// on downloads.
4//
5// node tests/x2_bytes.mjs
6//
7// The tip's web/ comes from `git archive` into a temporary folder and is served
8// by a second test server on another loopback port. The same steps run against
9// both, each in a fresh browser profile, and the requests of the measured page
10// are compared. Four states:
11// 1. no extensions;
12// 2. level 1 only: a theme installed and chosen;
13// 3. a code extension installed with its code turned off (Prettier's real
14// .vsix; on the tip, the same file gives its declarative parts);
15// 4. the Extensions panel open and a search done (Open VSX mocked the same
16// way for both).
17// In each: the same request URLs (path and query; Code's site and the CDN)
18// and the same count; nothing under /vendor/x2/ or /js/ext2/ and nothing from
19// the sandbox site. Code's bytes (each file counted at its size on disk, the
20// way the test server sends it, uncompressed): with no extension at all, within
21// +1 KB of the tip (the two hooks in ide.js and main.js). With level 1
22// extensions the level 1 modules carry level 2's hooks (host.js decides when
23// to load js/ext2/host2.js; the panel shows everyone what will work, the
24// "Works in Code" filter and how isolation works), so those states have a
25// budget instead, printed file by file: +5 KB with an extension active (2, 3)
26// and +20 KB with the panel open (4).
27// Then, with the code turned on: the manifest's three files fetched once each
28// and verified, and after a reload none of them asked from the server again.
29// (Tampering, ?noext, ?noext2 and the kill switch: tests/x2_smoke.mjs D and E.)
30import fs from 'node:fs';
31import os from 'node:os';
32import path from 'node:path';
33import { execFileSync } from 'node:child_process';
34import { fileURLToPath } from 'node:url';
35import { chromium } from 'playwright';
36import { startServer } from './lib/x2-server.mjs';
37import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
38import { mockOpenVsx } from './lib/openvsx-mock.mjs';
39import { themeVsix } from './ext_fixtures.mjs';
40
41const HERE = path.dirname(fileURLToPath(import.meta.url));
42const REPO = path.resolve(HERE, '..');
43// main justo antes de fusionar el nivel 2 (el nivel 1 incluido). Era 84cc38b,
44// la base de la rama; tras la fusión, eso medía como si fuera del nivel 2 todo lo
45// que main había añadido después (actividad.js, el panel nuevo, popular.json…).
46const TIP = 'd2a6b98';
47// 4: 25 KB y no 20 desde la fusión con main: el panel de main ya tenía su propio
48// filtro («solo las que funcionan») y el fusionado lleva los dos y su convivencia.
49const BUDGET = { 1: 1024, 2: 5 * 1024, 3: 5 * 1024, 4: 25 * 1024 };
50let fails = 0;
51const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
52const sleep = ms => new Promise(r => setTimeout(r, ms));
53async function until(fn, { timeout = 30000, every = 150 } = {}) {
54 const end = Date.now() + timeout;
55 let v;
56 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
57 return v;
58}
59
60// ── el árbol del nivel 1, tal cual ──
61const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'x2-bytes-'));
62execFileSync('/bin/sh', ['-c', `/usr/bin/git -C "$1" archive ${TIP} web | tar -x -C "$2"`, 'sh', REPO, tmp]);
63const tipWeb = path.join(tmp, 'web');
64if (!fs.existsSync(path.join(tipWeb, 'js/ide.js'))) { console.log('❌ git archive of the tip gave no web/'); process.exit(1); }
65
66let prettier;
67try { prettier = (await fetchVsix({ ...PINNED.find(p => p.name === 'prettier-vscode'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
68catch (e) { console.log(`⏭️ NOT RUN x2_bytes — esbenp.prettier-vscode@12.4.0: ${e.message}`); fs.rmSync(tmp, { recursive: true, force: true }); process.exit(0); }
69const theme = themeVsix();
70
71const now = await startServer();
72const tip = await startServer({ webRoot: tipWeb });
73const trees = { now: { srv: now, web: path.join(REPO, 'web') }, tip: { srv: tip, web: tipWeb } };
74const browser = await chromium.launch();
75
76// tamaño de lo que manda el servidor de pruebas: el fichero tal cual, o «not found»
77function sizeOf(web, urlPath) {
78 try { const st = fs.statSync(path.join(web, decodeURIComponent(urlPath))); return st.isDirectory() ? fs.statSync(path.join(web, decodeURIComponent(urlPath), 'index.html')).size : st.size; }
79 catch { return 'not found'.length; }
80}
81
82async function freshPage(tree) {
83 const ctx = await browser.newContext();
84 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
85 const page = await ctx.newPage();
86 await page.goto(tree.srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
87 await page.evaluate(async () => {
88 const o = await navigator.storage.getDirectory();
89 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(); };
90 await w('app.js', 'const x = {a:1}\n');
91 await w('notes.md', '# notes\n');
92 });
93 return { ctx, page };
94}
95const openIde = async (page, tree) => {
96 await page.goto(tree.srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
97 await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
98};
99const host = page => page.evaluate(async () => !!(await (await import('/js/ide.js')).loadExt()));
100async function installFile(page, name, bytes, opts = {}) {
101 return page.evaluate(async ({ name, b64, opts }) => {
102 const bin = atob(b64);
103 const u8 = new Uint8Array(bin.length);
104 for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
105 const h = await (await import('/js/ide.js')).loadExt();
106 const rec = await h.install(new File([u8], name), opts);
107 return rec.id;
108 }, { name, b64: Buffer.from(bytes).toString('base64'), opts });
109}
110
111// la página medida: cada petición, hasta que todo queda quieto
112async function measure(ctx, page, steps) {
113 const reqs = [];
114 let last = Date.now(), inflight = 0;
115 const onReq = r => { reqs.push(r.url()); inflight++; last = Date.now(); };
116 const onDone = () => { inflight--; last = Date.now(); };
117 ctx.on('request', onReq); ctx.on('requestfinished', onDone); ctx.on('requestfailed', onDone);
118 await steps();
119 await until(() => inflight <= 0 && Date.now() - last > 1500, { timeout: 30000, every: 100 });
120 ctx.off('request', onReq); ctx.off('requestfinished', onDone); ctx.off('requestfailed', onDone);
121 return reqs;
122}
123
124function summarize(tree, reqs) {
125 const origin = tree.srv.codeOrigin;
126 const own = [], cdn = [], sandbox = [];
127 for (const u of reqs) {
128 if (u.startsWith('data:') || u.startsWith('blob:')) continue;
129 const x = new URL(u);
130 if (x.origin === origin) own.push(x.pathname + x.search);
131 else if (x.hostname === 'localhost') sandbox.push(x.pathname);
132 else cdn.push(x.origin + x.pathname);
133 }
134 const bytes = own.reduce((n, p) => n + sizeOf(tree.web, p.split('?')[0]), 0);
135 return { own: own.sort(), cdn: cdn.sort(), sandbox, bytes };
136}
137
138const diff = (a, b) => {
139 const count = l => l.reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map());
140 const ca = count(a), cb = count(b), out = [];
141 for (const k of new Set([...a, ...b])) { const d = (ca.get(k) || 0) - (cb.get(k) || 0); if (d) out.push((d > 0 ? '+' : '') + d + ' ' + k); }
142 return out;
143};
144
145async function compare(label, run, budget, { comparable = true, porque = '' } = {}) {
146 const r = {};
147 for (const k of ['tip', 'now']) r[k] = summarize(trees[k], await run(trees[k], k));
148 const d = diff(r.now.own, r.tip.own);
149 const l2 = r.now.own.filter(p => /^\/vendor\/x2\/|^\/js\/ext2\//.test(p));
150 ok(`${label}: nothing from level 2 (vendor, js/ext2) and nothing from the sandbox site`, !l2.length && !r.now.sandbox.length, [...l2, ...r.now.sandbox].join(' '));
151 // Sin base comparable se dice, y no se inventa una igualdad que no se midió.
152 if (!comparable) { console.log(`ℹ️ ${label}: no comparable with the tip (${porque}); only the check above applies`); return r; }
153 ok(`${label}: the same ${r.tip.own.length} requests to Code’s site as the tip`, !d.length, d.slice(0, 6).join(' · '));
154 const dc = diff(r.now.cdn, r.tip.cdn);
155 ok(`${label}: the same ${r.tip.cdn.length} requests elsewhere (Monaco’s CDN) as the tip`, !dc.length, dc.slice(0, 4).join(' · '));
156 const delta = r.now.bytes - r.tip.bytes;
157 const grown = [...new Set(r.now.own.map(p => p.split('?')[0]))]
158 .map(p => [p, sizeOf(trees.now.web, p) - sizeOf(trees.tip.web, p)]).filter(([, n]) => n).sort((a, b) => b[1] - a[1]);
159 ok(`${label}: Code’s bytes within +${budget >= 2048 ? budget / 1024 + ' KB' : '1 KB'} of the tip (${r.tip.bytes} → ${r.now.bytes}, ${delta >= 0 ? '+' : ''}${delta})`, delta <= budget,
160 grown.slice(0, 8).map(([p, n]) => `${p} ${n > 0 ? '+' : ''}${n}`).join(' · '));
161 return r;
162}
163
164// ── 1. sin extensiones ──
165await compare('1 no extensions', async tree => {
166 const { ctx, page } = await freshPage(tree);
167 const reqs = await measure(ctx, page, async () => {
168 await openIde(page, tree);
169 await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
170 });
171 await ctx.close();
172 return reqs;
173}, BUDGET[1]);
174
175// ── 2. solo nivel 1: un tema instalado y elegido ──
176await compare('2 level 1 only', async tree => {
177 const { ctx, page } = await freshPage(tree);
178 await openIde(page, tree);
179 await host(page);
180 const id = await installFile(page, 'elf-theme.vsix', theme);
181 await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const t = h.themes().find(x => x.ext === id); await h.setTheme(t.id); }, id);
182 const reqs = await measure(ctx, page, async () => {
183 await openIde(page, tree);
184 await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
185 });
186 await ctx.close();
187 return reqs;
188}, BUDGET[2]);
189
190// ── 3. una extensión con código instalada, con el código apagado ──
191const runsOff = {};
192await compare('3 code extension installed, its code off', async (tree, k) => {
193 const { ctx, page } = await freshPage(tree);
194 await openIde(page, tree);
195 await host(page);
196 if (k === 'now') {
197 const id = await installFile(page, 'prettier.vsix', prettier, { withCode: true });
198 await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns(id, false); }, id);
199 runsOff.rec = await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const r = h.list().find(e => e.id === id); return { code: !!r.code, runs: r.runs }; }, id);
200 // el recinto que arrancó al instalarla se desmonta antes de medir
201 await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')), { timeout: 30000 });
202 } else {
203 // En la base (main antes del nivel 2) Prettier NO se instala: lo único que
204 // aportaría es su código, y main lo rechaza con «codeonly». Ese rechazo es
205 // el estado de antes del nivel 2; cualquier otro error sí es un fallo.
206 await installFile(page, 'prettier.vsix', prettier).catch(e => { if (!/codeonly/.test(String(e?.message || e))) throw e; });
207 }
208 const reqs = await measure(ctx, page, async () => {
209 await openIde(page, tree);
210 await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
211 });
212 await ctx.close();
213 return reqs;
214}, BUDGET[3], { comparable: false, porque: 'main before level 2 refuses to install Prettier: all it would add is its code (codeonly)' });
215ok('3 premise: the extension was installed with its code, and the code is off', runsOff.rec?.code === true && runsOff.rec?.runs === false, JSON.stringify(runsOff.rec));
216
217// ── 4. el panel abierto y una búsqueda hecha ──
218const fake = (name, extra) => ({ namespace: 'elffuss-test', name, version: '1.0.0', keywords: ['elffuss-bytes'], published: null,
219 manifest: { name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'Bytes ' + name, engines: { vscode: '^1.80.0' }, ...extra } });
220const fakes = [
221 fake('web', { browser: './web.js', contributes: { commands: [{ command: 'b.x', title: 'X' }] } }),
222 fake('node', { main: './out.js' }),
223 fake('theme', { contributes: { themes: [{ label: 'T', uiTheme: 'vs-dark', path: './t.json' }] } }),
224];
225await compare('4 the panel open and a search done', async tree => {
226 const { ctx, page } = await freshPage(tree);
227 await mockOpenVsx(ctx, fakes);
228 const reqs = await measure(ctx, page, async () => {
229 await openIde(page, tree);
230 await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
231 await page.waitForSelector('#ext-q');
232 await page.fill('#ext-q', 'elffuss-bytes');
233 await page.press('#ext-q', 'Enter');
234 await page.waitForFunction(() => document.querySelectorAll('#ext-results .ext-row').length === 3, null, { timeout: 15000 });
235 });
236 await ctx.close();
237 return reqs;
238}, BUDGET[4]);
239
240// ── 5. con el código encendido: el bundle una vez, verificado, y de la caché después ──
241{
242 const { ctx, page } = await freshPage(trees.now);
243 await openIde(page, trees.now);
244 await host(page);
245 const before = now.requests.length;
246 const id = await installFile(page, 'prettier.vsix', prettier, { withCode: true });
247 const st = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' || s.state === 'error' ? s.state : null; }), { timeout: 90000 });
248 const manifest = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
249 const vendor = now.requests.slice(before).map(r => r.url.split('?')[0]).filter(u => u.startsWith('/vendor/x2/'));
250 const want = manifest.files.map(f => `/vendor/x2/${manifest.buildId}/${f.name}.gz`).sort();
251 ok('5 code on: the sandbox runs on the verified bundle', st === 'running', String(st));
252 ok('5 the manifest’s three files, once each, from its buildId', JSON.stringify(vendor.sort()) === JSON.stringify(want), vendor.join(' '));
253 const before2 = now.requests.length;
254 await openIde(page, trees.now);
255 const st2 = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' || s.state === 'error' ? s.state : null; }), { timeout: 90000 });
256 const again = now.requests.slice(before2).map(r => r.url.split('?')[0]).filter(u => u.startsWith('/vendor/x2/'));
257 ok('5 after a reload the sandbox runs again and the server is not asked for the bundle again (HTTP cache)', st2 === 'running' && again.length === 0, `${st2}; ${again.join(' ')}`);
258 await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); await h.uninstall(id); }, id);
259 ok('5 uninstalling it takes the sandbox down', !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')))));
260 await ctx.close();
261}
262
263await browser.close();
264await now.close();
265await tip.close();
266fs.rmSync(tmp, { recursive: true, force: true });
267console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
268process.exit(fails ? 1 : 0);