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