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

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 (61) hide show
  1. package/README.md +209 -2
  2. package/dist/shared/repo-search.d.ts +9 -0
  3. package/dist/shared/repo-search.js +24 -0
  4. package/dist/shared/schemas/api.schema.d.ts +53 -0
  5. package/dist/shared/schemas/api.schema.js +11 -0
  6. package/dist/shared/schemas/ipc.schema.d.ts +26 -0
  7. package/dist/shared/schemas/ipc.schema.js +31 -0
  8. package/dist/shared/schemas/model.schema.d.ts +276 -0
  9. package/dist/shared/schemas/model.schema.js +116 -0
  10. package/dist/src/cli/setup-mcp.d.ts +24 -0
  11. package/dist/src/cli/setup-mcp.js +137 -0
  12. package/dist/src/core/commands.d.ts +26 -0
  13. package/dist/src/core/commands.js +101 -0
  14. package/dist/src/core/config.d.ts +12 -0
  15. package/dist/src/core/config.js +18 -0
  16. package/dist/src/core/data-dir.d.ts +11 -0
  17. package/dist/src/core/data-dir.js +27 -0
  18. package/dist/src/core/errors.d.ts +12 -0
  19. package/dist/src/core/errors.js +21 -0
  20. package/dist/src/core/github.d.ts +45 -0
  21. package/dist/src/core/github.js +141 -0
  22. package/dist/src/core/log-dir.d.ts +6 -0
  23. package/dist/src/core/log-dir.js +13 -0
  24. package/dist/src/core/npm-audit.d.ts +36 -0
  25. package/dist/src/core/npm-audit.js +115 -0
  26. package/dist/src/core/operations.d.ts +42 -0
  27. package/dist/src/core/operations.js +438 -0
  28. package/dist/src/core/repo-ref.d.ts +9 -0
  29. package/dist/src/core/repo-ref.js +33 -0
  30. package/dist/src/core/repos.d.ts +25 -0
  31. package/dist/src/core/repos.js +90 -0
  32. package/dist/src/core/store.d.ts +49 -0
  33. package/dist/src/core/store.js +266 -0
  34. package/dist/src/gui-worker.d.ts +1 -0
  35. package/dist/src/gui-worker.js +326 -0
  36. package/dist/src/index.d.ts +2 -0
  37. package/dist/src/index.js +365 -0
  38. package/dist/src/tools/format.d.ts +7 -0
  39. package/dist/src/tools/format.js +81 -0
  40. package/dist/src/tools/tools.d.ts +15 -0
  41. package/dist/src/tools/tools.js +56 -0
  42. package/dist/src/tools/types.d.ts +21 -0
  43. package/dist/src/tools/types.js +38 -0
  44. package/dist/src/version.d.ts +1 -0
  45. package/dist/src/version.js +16 -0
  46. package/gui/dist/assets/index-Bn8FyH44.css +1 -0
  47. package/gui/dist/assets/index-do_lp18L.js +63 -0
  48. package/gui/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  49. package/gui/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  50. package/gui/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  51. package/gui/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  52. package/gui/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  53. package/gui/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  54. package/gui/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  55. package/gui/dist/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  56. package/gui/dist/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  57. package/gui/dist/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  58. package/gui/dist/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  59. package/gui/dist/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  60. package/gui/dist/index.html +13 -0
  61. package/package.json +57 -4
