@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,194 @@
1
+ /**
2
+ * Servidor MCP (Model Context Protocol) para GhostDeps.
3
+ * Permite que agentes de IA como Claude Desktop, Cursor, Gemini CLI o ChatGPT
4
+ * llamen a GhostDeps como una herramienta (tool) a través de stdio (JSON-RPC 2.0).
5
+ */
6
+ import readline from 'node:readline';
7
+ import path from 'node:path';
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 { readLockfile, resolveTransitive } from '../parser/lockfile.js';
15
+ import { readManifest } from '../parser/manifest.js';
16
+ import { renderMarkdown } from '../render/markdown.js';
17
+ export function createAuditToolDefinition() {
18
+ return {
19
+ name: 'ghostdeps_audit',
20
+ description: 'Audita la salud social, de mantenimiento y ciberseguridad de las dependencias de un proyecto Node.js / JavaScript. ' +
21
+ 'Detecta paquetes abandonados, bus factor crítico (0 o 1 mantenedor), repositorios archivados y posibles señales de secuestro (hijacking).',
22
+ inputSchema: {
23
+ type: 'object',
24
+ properties: {
25
+ path: {
26
+ type: 'string',
27
+ description: 'Ruta al directorio que contiene el package.json (por defecto el directorio actual).',
28
+ },
29
+ dev: {
30
+ type: 'boolean',
31
+ description: 'Incluir también devDependencies en el análisis.',
32
+ },
33
+ transitive: {
34
+ type: 'boolean',
35
+ description: 'Incluir dependencias transitivas leyendo package-lock.json o yarn.lock.',
36
+ },
37
+ depth: {
38
+ type: 'integer',
39
+ description: 'Profundidad máxima para dependencias transitivas (1 = solo directas).',
40
+ },
41
+ failUnder: {
42
+ type: 'number',
43
+ description: 'Umbral mínimo de Health Score (0 a 100).',
44
+ },
45
+ ignore: {
46
+ type: 'array',
47
+ items: { type: 'string' },
48
+ description: 'Lista de nombres o patrones comodín a ignorar (ej: ["@types/*"]).',
49
+ },
50
+ },
51
+ },
52
+ };
53
+ }
54
+ export async function executeMcpAudit(args = {}, version) {
55
+ const targetDir = typeof args.path === 'string' && args.path ? path.resolve(args.path) : process.cwd();
56
+ const includeDev = Boolean(args.dev);
57
+ const includeTransitive = Boolean(args.transitive);
58
+ const depth = typeof args.depth === 'number' ? args.depth : undefined;
59
+ const failUnder = typeof args.failUnder === 'number' ? args.failUnder : undefined;
60
+ const ignoreList = Array.isArray(args.ignore) ? args.ignore.filter((i) => typeof i === 'string') : [];
61
+ const config = await loadConfig(targetDir);
62
+ const isIgnored = createIgnoreMatcher([...config.ignore, ...ignoreList]);
63
+ const manifest = await readManifest(targetDir, { includeDev: includeDev || (config.dev ?? false) });
64
+ let all = manifest.dependencies;
65
+ if (includeTransitive || config.transitive) {
66
+ try {
67
+ const { lock } = await readLockfile(targetDir);
68
+ const trans = resolveTransitive(lock, manifest.dependencies, {
69
+ maxDepth: depth ?? config.depth ?? Number.POSITIVE_INFINITY,
70
+ });
71
+ all = [...manifest.dependencies, ...trans];
72
+ }
73
+ catch (err) {
74
+ process.stderr.write(`[GhostDeps MCP] Advertencia al leer lockfile: ${err.message}\n`);
75
+ }
76
+ }
77
+ const ignored = all.filter((d) => isIgnored(d.name) || isIgnored(d.registryName)).map((d) => d.name);
78
+ const toAnalyze = all.filter((d) => !ignored.includes(d.name));
79
+ const token = process.env.GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || undefined;
80
+ const userAgent = `ghostdeps/${version} (+https://github.com/ghostdeps/ghostdeps)`;
81
+ const cache = new DiskCache(defaultCacheDir(), 24 * 3_600_000, true);
82
+ const gate = new RateLimitGate();
83
+ const now = new Date();
84
+ const npm = new NpmClient({ cache, timeoutMs: 15_000, retries: 3, userAgent });
85
+ const github = new GitHubClient({
86
+ cache,
87
+ token,
88
+ timeoutMs: 15_000,
89
+ retries: 3,
90
+ userAgent,
91
+ gate,
92
+ maxRateLimitWaitMs: 30_000,
93
+ now: () => now,
94
+ });
95
+ const reports = await analyzeAll(toAnalyze, { npm, github, now, weights: config.weights, thresholds: config.thresholds }, config.concurrency ?? 4);
96
+ const sorted = sortReports(reports);
97
+ const summary = summarize(sorted);
98
+ const failing = failUnder === undefined
99
+ ? []
100
+ : sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
101
+ return renderMarkdown(sorted, summary, now, {
102
+ version,
103
+ projectName: manifest.projectName,
104
+ thresholds: config.thresholds,
105
+ failUnder,
106
+ failing,
107
+ ignored,
108
+ });
109
+ }
110
+ export function startMcpServer(version) {
111
+ const rl = readline.createInterface({
112
+ input: process.stdin,
113
+ output: process.stdout,
114
+ terminal: false,
115
+ });
116
+ const sendResponse = (id, result) => {
117
+ if (id === undefined)
118
+ return;
119
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
120
+ process.stdout.write(`${msg}\n`);
121
+ };
122
+ const sendError = (id, code, message) => {
123
+ if (id === undefined)
124
+ return;
125
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
126
+ process.stdout.write(`${msg}\n`);
127
+ };
128
+ process.stderr.write(`[GhostDeps MCP Server] Iniciado sobre stdio (v${version})\n`);
129
+ rl.on('line', async (line) => {
130
+ const trimmed = line.trim();
131
+ if (!trimmed)
132
+ return;
133
+ let req;
134
+ try {
135
+ req = JSON.parse(trimmed);
136
+ }
137
+ catch {
138
+ sendError(undefined, -32700, 'Parse error: invalid JSON');
139
+ return;
140
+ }
141
+ const { id, method, params } = req;
142
+ try {
143
+ if (method === 'initialize') {
144
+ sendResponse(id, {
145
+ protocolVersion: '2024-11-05',
146
+ capabilities: { tools: {} },
147
+ serverInfo: {
148
+ name: '@efraindrummer/ghostdeps',
149
+ version,
150
+ },
151
+ });
152
+ return;
153
+ }
154
+ if (method === 'notifications/initialized') {
155
+ // Notificación del cliente, no requiere respuesta
156
+ return;
157
+ }
158
+ if (method === 'ping') {
159
+ sendResponse(id, {});
160
+ return;
161
+ }
162
+ if (method === 'tools/list') {
163
+ sendResponse(id, {
164
+ tools: [createAuditToolDefinition()],
165
+ });
166
+ return;
167
+ }
168
+ if (method === 'tools/call') {
169
+ const toolName = params?.name;
170
+ if (toolName !== 'ghostdeps_audit') {
171
+ sendError(id, -32601, `Herramienta desconocida: ${toolName}`);
172
+ return;
173
+ }
174
+ const args = params?.arguments ?? {};
175
+ const markdown = await executeMcpAudit(args, version);
176
+ sendResponse(id, {
177
+ content: [
178
+ {
179
+ type: 'text',
180
+ text: markdown,
181
+ },
182
+ ],
183
+ isError: false,
184
+ });
185
+ return;
186
+ }
187
+ // Método no implementado
188
+ sendError(id, -32601, `Método no soportado: ${method}`);
189
+ }
190
+ catch (err) {
191
+ sendError(id, -32603, `Error interno ejecutando ${method}: ${err.message}`);
192
+ }
193
+ });
194
+ }
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Resolución de dependencias transitivas a partir de lockfiles:
3
+ * - package-lock.json / npm-shrinkwrap.json (npm v2/v3, npm >= 7)
4
+ * - yarn.lock (Yarn v1 clásico)
5
+ *
6
+ * Recorre el grafo en anchura (BFS) para registrar el camino más corto
7
+ * desde el proyecto (`via`) y la profundidad de cada dependencia.
8
+ */
9
+ import { readFile } from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { ManifestError } from '../errors.js';
12
+ export const LOCKFILE_NAMES = ['npm-shrinkwrap.json', 'package-lock.json', 'yarn.lock'];
13
+ function unquote(s) {
14
+ const t = s.trim();
15
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
16
+ return t.slice(1, -1);
17
+ }
18
+ return t;
19
+ }
20
+ /**
21
+ * Parser ligero y seguro para yarn.lock (v1).
22
+ * Mapea especificaciones (`foo@^1.0.0`) a la versión resuelta y sus dependencias.
23
+ */
24
+ export function parseYarnLock(content) {
25
+ const entries = new Map();
26
+ const lines = content.split(/\r?\n/);
27
+ let currentHeaders = [];
28
+ let currentPkg = null;
29
+ let section = 'none';
30
+ const flush = () => {
31
+ if (currentHeaders.length > 0 && currentPkg && currentPkg.name && currentPkg.version) {
32
+ const pkg = {
33
+ name: currentPkg.name,
34
+ version: currentPkg.version,
35
+ resolved: currentPkg.resolved,
36
+ dependencies: currentPkg.dependencies ?? {},
37
+ optionalDependencies: currentPkg.optionalDependencies ?? {},
38
+ };
39
+ for (const h of currentHeaders) {
40
+ entries.set(h, pkg);
41
+ }
42
+ }
43
+ currentHeaders = [];
44
+ currentPkg = null;
45
+ section = 'none';
46
+ };
47
+ for (let i = 0; i < lines.length; i++) {
48
+ const rawLine = lines[i] ?? '';
49
+ const trimmed = rawLine.trim();
50
+ if (!trimmed || trimmed.startsWith('#'))
51
+ continue;
52
+ // Header de nivel superior (ej. "foo@^1.0.0", "foo@^1.2.0":)
53
+ if (!rawLine.startsWith(' ') && trimmed.endsWith(':')) {
54
+ flush();
55
+ const headerStr = trimmed.slice(0, -1);
56
+ const parts = headerStr.split(',').map((p) => unquote(p));
57
+ currentHeaders = parts;
58
+ const first = parts[0] ?? '';
59
+ const at = first.lastIndexOf('@');
60
+ const name = at > 0 ? first.slice(0, at) : first;
61
+ currentPkg = { name, dependencies: {}, optionalDependencies: {} };
62
+ continue;
63
+ }
64
+ if (!currentPkg)
65
+ continue;
66
+ // Propiedades directas (2 espacios de indentación)
67
+ if (rawLine.startsWith(' ') && !rawLine.startsWith(' ')) {
68
+ section = 'none';
69
+ if (trimmed.startsWith('version ')) {
70
+ currentPkg.version = unquote(trimmed.slice(8));
71
+ }
72
+ else if (trimmed.startsWith('resolved ')) {
73
+ currentPkg.resolved = unquote(trimmed.slice(9));
74
+ }
75
+ else if (trimmed === 'dependencies:') {
76
+ section = 'dependencies';
77
+ }
78
+ else if (trimmed === 'optionalDependencies:') {
79
+ section = 'optionalDependencies';
80
+ }
81
+ continue;
82
+ }
83
+ // Sub-claves de dependencias (4 espacios de indentación)
84
+ if (rawLine.startsWith(' ') && (section === 'dependencies' || section === 'optionalDependencies')) {
85
+ const parts = trimmed.split(/\s+/);
86
+ if (parts.length >= 2) {
87
+ const depName = unquote(parts[0] ?? '');
88
+ const depSpec = unquote(parts.slice(1).join(' '));
89
+ if (section === 'dependencies') {
90
+ currentPkg.dependencies[depName] = depSpec;
91
+ }
92
+ else {
93
+ currentPkg.optionalDependencies[depName] = depSpec;
94
+ }
95
+ }
96
+ }
97
+ }
98
+ flush();
99
+ return { type: 'yarn', entries };
100
+ }
101
+ export async function readLockfile(dir) {
102
+ for (const name of LOCKFILE_NAMES) {
103
+ const file = path.resolve(dir, name);
104
+ let content;
105
+ try {
106
+ content = await readFile(file, 'utf8');
107
+ }
108
+ catch (err) {
109
+ if (err.code === 'ENOENT')
110
+ continue;
111
+ throw new ManifestError(`No se pudo leer ${file}: ${err.message}`, { cause: err });
112
+ }
113
+ if (name === 'yarn.lock') {
114
+ try {
115
+ const lock = parseYarnLock(content);
116
+ return { file, lock };
117
+ }
118
+ catch (cause) {
119
+ throw new ManifestError(`Error al procesar ${file}: ${cause.message}`, { cause });
120
+ }
121
+ }
122
+ try {
123
+ const parsed = JSON.parse(content);
124
+ const lock = {
125
+ type: 'npm',
126
+ lockfileVersion: typeof parsed.lockfileVersion === 'number' ? parsed.lockfileVersion : undefined,
127
+ packages: typeof parsed.packages === 'object' && parsed.packages !== null ? parsed.packages : undefined,
128
+ };
129
+ return { file, lock };
130
+ }
131
+ catch (cause) {
132
+ throw new ManifestError(`${file} no es un JSON válido.`, { cause });
133
+ }
134
+ }
135
+ throw new ManifestError(`--transitive requiere package-lock.json o yarn.lock en ${path.resolve(dir)}. ` +
136
+ 'Ejecuta "npm install" o "yarn install".');
137
+ }
138
+ /**
139
+ * Resolución estilo Node para npm: busca `<from>/node_modules/<name>` y sube por los ancestros.
140
+ */
141
+ export function resolvePackageKey(packages, name, fromKey) {
142
+ let base = fromKey;
143
+ while (true) {
144
+ const candidate = base ? `${base}/node_modules/${name}` : `node_modules/${name}`;
145
+ if (packages[candidate])
146
+ return candidate;
147
+ if (!base)
148
+ return null;
149
+ const idx = base.lastIndexOf('/node_modules/');
150
+ base = idx >= 0 ? base.slice(0, idx) : '';
151
+ }
152
+ }
153
+ function unsupportedReasonFromUrl(resolved) {
154
+ if (!resolved)
155
+ return undefined;
156
+ if (resolved.startsWith('file:'))
157
+ return 'Dependencia local (file:)';
158
+ if (/^git(\+|:|@)/.test(resolved))
159
+ return 'Dependencia instalada desde git';
160
+ return undefined;
161
+ }
162
+ function resolveNpmTransitive(lock, direct, options) {
163
+ if (!lock.packages) {
164
+ throw new ManifestError(`lockfileVersion ${lock.lockfileVersion ?? '?'} no soportado para --transitive: regenera el lockfile con npm >= 7.`);
165
+ }
166
+ const packages = lock.packages;
167
+ const directNames = new Set(direct.map((d) => d.name));
168
+ const seenNames = new Set(directNames);
169
+ const visitedKeys = new Set();
170
+ const result = [];
171
+ const queue = [];
172
+ for (const d of direct) {
173
+ if (d.unsupportedReason)
174
+ continue;
175
+ const key = resolvePackageKey(packages, d.name, '');
176
+ if (!key || visitedKeys.has(key))
177
+ continue;
178
+ visitedKeys.add(key);
179
+ queue.push({ key, depth: 1, via: [d.name] });
180
+ }
181
+ while (queue.length > 0) {
182
+ const node = queue.shift();
183
+ if (node.depth >= options.maxDepth)
184
+ continue;
185
+ const entry = packages[node.key];
186
+ if (!entry || entry.link)
187
+ continue;
188
+ const children = { ...entry.dependencies, ...entry.optionalDependencies };
189
+ for (const childName of Object.keys(children).sort()) {
190
+ const childKey = resolvePackageKey(packages, childName, node.key);
191
+ if (!childKey || visitedKeys.has(childKey))
192
+ continue;
193
+ visitedKeys.add(childKey);
194
+ const child = packages[childKey];
195
+ const depth = node.depth + 1;
196
+ if (!seenNames.has(childName) && !child.link) {
197
+ seenNames.add(childName);
198
+ const spec = {
199
+ name: childName,
200
+ registryName: child.name ?? childName,
201
+ spec: child.version ?? '?',
202
+ kind: 'transitive',
203
+ depth,
204
+ via: node.via,
205
+ };
206
+ const reason = unsupportedReasonFromUrl(child.resolved);
207
+ if (reason)
208
+ spec.unsupportedReason = reason;
209
+ result.push(spec);
210
+ }
211
+ queue.push({ key: childKey, depth, via: [...node.via, childName] });
212
+ }
213
+ }
214
+ return result;
215
+ }
216
+ function resolveYarnTransitive(lock, direct, options) {
217
+ const entries = lock.entries;
218
+ const directNames = new Set(direct.map((d) => d.name));
219
+ const seenNames = new Set(directNames);
220
+ const visited = new Set();
221
+ const result = [];
222
+ const findEntry = (name, spec) => {
223
+ if (spec) {
224
+ const directKey = `${name}@${spec}`;
225
+ if (entries.has(directKey))
226
+ return entries.get(directKey);
227
+ }
228
+ const prefix = `${name}@`;
229
+ for (const [k, v] of entries) {
230
+ if (k.startsWith(prefix))
231
+ return v;
232
+ }
233
+ return undefined;
234
+ };
235
+ const queue = [];
236
+ for (const d of direct) {
237
+ if (d.unsupportedReason)
238
+ continue;
239
+ const pkg = findEntry(d.name, d.spec);
240
+ if (!pkg)
241
+ continue;
242
+ const visitKey = `${d.name}@${pkg.version}`;
243
+ if (visited.has(visitKey))
244
+ continue;
245
+ visited.add(visitKey);
246
+ queue.push({ name: d.name, pkg, depth: 1, via: [d.name] });
247
+ }
248
+ while (queue.length > 0) {
249
+ const node = queue.shift();
250
+ if (node.depth >= options.maxDepth)
251
+ continue;
252
+ const children = { ...node.pkg.dependencies, ...node.pkg.optionalDependencies };
253
+ for (const [childName, childSpec] of Object.entries(children).sort(([a], [b]) => a.localeCompare(b))) {
254
+ const childPkg = findEntry(childName, childSpec);
255
+ if (!childPkg)
256
+ continue;
257
+ const visitKey = `${childName}@${childPkg.version}`;
258
+ if (visited.has(visitKey))
259
+ continue;
260
+ visited.add(visitKey);
261
+ const depth = node.depth + 1;
262
+ if (!seenNames.has(childName)) {
263
+ seenNames.add(childName);
264
+ const spec = {
265
+ name: childName,
266
+ registryName: childPkg.name,
267
+ spec: childPkg.version,
268
+ kind: 'transitive',
269
+ depth,
270
+ via: node.via,
271
+ };
272
+ const reason = unsupportedReasonFromUrl(childPkg.resolved);
273
+ if (reason)
274
+ spec.unsupportedReason = reason;
275
+ result.push(spec);
276
+ }
277
+ queue.push({ name: childName, pkg: childPkg, depth, via: [...node.via, childName] });
278
+ }
279
+ }
280
+ return result;
281
+ }
282
+ /**
283
+ * Devuelve SOLO las dependencias transitivas (profundidad >= 2), deduplicadas por nombre,
284
+ * alcanzables desde las directas indicadas en un lockfile de npm o Yarn.
285
+ */
286
+ export function resolveTransitive(lock, direct, options) {
287
+ if (lock.type === 'yarn') {
288
+ return resolveYarnTransitive(lock, direct, options);
289
+ }
290
+ return resolveNpmTransitive(lock, direct, options);
291
+ }
@@ -0,0 +1,94 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { ManifestError } from '../errors.js';
4
+ /** Especificadores que no apuntan al registry de npm y por tanto no se evalúan. */
5
+ const NON_REGISTRY_PREFIXES = [
6
+ ['file:', 'Dependencia local (file:)'],
7
+ ['link:', 'Dependencia local (link:)'],
8
+ ['portal:', 'Dependencia local (portal:)'],
9
+ ['workspace:', 'Paquete del workspace (workspace:)'],
10
+ ['git+', 'Dependencia instalada desde git'],
11
+ ['git:', 'Dependencia instalada desde git'],
12
+ ['git@', 'Dependencia instalada desde git'],
13
+ ['http:', 'Dependencia instalada desde una URL (tarball)'],
14
+ ['https:', 'Dependencia instalada desde una URL (tarball)'],
15
+ ['github:', 'Dependencia instalada directamente desde GitHub'],
16
+ ['gitlab:', 'Dependencia instalada directamente desde GitLab'],
17
+ ['bitbucket:', 'Dependencia instalada directamente desde Bitbucket'],
18
+ ];
19
+ export function classifySpec(name, spec, kind) {
20
+ const trimmed = spec.trim();
21
+ const base = { name, registryName: name, spec: trimmed, kind, depth: 1, via: [] };
22
+ // Alias: "foo": "npm:bar@^1.0.0" -> se evalúa "bar".
23
+ if (trimmed.startsWith('npm:')) {
24
+ const rest = trimmed.slice(4);
25
+ const at = rest.lastIndexOf('@');
26
+ return { ...base, registryName: at > 0 ? rest.slice(0, at) : rest };
27
+ }
28
+ for (const [prefix, reason] of NON_REGISTRY_PREFIXES) {
29
+ if (trimmed.startsWith(prefix))
30
+ return { ...base, unsupportedReason: reason };
31
+ }
32
+ // Shorthand de GitHub como especificador: "usuario/repo" o "usuario/repo#rama".
33
+ // Un rango semver o un dist-tag nunca contienen "/".
34
+ if (trimmed.includes('/')) {
35
+ return { ...base, unsupportedReason: 'Dependencia instalada directamente desde GitHub (shorthand)' };
36
+ }
37
+ return base;
38
+ }
39
+ function readDependencyBlock(manifest, kind, manifestPath) {
40
+ const block = manifest[kind];
41
+ if (block === undefined || block === null)
42
+ return [];
43
+ if (typeof block !== 'object' || Array.isArray(block)) {
44
+ throw new ManifestError(`El campo "${kind}" de ${manifestPath} debe ser un objeto.`);
45
+ }
46
+ return Object.entries(block).map(([name, spec]) => {
47
+ if (typeof spec !== 'string') {
48
+ throw new ManifestError(`La versión de "${name}" en "${kind}" debe ser un string.`);
49
+ }
50
+ return classifySpec(name, spec, kind);
51
+ });
52
+ }
53
+ export function parseManifestContent(content, manifestPath, options) {
54
+ let json;
55
+ try {
56
+ json = JSON.parse(content);
57
+ }
58
+ catch (cause) {
59
+ throw new ManifestError(`${manifestPath} no es un JSON válido.`, { cause });
60
+ }
61
+ if (typeof json !== 'object' || json === null || Array.isArray(json)) {
62
+ throw new ManifestError(`${manifestPath} debe contener un objeto JSON.`);
63
+ }
64
+ const manifest = json;
65
+ const deps = readDependencyBlock(manifest, 'dependencies', manifestPath);
66
+ if (options.includeDev) {
67
+ const seen = new Set(deps.map((d) => d.name));
68
+ for (const dev of readDependencyBlock(manifest, 'devDependencies', manifestPath)) {
69
+ // Si está en ambos bloques, prevalece `dependencies`.
70
+ if (!seen.has(dev.name))
71
+ deps.push(dev);
72
+ }
73
+ }
74
+ return {
75
+ manifestPath,
76
+ projectName: typeof manifest.name === 'string' ? manifest.name : null,
77
+ dependencies: deps,
78
+ };
79
+ }
80
+ export async function readManifest(dir, options) {
81
+ const manifestPath = path.resolve(dir, 'package.json');
82
+ let content;
83
+ try {
84
+ content = await readFile(manifestPath, 'utf8');
85
+ }
86
+ catch (cause) {
87
+ const code = cause.code;
88
+ if (code === 'ENOENT') {
89
+ throw new ManifestError(`No se encontró package.json en ${path.resolve(dir)}. Usa --path <dir>.`);
90
+ }
91
+ throw new ManifestError(`No se pudo leer ${manifestPath}: ${cause.message}`, { cause });
92
+ }
93
+ return parseManifestContent(content, manifestPath, options);
94
+ }
@@ -0,0 +1,103 @@
1
+ const SHORTHAND_PROVIDER = /^(github|gitlab|bitbucket):([^/\s]+)\/([^/\s#]+?)(?:\.git)?(?:#.*)?$/i;
2
+ /** "owner/repo" sin protocolo: el registry lo interpreta como GitHub. */
3
+ const BARE_SHORTHAND = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:#.*)?$/;
4
+ /** Sintaxis tipo scp: git@github.com:owner/repo.git */
5
+ const SCP_LIKE = /^(?:[\w.-]+@)?([\w.-]+\.[a-z]{2,}):(?!\/\/)\/?([^/]+)\/(.+)$/i;
6
+ const PROVIDER_HOSTNAMES = {
7
+ github: 'github.com',
8
+ gitlab: 'gitlab.com',
9
+ bitbucket: 'bitbucket.org',
10
+ };
11
+ function hostFromHostname(hostname) {
12
+ if (hostname === 'github.com')
13
+ return 'github';
14
+ if (hostname === 'gitlab.com')
15
+ return 'gitlab';
16
+ if (hostname === 'bitbucket.org')
17
+ return 'bitbucket';
18
+ return 'other';
19
+ }
20
+ function cleanDirectory(dir) {
21
+ if (!dir)
22
+ return undefined;
23
+ const cleaned = dir.trim().replace(/^\.?\/+/, '').replace(/\/+$/, '');
24
+ return cleaned.length > 0 ? cleaned : undefined;
25
+ }
26
+ function cleanRepoName(repo) {
27
+ return repo.replace(/\.git$/i, '').replace(/#.*$/, '');
28
+ }
29
+ function build(hostname, owner, repo, directory) {
30
+ const name = cleanRepoName(repo);
31
+ if (!owner || !name)
32
+ return null;
33
+ const host = hostFromHostname(hostname);
34
+ const ref = { host, hostname, owner, repo: name, url: `https://${hostname}/${owner}/${name}` };
35
+ const dir = cleanDirectory(directory);
36
+ if (dir)
37
+ ref.directory = dir;
38
+ return ref;
39
+ }
40
+ /**
41
+ * Normaliza el campo `repository` de npm (string u objeto {type,url,directory}) a un RepoRef.
42
+ * Soporta: git+https, git://, git+ssh://, ssh scp-like (git@host:o/r), https con /tree/<rama>/<dir>,
43
+ * shorthand `github:o/r`, `gitlab:o/r`, `bitbucket:o/r` y `o/r`.
44
+ */
45
+ export function normalizeRepository(input) {
46
+ let raw;
47
+ let directory;
48
+ if (typeof input === 'string') {
49
+ raw = input;
50
+ }
51
+ else if (input && typeof input === 'object') {
52
+ const obj = input;
53
+ if (typeof obj.url === 'string')
54
+ raw = obj.url;
55
+ if (typeof obj.directory === 'string')
56
+ directory = obj.directory;
57
+ }
58
+ if (!raw)
59
+ return null;
60
+ raw = raw.trim();
61
+ if (!raw)
62
+ return null;
63
+ const provider = SHORTHAND_PROVIDER.exec(raw);
64
+ if (provider) {
65
+ const [, kind, owner, repo] = provider;
66
+ const hostname = PROVIDER_HOSTNAMES[(kind ?? '').toLowerCase()];
67
+ return hostname && owner && repo ? build(hostname, owner, repo, directory) : null;
68
+ }
69
+ const bare = BARE_SHORTHAND.exec(raw);
70
+ if (bare && !raw.includes(':')) {
71
+ const [, owner, repo] = bare;
72
+ return owner && repo ? build('github.com', owner, repo, directory) : null;
73
+ }
74
+ const scp = SCP_LIKE.exec(raw);
75
+ if (scp) {
76
+ const [, hostname, owner, rest] = scp;
77
+ if (!hostname || !owner || !rest)
78
+ return null;
79
+ const repo = rest.split('/')[0] ?? '';
80
+ return build(hostname.toLowerCase().replace(/^www\./, ''), owner, repo, directory);
81
+ }
82
+ let urlString = raw.replace(/^git\+/, '');
83
+ urlString = urlString.replace(/^git:\/\//, 'https://').replace(/^ssh:\/\//, 'https://');
84
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(urlString))
85
+ urlString = `https://${urlString}`;
86
+ let url;
87
+ try {
88
+ url = new URL(urlString);
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ const hostname = url.hostname.toLowerCase().replace(/^www\./, '');
94
+ const segments = url.pathname.split('/').filter(Boolean);
95
+ const [owner, repo, kind, , ...dirParts] = segments;
96
+ if (!owner || !repo)
97
+ return null;
98
+ // https://github.com/o/r/tree/main/packages/x -> directory = packages/x
99
+ if (!directory && (kind === 'tree' || kind === 'blob') && dirParts.length > 0) {
100
+ directory = dirParts.join('/');
101
+ }
102
+ return build(hostname, owner, repo, directory);
103
+ }