| 1 | // Static census of the WHOLE Open VSX catalog (manual, run once by the owner): |
| 2 | // every extension's package.json, classified with the panel's own rules |
| 3 | // (web/js/ext2/classify.js), so the README gives exact counts instead of an |
| 4 | // extrapolation from a sample. |
| 5 | // |
| 6 | // node tests/catalog_census.mjs |
| 7 | // every extension: about 20,000 requests to the Open VSX API, at most |
| 8 | // 2.5 a second (the API allows 3), resumable (see below); writes |
| 9 | // tests/catalog-census/summary.json and extensions.tsv (committed) |
| 10 | // node tests/catalog_census.mjs --ranks 1-20,10001-10020 |
| 11 | // only those download ranks (one block from each end of the paging), |
| 12 | // to try it: a few dozen requests; writes |
| 13 | // tests/.cache/catalog/summary-ranks.json |
| 14 | // node tests/catalog_census.mjs --recount |
| 15 | // no network: classify again what the cache holds (after a rule change) |
| 16 | // options: --gap <ms between two requests, 400> --out <folder> |
| 17 | // |
| 18 | // Listing: the search API stops at offset 10,000, so ranks up to 10,000 are |
| 19 | // read by downloads, descending, and the rest from the other end, ascending. |
| 20 | // Extensions with equal download counts can come back in a different order |
| 21 | // from the two ends, so one may appear twice and another never: the listing is |
| 22 | // always completed by a second pass sorted by publication date (those found |
| 23 | // only there have no rank), and whatever is still missing is counted and said. |
| 24 | // |
| 25 | // Manifests: for an extension published for all platforms, its package.json |
| 26 | // by its listed version (one request). For one published per platform, the |
| 27 | // "web" build of that same version if it has one (as tests/x2_census.mjs |
| 28 | // does; an older web build is not what an install gets), or else the listed |
| 29 | // platform's (two requests). No .vsix is ever downloaded and nothing is |
| 30 | // installed or run: that is tests/x2_census.mjs, on the top 500. |
| 31 | // |
| 32 | // What it reads goes to tests/.cache/catalog/raw.jsonl (one line per |
| 33 | // extension, the manifest without its build-only fields), so a stopped run |
| 34 | // continues where it was, and --recount classifies again without the network. |
| 35 | // Built-in languages are Monaco 0.52.2's (tests/lib/monaco-languages.json), as |
| 36 | // the panel sees them. The summary has counts, the date and the number of |
| 37 | // requests; no timings. |
| 38 | import fs from 'node:fs'; |
| 39 | import path from 'node:path'; |
| 40 | import { fileURLToPath } from 'node:url'; |
| 41 | import { classify, WORKBENCH } from '../web/js/ext2/classify.js'; |
| 42 | |
| 43 | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 44 | const API = 'https://open-vsx.org'; |
| 45 | const CAP = 10000; // la búsqueda no pasa de este desplazamiento |
| 46 | const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; }; |
| 47 | const GAP = Number(arg('--gap', 400)); |
| 48 | const RANKS = arg('--ranks', '') ? arg('--ranks').split(',').map(r => r.split('-').map(Number)) : null; |
| 49 | const RECOUNT = process.argv.includes('--recount'); |
| 50 | const CACHE = path.join(HERE, '.cache', 'catalog'); |
| 51 | const OUTDIR = path.resolve(arg('--out', RANKS ? CACHE : path.join(HERE, 'catalog-census'))); |
| 52 | fs.mkdirSync(CACHE, { recursive: true }); |
| 53 | fs.mkdirSync(OUTDIR, { recursive: true }); |
| 54 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 55 | const inRanks = r => !RANKS || (r != null && RANKS.some(([a, b]) => r >= a && r <= (b || a))); |
| 56 | const today = new Date().toISOString().slice(0, 10); |
| 57 | |
| 58 | // ── peticiones: como mucho una cada GAP ms a la API, y paciencia con el 429 ── |
| 59 | let requests = 0, nextSlot = 0; |
| 60 | async function slot() { |
| 61 | const now = Date.now(); |
| 62 | const at = Math.max(now, nextSlot); |
| 63 | nextSlot = at + GAP; |
| 64 | if (at > now) await sleep(at - now); |
| 65 | } |
| 66 | async function getJson(url, { notFound = false } = {}) { |
| 67 | for (let attempt = 1; attempt <= 6; attempt++) { |
| 68 | await slot(); |
| 69 | requests++; |
| 70 | let r; |
| 71 | try { r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-census' }, signal: AbortSignal.timeout(60000) }); } |
| 72 | catch (e) { if (attempt === 6) throw e; await sleep(5000 * attempt); continue; } |
| 73 | // cerca del tope: más despacio (una respuesta de la caché de Open VSX no trae la cabecera) |
| 74 | const left = r.headers.get('x-ratelimit-remaining'); |
| 75 | if (left !== null && /^\d+$/.test(left) && Number(left) < 300) nextSlot = Math.max(nextSlot, Date.now() + 5000); |
| 76 | if (r.status === 429 || r.status >= 500) { await r.body?.cancel(); await sleep((r.status === 429 ? 60000 : 15000) * attempt); continue; } |
| 77 | if (r.status === 404 && notFound) { await r.body?.cancel(); return null; } |
| 78 | if (!r.ok) { await r.body?.cancel(); throw Object.assign(new Error(`HTTP ${r.status}`), { status: r.status }); } |
| 79 | return r.json(); |
| 80 | } |
| 81 | throw new Error('gave up after retries'); |
| 82 | } |
| 83 | |
| 84 | // «…/api/ns/name/<plataforma>/<versión>/file/x.vsix» → la plataforma (o null) |
| 85 | function platformOf(download) { |
| 86 | try { |
| 87 | const parts = new URL(download).pathname.split('/').filter(Boolean); |
| 88 | return parts[0] === 'api' && parts.length === 7 && parts[5] === 'file' ? parts[3] : null; |
| 89 | } catch { return null; } |
| 90 | } |
| 91 | |
| 92 | // ── 1. la lista, por descargas (y, si faltan, por fecha) ── |
| 93 | const listFile = path.join(CACHE, RANKS ? `list-ranks.json` : `list-${today}.json`); |
| 94 | async function listing() { |
| 95 | if (RECOUNT || (!RANKS && fs.existsSync(listFile))) { |
| 96 | const files = fs.readdirSync(CACHE).filter(f => /^list-\d{4}-\d\d-\d\d\.json$/.test(f)).sort(); |
| 97 | if (!files.length) throw new Error('--recount: no listing in the cache'); |
| 98 | return JSON.parse(fs.readFileSync(path.join(CACHE, files.at(-1)), 'utf8')); |
| 99 | } |
| 100 | const search = (offset, sortBy, order) => getJson(`${API}/api/-/search?size=100&offset=${offset}&sortBy=${sortBy}&sortOrder=${order}&includeAllVersions=false`); |
| 101 | const first = await search(0, 'downloadCount', 'desc'); |
| 102 | const total = first.totalSize; |
| 103 | const byId = new Map(); |
| 104 | let repeated = 0; |
| 105 | const take = (exts, rankOf) => exts.forEach((e, i) => { |
| 106 | const id = `${e.namespace}.${e.name}`; |
| 107 | if (byId.has(id.toLowerCase())) { repeated++; return; } |
| 108 | byId.set(id.toLowerCase(), { rank: rankOf(i), id, namespace: e.namespace, name: e.name, version: e.version, platform: platformOf(e.files?.download), downloads: e.downloadCount ?? null }); |
| 109 | }); |
| 110 | const want = (lo, hi) => !RANKS || RANKS.some(([a, b]) => lo <= (b || a) && hi >= a); |
| 111 | for (let off = 0; off < Math.min(total, CAP); off += 100) { |
| 112 | if (!want(off + 1, off + 100)) continue; |
| 113 | const j = off === 0 ? first : await search(off, 'downloadCount', 'desc'); |
| 114 | take(j.extensions, i => off + i + 1); |
| 115 | } |
| 116 | for (let off = 0; off < total - CAP; off += 100) { // del final hacia arriba |
| 117 | if (!want(total - off - 99, total - off)) continue; |
| 118 | const j = await search(off, 'downloadCount', 'asc'); |
| 119 | take(j.extensions, i => total - off - i); |
| 120 | } |
| 121 | // los que el empate de descargas dejó fuera (puede haberlos aunque la lista |
| 122 | // no se quede corta: entre las dos puntas del orden pueden entrar extensiones |
| 123 | // nuevas): por fecha de publicación, siempre que se lee el catálogo entero |
| 124 | let filled = 0, totalAtEnd = total; |
| 125 | if (!RANKS) { |
| 126 | const seen = new Set(byId.keys()); |
| 127 | const add = j => { totalAtEnd = j.totalSize; for (const e of j.extensions) { const k = `${e.namespace}.${e.name}`.toLowerCase(); if (!seen.has(k)) { seen.add(k); filled++; byId.set(k, { rank: null, id: `${e.namespace}.${e.name}`, namespace: e.namespace, name: e.name, version: e.version, platform: platformOf(e.files?.download), downloads: e.downloadCount ?? null }); } } }; |
| 128 | for (let off = 0; off < Math.min(total, CAP); off += 100) add(await search(off, 'timestamp', 'desc')); |
| 129 | for (let off = 0; off < total - CAP; off += 100) add(await search(off, 'timestamp', 'asc')); |
| 130 | } |
| 131 | // (el catálogo crece mientras se lista: su tamaño al acabar es el que cuenta) |
| 132 | const list = { date: today, total, totalAtEnd, repeated, filledByDate: filled, missing: RANKS ? null : Math.max(0, totalAtEnd - byId.size), extensions: [...byId.values()] }; |
| 133 | fs.writeFileSync(listFile, JSON.stringify(list)); |
| 134 | return list; |
| 135 | } |
| 136 | |
| 137 | // ── 2. cada package.json, una vez, guardado tal cual (sin lo de compilar) ── |
| 138 | const DROP = ['scripts', 'devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies', 'bundledDependencies', 'resolutions', 'overrides', 'readme', 'files', 'jest', 'eslintConfig', 'prettier', 'lint-staged', 'husky', 'packageManager', 'volta', 'pnpm', 'workspaces', '__metadata']; |
| 139 | const slim = m => { if (!m || typeof m !== 'object' || Array.isArray(m)) return null; const o = { ...m }; for (const k of DROP) delete o[k]; return o; }; |
| 140 | async function read(e) { |
| 141 | const base = `${API}/api/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.name)}`; |
| 142 | const v = encodeURIComponent(e.version); |
| 143 | let variant = 'universal', url = `${base}/${v}/file/package.json`; |
| 144 | if (e.platform) { |
| 145 | // la web de ESTA versión, si la publica (una compilación web más vieja no |
| 146 | // es la que se instalaría), o la de la plataforma de la lista |
| 147 | const meta = await getJson(`${base}/${v}`, { notFound: true }); |
| 148 | if (meta?.downloads?.web) { variant = 'web'; url = `${base}/web/${v}/file/package.json`; } |
| 149 | else { variant = 'platform'; url = `${base}/${encodeURIComponent(e.platform)}/${v}/file/package.json`; } |
| 150 | } |
| 151 | const manifest = await getJson(url, { notFound: true }); |
| 152 | if (!manifest) return { id: e.id, version: e.version, rank: e.rank, variant, error: 'no package.json published' }; |
| 153 | return { id: e.id, version: e.version, rank: e.rank, variant, manifest: slim(manifest) }; |
| 154 | } |
| 155 | |
| 156 | const list = await listing(); |
| 157 | const todo = list.extensions.filter(e => inRanks(e.rank)).sort((a, b) => (a.rank ?? 1e9) - (b.rank ?? 1e9)); |
| 158 | console.log(`Open VSX on ${list.date}: ${list.total} extensions; listed ${list.extensions.length}${list.missing ? `, ${list.missing} not reachable by the search` : ''}; to classify: ${todo.length}${RANKS ? ' (ranks ' + arg('--ranks') + ')' : ''}`); |
| 159 | |
| 160 | const rawFile = path.join(CACHE, 'raw.jsonl'); |
| 161 | const done = new Map(); |
| 162 | if (fs.existsSync(rawFile)) { |
| 163 | for (const line of fs.readFileSync(rawFile, 'utf8').split('\n')) { |
| 164 | if (!line.trim()) continue; |
| 165 | try { const x = JSON.parse(line); done.set(x.id.toLowerCase(), x); } catch { /* línea a medias de una parada */ } |
| 166 | } |
| 167 | } |
| 168 | const runsFile = path.join(CACHE, 'runs.json'); |
| 169 | const runs = fs.existsSync(runsFile) ? JSON.parse(fs.readFileSync(runsFile, 'utf8')) : []; |
| 170 | if (!RECOUNT) { |
| 171 | // (una por extensión y versión: si la lista trae otra versión, se vuelve a leer) |
| 172 | const pending = todo.filter(e => { const d = done.get(e.id.toLowerCase()); return !d || d.version !== e.version; }); |
| 173 | const out = fs.openSync(rawFile, 'a'); |
| 174 | let n = 0; |
| 175 | const worker = async () => { |
| 176 | while (pending.length) { |
| 177 | const e = pending.shift(); |
| 178 | const x = await read(e).catch(err => ({ id: e.id, version: e.version, rank: e.rank, error: String(err.message || err).slice(0, 200) })); |
| 179 | x.rank = e.rank; |
| 180 | done.set(x.id.toLowerCase(), x); |
| 181 | fs.writeSync(out, JSON.stringify(x) + '\n'); |
| 182 | if (++n % 500 === 0) console.log(` ${n} read, ${pending.length} to go`); |
| 183 | } |
| 184 | }; |
| 185 | await Promise.all([1, 2, 3, 4].map(worker)); |
| 186 | fs.closeSync(out); |
| 187 | runs.push({ date: today, ranks: RANKS ? arg('--ranks') : 'all', requests, read: n }); |
| 188 | if (!RANKS) fs.writeFileSync(runsFile, JSON.stringify(runs, null, 1)); |
| 189 | } |
| 190 | |
| 191 | // ── 3. recuento, con las reglas del panel ── |
| 192 | const langs = JSON.parse(fs.readFileSync(path.join(HERE, 'lib/monaco-languages.json'), 'utf8')); |
| 193 | const builtin = new Set(langs.languages.map(l => l.id)); |
| 194 | const monarch = new Set(langs.languages.filter(l => l.monarch).map(l => l.id)); |
| 195 | const tested = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/tested.json'), 'utf8')); |
| 196 | const opts = { tested, builtinLanguage: id => builtin.has(id), grammarSkippedFor: id => builtin.has(id) && !monarch.has(id) }; |
| 197 | const rows = todo.map(e => ({ e, x: done.get(e.id.toLowerCase()) })).filter(r => r.x); |
| 198 | const classes = rows.map(({ e, x }) => { |
| 199 | if (x.error || !x.manifest) return { e, x, c: null }; |
| 200 | return { e, x, c: classify(x.manifest, opts) }; |
| 201 | }); |
| 202 | const ok = classes.filter(r => r.c); |
| 203 | const count = (set, f) => set.filter(f).length; |
| 204 | const tally = set => ({ |
| 205 | extensions: set.length, |
| 206 | browserEntry: count(set, r => r.c.runtime === 'browser'), |
| 207 | runsInSandbox: count(set, r => r.c.eligible), |
| 208 | nodeOnly: count(set, r => r.c.runtime === 'node'), |
| 209 | noCode: count(set, r => r.c.runtime === 'none'), |
| 210 | declarativeApplies: count(set, r => r.c.hasDeclarative), |
| 211 | worksInCode: count(set, r => r.c.works), |
| 212 | worksOnlyThroughCode: count(set, r => r.c.works && !r.c.hasDeclarative), |
| 213 | nothingWorks: count(set, r => !r.c.works), |
| 214 | }); |
| 215 | const bands = {}; |
| 216 | for (const n of [100, 500, 1000, 5000]) bands['top' + n] = tally(ok.filter(r => r.e.rank != null && r.e.rank <= n)); |
| 217 | const summary = { |
| 218 | schema: 1, |
| 219 | date: list.date, |
| 220 | method: 'Static census: every extension that the Open VSX search lists, its latest package.json (for one published per platform, the web build of that version if it has one, else the listed platform build), classified with Elffuss Code\'s panel rules (web/js/ext2/classify.js; Monaco 0.52.2\'s built-in languages; the runtime census in web/js/ext2/tested.json for the top 500). Nothing was downloaded as a .vsix, installed or run. "Runs in the sandbox" assumes a browser and a site where level 2 is available.', |
| 221 | catalog: list.totalAtEnd ?? list.total, |
| 222 | catalogWhenTheListingStarted: list.total, |
| 223 | listed: list.extensions.length, |
| 224 | notReachableBySearch: list.missing, |
| 225 | ranks: RANKS ? arg('--ranks') : 'all', |
| 226 | read: ok.length, |
| 227 | unreadable: classes.length - ok.length, |
| 228 | // las peticiones que pide leerlo todo una vez: dos listados de páginas de 100 |
| 229 | // (por descargas y por fecha), un package.json por extensión y, en las |
| 230 | // publicadas por plataforma, la consulta de su compilación web |
| 231 | requests: RANKS ? requests : 2 * Math.ceil((list.totalAtEnd ?? list.total) / 100) + classes.length + classes.filter(r => r.e.platform).length, |
| 232 | ...tally(ok), |
| 233 | browser: { |
| 234 | runsAndShowsWorkbenchParts: count(ok, r => r.c.eligible && r.c.unavailable.length > 0), |
| 235 | runsWithProposedApis: count(ok, r => r.c.eligible && r.c.apiProposals > 0), |
| 236 | cannotRun: count(ok, r => r.c.runtime === 'browser' && !r.c.eligible), |
| 237 | whyCannotRun: Object.fromEntries(['engine', 'never', 'census'].map(k => [k, count(ok, r => r.c.runtime === 'browser' && !r.c.eligible && r.c.reasons.includes(k))])), |
| 238 | missingDependencies: count(ok, r => r.c.runtime === 'browser' && r.c.deps.missing.length > 0), |
| 239 | testedInCode: count(ok, r => r.c.runtime === 'browser' && !!r.c.census), |
| 240 | }, |
| 241 | workbenchContributions: Object.fromEntries(WORKBENCH.map(k => [k, count(ok, r => r.c.unavailable.includes(k))]).filter(([, n]) => n)), |
| 242 | packs: count(ok, r => r.c.pack.length > 0), |
| 243 | webBuilds: count(ok, r => r.x.variant === 'web'), |
| 244 | bands, |
| 245 | }; |
| 246 | const name = RANKS ? 'summary-ranks.json' : 'summary.json'; |
| 247 | fs.writeFileSync(path.join(OUTDIR, name), JSON.stringify(summary, null, 1) + '\n'); |
| 248 | if (!RANKS) { |
| 249 | // una línea por extensión, para poder comprobar cada recuento |
| 250 | const b = v => (v ? 1 : 0); |
| 251 | const lines = ['rank\tid\tversion\tvariant\truntime\tdeclarative\truns_in_sandbox\tworks\tworkbench\twhy_not']; |
| 252 | for (const { e, x, c } of classes.sort((p, q) => (p.e.rank ?? 1e9) - (q.e.rank ?? 1e9) || p.e.id.localeCompare(q.e.id))) { |
| 253 | lines.push([e.rank ?? '-', e.id, x.version, x.variant || '-', c ? c.runtime : 'unreadable', b(c?.hasDeclarative), b(c?.eligible), b(c?.works), b(c && c.unavailable.length), c ? c.reasons.join(',') : (x.error || '')].join('\t')); |
| 254 | } |
| 255 | fs.writeFileSync(path.join(OUTDIR, 'extensions.tsv'), lines.join('\n') + '\n'); |
| 256 | } |
| 257 | console.log(JSON.stringify(summary, null, 1)); |
| 258 | console.log(`summary: ${path.relative(path.resolve(HERE, '..'), path.join(OUTDIR, name))}`); |