repoview 0.5.1 → 0.6.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 (57) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/CONTRIBUTING.md +4 -3
  3. package/DEVELOPMENT.md +84 -16
  4. package/README.md +71 -5
  5. package/dist/api.js +58 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/cli.js +454 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/csv.js +64 -0
  10. package/dist/csv.js.map +1 -0
  11. package/dist/format.js +25 -0
  12. package/dist/format.js.map +1 -0
  13. package/dist/gist-router.js +153 -0
  14. package/dist/gist-router.js.map +1 -0
  15. package/dist/gists.js +130 -0
  16. package/dist/gists.js.map +1 -0
  17. package/dist/git.js +67 -0
  18. package/dist/git.js.map +1 -0
  19. package/dist/gitignore.js +34 -0
  20. package/dist/gitignore.js.map +1 -0
  21. package/dist/linkcheck.js +310 -0
  22. package/dist/linkcheck.js.map +1 -0
  23. package/dist/markdown.js +493 -0
  24. package/dist/markdown.js.map +1 -0
  25. package/dist/net.js +10 -0
  26. package/dist/net.js.map +1 -0
  27. package/dist/paths.js +59 -0
  28. package/dist/paths.js.map +1 -0
  29. package/dist/reload.js +55 -0
  30. package/dist/reload.js.map +1 -0
  31. package/dist/repo-context.js +80 -0
  32. package/dist/repo-context.js.map +1 -0
  33. package/dist/repo-router.js +810 -0
  34. package/dist/repo-router.js.map +1 -0
  35. package/dist/review-cli.js +228 -0
  36. package/dist/review-cli.js.map +1 -0
  37. package/dist/server.js +122 -0
  38. package/dist/server.js.map +1 -0
  39. package/dist/session.js +86 -0
  40. package/dist/session.js.map +1 -0
  41. package/dist/types.js +2 -0
  42. package/dist/types.js.map +1 -0
  43. package/dist/views.js +780 -0
  44. package/dist/views.js.map +1 -0
  45. package/package.json +20 -9
  46. package/public/app.css +113 -0
  47. package/public/app.js +26 -3
  48. package/public/gist.js +60 -0
  49. package/public/review.js +9 -6
  50. package/public/session.js +61 -0
  51. package/src/cli.js +0 -91
  52. package/src/gitignore.js +0 -34
  53. package/src/linkcheck.js +0 -312
  54. package/src/markdown.js +0 -518
  55. package/src/review-cli.js +0 -245
  56. package/src/server.js +0 -1126
  57. package/src/views.js +0 -657