@@ -0,0 +1,266 @@
1
+ import crypto from "crypto";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { ACTIVE_STATUSES, OperationSchema, ReposFileSchema, } from "../../shared/schemas/model.schema.js";
5
+ import { ConflictError, NotFoundError, TrackerError } from "./errors.js";
6
+ const LOCK_STALE_MS = 10_000;
7
+ const LOCK_RETRY_MS = 25;
8
+ const LOCK_TIMEOUT_MS = 5_000;
9
+ /** Opérations terminées conservées par dépôt ; les plus anciennes sont supprimées. */
10
+ const KEPT_OPERATIONS_PER_REPO = 20;
11
+ const OPERATION_ID_PATTERN = /^[a-z0-9-]+$/;
12
+ /** Pause bloquante : le store est synchrone de bout en bout. */
13
+ function sleepSync(ms) {
14
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
15
+ }
16
+ /** Écriture atomique : fichier temporaire unique puis `rename`, JSON indenté. */
17
+ function writeJsonAtomic(target, value) {
18
+ const tmp = `${target}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
19
+ try {
20
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), "utf-8");
21
+ fs.renameSync(tmp, target);
22
+ }
23
+ catch (err) {
24
+ fs.rmSync(tmp, { force: true });
25
+ throw err;
26
+ }
27
+ }
28
+ /** Vrai si le processus `pid` existe encore. */
29
+ export function processAlive(pid) {
30
+ try {
31
+ process.kill(pid, 0);
32
+ return true;
33
+ }
34
+ catch (err) {
35
+ return err.code === "EPERM";
36
+ }
37
+ }
38
+ export function isActive(operation) {
39
+ return ACTIVE_STATUSES.includes(operation.status);
40
+ }
41
+ /**
42
+ * Persistance : `<dataDir>/repos.json` pour les dépôts suivis et
43
+ * `<dataDir>/operations/<id>.json` pour chaque opération. Plusieurs processus
44
+ * (une instance du serveur par session d'agent) partagent le répertoire :
45
+ * chaque écriture passe par le verrou `<dataDir>/data.lock`.
46
+ */
47
+ export class Store {
48
+ dataDir;
49
+ reposPath;
50
+ operationsDir;
51
+ lockPath;
52
+ constructor(dataDir) {
53
+ this.dataDir = dataDir;
54
+ this.reposPath = path.join(dataDir, "repos.json");
55
+ this.operationsDir = path.join(dataDir, "operations");
56
+ this.lockPath = path.join(dataDir, "data.lock");
57
+ fs.mkdirSync(this.operationsDir, { recursive: true });
58
+ }
59
+ /** Sérialise les écritures entre processus : `wx` échoue si le verrou existe déjà. Non réentrant. */
60
+ withLock(fn) {
61
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
62
+ let fd;
63
+ for (;;) {
64
+ try {
65
+ fd = fs.openSync(this.lockPath, "wx");
66
+ break;
67
+ }
68
+ catch (err) {
69
+ if (err.code !== "EEXIST")
70
+ throw err;
71
+ let mtimeMs;
72
+ try {
73
+ mtimeMs = fs.statSync(this.lockPath).mtimeMs;
74
+ }
75
+ catch (statErr) {
76
+ if (statErr.code === "ENOENT")
77
+ continue;
78
+ throw statErr;
79
+ }
80
+ if (Date.now() - mtimeMs > LOCK_STALE_MS) {
81
+ fs.rmSync(this.lockPath, { force: true });
82
+ continue;
83
+ }
84
+ if (Date.now() > deadline) {
85
+ throw new TrackerError(`The tracker data is being written by another process and did not free up in ${LOCK_TIMEOUT_MS} ms. Try again in a moment.`);
86
+ }
87
+ sleepSync(LOCK_RETRY_MS);
88
+ }
89
+ }
90
+ try {
91
+ return fn();
92
+ }
93
+ finally {
94
+ fs.closeSync(fd);
95
+ fs.rmSync(this.lockPath, { force: true });
96
+ }
97
+ }
98
+ // --- Dépôts -----------------------------------------------------------------
99
+ readRepos() {
100
+ let raw;
101
+ try {
102
+ raw = fs.readFileSync(this.reposPath, "utf-8");
103
+ }
104
+ catch (err) {
105
+ if (err.code === "ENOENT")
106
+ return [];
107
+ throw err;
108
+ }
109
+ const parsed = ReposFileSchema.safeParse(JSON.parse(raw));
110
+ if (!parsed.success)
111
+ throw new TrackerError(`${this.reposPath} is invalid: ${parsed.error.message}`);
112
+ return parsed.data.repos;
113
+ }
114
+ writeRepos(repos) {
115
+ writeJsonAtomic(this.reposPath, ReposFileSchema.parse({ repos }));
116
+ }
117
+ listRepos() {
118
+ return this.readRepos();
119
+ }
120
+ /** Dépôt d'identifiant `propriétaire/nom`, sans tenir compte de la casse, comme GitHub. */
121
+ findRepo(repoId) {
122
+ const key = repoId.toLowerCase();
123
+ return this.readRepos().find((repo) => repo.id.toLowerCase() === key) ?? null;
124
+ }
125
+ getRepo(repoId) {
126
+ const repo = this.findRepo(repoId);
127
+ if (!repo)
128
+ throw new NotFoundError(`Repository "${repoId}" is not tracked. Use list_repositories to see the tracked repositories.`);
129
+ return repo;
130
+ }
131
+ addRepo(repo) {
132
+ return this.withLock(() => {
133
+ const repos = this.readRepos();
134
+ if (repos.some((existing) => existing.id.toLowerCase() === repo.id.toLowerCase())) {
135
+ throw new ConflictError(`Repository ${repo.id} is already tracked.`);
136
+ }
137
+ this.writeRepos([...repos, repo]);
138
+ return repo;
139
+ });
140
+ }
141
+ updateRepo(repoId, fn) {
142
+ return this.withLock(() => {
143
+ const repos = this.readRepos();
144
+ const index = repos.findIndex((repo) => repo.id.toLowerCase() === repoId.toLowerCase());
145
+ if (index === -1)
146
+ throw new NotFoundError(`Repository "${repoId}" is not tracked.`);
147
+ const updated = fn(repos[index]);
148
+ repos[index] = updated;
149
+ this.writeRepos(repos);
150
+ return updated;
151
+ });
152
+ }
153
+ /** Retire un dépôt et ses opérations ; refusé pendant une opération en cours. */
154
+ removeRepo(repoId) {
155
+ this.withLock(() => {
156
+ const repos = this.readRepos();
157
+ const repo = repos.find((candidate) => candidate.id.toLowerCase() === repoId.toLowerCase());
158
+ if (!repo)
159
+ throw new NotFoundError(`Repository "${repoId}" is not tracked.`);
160
+ const operations = this.readOperationsOf(repo.id);
161
+ if (operations.some(isActive))
162
+ throw new ConflictError(`An operation is in progress on ${repo.id}: cancel it before removing the repository.`);
163
+ for (const operation of operations)
164
+ fs.rmSync(this.operationPath(operation.id), { force: true });
165
+ this.writeRepos(repos.filter((candidate) => candidate !== repo));
166
+ });
167
+ }
168
+ // --- Opérations ---------------------------------------------------------------
169
+ operationPath(id) {
170
+ if (!OPERATION_ID_PATTERN.test(id))
171
+ throw new NotFoundError(`Operation "${id}" not found.`);
172
+ return path.join(this.operationsDir, `${id}.json`);
173
+ }
174
+ readOperationFile(file) {
175
+ let raw;
176
+ try {
177
+ raw = fs.readFileSync(file, "utf-8");
178
+ }
179
+ catch (err) {
180
+ if (err.code === "ENOENT")
181
+ return null;
182
+ throw err;
183
+ }
184
+ const parsed = OperationSchema.safeParse(JSON.parse(raw));
185
+ if (!parsed.success)
186
+ throw new TrackerError(`${file} is invalid: ${parsed.error.message}`);
187
+ return parsed.data;
188
+ }
189
+ readAllOperations() {
190
+ const operations = [];
191
+ for (const entry of fs.readdirSync(this.operationsDir)) {
192
+ if (!entry.endsWith(".json"))
193
+ continue;
194
+ const operation = this.readOperationFile(path.join(this.operationsDir, entry));
195
+ if (operation)
196
+ operations.push(operation);
197
+ }
198
+ return operations.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
199
+ }
200
+ readOperationsOf(repoId) {
201
+ const key = repoId.toLowerCase();
202
+ return this.readAllOperations().filter((operation) => operation.repoId.toLowerCase() === key);
203
+ }
204
+ getOperation(id) {
205
+ const operation = this.readOperationFile(this.operationPath(id));
206
+ if (!operation)
207
+ throw new NotFoundError(`Operation "${id}" not found.`);
208
+ return operation;
209
+ }
210
+ /** Opérations d'un dépôt, de la plus récente à la plus ancienne. */
211
+ listOperations(repoId) {
212
+ return this.readOperationsOf(repoId);
213
+ }
214
+ activeOperation(repoId) {
215
+ return this.readOperationsOf(repoId).find(isActive) ?? null;
216
+ }
217
+ /**
218
+ * Enregistre une nouvelle opération ; refusé si une autre est en cours sur le
219
+ * même dépôt. Les opérations terminées au-delà des 20 plus récentes sont supprimées.
220
+ */
221
+ createOperation(operation) {
222
+ return this.withLock(() => {
223
+ const existing = this.readOperationsOf(operation.repoId);
224
+ const active = existing.find(isActive);
225
+ if (active) {
226
+ throw new ConflictError(`An operation is already in progress on ${operation.repoId} (${active.id}, ${active.status}). Wait for it to finish or cancel it.`);
227
+ }
228
+ writeJsonAtomic(this.operationPath(operation.id), OperationSchema.parse(operation));
229
+ for (const old of existing.slice(KEPT_OPERATIONS_PER_REPO - 1))
230
+ fs.rmSync(this.operationPath(old.id), { force: true });
231
+ return operation;
232
+ });
233
+ }
234
+ updateOperation(id, fn) {
235
+ return this.withLock(() => {
236
+ const current = this.getOperation(id);
237
+ const updated = OperationSchema.parse({ ...fn(current), updatedAt: new Date().toISOString() });
238
+ writeJsonAtomic(this.operationPath(id), updated);
239
+ return updated;
240
+ });
241
+ }
242
+ /**
243
+ * Opérations `running` dont le processus a disparu : elles passent en échec et
244
+ * leur clone est supprimé. Les opérations en attente d'une décision ne
245
+ * dépendent d'aucun processus et restent en l'état.
246
+ */
247
+ failOrphanedOperations() {
248
+ const orphans = this.readAllOperations().filter((operation) => operation.status === "running" && !processAlive(operation.pid));
249
+ return orphans.map((orphan) => {
250
+ const failed = this.updateOperation(orphan.id, (operation) => {
251
+ if (operation.status !== "running" || processAlive(operation.pid))
252
+ return operation;
253
+ return {
254
+ ...operation,
255
+ status: "failed",
256
+ error: "Interrupted: the process that ran this operation stopped.",
257
+ steps: Object.fromEntries(Object.entries(operation.steps).map(([name, state]) => [name, state === "running" ? "failed" : state])),
258
+ workDir: null,
259
+ };
260
+ });
261
+ if (orphan.workDir)
262
+ fs.rmSync(orphan.workDir, { recursive: true, force: true });
263
+ return failed;
264
+ });
265
+ }
266
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,326 @@
1
+ import { serve } from "@hono/node-server";
2
+ import { serveStatic } from "@hono/node-server/serve-static";
3
+ import { Hono } from "hono";
4
+ import { GUI_LISTEN_HOST, ProxyClient, createLogger, honoGuiGuard, setupLogging } from "@imenam/mcp-gui-interface";
5
+ import path from "path";
6
+ import fs from "fs";
7
+ import { fileURLToPath } from "url";
8
+ import { IPCMessageSchema } from "../shared/schemas/ipc.schema.js";
9
+ import { AddRepoBodySchema, ForceBodySchema, PushBodySchema, SetRightsBodySchema } from "../shared/schemas/api.schema.js";
10
+ import { resolveLogDir } from "./core/log-dir.js";
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+ function findProjectRoot(startDir) {
13
+ let current = startDir;
14
+ while (current !== path.dirname(current)) {
15
+ if (fs.existsSync(path.join(current, "gui")) || fs.existsSync(path.join(current, "package.json")))
16
+ return current;
17
+ current = path.dirname(current);
18
+ }
19
+ return startDir;
20
+ }
21
+ const rootDir = findProjectRoot(__dirname);
22
+ const absoluteStaticRoot = path.resolve(path.join(rootDir, "gui/dist"));
23
+ const configuredAppPath = process.env.APP_PATH || "/dependabot-tracker";
24
+ /**
25
+ * Chemin réellement monté par le proxy. Il diffère de `configuredAppPath` quand
26
+ * `APP_PATH_PREFIX` est défini : le client partagé préfixe alors le chemin et
27
+ * renvoie le chemin final dans `result.path`. Le `<base href>` suit ce chemin.
28
+ */
29
+ let effectiveAppPath = configuredAppPath;
30
+ function resolveGuiMode() {
31
+ const proxyUrl = process.env.PROXY_URL?.trim();
32
+ if (proxyUrl)
33
+ return { kind: "proxy", proxyUrl };
34
+ const rawPort = process.env.APP_PORT?.trim();
35
+ if (!rawPort)
36
+ return { kind: "disabled", reason: "PROXY_URL et APP_PORT non définis" };
37
+ const port = Number(rawPort);
38
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
39
+ return { kind: "disabled", reason: `APP_PORT invalide (${rawPort}) — attendu : entier entre 1 et 65535` };
40
+ }
41
+ return { kind: "standalone", port };
42
+ }
43
+ const guiMode = resolveGuiMode();
44
+ const isStandalone = guiMode.kind === "standalone";
45
+ setupLogging({ processLabel: "mcp-dependabot-tracker:GUI", logDir: resolveLogDir() });
46
+ const logger = createLogger("mcp-dependabot-tracker:GUI");
47
+ process.on("uncaughtException", (err) => {
48
+ logger.error(`Uncaught Exception: ${err.message}`);
49
+ logger.error(err.stack || "No stack trace");
50
+ process.exit(1);
51
+ });
52
+ process.on("unhandledRejection", (reason) => {
53
+ logger.error(`Unhandled Rejection: ${reason}`);
54
+ process.exit(1);
55
+ });
56
+ // Le master peut disparaître sans que l'évènement `disconnect` ne parvienne au
57
+ // worker (cas Windows). Deux garde-fous : le canal IPC, fermé dès que le parent
58
+ // meurt, et le PID parent, moins fiable car les PID sont recyclés sous Windows.
59
+ const parentPid = process.ppid;
60
+ const parentCheckInterval = setInterval(() => {
61
+ if (!process.connected) {
62
+ logger.info("IPC channel to the MCP master is closed. Exiting.");
63
+ clearInterval(parentCheckInterval);
64
+ process.exit(0);
65
+ return;
66
+ }
67
+ try {
68
+ process.kill(parentPid, 0);
69
+ }
70
+ catch {
71
+ logger.info(`Parent process (PID ${parentPid}) is gone. Exiting.`);
72
+ clearInterval(parentCheckInterval);
73
+ process.exit(0);
74
+ }
75
+ }, 2000);
76
+ const app = new Hono();
77
+ // Contrôle de l'hôte appelé et des requêtes de modification, avant toute route.
78
+ app.use("*", honoGuiGuard({ proxyUrl: guiMode.kind === "proxy" ? guiMode.proxyUrl : undefined }));
79
+ let proxyClient = null;
80
+ const pendingRequests = new Map();
81
+ /** Délai de réponse du master ; l'ajout d'un dépôt interroge GitHub. */
82
+ const IPC_TIMEOUT_MS = 45_000;
83
+ function safeSend(message) {
84
+ if (process.send && process.connected) {
85
+ try {
86
+ return process.send(message);
87
+ }
88
+ catch (err) {
89
+ logger.error(`[IPC] Failed to send message: ${err.message}`);
90
+ return false;
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+ /** Requête IPC vers le master. Ne rejette jamais : un timeout devient une réponse d'erreur. */
96
+ function ipcRequest(type, data) {
97
+ const correlationId = Math.random().toString(36).substring(2, 12);
98
+ const message = { type, correlationId, data, timestamp: new Date().toISOString() };
99
+ return new Promise((resolve) => {
100
+ const timer = setTimeout(() => {
101
+ if (pendingRequests.has(correlationId)) {
102
+ pendingRequests.delete(correlationId);
103
+ resolve({ error: `IPC request ${type} timed out after ${IPC_TIMEOUT_MS}ms` });
104
+ }
105
+ }, IPC_TIMEOUT_MS);
106
+ pendingRequests.set(correlationId, (msg) => {
107
+ clearTimeout(timer);
108
+ resolve(msg);
109
+ });
110
+ if (!safeSend(message)) {
111
+ clearTimeout(timer);
112
+ pendingRequests.delete(correlationId);
113
+ resolve({ error: "IPC channel to the MCP master is not available" });
114
+ }
115
+ });
116
+ }
117
+ function setupIpcHandlers() {
118
+ process.on("error", (err) => {
119
+ if (err.code === "ERR_IPC_CHANNEL_CLOSED")
120
+ return;
121
+ logger.error(`Process error: ${err.message}`);
122
+ });
123
+ process.on("disconnect", () => {
124
+ logger.warn("IPC disconnected from MCP master. GUI worker exits.");
125
+ process.exit(0);
126
+ });
127
+ process.on("message", (raw) => {
128
+ const parsed = IPCMessageSchema.safeParse(raw);
129
+ if (!parsed.success) {
130
+ logger.warn(`Invalid IPC message ignored: ${parsed.error.message}`);
131
+ return;
132
+ }
133
+ const msg = parsed.data;
134
+ if (msg.correlationId && pendingRequests.has(msg.correlationId)) {
135
+ const resolve = pendingRequests.get(msg.correlationId);
136
+ pendingRequests.delete(msg.correlationId);
137
+ resolve(msg);
138
+ return;
139
+ }
140
+ logger.debug(`Unhandled IPC message type: ${msg.type}`);
141
+ });
142
+ }
143
+ // --- Routes HTTP ------------------------------------------------------------
144
+ app.get("/proxy/health", (c) => {
145
+ const memory = process.memoryUsage();
146
+ return c.json({
147
+ status: "ok",
148
+ proxy: proxyClient ? proxyClient.getStatus() : isStandalone ? "standalone" : "error",
149
+ uptime: process.uptime(),
150
+ memory: { rss: memory.rss, heapUsed: memory.heapUsed },
151
+ ipc: process.connected ? "connected" : "disconnected",
152
+ timestamp: new Date().toISOString(),
153
+ });
154
+ });
155
+ /** Code HTTP d'une erreur renvoyée par le master ; une erreur locale (timeout, IPC absent) est une erreur serveur. */
156
+ const HTTP_STATUS_BY_ERROR_KIND = {
157
+ invalid: 400,
158
+ not_found: 404,
159
+ conflict: 409,
160
+ internal: 500,
161
+ };
162
+ /** Transmet une requête au master et renvoie sa réponse, ou `{ error }` avec le code HTTP correspondant. */
163
+ async function forward(c, type, data) {
164
+ const result = await ipcRequest(type, data);
165
+ if (result.error !== undefined) {
166
+ return c.json({ error: result.error }, HTTP_STATUS_BY_ERROR_KIND[result.errorKind ?? "internal"]);
167
+ }
168
+ return c.json(result.data);
169
+ }
170
+ /** Lit et valide le corps JSON d'une requête ; renvoie une réponse 400 explicite s'il est invalide. */
171
+ async function readBody(c, schema) {
172
+ let raw;
173
+ try {
174
+ raw = await c.req.json();
175
+ }
176
+ catch (err) {
177
+ return { response: c.json({ error: `The request body is not valid JSON: ${err?.message ?? err}` }, 400) };
178
+ }
179
+ const parsed = schema.safeParse(raw);
180
+ if (!parsed.success) {
181
+ const issues = parsed.error.issues.map((issue) => `${issue.path.map(String).join(".") || "(root)"} ${issue.message}`);
182
+ return { response: c.json({ error: `Invalid request body: ${issues.join("; ")}.` }, 400) };
183
+ }
184
+ return { body: parsed.data };
185
+ }
186
+ /** Identifiant `propriétaire/nom` d'un dépôt, porté par deux segments de chemin. */
187
+ function repoId(c) {
188
+ return `${c.req.param("owner")}/${c.req.param("name")}`;
189
+ }
190
+ app.get("/api/config", (c) => forward(c, "GET_CONFIG"));
191
+ app.get("/api/repos", (c) => forward(c, "LIST_REPOS"));
192
+ app.post("/api/repos", async (c) => {
193
+ const read = await readBody(c, AddRepoBodySchema);
194
+ if ("response" in read)
195
+ return read.response;
196
+ return forward(c, "ADD_REPO", { body: read.body });
197
+ });
198
+ app.get("/api/github/repos", (c) => forward(c, "LIST_ADDABLE_REPOS"));
199
+ app.get("/api/repos/:owner/:name", (c) => forward(c, "GET_REPO", { repoId: repoId(c) }));
200
+ app.delete("/api/repos/:owner/:name", (c) => forward(c, "REMOVE_REPO", { repoId: repoId(c) }));
201
+ app.put("/api/repos/:owner/:name/rights", async (c) => {
202
+ const read = await readBody(c, SetRightsBodySchema);
203
+ if ("response" in read)
204
+ return read.response;
205
+ return forward(c, "SET_RIGHTS", { repoId: repoId(c), body: read.body });
206
+ });
207
+ app.post("/api/repos/:owner/:name/operations", (c) => forward(c, "START_FIX", { repoId: repoId(c) }));
208
+ app.get("/api/operations/:id", (c) => forward(c, "GET_OPERATION", { operationId: c.req.param("id") }));
209
+ app.post("/api/operations/:id/force", async (c) => {
210
+ const read = await readBody(c, ForceBodySchema);
211
+ if ("response" in read)
212
+ return read.response;
213
+ return forward(c, "DECIDE_FORCE", { operationId: c.req.param("id"), body: read.body });
214
+ });
215
+ app.post("/api/operations/:id/push", async (c) => {
216
+ const read = await readBody(c, PushBodySchema);
217
+ if ("response" in read)
218
+ return read.response;
219
+ return forward(c, "PUSH_OPERATION", { operationId: c.req.param("id"), body: read.body });
220
+ });
221
+ app.post("/api/operations/:id/cancel", (c) => forward(c, "CANCEL_OPERATION", { operationId: c.req.param("id") }));
222
+ /** Route d'API inconnue : 404 explicite plutôt que la page de la SPA. */
223
+ app.all("/api/*", (c) => c.json({ error: `Unknown API route: ${c.req.method} ${c.req.path}` }, 404));
224
+ // Fichiers statiques de la SPA
225
+ app.use("/assets/*", serveStatic({ root: path.relative(process.cwd(), absoluteStaticRoot) }));
226
+ function getHtmlBaseHref(appPath) {
227
+ const normalized = appPath.startsWith("/") ? appPath : `/${appPath}`;
228
+ return normalized.endsWith("/") ? normalized : `${normalized}/`;
229
+ }
230
+ // Toute autre route renvoie la page de la SPA, avec la balise <base> du chemin de montage.
231
+ app.get("/*", (c, next) => {
232
+ const urlPath = c.req.path;
233
+ if (urlPath.startsWith("/api") || urlPath.startsWith("/proxy") || urlPath.startsWith("/assets"))
234
+ return next();
235
+ const indexPath = path.join(absoluteStaticRoot, "index.html");
236
+ if (!fs.existsSync(indexPath)) {
237
+ return c.text(`GUI build not found at ${absoluteStaticRoot}. Run "npm run build:gui" in the package.`, 404);
238
+ }
239
+ // ?__direct=1 : accès au worker sur son port local, sans le proxy — le
240
+ // préfixe de montage ne préfixe alors pas les assets. En mode standalone la
241
+ // GUI est servie à la racine : même règle.
242
+ const baseHref = isStandalone || c.req.query("__direct") === "1" ? "/" : getHtmlBaseHref(effectiveAppPath);
243
+ const html = fs.readFileSync(indexPath, "utf8").replace("<head>", `<head>\n <base href="${baseHref}" />`);
244
+ return c.html(html);
245
+ });
246
+ /**
247
+ * Lance Hono sur `port` et prévient le master. `publicUrl` est l'URL que
248
+ * l'utilisateur ouvre : via le proxy, ou directement en localhost.
249
+ */
250
+ function listen(port, publicUrl, isProxied) {
251
+ const serverInstance = serve({ fetch: app.fetch, port, hostname: GUI_LISTEN_HOST }, (info) => {
252
+ logger.info(`Dependabot Tracker GUI listening on port ${info.port} (${GUI_LISTEN_HOST})`);
253
+ safeSend(IPCMessageSchema.parse({ type: "READY", data: { port: info.port, isProxied, url: publicUrl }, timestamp: new Date().toISOString() }));
254
+ });
255
+ serverInstance.on("error", (err) => {
256
+ if (err.code === "EADDRINUSE") {
257
+ // Sortie avec le code 0 : le master ne relance pas de worker supplémentaire.
258
+ logger.error(`Port ${port} already in use — another GUI instance is running.`);
259
+ safeSend(IPCMessageSchema.parse({ type: "ALREADY_RUNNING", data: { url: publicUrl }, timestamp: new Date().toISOString() }));
260
+ process.exit(0);
261
+ }
262
+ logger.error(`Server error: ${err.message}`);
263
+ process.exit(1);
264
+ });
265
+ }
266
+ /** Sans proxy : la GUI écoute sur APP_PORT et est servie à la racine. */
267
+ function startStandalone(port) {
268
+ const publicUrl = `http://localhost:${port}`;
269
+ logger.info(`Standalone mode (no PROXY_URL): serving GUI on ${publicUrl}`);
270
+ setupIpcHandlers();
271
+ listen(port, publicUrl, false);
272
+ }
273
+ async function startServer() {
274
+ if (guiMode.kind === "disabled") {
275
+ process.stderr.write(`[GUI] ${guiMode.reason} — arrêt.\n`);
276
+ process.exit(0);
277
+ }
278
+ if (guiMode.kind === "standalone") {
279
+ startStandalone(guiMode.port);
280
+ return;
281
+ }
282
+ const proxyUrl = guiMode.proxyUrl;
283
+ const appPath = configuredAppPath;
284
+ const appName = process.env.APP_NAME || "Dependabot Tracker";
285
+ logger.info(`Starting server with proxyUrl=${proxyUrl}`);
286
+ proxyClient = new ProxyClient(proxyUrl);
287
+ let result;
288
+ try {
289
+ // APP_GROUP place la GUI dans une section repliable du proxy (facultatif).
290
+ result = await proxyClient.register({ path: appPath, name: appName, group: process.env.APP_GROUP });
291
+ }
292
+ catch (e) {
293
+ process.stderr.write("[GUI] Enregistrement proxy échoué — arrêt.\n");
294
+ logger.error(`Proxy registration error: ${e.message}`);
295
+ process.exit(1);
296
+ }
297
+ if (result.error === "HTTP 409") {
298
+ logger.info("Another GUI instance already registered.");
299
+ safeSend(IPCMessageSchema.parse({ type: "ALREADY_RUNNING", data: { url: `${proxyUrl}${appPath}` }, timestamp: new Date().toISOString() }));
300
+ process.exit(0);
301
+ }
302
+ if (!result.success) {
303
+ process.stderr.write("[GUI] Enregistrement proxy échoué — arrêt.\n");
304
+ logger.error(`Proxy registration failed: ${result.error}`);
305
+ process.exit(1);
306
+ }
307
+ const finalPort = result.port;
308
+ effectiveAppPath = result.path ?? appPath;
309
+ const publicUrl = result.url || `${proxyUrl}${effectiveAppPath}`;
310
+ logger.info(`Registered with proxy. Public URL: ${publicUrl}, Local Port: ${finalPort}`);
311
+ const cleanupProxy = async () => {
312
+ if (proxyClient)
313
+ await proxyClient.unregister();
314
+ process.exit(0);
315
+ };
316
+ process.on("SIGTERM", cleanupProxy);
317
+ process.on("SIGINT", cleanupProxy);
318
+ setupIpcHandlers();
319
+ listen(finalPort, publicUrl, true);
320
+ }
321
+ startServer().catch((err) => {
322
+ logger.error(`Failed to start GUI Worker: ${err.message}`);
323
+ if (err.stack)
324
+ logger.error(err.stack);
325
+ process.exit(1);
326
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};