@imenam/mcp-dependabot-tracker 0.0.0-stage → 1.0.1

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.
Files changed (59) hide show
  1. package/README.md +208 -2
  2. package/dist/shared/schemas/api.schema.d.ts +49 -0
  3. package/dist/shared/schemas/api.schema.js +11 -0
  4. package/dist/shared/schemas/ipc.schema.d.ts +26 -0
  5. package/dist/shared/schemas/ipc.schema.js +30 -0
  6. package/dist/shared/schemas/model.schema.d.ts +276 -0
  7. package/dist/shared/schemas/model.schema.js +116 -0
  8. package/dist/src/cli/setup-mcp.d.ts +24 -0
  9. package/dist/src/cli/setup-mcp.js +137 -0
  10. package/dist/src/core/commands.d.ts +26 -0
  11. package/dist/src/core/commands.js +101 -0
  12. package/dist/src/core/config.d.ts +12 -0
  13. package/dist/src/core/config.js +18 -0
  14. package/dist/src/core/data-dir.d.ts +11 -0
  15. package/dist/src/core/data-dir.js +27 -0
  16. package/dist/src/core/errors.d.ts +12 -0
  17. package/dist/src/core/errors.js +21 -0
  18. package/dist/src/core/github.d.ts +43 -0
  19. package/dist/src/core/github.js +122 -0
  20. package/dist/src/core/log-dir.d.ts +6 -0
  21. package/dist/src/core/log-dir.js +13 -0
  22. package/dist/src/core/npm-audit.d.ts +36 -0
  23. package/dist/src/core/npm-audit.js +115 -0
  24. package/dist/src/core/operations.d.ts +42 -0
  25. package/dist/src/core/operations.js +438 -0
  26. package/dist/src/core/repo-ref.d.ts +9 -0
  27. package/dist/src/core/repo-ref.js +33 -0
  28. package/dist/src/core/repos.d.ts +23 -0
  29. package/dist/src/core/repos.js +84 -0
  30. package/dist/src/core/store.d.ts +49 -0
  31. package/dist/src/core/store.js +266 -0
  32. package/dist/src/gui-worker.d.ts +1 -0
  33. package/dist/src/gui-worker.js +325 -0
  34. package/dist/src/index.d.ts +2 -0
  35. package/dist/src/index.js +363 -0
  36. package/dist/src/tools/format.d.ts +7 -0
  37. package/dist/src/tools/format.js +81 -0
  38. package/dist/src/tools/tools.d.ts +15 -0
  39. package/dist/src/tools/tools.js +56 -0
  40. package/dist/src/tools/types.d.ts +21 -0
  41. package/dist/src/tools/types.js +38 -0
  42. package/dist/src/version.d.ts +1 -0
  43. package/dist/src/version.js +16 -0
  44. package/gui/dist/assets/index-BBJkUr54.css +1 -0
  45. package/gui/dist/assets/index-DbT51E3H.js +63 -0
  46. package/gui/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  47. package/gui/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  48. package/gui/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  49. package/gui/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  50. package/gui/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  51. package/gui/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  52. package/gui/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  53. package/gui/dist/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  54. package/gui/dist/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  55. package/gui/dist/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  56. package/gui/dist/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  57. package/gui/dist/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  58. package/gui/dist/index.html +13 -0
  59. package/package.json +57 -4
