@efraindrummer/ghostdeps 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +602 -2
- package/dist/analyzer.js +87 -0
- package/dist/cli.js +241 -0
- package/dist/clients/cache.js +65 -0
- package/dist/clients/github.js +150 -0
- package/dist/clients/http.js +122 -0
- package/dist/clients/npm.js +115 -0
- package/dist/config.js +194 -0
- package/dist/errors.js +69 -0
- package/dist/parser/lockfile.js +291 -0
- package/dist/parser/manifest.js +94 -0
- package/dist/parser/repoUrl.js +103 -0
- package/dist/render/markdown.js +75 -0
- package/dist/render/sarif.js +139 -0
- package/dist/render/table.js +95 -0
- package/dist/scoring/scoring.js +113 -0
- package/dist/scoring/signals.js +19 -0
- package/dist/types.js +5 -0
- package/dist/utils.js +44 -0
- package/package.json +50 -4
- package/schema/ghostdepsrc.schema.json +67 -0
package/dist/analyzer.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { NotFoundError, errorMessage } from './errors.js';
|
|
2
|
+
import { computeScore, DEFAULT_WEIGHTS, THRESHOLDS } from './scoring/scoring.js';
|
|
3
|
+
import { buildSignals } from './scoring/signals.js';
|
|
4
|
+
import { mapWithConcurrency } from './utils.js';
|
|
5
|
+
const HOST_LABEL = { gitlab: 'GitLab', bitbucket: 'Bitbucket' };
|
|
6
|
+
function baseReport(dep) {
|
|
7
|
+
return {
|
|
8
|
+
name: dep.name,
|
|
9
|
+
registryName: dep.registryName,
|
|
10
|
+
spec: dep.spec,
|
|
11
|
+
kind: dep.kind,
|
|
12
|
+
depth: dep.depth,
|
|
13
|
+
via: dep.via,
|
|
14
|
+
status: 'evaluated',
|
|
15
|
+
reason: null,
|
|
16
|
+
npm: null,
|
|
17
|
+
github: null,
|
|
18
|
+
signals: null,
|
|
19
|
+
result: null,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** Analiza un paquete. Nunca lanza: cualquier fallo se refleja en `status`/`reason`. */
|
|
23
|
+
export async function analyzePackage(dep, deps) {
|
|
24
|
+
const report = baseReport(dep);
|
|
25
|
+
const notEvaluable = (reason) => ({ ...report, status: 'not-evaluable', reason });
|
|
26
|
+
const failed = (err) => ({ ...report, status: 'error', reason: errorMessage(err) });
|
|
27
|
+
if (dep.unsupportedReason)
|
|
28
|
+
return notEvaluable(dep.unsupportedReason);
|
|
29
|
+
try {
|
|
30
|
+
report.npm = await deps.npm.getPackageInfo(dep.registryName);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (err instanceof NotFoundError)
|
|
34
|
+
return notEvaluable('No existe en el registry público de npm (¿privado?)');
|
|
35
|
+
return failed(err);
|
|
36
|
+
}
|
|
37
|
+
const repo = report.npm.repository;
|
|
38
|
+
if (!repo)
|
|
39
|
+
return notEvaluable('Sin campo "repository" en npm');
|
|
40
|
+
if (repo.host !== 'github') {
|
|
41
|
+
const host = HOST_LABEL[repo.host] ?? repo.hostname;
|
|
42
|
+
return notEvaluable(`Repo en ${host}: solo GitHub está soportado en el MVP`);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
report.github = await deps.github.getRepoHealth(repo.owner, repo.repo, repo.directory);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (err instanceof NotFoundError)
|
|
49
|
+
return notEvaluable(`Repo ${repo.owner}/${repo.repo} no encontrado o privado`);
|
|
50
|
+
// RateLimitError, TimeoutError, HttpError...: el paquete queda como error y el análisis sigue.
|
|
51
|
+
return failed(err);
|
|
52
|
+
}
|
|
53
|
+
report.signals = buildSignals(report.npm, report.github, deps.now);
|
|
54
|
+
report.result = computeScore(report.signals, deps.weights ?? DEFAULT_WEIGHTS, deps.thresholds ?? THRESHOLDS);
|
|
55
|
+
return report;
|
|
56
|
+
}
|
|
57
|
+
export async function analyzeAll(dependencies, deps, concurrency, onProgress) {
|
|
58
|
+
let done = 0;
|
|
59
|
+
return mapWithConcurrency(dependencies, concurrency, async (dep) => {
|
|
60
|
+
const r = await analyzePackage(dep, deps);
|
|
61
|
+
onProgress?.(++done, dependencies.length, dep.name);
|
|
62
|
+
return r;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const STATUS_ORDER = { evaluated: 0, 'not-evaluable': 1, error: 2 };
|
|
66
|
+
/** Peor score primero; después "No evaluable" y por último errores. */
|
|
67
|
+
export function sortReports(reports) {
|
|
68
|
+
return [...reports].sort((a, b) => {
|
|
69
|
+
const s = STATUS_ORDER[a.status] - STATUS_ORDER[b.status];
|
|
70
|
+
if (s !== 0)
|
|
71
|
+
return s;
|
|
72
|
+
const diff = (a.result?.score ?? 0) - (b.result?.score ?? 0);
|
|
73
|
+
return diff !== 0 ? diff : a.name.localeCompare(b.name);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function summarize(reports) {
|
|
77
|
+
const summary = { total: reports.length, healthy: 0, caution: 0, critical: 0, notEvaluable: 0, errors: 0 };
|
|
78
|
+
for (const r of reports) {
|
|
79
|
+
if (r.status === 'error')
|
|
80
|
+
summary.errors++;
|
|
81
|
+
else if (r.status === 'not-evaluable')
|
|
82
|
+
summary.notEvaluable++;
|
|
83
|
+
else if (r.result)
|
|
84
|
+
summary[r.result.category]++;
|
|
85
|
+
}
|
|
86
|
+
return summary;
|
|
87
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
6
|
+
import chalk from 'chalk';
|
|
7
|
+
import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
|
|
8
|
+
import { analyzeAll, sortReports, summarize } from './analyzer.js';
|
|
9
|
+
import { DiskCache, defaultCacheDir } from './clients/cache.js';
|
|
10
|
+
import { GitHubClient } from './clients/github.js';
|
|
11
|
+
import { RateLimitGate } from './clients/http.js';
|
|
12
|
+
import { NpmClient } from './clients/npm.js';
|
|
13
|
+
import { createIgnoreMatcher, loadConfig } from './config.js';
|
|
14
|
+
import { GhostDepsError, errorMessage } from './errors.js';
|
|
15
|
+
import { readLockfile, resolveTransitive } from './parser/lockfile.js';
|
|
16
|
+
import { readManifest } from './parser/manifest.js';
|
|
17
|
+
import { renderMarkdown } from './render/markdown.js';
|
|
18
|
+
import { renderSarif } from './render/sarif.js';
|
|
19
|
+
import { renderExplain, renderSummary, renderTable } from './render/table.js';
|
|
20
|
+
/** Códigos de salida documentados. */
|
|
21
|
+
export const EXIT = { OK: 0, FAIL_UNDER: 1, FATAL: 2 };
|
|
22
|
+
function readVersion() {
|
|
23
|
+
try {
|
|
24
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
25
|
+
return pkg.version ?? '0.0.0';
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return '0.0.0';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function positiveInt(name, max = Number.MAX_SAFE_INTEGER) {
|
|
32
|
+
return (value) => {
|
|
33
|
+
const n = Number(value);
|
|
34
|
+
if (!Number.isInteger(n) || n < 1 || n > max) {
|
|
35
|
+
throw new InvalidArgumentError(`${name} debe ser un entero entre 1 y ${max}.`);
|
|
36
|
+
}
|
|
37
|
+
return n;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function scoreArg(value) {
|
|
41
|
+
const n = Number(value);
|
|
42
|
+
if (!Number.isFinite(n) || n < 0 || n > 100)
|
|
43
|
+
throw new InvalidArgumentError('Debe ser un número entre 0 y 100.');
|
|
44
|
+
return n;
|
|
45
|
+
}
|
|
46
|
+
/** `--ignore a,b --ignore "@types/*"` => ["a", "b", "@types/*"] */
|
|
47
|
+
function collectList(value, previous = []) {
|
|
48
|
+
return [...previous, ...value.split(',').map((s) => s.trim()).filter(Boolean)];
|
|
49
|
+
}
|
|
50
|
+
const log = (msg) => process.stderr.write(`${msg}\n`);
|
|
51
|
+
async function run(opts, command, version) {
|
|
52
|
+
const fromCli = (key) => command.getOptionValueSource(key) === 'cli';
|
|
53
|
+
const format = opts.json ? 'json' : opts.format;
|
|
54
|
+
const quiet = format !== 'table'; // en json/markdown, stderr solo para avisos importantes
|
|
55
|
+
// --- Configuración efectiva: CLI > archivo > defaults ---
|
|
56
|
+
const config = await loadConfig(opts.path, opts.config);
|
|
57
|
+
const dev = fromCli('dev') ? opts.dev : (config.dev ?? opts.dev);
|
|
58
|
+
const transitive = fromCli('transitive') ? opts.transitive : (config.transitive ?? opts.transitive);
|
|
59
|
+
const depth = opts.depth ?? config.depth;
|
|
60
|
+
const concurrency = fromCli('concurrency') ? opts.concurrency : (config.concurrency ?? opts.concurrency);
|
|
61
|
+
const failUnder = opts.failUnder ?? config.failUnder;
|
|
62
|
+
const isIgnored = createIgnoreMatcher([...config.ignore, ...opts.ignore]);
|
|
63
|
+
const token = process.env.GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || undefined;
|
|
64
|
+
if (!token) {
|
|
65
|
+
log(chalk.yellow('⚠ GITHUB_TOKEN no configurado: la API de GitHub permite solo 60 peticiones/hora sin autenticar\n' +
|
|
66
|
+
' (~15 paquetes). Crea un token sin permisos en https://github.com/settings/tokens y exporta GITHUB_TOKEN.'));
|
|
67
|
+
}
|
|
68
|
+
if (config.source && !quiet)
|
|
69
|
+
log(chalk.gray(`Configuración: ${config.source}`));
|
|
70
|
+
// --- Dependencias a analizar ---
|
|
71
|
+
const manifest = await readManifest(opts.path, { includeDev: dev });
|
|
72
|
+
let all = manifest.dependencies;
|
|
73
|
+
if (transitive) {
|
|
74
|
+
const { file, lock } = await readLockfile(opts.path);
|
|
75
|
+
const trans = resolveTransitive(lock, manifest.dependencies, { maxDepth: depth ?? Number.POSITIVE_INFINITY });
|
|
76
|
+
all = [...manifest.dependencies, ...trans];
|
|
77
|
+
if (!quiet)
|
|
78
|
+
log(chalk.gray(`Transitivas: ${trans.length} desde ${path.basename(file)}${depth ? ` (profundidad ≤ ${depth})` : ''}`));
|
|
79
|
+
}
|
|
80
|
+
const ignored = all.filter((d) => isIgnored(d.name) || isIgnored(d.registryName)).map((d) => d.name);
|
|
81
|
+
const toAnalyze = all.filter((d) => !ignored.includes(d.name));
|
|
82
|
+
if (ignored.length > 0 && !quiet)
|
|
83
|
+
log(chalk.gray(`Ignorados: ${ignored.join(', ')}`));
|
|
84
|
+
if (toAnalyze.length > 15 && !token) {
|
|
85
|
+
log(chalk.yellow(`⚠ ${toAnalyze.length} paquetes a analizar sin token: es muy probable agotar el rate limit.`));
|
|
86
|
+
}
|
|
87
|
+
else if (toAnalyze.length > 300) {
|
|
88
|
+
log(chalk.yellow(`⚠ ${toAnalyze.length} paquetes: ~${toAnalyze.length * 3} peticiones a GitHub. Considera --depth o "ignore".`));
|
|
89
|
+
}
|
|
90
|
+
const userAgent = `ghostdeps/${version} (+https://github.com/ghostdeps/ghostdeps)`;
|
|
91
|
+
const cache = new DiskCache(defaultCacheDir(), opts.cacheTtl * 3_600_000, opts.cache);
|
|
92
|
+
const gate = new RateLimitGate();
|
|
93
|
+
const retries = 3;
|
|
94
|
+
const now = new Date();
|
|
95
|
+
const npm = new NpmClient({ cache, timeoutMs: opts.timeout, retries, userAgent });
|
|
96
|
+
const github = new GitHubClient({
|
|
97
|
+
cache,
|
|
98
|
+
token,
|
|
99
|
+
timeoutMs: opts.timeout,
|
|
100
|
+
retries,
|
|
101
|
+
userAgent,
|
|
102
|
+
gate,
|
|
103
|
+
maxRateLimitWaitMs: opts.maxWait * 1000,
|
|
104
|
+
onRateLimitWait: (ms, resetAt) => log(chalk.yellow(`\n⏳ Rate limit de GitHub alcanzado; esperando ${Math.ceil(ms / 1000)} s (reset ${resetAt.toLocaleTimeString()})…`)),
|
|
105
|
+
now: () => now,
|
|
106
|
+
});
|
|
107
|
+
const interactive = !quiet && process.stderr.isTTY;
|
|
108
|
+
const reports = await analyzeAll(toAnalyze, { npm, github, now, weights: config.weights, thresholds: config.thresholds }, concurrency, (done, total, name) => {
|
|
109
|
+
if (interactive)
|
|
110
|
+
process.stderr.write(`\r\x1b[2K${chalk.gray(`Analizando ${done}/${total}: ${name}`)}`);
|
|
111
|
+
});
|
|
112
|
+
if (interactive)
|
|
113
|
+
process.stderr.write('\r\x1b[2K');
|
|
114
|
+
const sorted = sortReports(reports);
|
|
115
|
+
const summary = summarize(sorted);
|
|
116
|
+
const failing = failUnder === undefined
|
|
117
|
+
? []
|
|
118
|
+
: sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
|
|
119
|
+
// --- Salida ---
|
|
120
|
+
let rendered;
|
|
121
|
+
if (format === 'json') {
|
|
122
|
+
rendered = JSON.stringify({
|
|
123
|
+
tool: 'ghostdeps',
|
|
124
|
+
version,
|
|
125
|
+
generatedAt: now.toISOString(),
|
|
126
|
+
manifest: manifest.manifestPath,
|
|
127
|
+
config: config.source,
|
|
128
|
+
options: { dev, transitive, depth: depth ?? null, failUnder: failUnder ?? null, authenticated: Boolean(token) },
|
|
129
|
+
thresholds: config.thresholds,
|
|
130
|
+
summary,
|
|
131
|
+
ignored,
|
|
132
|
+
failUnder: failUnder === undefined ? null : { threshold: failUnder, failing },
|
|
133
|
+
packages: sorted,
|
|
134
|
+
}, null, 2);
|
|
135
|
+
}
|
|
136
|
+
else if (format === 'markdown') {
|
|
137
|
+
rendered = renderMarkdown(sorted, summary, now, {
|
|
138
|
+
version,
|
|
139
|
+
projectName: manifest.projectName,
|
|
140
|
+
thresholds: config.thresholds,
|
|
141
|
+
failUnder,
|
|
142
|
+
failing,
|
|
143
|
+
ignored,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
else if (format === 'sarif') {
|
|
147
|
+
rendered = renderSarif(sorted, {
|
|
148
|
+
version,
|
|
149
|
+
manifestPath: manifest.manifestPath,
|
|
150
|
+
thresholds: config.thresholds,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
const title = manifest.projectName ? ` · ${manifest.projectName}` : '';
|
|
155
|
+
rendered = [
|
|
156
|
+
chalk.bold(`\n👻 GhostDeps v${version}${title}`),
|
|
157
|
+
renderTable(sorted, now),
|
|
158
|
+
renderSummary(summary, config.thresholds),
|
|
159
|
+
...(opts.explain ? [renderExplain(sorted)] : []),
|
|
160
|
+
].join('\n');
|
|
161
|
+
}
|
|
162
|
+
if (opts.output) {
|
|
163
|
+
const file = path.resolve(opts.output);
|
|
164
|
+
await writeFile(file, `${stripVTControlCharacters(rendered)}\n`, 'utf8');
|
|
165
|
+
log(chalk.green(`✔ Informe escrito en ${file}`));
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
process.stdout.write(`${rendered}\n`);
|
|
169
|
+
}
|
|
170
|
+
if (gate.resetAt && gate.resetAt.getTime() > Date.now() && summary.errors > 0) {
|
|
171
|
+
log(chalk.red(`\n✖ Se agotó el rate limit de GitHub (reset ${gate.resetAt.toLocaleTimeString()}). ` +
|
|
172
|
+
'Los paquetes restantes quedaron como error; reintenta luego (los resultados ya obtenidos están en caché) ' +
|
|
173
|
+
(token ? 'o aumenta --max-wait.' : 'o configura GITHUB_TOKEN.')));
|
|
174
|
+
}
|
|
175
|
+
if (failUnder !== undefined) {
|
|
176
|
+
if (failing.length > 0) {
|
|
177
|
+
log(chalk.red(`\n✖ ${failing.length} paquete(s) por debajo de --fail-under ${failUnder}: ${failing.join(', ')}`));
|
|
178
|
+
return EXIT.FAIL_UNDER;
|
|
179
|
+
}
|
|
180
|
+
if (!quiet)
|
|
181
|
+
log(chalk.green(`\n✔ Ningún paquete evaluado por debajo de ${failUnder}.`));
|
|
182
|
+
}
|
|
183
|
+
return EXIT.OK;
|
|
184
|
+
}
|
|
185
|
+
async function main() {
|
|
186
|
+
const version = readVersion();
|
|
187
|
+
const program = new Command();
|
|
188
|
+
program
|
|
189
|
+
.name('ghostdeps')
|
|
190
|
+
.description('Detecta dependencias fantasma: abandonadas, con bus factor bajo o con señales de secuestro.')
|
|
191
|
+
.version(version, '-v, --version')
|
|
192
|
+
.option('-p, --path <dir>', 'directorio que contiene el package.json', process.cwd())
|
|
193
|
+
.option('--config <file>', 'archivo de configuración (por defecto .ghostdepsrc.json o "ghostdeps" en package.json)')
|
|
194
|
+
.option('-d, --dev', 'incluir también devDependencies', false)
|
|
195
|
+
.option('-t, --transitive', 'incluir dependencias transitivas (requiere package-lock.json)', false)
|
|
196
|
+
.option('--depth <n>', 'profundidad máxima con --transitive (1 = solo directas)', positiveInt('--depth', 100))
|
|
197
|
+
.option('-i, --ignore <paquetes>', 'paquetes a omitir, separados por coma; admite * (ej. "@types/*")', collectList, [])
|
|
198
|
+
.addOption(new Option('-f, --format <formato>', 'formato de salida').choices(['table', 'json', 'markdown', 'sarif']).default('table'))
|
|
199
|
+
.option('--json', 'atajo de --format json', false)
|
|
200
|
+
.option('-o, --output <file>', 'escribir el informe en un archivo en lugar de stdout')
|
|
201
|
+
.option('--fail-under <score>', 'exit code 1 si algún paquete evaluado queda por debajo del score', scoreArg)
|
|
202
|
+
.option('-c, --concurrency <n>', 'paquetes analizados en paralelo', positiveInt('--concurrency', 32), 4)
|
|
203
|
+
.option('--no-cache', 'ignorar y no escribir la caché en disco')
|
|
204
|
+
.option('--cache-ttl <hours>', 'TTL de la caché en horas', positiveInt('--cache-ttl'), 24)
|
|
205
|
+
.option('--timeout <ms>', 'timeout por request en milisegundos', positiveInt('--timeout'), 15_000)
|
|
206
|
+
.option('--max-wait <seconds>', 'espera máxima ante rate limit antes de abortar', positiveInt('--max-wait'), 60)
|
|
207
|
+
.option('--explain', 'mostrar el desglose de penalizaciones de cada paquete', false)
|
|
208
|
+
.addHelpText('after', [
|
|
209
|
+
'',
|
|
210
|
+
'Ejemplos:',
|
|
211
|
+
' ghostdeps --dev --explain',
|
|
212
|
+
' ghostdeps --transitive --depth 3 --ignore "@types/*"',
|
|
213
|
+
' ghostdeps --format markdown -o ghostdeps.md',
|
|
214
|
+
' ghostdeps --fail-under 40',
|
|
215
|
+
'',
|
|
216
|
+
'Variables de entorno:',
|
|
217
|
+
' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
|
|
218
|
+
' GHOSTDEPS_CACHE_DIR directorio de caché personalizado',
|
|
219
|
+
'',
|
|
220
|
+
'Códigos de salida: 0 OK · 1 --fail-under incumplido · 2 error fatal',
|
|
221
|
+
].join('\n'))
|
|
222
|
+
.action(async (opts, command) => {
|
|
223
|
+
process.exitCode = await run(opts, command, version);
|
|
224
|
+
});
|
|
225
|
+
// Evita que Commander haga process.exit(1) en errores de uso (colisionaría con --fail-under).
|
|
226
|
+
program.exitOverride();
|
|
227
|
+
try {
|
|
228
|
+
await program.parseAsync(process.argv);
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
if (err instanceof CommanderError) {
|
|
232
|
+
// Commander ya imprimió el mensaje (o la ayuda/versión).
|
|
233
|
+
process.exitCode = err.exitCode === 0 ? EXIT.OK : EXIT.FATAL;
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const msg = err instanceof GhostDepsError ? err.message : `Error inesperado: ${errorMessage(err)}`;
|
|
237
|
+
log(chalk.red(`✖ ${msg}`));
|
|
238
|
+
process.exitCode = EXIT.FATAL;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
void main();
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
/** Incrementar cuando cambie la forma de los datos cacheados. */
|
|
6
|
+
const CACHE_SCHEMA = 'v1';
|
|
7
|
+
export function defaultCacheDir() {
|
|
8
|
+
const env = process.env;
|
|
9
|
+
if (env.GHOSTDEPS_CACHE_DIR)
|
|
10
|
+
return env.GHOSTDEPS_CACHE_DIR;
|
|
11
|
+
if (env.XDG_CACHE_HOME)
|
|
12
|
+
return path.join(env.XDG_CACHE_HOME, 'ghostdeps');
|
|
13
|
+
if (process.platform === 'win32' && env.LOCALAPPDATA) {
|
|
14
|
+
return path.join(env.LOCALAPPDATA, 'ghostdeps', 'cache');
|
|
15
|
+
}
|
|
16
|
+
return path.join(os.homedir(), '.cache', 'ghostdeps');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Caché clave/valor en disco con TTL. Guarda datos ya extraídos (no las respuestas crudas)
|
|
20
|
+
* para mantener los archivos pequeños. Cualquier fallo de lectura/escritura se ignora:
|
|
21
|
+
* la caché nunca debe romper un análisis.
|
|
22
|
+
*/
|
|
23
|
+
export class DiskCache {
|
|
24
|
+
dir;
|
|
25
|
+
ttlMs;
|
|
26
|
+
enabled;
|
|
27
|
+
constructor(dir, ttlMs, enabled = true) {
|
|
28
|
+
this.dir = dir;
|
|
29
|
+
this.ttlMs = ttlMs;
|
|
30
|
+
this.enabled = enabled;
|
|
31
|
+
}
|
|
32
|
+
fileFor(key) {
|
|
33
|
+
const hash = createHash('sha256').update(`${CACHE_SCHEMA}:${key}`).digest('hex');
|
|
34
|
+
return path.join(this.dir, `${hash}.json`);
|
|
35
|
+
}
|
|
36
|
+
async get(key) {
|
|
37
|
+
if (!this.enabled)
|
|
38
|
+
return undefined;
|
|
39
|
+
try {
|
|
40
|
+
const raw = await readFile(this.fileFor(key), 'utf8');
|
|
41
|
+
const entry = JSON.parse(raw);
|
|
42
|
+
if (typeof entry.storedAt !== 'number' || Date.now() - entry.storedAt > this.ttlMs)
|
|
43
|
+
return undefined;
|
|
44
|
+
return entry.value;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async set(key, value) {
|
|
51
|
+
if (!this.enabled)
|
|
52
|
+
return;
|
|
53
|
+
try {
|
|
54
|
+
await mkdir(this.dir, { recursive: true });
|
|
55
|
+
const file = this.fileFor(key);
|
|
56
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
57
|
+
const entry = { storedAt: Date.now(), value };
|
|
58
|
+
await writeFile(tmp, JSON.stringify(entry), 'utf8');
|
|
59
|
+
await rename(tmp, file); // escritura atómica
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Ignorado a propósito.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { NotFoundError, HttpError } from '../errors.js';
|
|
2
|
+
import { isoDaysAgo } from '../utils.js';
|
|
3
|
+
import { fetchJson } from './http.js';
|
|
4
|
+
const API = 'https://api.github.com';
|
|
5
|
+
/** Ventana para "mantenedores activos" (autores únicos de commits). */
|
|
6
|
+
export const ACTIVE_WINDOW_DAYS = 365;
|
|
7
|
+
/** Antigüedad mínima de un issue abierto sin comentarios para contarlo como "sin respuesta". */
|
|
8
|
+
export const UNANSWERED_ISSUE_MIN_AGE_DAYS = 30;
|
|
9
|
+
/** Tope de páginas (x100 commits) al contar autores, para acotar el consumo de rate limit. */
|
|
10
|
+
const MAX_COMMIT_PAGES = 3;
|
|
11
|
+
const PER_PAGE = 100;
|
|
12
|
+
const BOT_LOGIN = /\[bot\]$|^(dependabot|renovate|greenkeeper|github-actions|snyk-bot|semantic-release-bot)/i;
|
|
13
|
+
/** Identidad única de un autor de commit; null si es un bot. */
|
|
14
|
+
export function commitAuthorKey(c) {
|
|
15
|
+
const login = c.author?.login;
|
|
16
|
+
if (login) {
|
|
17
|
+
if (c.author?.type === 'Bot' || BOT_LOGIN.test(login))
|
|
18
|
+
return null;
|
|
19
|
+
return `login:${login.toLowerCase()}`;
|
|
20
|
+
}
|
|
21
|
+
const name = c.commit.author?.name ?? '';
|
|
22
|
+
if (BOT_LOGIN.test(name))
|
|
23
|
+
return null;
|
|
24
|
+
const email = c.commit.author?.email?.toLowerCase();
|
|
25
|
+
if (email)
|
|
26
|
+
return `email:${email}`;
|
|
27
|
+
return name ? `name:${name.toLowerCase()}` : null;
|
|
28
|
+
}
|
|
29
|
+
export class GitHubClient {
|
|
30
|
+
opts;
|
|
31
|
+
http;
|
|
32
|
+
now;
|
|
33
|
+
constructor(opts) {
|
|
34
|
+
this.opts = opts;
|
|
35
|
+
const headers = {
|
|
36
|
+
accept: 'application/vnd.github+json',
|
|
37
|
+
'x-github-api-version': '2022-11-28',
|
|
38
|
+
'user-agent': opts.userAgent,
|
|
39
|
+
};
|
|
40
|
+
if (opts.token)
|
|
41
|
+
headers.authorization = `Bearer ${opts.token}`;
|
|
42
|
+
this.http = {
|
|
43
|
+
timeoutMs: opts.timeoutMs,
|
|
44
|
+
retries: opts.retries,
|
|
45
|
+
headers,
|
|
46
|
+
rateLimit: { gate: opts.gate, maxWaitMs: opts.maxRateLimitWaitMs, onWait: opts.onRateLimitWait },
|
|
47
|
+
};
|
|
48
|
+
this.now = opts.now ?? (() => new Date());
|
|
49
|
+
}
|
|
50
|
+
get(pathAndQuery) {
|
|
51
|
+
return fetchJson(`${API}${pathAndQuery}`, this.http);
|
|
52
|
+
}
|
|
53
|
+
async getRepoHealth(owner, repo, directory) {
|
|
54
|
+
const requestedFullName = `${owner}/${repo}`;
|
|
55
|
+
const key = `gh:${requestedFullName.toLowerCase()}:${directory ?? ''}`;
|
|
56
|
+
const cached = await this.opts.cache.get(key);
|
|
57
|
+
if (cached)
|
|
58
|
+
return cached;
|
|
59
|
+
const repoRes = await this.get(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
|
|
60
|
+
const meta = repoRes.data;
|
|
61
|
+
// fetch sigue el 301 automáticamente; lo detectamos comparando el full_name final.
|
|
62
|
+
const redirected = meta.full_name.toLowerCase() !== requestedFullName.toLowerCase();
|
|
63
|
+
const base = `/repos/${meta.full_name}`;
|
|
64
|
+
const now = this.now();
|
|
65
|
+
const [commitStats, issues] = await Promise.all([
|
|
66
|
+
this.commitStats(base, meta.default_branch, directory, now),
|
|
67
|
+
meta.has_issues ? this.unansweredIssues(base, now) : Promise.resolve(null),
|
|
68
|
+
]);
|
|
69
|
+
const info = {
|
|
70
|
+
requestedFullName,
|
|
71
|
+
fullName: meta.full_name,
|
|
72
|
+
redirected,
|
|
73
|
+
archived: meta.archived,
|
|
74
|
+
defaultBranch: meta.default_branch,
|
|
75
|
+
lastCommitAt: commitStats.lastCommitAt,
|
|
76
|
+
activeMaintainers: commitStats.activeMaintainers,
|
|
77
|
+
activeMaintainersCapped: commitStats.capped,
|
|
78
|
+
unansweredIssues: issues?.count ?? null,
|
|
79
|
+
unansweredIssuesCapped: issues?.capped ?? false,
|
|
80
|
+
scopedToDirectory: commitStats.scopedToDirectory,
|
|
81
|
+
};
|
|
82
|
+
await this.opts.cache.set(key, info);
|
|
83
|
+
return info;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Una sola paginación de commits (rama por defecto, últimos 12 meses) sirve para:
|
|
87
|
+
* - autores únicos (mantenedores activos)
|
|
88
|
+
* - fecha del último commit (primer elemento, orden descendente)
|
|
89
|
+
* Solo si no hay commits recientes se hace una petición extra para el último commit histórico.
|
|
90
|
+
* En monorepos se filtra por `path=<directory>`; si el filtro no devuelve nada se cae al repo entero.
|
|
91
|
+
*/
|
|
92
|
+
async commitStats(base, branch, directory, now) {
|
|
93
|
+
const run = async (dir) => {
|
|
94
|
+
const since = isoDaysAgo(ACTIVE_WINDOW_DAYS, now);
|
|
95
|
+
const pathParam = dir ? `&path=${encodeURIComponent(dir)}` : '';
|
|
96
|
+
const authors = new Set();
|
|
97
|
+
let lastCommitAt = null;
|
|
98
|
+
let capped = false;
|
|
99
|
+
for (let page = 1; page <= MAX_COMMIT_PAGES; page++) {
|
|
100
|
+
const commits = await this.safeCommits(`${base}/commits?sha=${encodeURIComponent(branch)}&since=${encodeURIComponent(since)}&per_page=${PER_PAGE}&page=${page}${pathParam}`);
|
|
101
|
+
if (page === 1 && commits[0])
|
|
102
|
+
lastCommitAt = commits[0].commit.committer?.date ?? null;
|
|
103
|
+
for (const c of commits) {
|
|
104
|
+
const k = commitAuthorKey(c);
|
|
105
|
+
if (k)
|
|
106
|
+
authors.add(k);
|
|
107
|
+
}
|
|
108
|
+
if (commits.length < PER_PAGE)
|
|
109
|
+
break;
|
|
110
|
+
if (page === MAX_COMMIT_PAGES)
|
|
111
|
+
capped = true;
|
|
112
|
+
}
|
|
113
|
+
if (!lastCommitAt) {
|
|
114
|
+
const latest = await this.safeCommits(`${base}/commits?sha=${encodeURIComponent(branch)}&per_page=1${pathParam}`);
|
|
115
|
+
lastCommitAt = latest[0]?.commit.committer?.date ?? null;
|
|
116
|
+
}
|
|
117
|
+
return { lastCommitAt, activeMaintainers: authors.size, capped };
|
|
118
|
+
};
|
|
119
|
+
if (directory) {
|
|
120
|
+
const scoped = await run(directory);
|
|
121
|
+
if (scoped.lastCommitAt)
|
|
122
|
+
return { ...scoped, scopedToDirectory: directory };
|
|
123
|
+
}
|
|
124
|
+
return { ...(await run(undefined)), scopedToDirectory: null };
|
|
125
|
+
}
|
|
126
|
+
/** Repos vacíos devuelven 409: lo tratamos como "sin commits". */
|
|
127
|
+
async safeCommits(pathAndQuery) {
|
|
128
|
+
try {
|
|
129
|
+
return (await this.get(pathAndQuery)).data;
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
if (err instanceof HttpError && err.status === 409)
|
|
133
|
+
return [];
|
|
134
|
+
if (err instanceof NotFoundError)
|
|
135
|
+
return [];
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Issues abiertos hace más de 30 días y con 0 comentarios. Se piden los 100 más antiguos
|
|
141
|
+
* (orden ascendente), que son justamente los candidatos; si hay más de 100 abiertos el
|
|
142
|
+
* resultado se marca como "capped" (cota inferior).
|
|
143
|
+
*/
|
|
144
|
+
async unansweredIssues(base, now) {
|
|
145
|
+
const { data } = await this.get(`${base}/issues?state=open&sort=created&direction=asc&per_page=${PER_PAGE}`);
|
|
146
|
+
const cutoff = Date.parse(isoDaysAgo(UNANSWERED_ISSUE_MIN_AGE_DAYS, now));
|
|
147
|
+
const count = data.filter((i) => !i.pull_request && i.comments === 0 && Date.parse(i.created_at) < cutoff).length;
|
|
148
|
+
return { count, capped: data.length === PER_PAGE };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { HttpError, NetworkError, NotFoundError, RateLimitError, TimeoutError } from '../errors.js';
|
|
2
|
+
import { sleep } from '../utils.js';
|
|
3
|
+
/**
|
|
4
|
+
* Compuerta compartida de rate limit: cuando una respuesta indica que el cupo se agotó
|
|
5
|
+
* (X-RateLimit-Remaining: 0), todas las peticiones posteriores esperan hasta el reset
|
|
6
|
+
* o abortan rápido si la espera supera el máximo permitido.
|
|
7
|
+
*/
|
|
8
|
+
export class RateLimitGate {
|
|
9
|
+
blockedUntil = 0;
|
|
10
|
+
remaining = null;
|
|
11
|
+
limit = null;
|
|
12
|
+
block(untilMs) {
|
|
13
|
+
this.blockedUntil = Math.max(this.blockedUntil, untilMs);
|
|
14
|
+
}
|
|
15
|
+
get resetAt() {
|
|
16
|
+
return this.blockedUntil > 0 ? new Date(this.blockedUntil) : null;
|
|
17
|
+
}
|
|
18
|
+
async wait(maxWaitMs, onWait) {
|
|
19
|
+
const ms = this.blockedUntil - Date.now();
|
|
20
|
+
if (ms <= 0)
|
|
21
|
+
return;
|
|
22
|
+
if (ms > maxWaitMs) {
|
|
23
|
+
throw new RateLimitError(new Date(this.blockedUntil), 'Configura GITHUB_TOKEN (5000 req/h) o aumenta --max-wait.');
|
|
24
|
+
}
|
|
25
|
+
onWait?.(ms, new Date(this.blockedUntil));
|
|
26
|
+
await sleep(ms);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const MAX_BACKOFF_MS = 10_000;
|
|
30
|
+
export function backoffDelay(attempt, baseMs = 500) {
|
|
31
|
+
const exp = Math.min(baseMs * 2 ** attempt, MAX_BACKOFF_MS);
|
|
32
|
+
return exp + Math.floor(Math.random() * 250);
|
|
33
|
+
}
|
|
34
|
+
function intHeader(headers, name) {
|
|
35
|
+
const value = headers.get(name);
|
|
36
|
+
if (value === null)
|
|
37
|
+
return null;
|
|
38
|
+
const n = Number.parseInt(value, 10);
|
|
39
|
+
return Number.isFinite(n) ? n : null;
|
|
40
|
+
}
|
|
41
|
+
function isTimeout(err) {
|
|
42
|
+
return err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
|
|
43
|
+
}
|
|
44
|
+
async function safeText(res) {
|
|
45
|
+
try {
|
|
46
|
+
return await res.text();
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return '';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* GET JSON con timeout por request, reintentos con backoff exponencial (red, 403, 429, 5xx)
|
|
54
|
+
* y lectura de cabeceras de rate limit (X-RateLimit-Remaining / X-RateLimit-Reset / Retry-After).
|
|
55
|
+
*/
|
|
56
|
+
export async function fetchJson(url, options) {
|
|
57
|
+
const { retries, timeoutMs, rateLimit } = options;
|
|
58
|
+
const baseMs = options.backoffBaseMs ?? 500;
|
|
59
|
+
for (let attempt = 0;; attempt++) {
|
|
60
|
+
if (rateLimit)
|
|
61
|
+
await rateLimit.gate.wait(rateLimit.maxWaitMs, rateLimit.onWait);
|
|
62
|
+
let res;
|
|
63
|
+
try {
|
|
64
|
+
res = await fetch(url, {
|
|
65
|
+
headers: options.headers,
|
|
66
|
+
redirect: 'follow',
|
|
67
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
const typed = isTimeout(err) ? new TimeoutError(url, timeoutMs) : new NetworkError(url, err);
|
|
72
|
+
if (attempt >= retries)
|
|
73
|
+
throw typed;
|
|
74
|
+
await sleep(backoffDelay(attempt, baseMs));
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const remaining = intHeader(res.headers, 'x-ratelimit-remaining');
|
|
78
|
+
const reset = intHeader(res.headers, 'x-ratelimit-reset');
|
|
79
|
+
if (rateLimit) {
|
|
80
|
+
if (remaining !== null)
|
|
81
|
+
rateLimit.gate.remaining = remaining;
|
|
82
|
+
const limit = intHeader(res.headers, 'x-ratelimit-limit');
|
|
83
|
+
if (limit !== null)
|
|
84
|
+
rateLimit.gate.limit = limit;
|
|
85
|
+
// +1 s de margen por desfase de reloj.
|
|
86
|
+
if (remaining === 0 && reset !== null)
|
|
87
|
+
rateLimit.gate.block(reset * 1000 + 1000);
|
|
88
|
+
}
|
|
89
|
+
if (res.ok) {
|
|
90
|
+
const data = (await res.json());
|
|
91
|
+
return { data, status: res.status, redirected: res.redirected, finalUrl: res.url, headers: res.headers };
|
|
92
|
+
}
|
|
93
|
+
if (res.status === 404 || res.status === 410) {
|
|
94
|
+
await res.body?.cancel();
|
|
95
|
+
throw new NotFoundError(url);
|
|
96
|
+
}
|
|
97
|
+
const rateLimited = (res.status === 403 || res.status === 429) && remaining === 0;
|
|
98
|
+
const retryable = res.status === 403 || res.status === 429 || res.status >= 500;
|
|
99
|
+
if (!retryable || attempt >= retries) {
|
|
100
|
+
if (rateLimited) {
|
|
101
|
+
await res.body?.cancel();
|
|
102
|
+
throw new RateLimitError(reset !== null ? new Date(reset * 1000) : null);
|
|
103
|
+
}
|
|
104
|
+
throw new HttpError(url, res.status, await safeText(res));
|
|
105
|
+
}
|
|
106
|
+
await res.body?.cancel();
|
|
107
|
+
// Rate limit primario: la compuerta esperará (o abortará) al inicio de la siguiente iteración.
|
|
108
|
+
if (rateLimited)
|
|
109
|
+
continue;
|
|
110
|
+
// Rate limit secundario / 429: respetar Retry-After si existe.
|
|
111
|
+
const retryAfter = intHeader(res.headers, 'retry-after');
|
|
112
|
+
if (retryAfter !== null) {
|
|
113
|
+
const waitMs = retryAfter * 1000;
|
|
114
|
+
if (rateLimit && waitMs > rateLimit.maxWaitMs) {
|
|
115
|
+
throw new RateLimitError(new Date(Date.now() + waitMs), 'GitHub pidió esperar (Retry-After).');
|
|
116
|
+
}
|
|
117
|
+
await sleep(waitMs);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
await sleep(backoffDelay(attempt, baseMs));
|
|
121
|
+
}
|
|
122
|
+
}
|