@@ -0,0 +1,810 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import express from "express";
4
+ import mime from "mime-types";
5
+ import diff2html from "diff2html";
6
+ import { escapeHtml, renderBrokenLinksPage, renderDiffPage, renderErrorPage, renderFilePage, renderReviewListPage, renderReviewThreadPage, renderSessionPage, renderTreePage, } from "./views.js";
7
+ import { toPosixPath, encodePathForUrl, safeRealpath, statSafe } from "./paths.js";
8
+ import { isLoopbackAddress } from "./net.js";
9
+ import { formatBytes, formatDate } from "./format.js";
10
+ import { parseCsv, renderCsvTable } from "./csv.js";
11
+ import { validateGitRef, getGitBranches, getGitTags, getGitDiffRaw, execGit, } from "./git.js";
12
+ const THREAD_ID_RE = /^[a-zA-Z0-9_-]+$/;
13
+ function qstr(v) {
14
+ return typeof v === "string" ? v : undefined;
15
+ }
16
+ function validateThreadId(id) {
17
+ return !!id && typeof id === "string" && THREAD_ID_RE.test(id);
18
+ }
19
+ /**
20
+ * Build an express.Router serving a single repo (the given context). All
21
+ * generated app URLs are prefixed with `repoBase` (e.g. "/r/myrepo").
22
+ */
23
+ function buildRepoRouter(ctx, repoBase, session) {
24
+ const { md } = ctx;
25
+ const router = express.Router();
26
+ const errorPage = (title, message) => renderErrorPage({ title, message, repoBase, repos: session.listRepos(), currentRepoId: ctx.id });
27
+ router.get("/rev", (req, res) => {
28
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
29
+ res.status(200).send({ revision: ctx.reloadHub.getRevision() });
30
+ });
31
+ router.get("/broken-links.json", (req, res) => {
32
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
33
+ res.status(200).send(ctx.linkScanner.getState());
34
+ });
35
+ router.get("/broken-links", (req, res) => {
36
+ const showIgnored = req.query.ignored === "1";
37
+ const query = new URLSearchParams();
38
+ if (req.query.watch === "0")
39
+ query.set("watch", "0");
40
+ if (showIgnored)
41
+ query.set("ignored", "1");
42
+ const querySuffix = query.toString() ? `?${query.toString()}` : "";
43
+ const toggleIgnoredSuffix = (() => {
44
+ const q = new URLSearchParams(query);
45
+ if (showIgnored)
46
+ q.delete("ignored");
47
+ else
48
+ q.set("ignored", "1");
49
+ return q.toString() ? `?${q.toString()}` : "";
50
+ })();
51
+ const toggleIgnoredHref = `${repoBase}/broken-links${toggleIgnoredSuffix}`;
52
+ const state = ctx.linkScanner.getState();
53
+ res.status(200).send(renderBrokenLinksPage({
54
+ title: `${ctx.repoName} · Broken links`,
55
+ repoName: ctx.repoName,
56
+ gitInfo: ctx.gitInfo,
57
+ relPathPosix: "",
58
+ scanState: state,
59
+ querySuffix,
60
+ toggleIgnoredHref,
61
+ showIgnored,
62
+ repoBase,
63
+ repos: session.listRepos(),
64
+ currentRepoId: ctx.id,
65
+ }));
66
+ });
67
+ router.get("/events", (req, res) => {
68
+ res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
69
+ res.setHeader("Cache-Control", "no-cache, no-transform");
70
+ res.setHeader("Connection", "keep-alive");
71
+ res.flushHeaders?.();
72
+ res.write("event: hello\ndata: ok\n\n");
73
+ // Scope reloads to what the page is actually showing (file/dir), defaulting
74
+ // to "all" for repo-wide views (diff, broken-links) and unknown scopes.
75
+ const scopeType = qstr(req.query.scope);
76
+ const scopePath = qstr(req.query.path) ?? "";
77
+ const scope = scopeType === "file"
78
+ ? { type: "file", path: scopePath }
79
+ : scopeType === "dir"
80
+ ? { type: "dir", path: scopePath }
81
+ : { type: "all" };
82
+ ctx.reloadHub.add(res, scope);
83
+ const interval = setInterval(() => {
84
+ try {
85
+ res.write(":\n\n");
86
+ ctx.reloadHub.broadcastPing();
87
+ }
88
+ catch {
89
+ // ignore
90
+ }
91
+ }, 15000);
92
+ res.on("close", () => clearInterval(interval));
93
+ });
94
+ router.get("/diff", async (req, res) => {
95
+ try {
96
+ const base = qstr(req.query.base) || "HEAD";
97
+ if (!validateGitRef(base)) {
98
+ const err = new Error("Invalid base ref");
99
+ err.statusCode = 400;
100
+ throw err;
101
+ }
102
+ if (!ctx.gitInfo.commit) {
103
+ const err = new Error("Not a git repository");
104
+ err.statusCode = 400;
105
+ throw err;
106
+ }
107
+ const query = new URLSearchParams();
108
+ if (req.query.watch === "0")
109
+ query.set("watch", "0");
110
+ if (req.query.ignored === "1")
111
+ query.set("ignored", "1");
112
+ if (base !== "HEAD")
113
+ query.set("base", base);
114
+ if (req.query.show_all === "1")
115
+ query.set("show_all", "1");
116
+ const querySuffix = query.toString() ? `?${query.toString()}` : "";
117
+ const [branches, tags, diffResult] = await Promise.all([
118
+ getGitBranches(ctx.repoRootReal),
119
+ getGitTags(ctx.repoRootReal),
120
+ getGitDiffRaw(ctx.repoRootReal, base),
121
+ ]);
122
+ const MAX_DIFF_FILES = 30;
123
+ let diffHtml = "";
124
+ let fileCount = 0;
125
+ const showAll = req.query.show_all === "1";
126
+ if (!diffResult.tooLarge && diffResult.raw) {
127
+ const parsed = diff2html.parse(diffResult.raw);
128
+ fileCount = parsed.length;
129
+ const toRender = (!showAll && parsed.length > MAX_DIFF_FILES)
130
+ ? parsed.slice(0, MAX_DIFF_FILES)
131
+ : parsed;
132
+ diffHtml = diff2html.html(toRender, {
133
+ outputFormat: "line-by-line",
134
+ drawFileList: true,
135
+ });
136
+ }
137
+ res.status(200).send(renderDiffPage({
138
+ title: `${ctx.repoName} · Diff`,
139
+ repoName: ctx.repoName,
140
+ gitInfo: ctx.gitInfo,
141
+ relPathPosix: "",
142
+ querySuffix,
143
+ base,
144
+ branches,
145
+ tags,
146
+ diffHtml,
147
+ tooLarge: diffResult.tooLarge,
148
+ empty: !diffResult.raw,
149
+ fileCount,
150
+ showAll,
151
+ repoBase,
152
+ repos: session.listRepos(),
153
+ currentRepoId: ctx.id,
154
+ }));
155
+ }
156
+ catch (e) {
157
+ const err = e;
158
+ res
159
+ .status(err.statusCode || 500)
160
+ .send(errorPage("Error", e.message ?? "Error"));
161
+ }
162
+ });
163
+ router.get(["/tree/*", "/tree"], async (req, res) => {
164
+ try {
165
+ const showIgnored = req.query.ignored === "1";
166
+ const query = new URLSearchParams();
167
+ if (req.query.watch === "0")
168
+ query.set("watch", "0");
169
+ if (showIgnored)
170
+ query.set("ignored", "1");
171
+ const querySuffix = query.toString() ? `?${query.toString()}` : "";
172
+ const toggleIgnoredSuffix = (() => {
173
+ const q = new URLSearchParams(query);
174
+ if (showIgnored)
175
+ q.delete("ignored");
176
+ else
177
+ q.set("ignored", "1");
178
+ return q.toString() ? `?${q.toString()}` : "";
179
+ })();
180
+ const p = req.params[0] ?? "";
181
+ const { stripped, resolved } = await safeRealpath(ctx.repoRootReal, p);
182
+ const toggleIgnoredHref = `${repoBase}/tree/${encodePathForUrl(toPosixPath(stripped))}${toggleIgnoredSuffix}`;
183
+ const st = await statSafe(resolved);
184
+ if (st === null) {
185
+ const err = new Error("Permission denied");
186
+ err.statusCode = 403;
187
+ throw err;
188
+ }
189
+ if (st.isFile)
190
+ return res.redirect(`${repoBase}/blob/${encodePathForUrl(toPosixPath(stripped))}${querySuffix}`);
191
+ let entries;
192
+ try {
193
+ entries = await fs.readdir(resolved, { withFileTypes: true });
194
+ }
195
+ catch (e) {
196
+ if (e.code === "EACCES" || e.code === "EPERM") {
197
+ const err = new Error("Permission denied");
198
+ err.statusCode = 403;
199
+ throw err;
200
+ }
201
+ throw e;
202
+ }
203
+ const readmeEntry = entries.find((e) => e.isFile() &&
204
+ /^readme(?:\.(?:md|markdown|mdown|mkd|mkdn))?$/i.test(e.name));
205
+ const rows = (await Promise.all(entries
206
+ .filter((e) => {
207
+ if (e.name === ".git")
208
+ return false;
209
+ if (showIgnored)
210
+ return true;
211
+ const relPosix = toPosixPath(path.posix.join(toPosixPath(stripped), e.name));
212
+ return !ctx.ignoreMatcher.ignores(relPosix, { isDir: e.isDirectory() });
213
+ })
214
+ .map(async (e) => {
215
+ const relPosix = toPosixPath(path.posix.join(toPosixPath(stripped), e.name));
216
+ const full = path.join(resolved, e.name);
217
+ const info = await statSafe(full, { followSymlinks: false });
218
+ if (info === null)
219
+ return null;
220
+ const isDir = e.isDirectory();
221
+ const href = isDir
222
+ ? `${repoBase}/tree/${encodePathForUrl(relPosix)}${querySuffix}`
223
+ : `${repoBase}/blob/${encodePathForUrl(relPosix)}${querySuffix}`;
224
+ return {
225
+ name: e.name,
226
+ isDir,
227
+ href,
228
+ size: isDir ? "" : formatBytes(info.size),
229
+ mtime: formatDate(info.mtimeMs),
230
+ mtimeMs: info.mtimeMs,
231
+ };
232
+ }))).filter((row) => row !== null);
233
+ rows.sort((a, b) => {
234
+ if (a.isDir !== b.isDir)
235
+ return a.isDir ? -1 : 1;
236
+ return a.name.localeCompare(b.name);
237
+ });
238
+ let readmeHtml = "";
239
+ if (readmeEntry) {
240
+ try {
241
+ const readmeRel = toPosixPath(path.posix.join(toPosixPath(stripped), readmeEntry.name));
242
+ if (!showIgnored && ctx.ignoreMatcher.ignores(readmeRel, { isDir: false }))
243
+ throw new Error("ignored");
244
+ const { resolved: readmePath } = await safeRealpath(ctx.repoRootReal, readmeRel);
245
+ const readmeStat = await statSafe(readmePath);
246
+ if (readmeStat && readmeStat.size <= 2 * 1024 * 1024) {
247
+ const buf = await fs.readFile(readmePath);
248
+ readmeHtml = md.render(buf.toString("utf8"), {
249
+ baseDirPosix: toPosixPath(stripped),
250
+ repoBase,
251
+ });
252
+ }
253
+ }
254
+ catch {
255
+ readmeHtml = "";
256
+ }
257
+ }
258
+ res.status(200).send(renderTreePage({
259
+ title: `${ctx.repoName}${stripped ? `/${stripped}` : ""}`,
260
+ repoName: ctx.repoName,
261
+ gitInfo: ctx.gitInfo,
262
+ brokenLinks: ctx.linkScanner.getState(),
263
+ relPathPosix: toPosixPath(stripped),
264
+ querySuffix,
265
+ toggleIgnoredHref,
266
+ showIgnored,
267
+ rows,
268
+ readmeHtml,
269
+ repoBase,
270
+ repos: session.listRepos(),
271
+ currentRepoId: ctx.id,
272
+ }));
273
+ }
274
+ catch (e) {
275
+ const err = e;
276
+ res
277
+ .status(err.statusCode || 500)
278
+ .send(errorPage("Error", e.message ?? "Error"));
279
+ }
280
+ });
281
+ router.get(["/blob/*", "/blob"], async (req, res) => {
282
+ try {
283
+ const showIgnored = req.query.ignored === "1";
284
+ const query = new URLSearchParams();
285
+ if (req.query.watch === "0")
286
+ query.set("watch", "0");
287
+ if (showIgnored)
288
+ query.set("ignored", "1");
289
+ const querySuffix = query.toString() ? `?${query.toString()}` : "";
290
+ const toggleIgnoredSuffix = (() => {
291
+ const q = new URLSearchParams(query);
292
+ if (showIgnored)
293
+ q.delete("ignored");
294
+ else
295
+ q.set("ignored", "1");
296
+ return q.toString() ? `?${q.toString()}` : "";
297
+ })();
298
+ const p = req.params[0] ?? "";
299
+ const { stripped, resolved } = await safeRealpath(ctx.repoRootReal, p);
300
+ const toggleIgnoredHref = `${repoBase}/blob/${encodePathForUrl(toPosixPath(stripped))}${toggleIgnoredSuffix}`;
301
+ const st = await statSafe(resolved);
302
+ if (st === null) {
303
+ const err = new Error("Permission denied");
304
+ err.statusCode = 403;
305
+ throw err;
306
+ }
307
+ if (st.isDir)
308
+ return res.redirect(`${repoBase}/tree/${encodePathForUrl(toPosixPath(stripped))}${querySuffix}`);
309
+ const fileName = path.basename(resolved);
310
+ const ext = path.extname(fileName).toLowerCase();
311
+ const isMarkdown = [".md", ".markdown", ".mdown", ".mkd", ".mkdn"].includes(ext);
312
+ const isPdf = ext === ".pdf";
313
+ const isImage = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".bmp"].includes(ext);
314
+ const isCsv = [".csv", ".tsv"].includes(ext);
315
+ const maxBytes = 2 * 1024 * 1024;
316
+ const rawSrc = `${repoBase}/raw/${encodePathForUrl(toPosixPath(stripped))}`;
317
+ if (isPdf) {
318
+ res.status(200).send(renderFilePage({
319
+ title: `${ctx.repoName}/${stripped}`,
320
+ repoName: ctx.repoName,
321
+ gitInfo: ctx.gitInfo,
322
+ brokenLinks: ctx.linkScanner.getState(),
323
+ relPathPosix: toPosixPath(stripped),
324
+ querySuffix,
325
+ toggleIgnoredHref,
326
+ showIgnored,
327
+ fileName,
328
+ isMarkdown: false,
329
+ mediaType: "pdf",
330
+ renderedHtml: `<iframe class="pdf-frame" src="${rawSrc}"></iframe>`,
331
+ repoBase,
332
+ repos: session.listRepos(),
333
+ currentRepoId: ctx.id,
334
+ }));
335
+ return;
336
+ }
337
+ if (isImage) {
338
+ res.status(200).send(renderFilePage({
339
+ title: `${ctx.repoName}/${stripped}`,
340
+ repoName: ctx.repoName,
341
+ gitInfo: ctx.gitInfo,
342
+ brokenLinks: ctx.linkScanner.getState(),
343
+ relPathPosix: toPosixPath(stripped),
344
+ querySuffix,
345
+ toggleIgnoredHref,
346
+ showIgnored,
347
+ fileName,
348
+ isMarkdown: false,
349
+ mediaType: "image",
350
+ renderedHtml: `<img class="image-preview" src="${rawSrc}" alt="${escapeHtml(fileName)}" />`,
351
+ repoBase,
352
+ repos: session.listRepos(),
353
+ currentRepoId: ctx.id,
354
+ }));
355
+ return;
356
+ }
357
+ if (st.size > maxBytes) {
358
+ res.status(200).send(renderFilePage({
359
+ title: `${ctx.repoName}/${stripped}`,
360
+ repoName: ctx.repoName,
361
+ gitInfo: ctx.gitInfo,
362
+ brokenLinks: ctx.linkScanner.getState(),
363
+ relPathPosix: toPosixPath(stripped),
364
+ querySuffix,
365
+ toggleIgnoredHref,
366
+ showIgnored,
367
+ fileName,
368
+ isMarkdown: false,
369
+ renderedHtml: `<div class="note">File is too large to render (${formatBytes(st.size)}). Use <a href="${repoBase}/raw/${encodePathForUrl(toPosixPath(stripped))}${querySuffix}">Raw</a>.</div>`,
370
+ repoBase,
371
+ repos: session.listRepos(),
372
+ currentRepoId: ctx.id,
373
+ }));
374
+ return;
375
+ }
376
+ const raw = await fs.readFile(resolved);
377
+ const text = raw.toString("utf8");
378
+ let renderedHtml;
379
+ let mediaType;
380
+ if (isCsv) {
381
+ const delimiter = ext === ".tsv" ? "\t" : ",";
382
+ const rows = parseCsv(text, delimiter);
383
+ renderedHtml = renderCsvTable(rows, escapeHtml);
384
+ mediaType = "csv";
385
+ }
386
+ else if (isMarkdown) {
387
+ const baseDir = toPosixPath(path.posix.dirname(toPosixPath(stripped)));
388
+ renderedHtml = md.render(text, { baseDirPosix: baseDir === "." ? "" : baseDir, repoBase });
389
+ }
390
+ else {
391
+ renderedHtml = md.renderCodeBlock(text, {
392
+ languageHint: ext ? ext.slice(1) : "",
393
+ });
394
+ }
395
+ res.status(200).send(renderFilePage({
396
+ title: `${ctx.repoName}/${stripped}`,
397
+ repoName: ctx.repoName,
398
+ gitInfo: ctx.gitInfo,
399
+ brokenLinks: ctx.linkScanner.getState(),
400
+ relPathPosix: toPosixPath(stripped),
401
+ querySuffix,
402
+ toggleIgnoredHref,
403
+ showIgnored,
404
+ fileName,
405
+ isMarkdown,
406
+ mediaType,
407
+ renderedHtml,
408
+ repoBase,
409
+ repos: session.listRepos(),
410
+ currentRepoId: ctx.id,
411
+ }));
412
+ }
413
+ catch (e) {
414
+ const err = e;
415
+ res
416
+ .status(err.statusCode || 500)
417
+ .send(errorPage("Error", e.message ?? "Error"));
418
+ }
419
+ });
420
+ // --- Review routes ---
421
+ const reviewDir = ctx.reviewDir;
422
+ router.get("/review/", async (req, res) => {
423
+ try {
424
+ let entries = [];
425
+ try {
426
+ entries = await fs.readdir(reviewDir, { withFileTypes: true });
427
+ }
428
+ catch {
429
+ // no review dir yet
430
+ }
431
+ const threads = [];
432
+ for (const entry of entries) {
433
+ if (!entry.isDirectory())
434
+ continue;
435
+ const threadFile = path.join(reviewDir, entry.name, "thread.json");
436
+ try {
437
+ const thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
438
+ let messageCount = 0;
439
+ let lastMessageId = null;
440
+ try {
441
+ const msgs = (await fs.readdir(path.join(reviewDir, entry.name, "messages")))
442
+ .filter((f) => f.endsWith(".json"))
443
+ .sort();
444
+ messageCount = msgs.length;
445
+ lastMessageId = msgs.length ? msgs[msgs.length - 1].replace(".json", "") : null;
446
+ }
447
+ catch {
448
+ // no messages
449
+ }
450
+ const unreadCount = thread.readUntil && lastMessageId
451
+ ? Math.max(0, parseInt(lastMessageId, 10) - parseInt(thread.readUntil, 10))
452
+ : thread.readUntil ? 0 : messageCount;
453
+ threads.push({ ...thread, messageCount, lastMessageId, unreadCount });
454
+ }
455
+ catch {
456
+ // skip
457
+ }
458
+ }
459
+ threads.sort((a, b) => new Date(b.lastActivityAt).getTime() - new Date(a.lastActivityAt).getTime());
460
+ res.status(200).send(renderReviewListPage({
461
+ title: `${ctx.repoName} · Reviews`,
462
+ repoName: ctx.repoName,
463
+ gitInfo: ctx.gitInfo,
464
+ threads,
465
+ repoBase,
466
+ repos: session.listRepos(),
467
+ currentRepoId: ctx.id,
468
+ }));
469
+ }
470
+ catch (e) {
471
+ res.status(500).send(errorPage("Error", e.message ?? "Error"));
472
+ }
473
+ });
474
+ router.get("/review/:threadId", async (req, res) => {
475
+ try {
476
+ const { threadId } = req.params;
477
+ if (!validateThreadId(threadId)) {
478
+ return res.status(400).send(errorPage("Error", "Invalid thread ID"));
479
+ }
480
+ const threadDir = path.join(reviewDir, threadId);
481
+ const threadFile = path.join(threadDir, "thread.json");
482
+ let thread;
483
+ try {
484
+ thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
485
+ }
486
+ catch {
487
+ return res.status(404).send(errorPage("Error", "Thread not found"));
488
+ }
489
+ const messagesDir = path.join(threadDir, "messages");
490
+ let messageFiles = [];
491
+ try {
492
+ messageFiles = (await fs.readdir(messagesDir)).filter((f) => f.endsWith(".json")).sort();
493
+ }
494
+ catch {
495
+ // no messages
496
+ }
497
+ const messages = [];
498
+ for (const f of messageFiles) {
499
+ messages.push(JSON.parse(await fs.readFile(path.join(messagesDir, f), "utf8")));
500
+ }
501
+ let comments = [];
502
+ try {
503
+ const commentsData = JSON.parse(await fs.readFile(path.join(threadDir, "comments.json"), "utf8"));
504
+ comments = commentsData.comments || [];
505
+ }
506
+ catch {
507
+ // no comments
508
+ }
509
+ // Render agent messages as markdown, user messages as plain text
510
+ const renderedMessages = messages.map((msg) => {
511
+ if (msg.role === "agent" && msg.format === "markdown") {
512
+ return md.render(msg.body, { baseDirPosix: "", emitLineMap: true, repoBase });
513
+ }
514
+ return msg.body;
515
+ });
516
+ // Mark as read
517
+ if (messageFiles.length) {
518
+ const lastMsgId = messageFiles[messageFiles.length - 1].replace(".json", "");
519
+ thread.readUntil = lastMsgId;
520
+ await fs.writeFile(threadFile, JSON.stringify(thread, null, 2) + "\n");
521
+ }
522
+ res.status(200).send(renderReviewThreadPage({
523
+ title: `${ctx.repoName} · ${thread.title}`,
524
+ repoName: ctx.repoName,
525
+ gitInfo: ctx.gitInfo,
526
+ thread,
527
+ messages,
528
+ comments,
529
+ renderedMessages,
530
+ repoBase,
531
+ repos: session.listRepos(),
532
+ currentRepoId: ctx.id,
533
+ }));
534
+ }
535
+ catch (e) {
536
+ res.status(500).send(errorPage("Error", e.message ?? "Error"));
537
+ }
538
+ });
539
+ router.post("/review/:threadId/messages", express.json(), async (req, res) => {
540
+ try {
541
+ const { threadId } = req.params;
542
+ if (!validateThreadId(threadId)) {
543
+ return res.status(400).json({ error: "Invalid thread ID" });
544
+ }
545
+ const threadDir = path.join(reviewDir, threadId);
546
+ const threadFile = path.join(threadDir, "thread.json");
547
+ const messagesDir = path.join(threadDir, "messages");
548
+ let thread;
549
+ try {
550
+ thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
551
+ }
552
+ catch {
553
+ return res.status(404).json({ error: "Thread not found" });
554
+ }
555
+ const { body } = req.body;
556
+ if (!body || !body.trim()) {
557
+ return res.status(400).json({ error: "Message body is required" });
558
+ }
559
+ let entries = [];
560
+ try {
561
+ entries = (await fs.readdir(messagesDir)).filter((f) => f.endsWith(".json"));
562
+ }
563
+ catch {
564
+ await fs.mkdir(messagesDir, { recursive: true });
565
+ }
566
+ const existingIds = entries.map((e) => e.replace(".json", ""));
567
+ let max = 0;
568
+ for (const id of existingIds) {
569
+ const n = parseInt(id, 10);
570
+ if (n > max)
571
+ max = n;
572
+ }
573
+ const nextId = String(max + 1).padStart(3, "0");
574
+ const now = new Date().toISOString();
575
+ const message = {
576
+ id: nextId,
577
+ role: "user",
578
+ format: "text",
579
+ body: body.trim(),
580
+ createdAt: now,
581
+ };
582
+ await fs.writeFile(path.join(messagesDir, `${nextId}.json`), JSON.stringify(message, null, 2) + "\n");
583
+ thread.lastActivityAt = now;
584
+ await fs.writeFile(threadFile, JSON.stringify(thread, null, 2) + "\n");
585
+ res.status(201).json(message);
586
+ }
587
+ catch (e) {
588
+ res.status(500).json({ error: e.message });
589
+ }
590
+ });
591
+ router.post("/review/:threadId/comments", express.json(), async (req, res) => {
592
+ try {
593
+ const { threadId } = req.params;
594
+ if (!validateThreadId(threadId)) {
595
+ return res.status(400).json({ error: "Invalid thread ID" });
596
+ }
597
+ const threadDir = path.join(reviewDir, threadId);
598
+ const commentsFile = path.join(threadDir, "comments.json");
599
+ const { messageId, anchorLine, anchorEndLine, anchorText, body } = req.body;
600
+ if (!body || !body.trim()) {
601
+ return res.status(400).json({ error: "Comment body is required" });
602
+ }
603
+ let commentsData = { comments: [] };
604
+ try {
605
+ commentsData = JSON.parse(await fs.readFile(commentsFile, "utf8"));
606
+ }
607
+ catch {
608
+ // fresh comments
609
+ }
610
+ const id = `c_${Date.now()}_${Math.random().toString(36).slice(2, 5)}`;
611
+ const comment = {
612
+ id,
613
+ messageId: messageId || null,
614
+ anchorLine: anchorLine || null,
615
+ anchorEndLine: anchorEndLine || null,
616
+ anchorText: anchorText || null,
617
+ body: body.trim(),
618
+ createdAt: new Date().toISOString(),
619
+ resolved: false,
620
+ };
621
+ commentsData.comments.push(comment);
622
+ await fs.writeFile(commentsFile, JSON.stringify(commentsData, null, 2) + "\n");
623
+ res.status(201).json(comment);
624
+ }
625
+ catch (e) {
626
+ res.status(500).json({ error: e.message });
627
+ }
628
+ });
629
+ router.patch("/review/:threadId/comments/:commentId", express.json(), async (req, res) => {
630
+ try {
631
+ const { threadId, commentId } = req.params;
632
+ if (!validateThreadId(threadId)) {
633
+ return res.status(400).json({ error: "Invalid thread ID" });
634
+ }
635
+ const commentsFile = path.join(reviewDir, threadId, "comments.json");
636
+ let commentsData;
637
+ try {
638
+ commentsData = JSON.parse(await fs.readFile(commentsFile, "utf8"));
639
+ }
640
+ catch {
641
+ return res.status(404).json({ error: "Comments not found" });
642
+ }
643
+ const comment = commentsData.comments.find((c) => c.id === commentId);
644
+ if (!comment) {
645
+ return res.status(404).json({ error: "Comment not found" });
646
+ }
647
+ if (req.body.resolved !== undefined)
648
+ comment.resolved = req.body.resolved;
649
+ if (req.body.body !== undefined)
650
+ comment.body = req.body.body;
651
+ await fs.writeFile(commentsFile, JSON.stringify(commentsData, null, 2) + "\n");
652
+ res.status(200).json(comment);
653
+ }
654
+ catch (e) {
655
+ res.status(500).json({ error: e.message });
656
+ }
657
+ });
658
+ router.delete("/review/:threadId/comments/:commentId", async (req, res) => {
659
+ try {
660
+ const { threadId, commentId } = req.params;
661
+ if (!validateThreadId(threadId)) {
662
+ return res.status(400).json({ error: "Invalid thread ID" });
663
+ }
664
+ const commentsFile = path.join(reviewDir, threadId, "comments.json");
665
+ let commentsData;
666
+ try {
667
+ commentsData = JSON.parse(await fs.readFile(commentsFile, "utf8"));
668
+ }
669
+ catch {
670
+ return res.status(404).json({ error: "Comments not found" });
671
+ }
672
+ const idx = commentsData.comments.findIndex((c) => c.id === commentId);
673
+ if (idx === -1) {
674
+ return res.status(404).json({ error: "Comment not found" });
675
+ }
676
+ commentsData.comments.splice(idx, 1);
677
+ await fs.writeFile(commentsFile, JSON.stringify(commentsData, null, 2) + "\n");
678
+ res.status(200).json({ ok: true });
679
+ }
680
+ catch (e) {
681
+ res.status(500).json({ error: e.message });
682
+ }
683
+ });
684
+ router.post("/review/:threadId/mark-read", express.json(), async (req, res) => {
685
+ try {
686
+ const { threadId } = req.params;
687
+ if (!validateThreadId(threadId)) {
688
+ return res.status(400).json({ error: "Invalid thread ID" });
689
+ }
690
+ const threadFile = path.join(reviewDir, threadId, "thread.json");
691
+ let thread;
692
+ try {
693
+ thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
694
+ }
695
+ catch {
696
+ return res.status(404).json({ error: "Thread not found" });
697
+ }
698
+ const { readUntil } = req.body;
699
+ if (readUntil)
700
+ thread.readUntil = readUntil;
701
+ await fs.writeFile(threadFile, JSON.stringify(thread, null, 2) + "\n");
702
+ res.status(200).json({ ok: true });
703
+ }
704
+ catch (e) {
705
+ res.status(500).json({ error: e.message });
706
+ }
707
+ });
708
+ // --- Code context API for inline code popups ---
709
+ router.get("/api/code-context", async (req, res) => {
710
+ try {
711
+ const filePath = req.query.file;
712
+ if (!filePath || typeof filePath !== "string") {
713
+ return res.status(400).json({ error: "file parameter required" });
714
+ }
715
+ const line = parseInt(qstr(req.query.line) ?? "", 10) || 1;
716
+ const endLine = parseInt(qstr(req.query.endLine) ?? "", 10) || line;
717
+ const context = Math.min(parseInt(qstr(req.query.context) ?? "", 10) || 20, 200);
718
+ const { resolved, stripped } = await safeRealpath(ctx.repoRootReal, filePath);
719
+ const st = await statSafe(resolved);
720
+ if (!st || !st.isFile) {
721
+ return res.status(404).json({ error: "File not found" });
722
+ }
723
+ if (st.size > 2 * 1024 * 1024) {
724
+ return res.status(400).json({ error: "File too large" });
725
+ }
726
+ const raw = await fs.readFile(resolved, "utf8");
727
+ const allLines = raw.split("\n");
728
+ const startLine = Math.max(1, Math.min(line, endLine) - context);
729
+ const stopLine = Math.min(allLines.length, Math.max(line, endLine) + context);
730
+ const snippet = allLines.slice(startLine - 1, stopLine);
731
+ const ext = path.extname(stripped).slice(1);
732
+ // Get diff for this file (against HEAD)
733
+ let diff = null;
734
+ const diffResult = await execGit(ctx.repoRootReal, ["diff", "HEAD", "--", stripped], 256 * 1024);
735
+ if (diffResult.output) {
736
+ diff = diffResult.output;
737
+ }
738
+ res.json({
739
+ file: toPosixPath(stripped),
740
+ startLine,
741
+ stopLine,
742
+ highlightStart: Math.min(line, endLine),
743
+ highlightEnd: Math.max(line, endLine),
744
+ lines: snippet,
745
+ language: ext,
746
+ totalLines: allLines.length,
747
+ diff,
748
+ });
749
+ }
750
+ catch (e) {
751
+ const err = e;
752
+ res.status(err.statusCode || 500).json({ error: err.message });
753
+ }
754
+ });
755
+ router.get(["/raw/*", "/raw"], async (req, res) => {
756
+ try {
757
+ const p = req.params[0] ?? "";
758
+ const { resolved } = await safeRealpath(ctx.repoRootReal, p);
759
+ const st = await statSafe(resolved);
760
+ if (st === null) {
761
+ const err = new Error("Permission denied");
762
+ err.statusCode = 403;
763
+ throw err;
764
+ }
765
+ if (!st.isFile) {
766
+ const err = new Error("Not a file");
767
+ err.statusCode = 400;
768
+ throw err;
769
+ }
770
+ const contentType = mime.contentType(path.extname(resolved)) || "application/octet-stream";
771
+ res.setHeader("Content-Type", contentType);
772
+ res.sendFile(resolved);
773
+ }
774
+ catch (e) {
775
+ const err = e;
776
+ res
777
+ .status(err.statusCode || 500)
778
+ .send(errorPage("Error", e.message ?? "Error"));
779
+ }
780
+ });
781
+ return router;
782
+ }
783
+ /**
784
+ * Build a parent router serving every repo in the session under
785
+ * `/r/:repoId/...`. Each repo's child router is built lazily and cached.
786
+ */
787
+ export function createReposRouter(session) {
788
+ const cache = new WeakMap();
789
+ const parent = express.Router();
790
+ parent.use("/:repoId", (req, res, next) => {
791
+ const ctx = session.getRepo(req.params.repoId);
792
+ if (!ctx) {
793
+ // Friendly fallback: show the session page (lists available repos) so a
794
+ // stale bookmark or a removed repo doesn't dead-end on a bare error.
795
+ return res.status(404).send(renderSessionPage({
796
+ repos: session.listRepos(),
797
+ notice: `Repository "${req.params.repoId}" is not in this session.`,
798
+ canManage: isLoopbackAddress(req.socket.remoteAddress),
799
+ }));
800
+ }
801
+ let child = cache.get(ctx);
802
+ if (!child) {
803
+ child = buildRepoRouter(ctx, `/r/${ctx.id}`, session);
804
+ cache.set(ctx, child);
805
+ }
806
+ return child(req, res, next);
807
+ });
808
+ return parent;
809
+ }
810
+ //# sourceMappingURL=repo-router.js.map