Elffuss BraidHub

utopia-ia/elffuss-code public

3402fd88d963 · 6.3 KiBRawPermalink
1// Cliente de Open VSX (open-vsx.org, de la Eclipse Foundation). La API, los
2// ficheros sueltos y los .vsix mandan Access-Control-Allow-Origin: *, así que
3// el navegador habla con Open VSX directamente: sin proxy, y nada de tu
4// proyecto sale nunca hacia allí — solo lo que buscas y lo que instalas.
5// (El Marketplace de Microsoft no se usa: sus términos solo permiten sus
6// productos.)
7
8export const BASE = 'https://open-vsx.org';
9const ORIGENES_ICONO = new Set(['https://open-vsx.org', 'https://openvsx.eclipsecontent.org']);
10export const BIG = 25 * 1024 * 1024; // por encima, se pregunta antes de bajar
11const MAX = 120 * 1024 * 1024; // tope duro de un .vsix
12
13// `code` lo traduce el panel; `status` y `mb` son datos para el mensaje.
14class OpenVsxError extends Error {
15 constructor(msg, code, extra = {}) { super(msg); this.code = code; Object.assign(this, extra); }
16}
17
18async function getJson(url, signal) {
19 let res;
20 try { res = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); }
21 catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); }
22 if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate');
23 if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, res.status === 404 ? 'notfound' : 'http', { status: res.status });
24 return res.json();
25}
26// solo URLs de la propia API (las de ficheros redirigen después a su CDN)
27function deOpenVsx(u) {
28 try { const x = new URL(u); return x.origin === BASE ? x.href : null; } catch { return null; }
29}
30const seg = s => encodeURIComponent(String(s));
31
32const resumen = e => ({
33 namespace: String(e.namespace || ''), name: String(e.name || ''), version: String(e.version || ''),
34 displayName: String(e.displayName || e.name || ''), description: String(e.description || ''),
35 downloadCount: Number(e.downloadCount) || 0, verified: !!e.verified, deprecated: !!e.deprecated,
36 icon: (() => { try { const u = new URL(e.files?.icon); return ORIGENES_ICONO.has(u.origin) ? u.href : null; } catch { return null; } })(),
37});
38
39export async function search(query, { category = '', offset = 0, size = 20, signal } = {}) {
40 const q = new URLSearchParams({ size: String(size), offset: String(offset) });
41 if (query) q.set('query', query);
42 if (category) q.set('category', category);
43 if (query) q.set('sortBy', 'relevance');
44 else { q.set('sortBy', 'downloadCount'); q.set('sortOrder', 'desc'); }
45 const j = await getJson(`${BASE}/api/-/search?${q}`, signal);
46 return { total: Number(j.totalSize) || 0, offset: Number(j.offset) || 0, items: (j.extensions || []).map(resumen) };
47}
48
49export async function metadata(namespace, name, version = '', { signal } = {}) {
50 const j = await getJson(`${BASE}/api/${seg(namespace)}/${seg(name)}${version ? '/' + seg(version) : ''}`, signal);
51 if (j.error) throw new OpenVsxError(String(j.error), 'notfound');
52 return {
53 ...resumen(j), license: String(j.license || ''), categories: Array.isArray(j.categories) ? j.categories.map(String) : [],
54 files: Object.fromEntries(['download', 'sha256', 'manifest', 'license', 'readme'].map(k => [k, deOpenVsx(j.files?.[k])])),
55 homepage: String(j.homepage || ''), repository: String(j.repository || ''),
56 };
57}
58
59// package.json publicado: sirve para decir qué aplicaría sin bajar el .vsix.
60export async function manifest(meta, { signal } = {}) {
61 if (!meta.files.manifest) throw new OpenVsxError('esta versión no publica su package.json', 'notfound');
62 return getJson(meta.files.manifest, signal);
63}
64
65export async function text(url, { signal, max = 200_000 } = {}) {
66 const u = deOpenVsx(url);
67 if (!u) throw new OpenVsxError('URL fuera de Open VSX', 'http');
68 const res = await fetch(u, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' });
69 if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, 'http', { status: res.status });
70 return (await res.text()).slice(0, max);
71}
72
73export async function sha256Hex(bytes) {
74 const d = await crypto.subtle.digest('SHA-256', bytes);
75 return [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join('');
76}
77
78// Baja el .vsix y comprueba su SHA-256 contra la que publica Open VSX.
79// `confirmLarge(mb)` decide si seguir con uno de más de 25 MB.
80export async function download(meta, { onProgress = () => {}, confirmLarge = async () => false, signal } = {}) {
81 if (!meta.files.download) throw new OpenVsxError('esta versión no se puede descargar', 'notfound');
82 const ctl = new AbortController();
83 signal?.addEventListener('abort', () => ctl.abort(), { once: true });
84 let res;
85 try { res = await fetch(meta.files.download, { signal: ctl.signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); }
86 catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); }
87 if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate');
88 if (!res.ok) throw new OpenVsxError(`descarga: ${res.status}`, res.status === 404 ? 'notfound' : 'http', { status: res.status });
89 const total = Number(res.headers.get('content-length')) || 0;
90 if (total > MAX) { ctl.abort(); throw new OpenVsxError(`demasiado grande (${(total / 1048576).toFixed(0)} MB)`, 'big', { mb: Math.round(total / 1048576) }); }
91 if (total > BIG && !(await confirmLarge(Math.round(total / 1048576)))) { ctl.abort(); throw new OpenVsxError('cancelado', 'cancel'); }
92 const reader = res.body.getReader();
93 const trozos = [];
94 let n = 0;
95 for (;;) {
96 const { done, value } = await reader.read();
97 if (done) break;
98 n += value.length;
99 if (n > MAX) { ctl.abort(); throw new OpenVsxError('demasiado grande', 'big', { mb: Math.round(n / 1048576) }); }
100 trozos.push(value);
101 onProgress(n, total);
102 }
103 const bytes = new Uint8Array(n);
104 let o = 0;
105 for (const t of trozos) { bytes.set(t, o); o += t.length; }
106 const sha = await sha256Hex(bytes);
107 let publicada = null;
108 if (meta.files.sha256) {
109 try { publicada = (await text(meta.files.sha256, { signal: ctl.signal, max: 200 })).trim().split(/\s+/)[0].toLowerCase(); }
110 catch { publicada = null; }
111 if (!/^[0-9a-f]{64}$/.test(publicada || '')) publicada = null; // no es una suma: como si no la publicara
112 }
113 if (publicada && publicada !== sha) throw new OpenVsxError('la suma SHA-256 no coincide con la publicada', 'sha');
114 return { bytes, sha256: sha, verified: !!publicada };
115}