@@ -0,0 +1,116 @@
1
+ import { z } from "zod";
2
+ /** Gravités d'une alerte Dependabot, de la plus grave à la moins grave. */
3
+ export const ALERT_SEVERITIES = ["critical", "high", "medium", "low"];
4
+ /** Gravités d'une vulnérabilité rapportée par `npm audit`, de la plus grave à la moins grave. */
5
+ export const NPM_SEVERITIES = ["critical", "high", "moderate", "low", "info"];
6
+ /** Actions que l'agent peut être autorisé à lancer sur un dépôt, par les outils MCP. */
7
+ export const RIGHTS = ["audit", "fix", "force", "push"];
8
+ export const RightsSchema = z.object({
9
+ audit: z.boolean(),
10
+ fix: z.boolean(),
11
+ force: z.boolean(),
12
+ push: z.boolean(),
13
+ });
14
+ /** Droits d'un dépôt qui vient d'être ajouté : l'audit seul. */
15
+ export const DEFAULT_RIGHTS = { audit: true, fix: false, force: false, push: false };
16
+ /** Alerte Dependabot ouverte, telle que la renvoie l'API GitHub, réduite à ce qui s'affiche. */
17
+ export const AlertSchema = z.object({
18
+ number: z.number().int(),
19
+ severity: z.enum(ALERT_SEVERITIES),
20
+ ecosystem: z.string(),
21
+ package: z.string(),
22
+ manifestPath: z.string(),
23
+ summary: z.string(),
24
+ url: z.string(),
25
+ patchedVersion: z.string().nullable(),
26
+ });
27
+ /** Dépôt suivi. `id` est le nom complet GitHub, `propriétaire/nom`. */
28
+ export const RepoSchema = z.object({
29
+ id: z.string(),
30
+ owner: z.string(),
31
+ name: z.string(),
32
+ defaultBranch: z.string(),
33
+ addedAt: z.string(),
34
+ rights: RightsSchema,
35
+ alerts: z.array(AlertSchema),
36
+ syncedAt: z.string().nullable(),
37
+ syncError: z.string().nullable(),
38
+ });
39
+ export const ReposFileSchema = z.object({ repos: z.array(RepoSchema) });
40
+ /** `audit` : clone et `npm audit` seulement ; `fix` : jusqu'aux corrections, à la branche et à la PR. */
41
+ export const OPERATION_KINDS = ["audit", "fix"];
42
+ /** Qui a lancé l'opération : l'utilisateur depuis la GUI, ou l'agent par un outil MCP. */
43
+ export const ORIGINS = ["user", "agent"];
44
+ /**
45
+ * `running` : une étape s'exécute ; `waiting_force` et `waiting_push` : l'utilisateur
46
+ * doit décider de la suite ; les trois derniers états sont terminaux.
47
+ */
48
+ export const OPERATION_STATUSES = ["running", "waiting_force", "waiting_push", "done", "failed", "cancelled"];
49
+ export const ACTIVE_STATUSES = ["running", "waiting_force", "waiting_push"];
50
+ export const STEP_NAMES = ["clone", "audit", "fix", "force", "push"];
51
+ export const STEP_STATES = ["pending", "running", "done", "skipped", "failed"];
52
+ /** Correction proposée par `npm audit` : aucune, dans les plages déclarées, ou par une version majeure (`--force`). */
53
+ export const FIX_KINDS = ["none", "available", "major"];
54
+ /** Vulnérabilité d'un projet npm du dépôt ; `project` est le dossier du lockfile, `""` pour la racine. */
55
+ export const VulnerabilitySchema = z.object({
56
+ project: z.string(),
57
+ name: z.string(),
58
+ severity: z.enum(NPM_SEVERITIES),
59
+ fix: z.enum(FIX_KINDS),
60
+ });
61
+ /** Paquet que `npm audit fix --force` monterait d'une version majeure, et le nombre de vulnérabilités que cela corrige. */
62
+ export const ForceCandidateSchema = z.object({
63
+ project: z.string(),
64
+ name: z.string(),
65
+ from: z.string().nullable(),
66
+ to: z.string(),
67
+ vulnerabilities: z.number().int(),
68
+ });
69
+ /** Paquet du lockfile dont la version a changé ; `from` null pour un ajout, `to` null pour un retrait. */
70
+ export const ChangeSchema = z.object({
71
+ project: z.string(),
72
+ name: z.string(),
73
+ from: z.string().nullable(),
74
+ to: z.string().nullable(),
75
+ });
76
+ export const LogEntrySchema = z.object({ at: z.string(), text: z.string() });
77
+ /**
78
+ * Opération d'audit ou de correction sur un clone temporaire. `workDir` est le
79
+ * clone, présent tant que l'opération n'est pas terminée ; `pid` est le processus
80
+ * qui exécute l'étape en cours.
81
+ */
82
+ export const OperationSchema = z.object({
83
+ id: z.string(),
84
+ repoId: z.string(),
85
+ kind: z.enum(OPERATION_KINDS),
86
+ origin: z.enum(ORIGINS),
87
+ status: z.enum(OPERATION_STATUSES),
88
+ createdAt: z.string(),
89
+ updatedAt: z.string(),
90
+ pid: z.number().int(),
91
+ workDir: z.string().nullable(),
92
+ baseBranch: z.string(),
93
+ cancelRequested: z.boolean(),
94
+ steps: z.object({
95
+ clone: z.enum(STEP_STATES),
96
+ audit: z.enum(STEP_STATES),
97
+ fix: z.enum(STEP_STATES),
98
+ force: z.enum(STEP_STATES),
99
+ push: z.enum(STEP_STATES),
100
+ }),
101
+ projects: z.array(z.string()),
102
+ counts: z.object({
103
+ initial: z.number().int().nullable(),
104
+ afterFix: z.number().int().nullable(),
105
+ afterForce: z.number().int().nullable(),
106
+ }),
107
+ remaining: z.array(VulnerabilitySchema),
108
+ forceCandidates: z.array(ForceCandidateSchema),
109
+ changes: z.array(ChangeSchema),
110
+ commitMessage: z.string(),
111
+ branch: z.string().nullable(),
112
+ pullRequest: z.object({ number: z.number().int(), url: z.string() }).nullable(),
113
+ error: z.string().nullable(),
114
+ log: z.array(LogEntrySchema),
115
+ });
116
+ export const DEFAULT_COMMIT_MESSAGE = "fix(deps): resolve npm audit vulnerabilities";
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Comment la GUI sera exposée. `undefined` des deux côtés = rien n'a été passé
3
+ * en ligne de commande : on retombe sur le placeholder PROXY_URL à compléter.
4
+ */
5
+ export interface GuiExposure {
6
+ proxyUrl?: string;
7
+ appPort?: number;
8
+ }
9
+ /**
10
+ * Traduit `--proxy_url=` / `--app_port=` en mode d'exposition de la GUI.
11
+ * Les deux ensemble sont refusés : au runtime PROXY_URL primerait toujours,
12
+ * donc un fichier portant les deux serait silencieusement trompeur.
13
+ */
14
+ export declare function parseGuiExposure(argv: string[]): {
15
+ exposure: GuiExposure;
16
+ } | {
17
+ error: string;
18
+ };
19
+ export interface SetupMcpOptions {
20
+ cwd: string;
21
+ force: boolean;
22
+ exposure?: GuiExposure;
23
+ }
24
+ export declare function runSetupMcp({ cwd, force, exposure }: SetupMcpOptions): number;
@@ -0,0 +1,137 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ const SERVER_NAME = "mcp-dependabot-tracker";
4
+ const PACKAGE_NAME = "@imenam/mcp-dependabot-tracker";
5
+ /**
6
+ * Valeurs volontairement vides : chaque variable est inactive tant qu'elle n'est
7
+ * pas remplie (PROXY_URL et APP_PORT vides = GUI désactivée), sauf CLONE_DIR,
8
+ * obligatoire. Les dépôts suivis ne dépendent pas du projet : le répertoire des
9
+ * données reste celui par défaut.
10
+ */
11
+ function buildServerEntry(exposure) {
12
+ // Un port explicite désactive le placeholder proxy : les deux variables ne
13
+ // doivent jamais être renseignées ensemble, PROXY_URL primant au runtime.
14
+ const proxyUrl = exposure.appPort !== undefined ? "" : exposure.proxyUrl ?? "http://localhost:";
15
+ return {
16
+ command: "npx",
17
+ args: ["-y", PACKAGE_NAME],
18
+ env: {
19
+ GITHUB_TOKEN: "",
20
+ PROXY_URL: proxyUrl,
21
+ APP_PORT: exposure.appPort !== undefined ? String(exposure.appPort) : "",
22
+ APP_GROUP: "",
23
+ APP_NAME: "Dependabot Tracker",
24
+ APP_PATH: "/dependabot-tracker",
25
+ CLONE_DIR: "",
26
+ MCP_DATA_DIR: "",
27
+ MCP_LOG_DIR: "",
28
+ },
29
+ };
30
+ }
31
+ const GENERATED_VARS = [
32
+ ["GITHUB_TOKEN", "token GitHub : Dependabot alerts (lecture), Contents et Pull requests (lecture et écriture)"],
33
+ ["PROXY_URL", "URL du proxy pour exposer la GUI (compléter le port)"],
34
+ ["APP_PORT", "port local si aucun proxy — la GUI est servie sur http://localhost:<port>"],
35
+ ["APP_GROUP", "groupe d'affichage dans le dashboard du proxy"],
36
+ ["APP_NAME", "nom affiché de la GUI dans le dashboard du proxy"],
37
+ ["APP_PATH", "chemin de montage de la GUI derrière le proxy"],
38
+ ["CLONE_DIR", "dossier des clones temporaires, créé s'il n'existe pas (obligatoire)"],
39
+ ["MCP_DATA_DIR", "répertoire des données (défaut : ~/.mcp-dependabot-tracker)"],
40
+ ["MCP_LOG_DIR", "répertoire des logs (défaut : <données>/logs)"],
41
+ ];
42
+ /** Lit `--flag=valeur` (tirets ou underscores acceptés). */
43
+ function readFlag(argv, name) {
44
+ const prefixes = [`--${name}=`, `--${name.replace(/_/g, "-")}=`];
45
+ for (const arg of argv) {
46
+ const prefix = prefixes.find((p) => arg.startsWith(p));
47
+ if (prefix)
48
+ return arg.slice(prefix.length).trim();
49
+ }
50
+ return undefined;
51
+ }
52
+ /**
53
+ * Traduit `--proxy_url=` / `--app_port=` en mode d'exposition de la GUI.
54
+ * Les deux ensemble sont refusés : au runtime PROXY_URL primerait toujours,
55
+ * donc un fichier portant les deux serait silencieusement trompeur.
56
+ */
57
+ export function parseGuiExposure(argv) {
58
+ const rawProxyUrl = readFlag(argv, "proxy_url");
59
+ const rawAppPort = readFlag(argv, "app_port");
60
+ if (rawProxyUrl !== undefined && rawAppPort !== undefined) {
61
+ return { error: "--proxy_url et --app_port sont exclusifs : la GUI passe par le proxy, ou écoute sur un port local." };
62
+ }
63
+ if (rawProxyUrl !== undefined) {
64
+ if (rawProxyUrl === "")
65
+ return { error: "--proxy_url attend une URL, ex : --proxy_url=http://localhost:3000" };
66
+ let parsed;
67
+ try {
68
+ parsed = new URL(rawProxyUrl);
69
+ }
70
+ catch {
71
+ return { error: `--proxy_url invalide : "${rawProxyUrl}" n'est pas une URL absolue (ex : http://localhost:3000).` };
72
+ }
73
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
74
+ return { error: `--proxy_url invalide : protocole "${parsed.protocol}" non supporté (http ou https attendu).` };
75
+ }
76
+ // Une barre finale casserait la concaténation PROXY_URL + APP_PATH.
77
+ return { exposure: { proxyUrl: rawProxyUrl.replace(/\/+$/, "") } };
78
+ }
79
+ if (rawAppPort !== undefined) {
80
+ const port = Number(rawAppPort);
81
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
82
+ return { error: `--app_port invalide : "${rawAppPort}" n'est pas un entier entre 1 et 65535.` };
83
+ }
84
+ return { exposure: { appPort: port } };
85
+ }
86
+ return { exposure: {} };
87
+ }
88
+ export function runSetupMcp({ cwd, force, exposure = {} }) {
89
+ const target = path.join(cwd, ".mcp.json");
90
+ let config = {};
91
+ const exists = fs.existsSync(target);
92
+ if (exists) {
93
+ const raw = fs.readFileSync(target, "utf-8").trim();
94
+ if (raw !== "") {
95
+ try {
96
+ config = JSON.parse(raw);
97
+ }
98
+ catch (err) {
99
+ console.error(`Erreur : ${target} contient du JSON invalide (${err.message}).`);
100
+ console.error("Corrigez le fichier ou supprimez-le, puis relancez la commande.");
101
+ return 1;
102
+ }
103
+ }
104
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
105
+ console.error(`Erreur : ${target} ne contient pas un objet JSON.`);
106
+ return 1;
107
+ }
108
+ }
109
+ if (typeof config.mcpServers !== "object" || config.mcpServers === null || Array.isArray(config.mcpServers)) {
110
+ config.mcpServers = {};
111
+ }
112
+ const alreadyPresent = Object.prototype.hasOwnProperty.call(config.mcpServers, SERVER_NAME);
113
+ if (alreadyPresent && !force) {
114
+ console.error(`Le serveur "${SERVER_NAME}" est déjà configuré dans ${target}.`);
115
+ console.error("Relancez avec --force pour écraser cette entrée (les autres serveurs sont préservés).");
116
+ return 1;
117
+ }
118
+ config.mcpServers[SERVER_NAME] = buildServerEntry(exposure);
119
+ fs.writeFileSync(target, JSON.stringify(config, null, 2) + "\n", "utf-8");
120
+ const action = alreadyPresent ? "remplacée" : exists ? "ajoutée" : "créée";
121
+ console.log(`Configuration ${SERVER_NAME} ${action} dans ${target}`);
122
+ console.log("");
123
+ if (exposure.appPort !== undefined) {
124
+ console.log(`GUI en accès direct : http://localhost:${exposure.appPort} (sans proxy).`);
125
+ }
126
+ else if (exposure.proxyUrl !== undefined) {
127
+ console.log(`GUI exposée via le proxy ${exposure.proxyUrl}.`);
128
+ }
129
+ console.log('À compléter dans le champ "env" :');
130
+ for (const [name, description] of GENERATED_VARS) {
131
+ console.log(` ${name.padEnd(16)} ${description}`);
132
+ }
133
+ console.log("");
134
+ console.log("Une variable laissée vide est simplement inactive, sauf CLONE_DIR : sans elle, le serveur refuse de démarrer.");
135
+ console.log("PROXY_URL et APP_PORT s'excluent : PROXY_URL prime si les deux sont renseignés.");
136
+ return 0;
137
+ }
@@ -0,0 +1,26 @@
1
+ export interface CommandResult {
2
+ code: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ export interface CommandOptions {
7
+ cwd: string;
8
+ env?: Record<string, string>;
9
+ signal?: AbortSignal;
10
+ timeoutMs?: number;
11
+ }
12
+ /** Commande interrompue par l'annulation de l'opération. */
13
+ export declare class CommandAbortedError extends Error {
14
+ constructor();
15
+ }
16
+ /**
17
+ * Lance `git` ou `npm` sans shell, et attend sa fin. La commande reçoit
18
+ * l'environnement du serveur sans GITHUB_TOKEN, plus `options.env`. Sous Windows,
19
+ * `npm` est un script `.cmd` que Node ne lance qu'à travers un shell : ses
20
+ * arguments sont alors des options fixes, jamais une valeur venue de
21
+ * l'utilisateur. Le code de sortie n'est pas interprété ici ; un dépassement de
22
+ * `timeoutMs` ou l'annulation par `signal` arrêtent la commande.
23
+ */
24
+ export declare function runCommand(command: "git" | "npm", args: string[], options: CommandOptions): Promise<CommandResult>;
25
+ /** Dernières lignes non vides d'une sortie, pour un message d'erreur ou le journal. */
26
+ export declare function tail(text: string, lines?: number): string;
@@ -0,0 +1,101 @@
1
+ import { spawn, spawnSync } from "child_process";
2
+ import { TrackerError } from "./errors.js";
3
+ /** Commande interrompue par l'annulation de l'opération. */
4
+ export class CommandAbortedError extends Error {
5
+ constructor() {
6
+ super("Cancelled.");
7
+ this.name = "CommandAbortedError";
8
+ }
9
+ }
10
+ const DEFAULT_TIMEOUT_MS = 10 * 60_000;
11
+ /** Arrête le processus et ses enfants : sous Windows, `npm` tourne dans un `cmd.exe` qui ne transmet pas le signal. */
12
+ function killTree(pid) {
13
+ if (process.platform === "win32") {
14
+ spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
15
+ return;
16
+ }
17
+ try {
18
+ process.kill(-pid, "SIGKILL");
19
+ }
20
+ catch {
21
+ // Le groupe de processus est déjà terminé.
22
+ }
23
+ }
24
+ /** Environnement du serveur transmis aux commandes, sans le token GitHub. */
25
+ function inheritedEnv() {
26
+ const { GITHUB_TOKEN: _token, ...env } = process.env;
27
+ return env;
28
+ }
29
+ /**
30
+ * Lance `git` ou `npm` sans shell, et attend sa fin. La commande reçoit
31
+ * l'environnement du serveur sans GITHUB_TOKEN, plus `options.env`. Sous Windows,
32
+ * `npm` est un script `.cmd` que Node ne lance qu'à travers un shell : ses
33
+ * arguments sont alors des options fixes, jamais une valeur venue de
34
+ * l'utilisateur. Le code de sortie n'est pas interprété ici ; un dépassement de
35
+ * `timeoutMs` ou l'annulation par `signal` arrêtent la commande.
36
+ */
37
+ export function runCommand(command, args, options) {
38
+ const viaShell = command === "npm" && process.platform === "win32";
39
+ if (viaShell && args.some((arg) => !/^[A-Za-z0-9=._-]+$/.test(arg))) {
40
+ throw new TrackerError(`Refused npm argument list: ${JSON.stringify(args)}.`);
41
+ }
42
+ if (options.signal?.aborted)
43
+ return Promise.reject(new CommandAbortedError());
44
+ return new Promise((resolve, reject) => {
45
+ const child = spawn(command, args, {
46
+ cwd: options.cwd,
47
+ env: { ...inheritedEnv(), ...options.env },
48
+ shell: viaShell,
49
+ detached: process.platform !== "win32",
50
+ windowsHide: true,
51
+ stdio: ["ignore", "pipe", "pipe"],
52
+ });
53
+ const stdout = [];
54
+ const stderr = [];
55
+ let settled = false;
56
+ let timedOut = false;
57
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
58
+ const stop = () => {
59
+ if (child.pid !== undefined && child.exitCode === null)
60
+ killTree(child.pid);
61
+ };
62
+ const onAbort = () => stop();
63
+ const timer = setTimeout(() => {
64
+ timedOut = true;
65
+ stop();
66
+ }, timeoutMs);
67
+ options.signal?.addEventListener("abort", onAbort);
68
+ const finish = (fn) => {
69
+ if (settled)
70
+ return;
71
+ settled = true;
72
+ clearTimeout(timer);
73
+ options.signal?.removeEventListener("abort", onAbort);
74
+ fn();
75
+ };
76
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
77
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
78
+ child.on("error", (err) => {
79
+ finish(() => reject(err.code === "ENOENT"
80
+ ? new TrackerError(`"${command}" is not installed or not in the PATH of the MCP server.`)
81
+ : new TrackerError(`Could not run ${command}: ${err.message}`)));
82
+ });
83
+ child.on("close", (code) => {
84
+ finish(() => {
85
+ if (options.signal?.aborted)
86
+ return reject(new CommandAbortedError());
87
+ if (timedOut)
88
+ return reject(new TrackerError(`${command} ${args.join(" ")} did not finish in ${Math.round(timeoutMs / 1000)} s and was stopped.`));
89
+ resolve({ code: code ?? 1, stdout: Buffer.concat(stdout).toString("utf-8"), stderr: Buffer.concat(stderr).toString("utf-8") });
90
+ });
91
+ });
92
+ });
93
+ }
94
+ /** Dernières lignes non vides d'une sortie, pour un message d'erreur ou le journal. */
95
+ export function tail(text, lines = 12) {
96
+ return text
97
+ .split(/\r?\n/)
98
+ .filter((line) => line.trim() !== "")
99
+ .slice(-lines)
100
+ .join("\n");
101
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Accès à GitHub. `apiUrl` et `serverUrl` désignent github.com par défaut ;
3
+ * GITHUB_API_URL et GITHUB_SERVER_URL les changent pour GitHub Enterprise Server.
4
+ */
5
+ export interface GitHubConfig {
6
+ token: string;
7
+ apiUrl: string;
8
+ serverUrl: string;
9
+ }
10
+ export declare function githubConfigured(): boolean;
11
+ /** Configuration GitHub lue dans l'environnement ; lève une erreur si GITHUB_TOKEN manque. */
12
+ export declare function readGitHubConfig(): GitHubConfig;
@@ -0,0 +1,18 @@
1
+ import { TrackerError } from "./errors.js";
2
+ const DEFAULT_API_URL = "https://api.github.com";
3
+ const DEFAULT_SERVER_URL = "https://github.com";
4
+ export function githubConfigured() {
5
+ return !!process.env.GITHUB_TOKEN?.trim();
6
+ }
7
+ /** Configuration GitHub lue dans l'environnement ; lève une erreur si GITHUB_TOKEN manque. */
8
+ export function readGitHubConfig() {
9
+ const token = process.env.GITHUB_TOKEN?.trim();
10
+ if (!token) {
11
+ throw new TrackerError("GITHUB_TOKEN is not set: declare a GitHub token in the env block of mcp-dependabot-tracker (Dependabot alerts: read, Contents: read and write, Pull requests: read and write).");
12
+ }
13
+ return {
14
+ token,
15
+ apiUrl: (process.env.GITHUB_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, ""),
16
+ serverUrl: (process.env.GITHUB_SERVER_URL?.trim() || DEFAULT_SERVER_URL).replace(/\/+$/, ""),
17
+ };
18
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Répertoire des données : MCP_DATA_DIR, puis `~/.mcp-dependabot-tracker`. Les
3
+ * dépôts suivis ne dépendent d'aucun projet : le répertoire par défaut est
4
+ * propre à l'utilisateur.
5
+ */
6
+ export declare function resolveDataDir(): string;
7
+ /**
8
+ * Dossier où chaque opération crée son clone, fixé par CLONE_DIR et créé s'il
9
+ * n'existe pas. Lève une erreur si la variable n'est pas renseignée.
10
+ */
11
+ export declare function resolveCloneDir(): string;
@@ -0,0 +1,27 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ /**
5
+ * Répertoire des données : MCP_DATA_DIR, puis `~/.mcp-dependabot-tracker`. Les
6
+ * dépôts suivis ne dépendent d'aucun projet : le répertoire par défaut est
7
+ * propre à l'utilisateur.
8
+ */
9
+ export function resolveDataDir() {
10
+ const configured = process.env.MCP_DATA_DIR?.trim();
11
+ if (configured)
12
+ return path.resolve(configured);
13
+ return path.join(os.homedir(), ".mcp-dependabot-tracker");
14
+ }
15
+ /**
16
+ * Dossier où chaque opération crée son clone, fixé par CLONE_DIR et créé s'il
17
+ * n'existe pas. Lève une erreur si la variable n'est pas renseignée.
18
+ */
19
+ export function resolveCloneDir() {
20
+ const configured = process.env.CLONE_DIR?.trim();
21
+ if (!configured) {
22
+ throw new Error("CLONE_DIR is not set: declare the folder where the repositories are cloned for npm audit in the env block of mcp-dependabot-tracker.");
23
+ }
24
+ const dir = path.resolve(configured);
25
+ fs.mkdirSync(dir, { recursive: true });
26
+ return dir;
27
+ }
@@ -0,0 +1,12 @@
1
+ /** Erreur métier dont le message s'adresse directement à l'agent ou à la GUI. */
2
+ export declare class TrackerError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ /** Dépôt ou opération introuvable. */
6
+ export declare class NotFoundError extends TrackerError {
7
+ constructor(message: string);
8
+ }
9
+ /** Action refusée par l'état courant : opération déjà en cours, étape qui n'attend pas cette décision. */
10
+ export declare class ConflictError extends TrackerError {
11
+ constructor(message: string);
12
+ }
@@ -0,0 +1,21 @@
1
+ /** Erreur métier dont le message s'adresse directement à l'agent ou à la GUI. */
2
+ export class TrackerError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "TrackerError";
6
+ }
7
+ }
8
+ /** Dépôt ou opération introuvable. */
9
+ export class NotFoundError extends TrackerError {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "NotFoundError";
13
+ }
14
+ }
15
+ /** Action refusée par l'état courant : opération déjà en cours, étape qui n'attend pas cette décision. */
16
+ export class ConflictError extends TrackerError {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "ConflictError";
20
+ }
21
+ }
@@ -0,0 +1,43 @@
1
+ import { type Alert } from "../../shared/schemas/model.schema.js";
2
+ import type { GitHubConfig } from "./config.js";
3
+ import { TrackerError } from "./errors.js";
4
+ /** Dépôt GitHub tel que le tracker l'enregistre. */
5
+ export interface GitHubRepository {
6
+ owner: string;
7
+ name: string;
8
+ fullName: string;
9
+ defaultBranch: string;
10
+ }
11
+ /** Compte du token, auteur des commits de correction. */
12
+ export interface GitHubUser {
13
+ login: string;
14
+ id: number;
15
+ name: string | null;
16
+ }
17
+ export interface PullRequest {
18
+ number: number;
19
+ url: string;
20
+ }
21
+ /** URL de la page suivante dans un en-tête `Link` de pagination, ou null. */
22
+ export declare function nextPageUrl(link: string | null): string | null;
23
+ /** Client REST minimal de l'API GitHub, authentifié par le token de la configuration. */
24
+ export declare class GitHubClient {
25
+ private readonly config;
26
+ constructor(config: GitHubConfig);
27
+ private request;
28
+ getRepository(owner: string, name: string): Promise<GitHubRepository>;
29
+ /** Alertes Dependabot ouvertes du dépôt, toutes pages comprises. */
30
+ listOpenAlerts(owner: string, name: string): Promise<Alert[]>;
31
+ getAuthenticatedUser(): Promise<GitHubUser>;
32
+ createPullRequest(owner: string, name: string, pr: {
33
+ title: string;
34
+ head: string;
35
+ base: string;
36
+ body: string;
37
+ }): Promise<PullRequest>;
38
+ }
39
+ /** Échec HTTP de l'API GitHub, avec son code. */
40
+ export declare class GitHubApiError extends TrackerError {
41
+ readonly status: number;
42
+ constructor(status: number, message: string);
43
+ }