Elffuss BraidHub

utopia-ia/elffuss-code public

main · 7.1 KiBRawPermalink
1// .vsix reales de Open VSX para las pruebas en vivo y el censo del nivel 2.
2//
3// fetchVsix() baja un .vsix (o lo toma de tests/.cache/vsix/) y comprueba su
4// SHA-256 contra la que publica Open VSX, fallando cerrado: sin suma
5// publicada, o si no coincide, no hay extensión. Si la prueba fija además su
6// propia suma, también tiene que coincidir.
7// readCode() lo abre con el lector de zip del nivel 1 (web/js/ext/unzip.js) y
8// devuelve el manifiesto (con %nls% resuelto) y todos sus ficheros bajo
9// extension/, menos node_modules/** y **/*.map, con topes de tamaño.
10// seedReal() lo guarda en la página como si se hubiera instalado.
11import fs from 'node:fs';
12import path from 'node:path';
13import crypto from 'node:crypto';
14import { fileURLToPath } from 'node:url';
15import { openZip } from '../../web/js/ext/unzip.js';
16import { parseJsonc } from '../../web/js/ext/formats.js';
17import { resolveNls } from '../../web/js/ext/vsix.js';
18
19const HERE = path.dirname(fileURLToPath(import.meta.url));
20export const CACHE = path.join(HERE, '..', '.cache', 'vsix');
21// Las dos extensiones reales de las pruebas, con versión y SHA-256 fijadas
22export const PINNED = [
23 { namespace: 'Tyriar', name: 'sort-lines', version: '1.12.0', sha256: 'feecf004b40c9a9e73ba81347d61b69bb231f24df72d01b6b9a17435542deec9' },
24 { namespace: 'esbenp', name: 'prettier-vscode', version: '12.4.0', sha256: 'fb730ea4306d09cdc0a3aaa9e9baae28058cc97a4fbfce8b056b377a0639a9fe' },
25];
26const API = 'https://open-vsx.org';
27const MAX_ENTRY = 32 << 20, MAX_TOTAL = 64 << 20;
28const sha256 = b => crypto.createHash('sha256').update(b).digest('hex');
29
30async function getJson(url) {
31 const r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-tests' } });
32 if (!r.ok) throw Object.assign(new Error(`${url}: HTTP ${r.status}`), { status: r.status });
33 return r.json();
34}
35
36// targetPlatform: 'web' para la compilación que un paquete publica para el
37// navegador (las extensiones por plataforma pueden traer una)
38export async function metadata(namespace, name, version = '', targetPlatform = '') {
39 return getJson(`${API}/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}${targetPlatform ? '/' + encodeURIComponent(targetPlatform) : ''}${version ? '/' + encodeURIComponent(version) : ''}`);
40}
41
42export async function fetchVsix({ namespace, name, version, targetPlatform = '', sha256: pinned, offline = false }) {
43 fs.mkdirSync(CACHE, { recursive: true });
44 const file = path.join(CACHE, `${namespace}.${name}-${version}${targetPlatform ? '@' + targetPlatform : ''}.vsix`);
45 if (fs.existsSync(file)) {
46 const bytes = fs.readFileSync(file);
47 const sum = sha256(bytes);
48 if (!pinned || sum === pinned) return { bytes, sha256: sum, cached: true };
49 fs.rmSync(file);
50 }
51 if (offline) throw Object.assign(new Error('offline and not cached'), { code: 'offline' });
52 const meta = await metadata(namespace, name, version, targetPlatform);
53 if (meta.error) throw new Error(String(meta.error));
54 if (!meta.files?.download || !meta.files?.sha256) throw Object.assign(new Error('Open VSX publishes no SHA-256 for this version'), { code: 'nosha' });
55 const published = (await (await fetch(meta.files.sha256)).text()).trim().split(/\s+/)[0].toLowerCase();
56 if (!/^[0-9a-f]{64}$/.test(published)) throw Object.assign(new Error('the published SHA-256 is not a hash'), { code: 'nosha' });
57 const r = await fetch(meta.files.download);
58 if (!r.ok) throw new Error('download: HTTP ' + r.status);
59 const bytes = Buffer.from(await r.arrayBuffer());
60 const sum = sha256(bytes);
61 if (sum !== published) throw Object.assign(new Error('SHA-256 does not match the published one'), { code: 'sha' });
62 if (pinned && sum !== pinned) throw Object.assign(new Error('SHA-256 does not match the pinned one'), { code: 'sha' });
63 fs.writeFileSync(file, bytes);
64 return { bytes, sha256: sum, cached: false, license: meta.license };
65}
66
67export async function readCode(bytes, { lang = 'en' } = {}) {
68 const zip = openZip(bytes, { maxEntry: MAX_ENTRY, maxTotal: MAX_TOTAL });
69 const dec = new TextDecoder();
70 if (!zip.has('extension/package.json')) throw Object.assign(new Error('not a VS Code extension'), { code: 'notvsix' });
71 let manifest = parseJsonc(dec.decode(await zip.read('extension/package.json')));
72 let nls = {};
73 for (const f of ['extension/package.nls.json', `extension/package.nls.${lang}.json`]) {
74 if (zip.has(f)) { try { nls = { ...nls, ...parseJsonc(dec.decode(await zip.read(f))) }; } catch { /* sin traducción */ } }
75 }
76 manifest = resolveNls(manifest, nls);
77 const files = {};
78 let total = 0;
79 for (const name of zip.names) {
80 if (!name.startsWith('extension/')) continue;
81 const rel = name.slice('extension/'.length);
82 if (!rel || /(^|\/)node_modules\//.test(rel) || /\.map$/i.test(rel)) continue;
83 const data = await zip.read(name);
84 total += data.length;
85 files[rel] = data;
86 }
87 return { manifest, files, bytes: total };
88}
89
90// Guarda una extensión real en la página (IndexedDB de Code), con `runs`.
91// `languages` (de readVsix del nivel 1) hace que Code reconozca sus ficheros.
92export async function seedReal(page, { manifest, files, bytes }, { runs = true, languages = [] } = {}) {
93 const id = `${manifest.publisher}.${manifest.name}`.toLowerCase();
94 const rec = {
95 id, publisher: manifest.publisher, name: manifest.name, version: String(manifest.version),
96 displayName: typeof manifest.displayName === 'string' ? manifest.displayName : manifest.name, description: '', license: String(manifest.license || ''),
97 sha256: '0'.repeat(64), verified: true, source: 'test', size: bytes, installedAt: Date.now(), enabled: true, runs,
98 hasCode: true, ignored: [], pack: [], warnings: [], themes: [], grammars: [], snippets: [], licenseKey: null,
99 languages: languages.map(l => ({ id: l.id, aliases: l.aliases, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, firstLine: l.firstLine, mimetypes: l.mimetypes, configKey: null })),
100 code: { entry: manifest.browser, files: Object.keys(files), bytes, manifest },
101 };
102 // en trozos: page.evaluate no quiere mensajes enormes
103 const entries = Object.entries(files).map(([p, b]) => [p, Buffer.from(b).toString('base64')]);
104 await page.evaluate(async rec => { const store = await import('/js/ext/store.js'); await store.put(rec, new Map()); }, rec);
105 for (let i = 0; i < entries.length; i += 50) {
106 await page.evaluate(async ({ id, version, chunk }) => {
107 const store = await import('/js/ext/store.js');
108 const db = await new Promise((res, rej) => { const r = indexedDB.open('elffuss-code-ext', 1); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
109 const tx = db.transaction('files', 'readwrite');
110 for (const [p, b64] of chunk) {
111 const bin = atob(b64);
112 const u8 = new Uint8Array(bin.length);
113 for (let k = 0; k < bin.length; k++) u8[k] = bin.charCodeAt(k);
114 tx.objectStore('files').put(u8.buffer, store.codeKey(id, version, p));
115 }
116 await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); });
117 db.close();
118 }, { id, version: rec.version, chunk: entries.slice(i, i + 50) });
119 }
120 return id;
121}