| 1 | // Static census of the WHOLE Open VSX catalog (manual, run once by the owner): |
| 2 | // one package.json per extension, classified with Code's own rules, so the |
| 3 | // README can give exact counts instead of an extrapolation from a sample. |
| 4 | // |
| 5 | // node tests/catalog_census.mjs |
| 6 | // every extension: tens of thousands of requests to Open VSX, 4 at a |
| 7 | // time with a pause between batches; resumable (see below) |
| 8 | // node tests/catalog_census.mjs --ranks 1-20,19301-19320 |
| 9 | // only those download ranks, to try it (a few dozen requests) |
| 10 | // options: --pause <ms between batches, 300> --out <summary file> |
| 11 | // |
| 12 | // Paging: the search API stops at offset 10,000, so ranks up to 10,000 are read |
| 13 | // by downloads, descending, and the rest from the other end, ascending. Every |
| 14 | // extension is then read once: its metadata (for a platform-specific one, its |
| 15 | // "web" build if it has one, as an install would) and its package.json. No |
| 16 | // .vsix is ever downloaded, and nothing is installed or run: that is |
| 17 | // tests/x2_census.mjs, on the top 500. |
| 18 | // |
| 19 | // Each extension is classified with level 1's analyzeManifest and |
| 20 | // web/js/ext2/classify.js: declarative parts that apply, browser code that |
| 21 | // can run in the sandbox (or why not), Node only, workbench parts that won't |
| 22 | // appear. What it reads goes to tests/.cache/catalog/ (one line per extension), |
| 23 | // so a stopped run continues where it was and a second run only recounts. |
| 24 | // The summary (counts, the date, no timings) is printed and written as JSON. |
| 25 | import fs from 'node:fs'; |
| 26 | import path from 'node:path'; |
| 27 | import { fileURLToPath } from 'node:url'; |
| 28 | import { classify } from '../web/js/ext2/classify.js'; |
| 29 | |
| 30 | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 31 | const API = 'https://open-vsx.org'; |
| 32 | const CAP = 10000; // la búsqueda no pasa de este desplazamiento |
| 33 | const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; }; |
| 34 | const PAUSE = Number(arg('--pause', 300)); |
| 35 | const RANKS = arg('--ranks', '') ? arg('--ranks').split(',').map(r => r.split('-').map(Number)) : null; |
| 36 | const CACHE = path.join(HERE, '.cache', 'catalog'); |
| 37 | const OUT = path.resolve(arg('--out', path.join(CACHE, RANKS ? 'summary-ranks.json' : 'summary.json'))); |
| 38 | fs.mkdirSync(CACHE, { recursive: true }); |
| 39 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 40 | const inRanks = r => !RANKS || RANKS.some(([a, b]) => r >= a && r <= (b || a)); |
| 41 | |
| 42 | let requests = 0; |
| 43 | async function getJson(url) { |
| 44 | for (let attempt = 0; attempt < 4; attempt++) { |
| 45 | requests++; |
| 46 | let r; |
| 47 | try { r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-census' }, signal: AbortSignal.timeout(30000) }); } |
| 48 | catch (e) { if (attempt === 3) throw e; await sleep(5000 * (attempt + 1)); continue; } |
| 49 | if (r.status === 429 || r.status >= 500) { await sleep(15000 * (attempt + 1)); continue; } |
| 50 | if (!r.ok) throw Object.assign(new Error(`HTTP ${r.status}`), { status: r.status }); |
| 51 | return r.json(); |
| 52 | } |
| 53 | throw new Error('gave up after retries'); |
| 54 | } |
| 55 | |
| 56 | // ── 1. la lista, por descargas ── |
| 57 | const search = (offset, order) => getJson(`${API}/api/-/search?size=100&offset=${offset}&sortBy=downloadCount&sortOrder=${order}&includeAllVersions=false`); |
| 58 | const first = await search(0, 'desc'); |
| 59 | const total = first.totalSize; |
| 60 | const today = new Date().toISOString().slice(0, 10); |
| 61 | const listFile = path.join(CACHE, `list-${today}.json`); |
| 62 | let list; |
| 63 | if (fs.existsSync(listFile)) list = JSON.parse(fs.readFileSync(listFile, 'utf8')); |
| 64 | else { |
| 65 | list = []; |
| 66 | const take = (exts, rankOf) => exts.forEach((e, i) => list.push({ rank: rankOf(i), id: `${e.namespace}.${e.name}`, namespace: e.namespace, name: e.name, version: e.version })); |
| 67 | const want = page => !RANKS || RANKS.some(([a, b]) => page.lo <= (b || a) && page.hi >= a); |
| 68 | for (let off = 0; off < Math.min(total, CAP); off += 100) { |
| 69 | const page = { lo: off + 1, hi: off + 100 }; |
| 70 | if (!want(page)) continue; |
| 71 | const j = off === 0 ? first : await search(off, 'desc'); |
| 72 | take(j.extensions, i => off + i + 1); |
| 73 | await sleep(PAUSE); |
| 74 | } |
| 75 | for (let off = 0; off < total - CAP; off += 100) { // del final hacia arriba |
| 76 | const page = { lo: total - off - 99, hi: total - off }; |
| 77 | if (!want(page)) continue; |
| 78 | const j = await search(off, 'asc'); |
| 79 | take(j.extensions, i => total - off - i); |
| 80 | await sleep(PAUSE); |
| 81 | } |
| 82 | if (!RANKS) fs.writeFileSync(listFile, JSON.stringify(list)); |
| 83 | } |
| 84 | const seen = new Map(); |
| 85 | for (const e of list) if (!seen.has(e.id.toLowerCase())) seen.set(e.id.toLowerCase(), e); |
| 86 | const todo = [...seen.values()].filter(e => inRanks(e.rank)).sort((a, b) => a.rank - b.rank); |
| 87 | console.log(`Open VSX today: ${total} extensions; to classify: ${todo.length}${RANKS ? ' (ranks ' + arg('--ranks') + ')' : ''}; repeated in the paging: ${list.length - seen.size}`); |
| 88 | |
| 89 | // ── 2. cada package.json, una vez (4 a la vez, con pausa), y su clase ── |
| 90 | const progress = path.join(CACHE, 'manifests.jsonl'); |
| 91 | const done = new Map(); |
| 92 | if (fs.existsSync(progress)) { |
| 93 | for (const line of fs.readFileSync(progress, 'utf8').split('\n')) { |
| 94 | if (!line.trim()) continue; |
| 95 | try { const x = JSON.parse(line); done.set(x.id.toLowerCase(), x); } catch { /* línea a medias de una parada */ } |
| 96 | } |
| 97 | } |
| 98 | function classOf(manifest) { |
| 99 | const c = classify(manifest); |
| 100 | return { |
| 101 | browser: typeof manifest.browser === 'string', main: typeof manifest.main === 'string', runtime: c.runtime, |
| 102 | declarative: c.hasDeclarative, eligible: !!c.eligible, works: !!c.works, workbench: c.unavailable.length > 0, |
| 103 | reasons: c.reasons || [], pack: Array.isArray(c.pack) && c.pack.length > 0, |
| 104 | }; |
| 105 | } |
| 106 | async function read(e) { |
| 107 | const base = `${API}/api/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.name)}`; |
| 108 | let meta = await getJson(base); |
| 109 | let variant = (meta.targetPlatform || 'universal') === 'universal' ? 'universal' : 'platform'; |
| 110 | if (variant === 'platform' && meta.downloads && meta.downloads.web) { meta = await getJson(base + '/web'); variant = 'web'; } |
| 111 | if (!meta.files?.manifest) return { id: e.id, version: meta.version || e.version, rank: e.rank, variant, error: 'no package.json published' }; |
| 112 | const manifest = await getJson(meta.files.manifest); |
| 113 | return { id: e.id, version: meta.version || e.version, rank: e.rank, variant, ...classOf(manifest) }; |
| 114 | } |
| 115 | const out = fs.openSync(progress, 'a'); |
| 116 | let fresh = 0; |
| 117 | // (una por extensión: para volver a leerlas otro día, bórrese tests/.cache/catalog/) |
| 118 | const pending = todo.filter(e => !done.has(e.id.toLowerCase())); |
| 119 | for (let i = 0; i < pending.length; i += 4) { |
| 120 | const batch = pending.slice(i, i + 4); |
| 121 | const got = await Promise.all(batch.map(e => read(e).catch(err => ({ id: e.id, version: e.version, rank: e.rank, error: String(err.message || err).slice(0, 200) })))); |
| 122 | for (const x of got) { done.set(x.id.toLowerCase(), x); fs.writeSync(out, JSON.stringify(x) + '\n'); fresh++; } |
| 123 | if ((i / 4) % 50 === 0) console.log(` ${Math.min(i + 4, pending.length)} of ${pending.length} read`); |
| 124 | await sleep(PAUSE); |
| 125 | } |
| 126 | fs.closeSync(out); |
| 127 | |
| 128 | // ── 3. recuento ── |
| 129 | const rows = todo.map(e => done.get(e.id.toLowerCase())).filter(Boolean); |
| 130 | const ok = rows.filter(r => !r.error); |
| 131 | const n = f => ok.filter(f).length; |
| 132 | const summary = { |
| 133 | date: today, catalog: total, classified: ok.length, unreadable: rows.length - ok.length, |
| 134 | ranks: RANKS ? arg('--ranks') : 'all', requestsThisRun: requests, readThisRun: fresh, |
| 135 | browserEntry: n(r => r.browser), |
| 136 | browserRunsInSandbox: n(r => r.browser && r.eligible), |
| 137 | browserRunsAndShowsWorkbenchParts: n(r => r.browser && r.eligible && r.workbench), |
| 138 | browserCannotRun: n(r => r.browser && !r.eligible), |
| 139 | nodeOnly: n(r => r.main && !r.browser), |
| 140 | noCode: n(r => !r.main && !r.browser), |
| 141 | declarativeApplies: n(r => r.declarative), |
| 142 | worksInCode: n(r => r.works), |
| 143 | worksOnlyThroughCode: n(r => r.works && !r.declarative), |
| 144 | nothingWorks: n(r => !r.works), |
| 145 | packs: n(r => r.pack), |
| 146 | whyBrowserCannotRun: Object.fromEntries(['engine', 'proposals', 'never', 'deps'].map(k => [k, n(r => r.browser && !r.eligible && r.reasons.includes(k))])), |
| 147 | webBuilds: n(r => r.variant === 'web'), |
| 148 | }; |
| 149 | fs.writeFileSync(OUT, JSON.stringify(summary, null, 1) + '\n'); |
| 150 | console.log(JSON.stringify(summary, null, 1)); |
| 151 | console.log(`summary: ${path.relative(path.resolve(HERE, '..'), OUT)}`); |