@efraindrummer/ghostdeps 0.0.0-stage → 0.3.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.
@@ -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
+ }
@@ -0,0 +1,115 @@
1
+ import { normalizeRepository } from '../parser/repoUrl.js';
2
+ import { fetchJson } from './http.js';
3
+ const REGISTRY = 'https://registry.npmjs.org';
4
+ /** Nº de versiones previas a la última que se usan para comparar publicadores. */
5
+ const PUBLISHER_HISTORY = 5;
6
+ function personName(p) {
7
+ if (!p)
8
+ return null;
9
+ if (typeof p === 'string')
10
+ return p.replace(/\s*<.*$/, '').trim() || null;
11
+ return p.name ?? p.email ?? null;
12
+ }
13
+ function personList(value) {
14
+ if (value === undefined)
15
+ return null;
16
+ const arr = Array.isArray(value) ? value : [value];
17
+ return [...new Set(arr.map(personName).filter((n) => !!n))].sort();
18
+ }
19
+ function diffMaintainers(previous, current) {
20
+ const prev = new Set(previous);
21
+ const curr = new Set(current);
22
+ return {
23
+ added: current.filter((m) => !prev.has(m)),
24
+ removed: previous.filter((m) => !curr.has(m)),
25
+ };
26
+ }
27
+ export function registryUrl(name) {
28
+ const encoded = name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
29
+ return `${REGISTRY}/${encoded}`;
30
+ }
31
+ /** Extracción pura (testeable) de la información relevante del "packument" de npm. */
32
+ export function extractNpmInfo(name, doc) {
33
+ const versions = doc.versions ?? {};
34
+ const time = doc.time ?? {};
35
+ // Versiones ordenadas cronológicamente por fecha de publicación.
36
+ const chronological = Object.entries(time)
37
+ .filter(([v]) => v !== 'created' && v !== 'modified' && versions[v] !== undefined)
38
+ .sort(([, a], [, b]) => Date.parse(a) - Date.parse(b))
39
+ .map(([v]) => v);
40
+ const latestTag = doc['dist-tags']?.latest;
41
+ const latestVersion = latestTag && versions[latestTag] ? latestTag : (chronological[chronological.length - 1] ?? null);
42
+ const latestDoc = latestVersion ? versions[latestVersion] : undefined;
43
+ const latestPublishedAt = latestVersion ? (time[latestVersion] ?? null) : null;
44
+ // Versiones publicadas antes que la "latest" (excluye versiones posteriores, p. ej. backports).
45
+ const latestTime = latestPublishedAt ? Date.parse(latestPublishedAt) : Number.POSITIVE_INFINITY;
46
+ const previous = chronological.filter((v) => v !== latestVersion && Date.parse(time[v] ?? '') < latestTime);
47
+ const previousVersion = previous[previous.length - 1] ?? null;
48
+ const previousDoc = previousVersion ? versions[previousVersion] : undefined;
49
+ const latestPublisher = personName(latestDoc?._npmUser);
50
+ const previousPublishers = [
51
+ ...new Set(previous
52
+ .slice(-PUBLISHER_HISTORY)
53
+ .map((v) => personName(versions[v]?._npmUser))
54
+ .filter((n) => !!n)),
55
+ ];
56
+ const latestMaintainers = personList(latestDoc?.maintainers);
57
+ const previousMaintainers = personList(previousDoc?.maintainers);
58
+ const maintainersChange = latestMaintainers && previousMaintainers ? diffMaintainers(previousMaintainers, latestMaintainers) : null;
59
+ // Repo: preferimos el de la última versión; si falta, el del documento; si falta, homepage.
60
+ const repoField = latestDoc?.repository ?? doc.repository;
61
+ let repository = normalizeRepository(repoField);
62
+ if (!repository) {
63
+ const homepage = latestDoc?.homepage ?? doc.homepage;
64
+ const fromHomepage = homepage ? normalizeRepository(homepage) : null;
65
+ if (fromHomepage && fromHomepage.host === 'github')
66
+ repository = fromHomepage;
67
+ }
68
+ let rawRepositoryUrl = null;
69
+ if (typeof repoField === 'string')
70
+ rawRepositoryUrl = repoField;
71
+ else if (repoField && typeof repoField === 'object') {
72
+ const url = repoField.url;
73
+ if (typeof url === 'string')
74
+ rawRepositoryUrl = url;
75
+ }
76
+ const deprecatedRaw = latestDoc?.deprecated;
77
+ const deprecated = typeof deprecatedRaw === 'string' && deprecatedRaw.length > 0
78
+ ? deprecatedRaw
79
+ : deprecatedRaw === true
80
+ ? 'deprecated'
81
+ : null;
82
+ return {
83
+ name: doc.name ?? name,
84
+ latestVersion,
85
+ latestPublishedAt,
86
+ previousPublishedAt: previousVersion ? (time[previousVersion] ?? null) : null,
87
+ deprecated,
88
+ maintainers: personList(doc.maintainers) ?? [],
89
+ repository,
90
+ rawRepositoryUrl,
91
+ latestPublisher,
92
+ previousPublishers,
93
+ maintainersChange,
94
+ };
95
+ }
96
+ export class NpmClient {
97
+ opts;
98
+ constructor(opts) {
99
+ this.opts = opts;
100
+ }
101
+ async getPackageInfo(name) {
102
+ const key = `npm:${name}`;
103
+ const cached = await this.opts.cache.get(key);
104
+ if (cached)
105
+ return cached;
106
+ const { data } = await fetchJson(registryUrl(name), {
107
+ timeoutMs: this.opts.timeoutMs,
108
+ retries: this.opts.retries,
109
+ headers: { accept: 'application/json', 'user-agent': this.opts.userAgent },
110
+ });
111
+ const info = extractNpmInfo(name, data);
112
+ await this.opts.cache.set(key, info);
113
+ return info;
114
+ }
115
+ }
package/dist/config.js ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Configuración por proyecto. Se busca, en orden:
3
+ * 1. el archivo indicado con --config
4
+ * 2. .ghostdepsrc.json o .ghostdepsrc (JSON) en el directorio analizado
5
+ * 3. la clave "ghostdeps" del package.json
6
+ * Precedencia final: flags de CLI > archivo de configuración > valores por defecto.
7
+ */
8
+ import { readFile } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { ConfigError } from './errors.js';
11
+ import { DEFAULT_WEIGHTS, THRESHOLDS } from './scoring/scoring.js';
12
+ export const CONFIG_FILES = ['.ghostdepsrc.json', '.ghostdepsrc'];
13
+ const TOP_LEVEL_KEYS = ['$schema', 'ignore', 'failUnder', 'dev', 'transitive', 'depth', 'concurrency', 'weights', 'thresholds'];
14
+ const NUMERIC_WEIGHTS = [
15
+ 'archived',
16
+ 'deprecated',
17
+ 'repoRedirect',
18
+ 'maintainersChanged',
19
+ 'newPublisher',
20
+ 'hijackPattern',
21
+ 'dormantRevivalDays',
22
+ ];
23
+ const TIER_WEIGHTS = ['abandonment', 'unansweredIssues'];
24
+ const WEIGHT_KEYS = [...NUMERIC_WEIGHTS, ...TIER_WEIGHTS, 'stalePublish', 'busFactor'];
25
+ function isObj(v) {
26
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
27
+ }
28
+ function checkKeys(obj, allowed, where, source) {
29
+ const unknown = Object.keys(obj).filter((k) => !allowed.includes(k));
30
+ if (unknown.length > 0) {
31
+ throw new ConfigError(`${source}: clave(s) desconocida(s) en ${where}: ${unknown.join(', ')}. Permitidas: ${allowed.join(', ')}.`);
32
+ }
33
+ }
34
+ function num(v, where, source, min, max, integer = false) {
35
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < min || v > max || (integer && !Number.isInteger(v))) {
36
+ throw new ConfigError(`${source}: "${where}" debe ser un ${integer ? 'entero' : 'número'} entre ${min} y ${max}.`);
37
+ }
38
+ return v;
39
+ }
40
+ function bool(v, where, source) {
41
+ if (typeof v !== 'boolean')
42
+ throw new ConfigError(`${source}: "${where}" debe ser true o false.`);
43
+ return v;
44
+ }
45
+ function tier(v, where, source) {
46
+ if (!isObj(v))
47
+ throw new ConfigError(`${source}: "${where}" debe ser un objeto { "threshold", "points" }.`);
48
+ checkKeys(v, ['threshold', 'points'], where, source);
49
+ return {
50
+ threshold: num(v.threshold, `${where}.threshold`, source, 0, 100_000),
51
+ points: num(v.points, `${where}.points`, source, 0, 100),
52
+ };
53
+ }
54
+ function tiers(v, where, source) {
55
+ if (!Array.isArray(v))
56
+ throw new ConfigError(`${source}: "${where}" debe ser un array de tramos.`);
57
+ // El motor espera los tramos de mayor a menor umbral.
58
+ return v.map((t, i) => tier(t, `${where}[${i}]`, source)).sort((a, b) => b.threshold - a.threshold);
59
+ }
60
+ function parseWeights(v, source) {
61
+ const w = {
62
+ ...DEFAULT_WEIGHTS,
63
+ busFactor: { ...DEFAULT_WEIGHTS.busFactor },
64
+ stalePublish: { ...DEFAULT_WEIGHTS.stalePublish },
65
+ };
66
+ if (v === undefined)
67
+ return w;
68
+ if (!isObj(v))
69
+ throw new ConfigError(`${source}: "weights" debe ser un objeto.`);
70
+ checkKeys(v, WEIGHT_KEYS, 'weights', source);
71
+ for (const key of NUMERIC_WEIGHTS) {
72
+ if (v[key] !== undefined) {
73
+ const max = key === 'dormantRevivalDays' ? 100_000 : 100;
74
+ w[key] = num(v[key], `weights.${key}`, source, 0, max);
75
+ }
76
+ }
77
+ for (const key of TIER_WEIGHTS) {
78
+ if (v[key] !== undefined)
79
+ w[key] = tiers(v[key], `weights.${key}`, source);
80
+ }
81
+ if (v.stalePublish !== undefined)
82
+ w.stalePublish = tier(v.stalePublish, 'weights.stalePublish', source);
83
+ if (v.busFactor !== undefined) {
84
+ if (!isObj(v.busFactor))
85
+ throw new ConfigError(`${source}: "weights.busFactor" debe ser un objeto.`);
86
+ checkKeys(v.busFactor, ['zero', 'one', 'two'], 'weights.busFactor', source);
87
+ for (const k of ['zero', 'one', 'two']) {
88
+ if (v.busFactor[k] !== undefined)
89
+ w.busFactor[k] = num(v.busFactor[k], `weights.busFactor.${k}`, source, 0, 100);
90
+ }
91
+ }
92
+ return w;
93
+ }
94
+ function parseThresholds(v, source) {
95
+ const t = { ...THRESHOLDS };
96
+ if (v === undefined)
97
+ return t;
98
+ if (!isObj(v))
99
+ throw new ConfigError(`${source}: "thresholds" debe ser un objeto.`);
100
+ checkKeys(v, ['healthy', 'caution'], 'thresholds', source);
101
+ if (v.healthy !== undefined)
102
+ t.healthy = num(v.healthy, 'thresholds.healthy', source, 0, 100);
103
+ if (v.caution !== undefined)
104
+ t.caution = num(v.caution, 'thresholds.caution', source, 0, 100);
105
+ if (t.caution > t.healthy) {
106
+ throw new ConfigError(`${source}: "thresholds.caution" (${t.caution}) no puede ser mayor que "healthy" (${t.healthy}).`);
107
+ }
108
+ return t;
109
+ }
110
+ /** Valida y normaliza un objeto de configuración ya parseado. */
111
+ export function parseConfig(raw, source) {
112
+ if (!isObj(raw))
113
+ throw new ConfigError(`${source}: la configuración debe ser un objeto JSON.`);
114
+ checkKeys(raw, TOP_LEVEL_KEYS, 'la raíz', source);
115
+ let ignore = [];
116
+ if (raw.ignore !== undefined) {
117
+ if (!Array.isArray(raw.ignore) || raw.ignore.some((p) => typeof p !== 'string' || p.trim() === '')) {
118
+ throw new ConfigError(`${source}: "ignore" debe ser un array de nombres/patrones (ej. ["left-pad", "@types/*"]).`);
119
+ }
120
+ ignore = raw.ignore.map((p) => p.trim());
121
+ }
122
+ const config = {
123
+ source,
124
+ ignore,
125
+ weights: parseWeights(raw.weights, source),
126
+ thresholds: parseThresholds(raw.thresholds, source),
127
+ };
128
+ if (raw.failUnder !== undefined)
129
+ config.failUnder = num(raw.failUnder, 'failUnder', source, 0, 100);
130
+ if (raw.dev !== undefined)
131
+ config.dev = bool(raw.dev, 'dev', source);
132
+ if (raw.transitive !== undefined)
133
+ config.transitive = bool(raw.transitive, 'transitive', source);
134
+ if (raw.depth !== undefined)
135
+ config.depth = num(raw.depth, 'depth', source, 1, 100, true);
136
+ if (raw.concurrency !== undefined)
137
+ config.concurrency = num(raw.concurrency, 'concurrency', source, 1, 32, true);
138
+ return config;
139
+ }
140
+ export function defaultConfig() {
141
+ return { ...parseConfig({}, '(defaults)'), source: null };
142
+ }
143
+ async function readJson(file) {
144
+ let content;
145
+ try {
146
+ content = await readFile(file, 'utf8');
147
+ }
148
+ catch (err) {
149
+ if (err.code === 'ENOENT')
150
+ return undefined;
151
+ throw new ConfigError(`No se pudo leer ${file}: ${err.message}`, { cause: err });
152
+ }
153
+ try {
154
+ return JSON.parse(content);
155
+ }
156
+ catch (cause) {
157
+ throw new ConfigError(`${file} no es un JSON válido.`, { cause });
158
+ }
159
+ }
160
+ export async function loadConfig(dir, explicitPath) {
161
+ if (explicitPath) {
162
+ const file = path.resolve(explicitPath);
163
+ const raw = await readJson(file);
164
+ if (raw === undefined)
165
+ throw new ConfigError(`No existe el archivo de configuración ${file}.`);
166
+ return parseConfig(raw, file);
167
+ }
168
+ for (const name of CONFIG_FILES) {
169
+ const file = path.resolve(dir, name);
170
+ const raw = await readJson(file);
171
+ if (raw !== undefined)
172
+ return parseConfig(raw, file);
173
+ }
174
+ const pkgFile = path.resolve(dir, 'package.json');
175
+ try {
176
+ const pkg = await readJson(pkgFile);
177
+ if (isObj(pkg) && pkg.ghostdeps !== undefined)
178
+ return parseConfig(pkg.ghostdeps, `${pkgFile} ("ghostdeps")`);
179
+ }
180
+ catch {
181
+ // Un package.json inválido lo reportará el lector de manifest con un mensaje más preciso.
182
+ }
183
+ return defaultConfig();
184
+ }
185
+ /** Convierte un patrón con `*` en RegExp anclada. */
186
+ function patternToRegExp(pattern) {
187
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
188
+ return new RegExp(`^${escaped}$`);
189
+ }
190
+ /** Devuelve un predicado que indica si un paquete está ignorado (por nombre o patrón con `*`). */
191
+ export function createIgnoreMatcher(patterns) {
192
+ const regexes = patterns.map(patternToRegExp);
193
+ return (name) => regexes.some((r) => r.test(name));
194
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Jerarquía de errores tipados. Cada error lleva un `code` estable (útil en --json/CI)
3
+ * y un mensaje legible para humanos.
4
+ */
5
+ export class GhostDepsError extends Error {
6
+ code;
7
+ constructor(code, message, options) {
8
+ super(message, options);
9
+ this.name = new.target.name;
10
+ this.code = code;
11
+ }
12
+ }
13
+ export class ManifestError extends GhostDepsError {
14
+ constructor(message, options) {
15
+ super('MANIFEST_ERROR', message, options);
16
+ }
17
+ }
18
+ export class ConfigError extends GhostDepsError {
19
+ constructor(message, options) {
20
+ super('CONFIG_ERROR', message, options);
21
+ }
22
+ }
23
+ export class NetworkError extends GhostDepsError {
24
+ url;
25
+ constructor(url, cause) {
26
+ const detail = cause instanceof Error ? cause.message : String(cause);
27
+ super('NETWORK_ERROR', `Error de red al consultar ${url}: ${detail}`, { cause });
28
+ this.url = url;
29
+ }
30
+ }
31
+ export class TimeoutError extends GhostDepsError {
32
+ url;
33
+ timeoutMs;
34
+ constructor(url, timeoutMs) {
35
+ super('TIMEOUT', `Timeout (${timeoutMs} ms) al consultar ${url}`);
36
+ this.url = url;
37
+ this.timeoutMs = timeoutMs;
38
+ }
39
+ }
40
+ export class HttpError extends GhostDepsError {
41
+ url;
42
+ status;
43
+ constructor(url, status, body) {
44
+ const snippet = body ? `: ${body.slice(0, 200)}` : '';
45
+ super('HTTP_ERROR', `HTTP ${status} al consultar ${url}${snippet}`);
46
+ this.url = url;
47
+ this.status = status;
48
+ }
49
+ }
50
+ export class NotFoundError extends GhostDepsError {
51
+ url;
52
+ constructor(url) {
53
+ super('NOT_FOUND', `Recurso no encontrado (404): ${url}`);
54
+ this.url = url;
55
+ }
56
+ }
57
+ export class RateLimitError extends GhostDepsError {
58
+ resetAt;
59
+ constructor(resetAt, hint) {
60
+ const when = resetAt ? ` hasta las ${resetAt.toLocaleTimeString()}` : '';
61
+ super('RATE_LIMITED', `Rate limit de GitHub agotado${when}.${hint ? ' ' + hint : ''}`);
62
+ this.resetAt = resetAt;
63
+ }
64
+ }
65
+ export function errorMessage(err) {
66
+ if (err instanceof Error)
67
+ return err.message;
68
+ return String(err);
69
+ }