import { randomBytes, randomUUID } from "node:crypto"; import { createServer, type IncomingMessage, type Server, type ServerResponse, } from "node:http"; import { ANCHOR_CONTEXT_LINES, HEARTBEAT_CHECK_INTERVAL_MS, HEARTBEAT_LOST_MS, REQUEST_BODY_MAX_BYTES, REVIEW_PORT, TOKEN_COOKIE, } from "./constants.js"; import { renderFindings } from "./render.js"; import type { BrowserResult, CollectedDiff, Finding, FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide, ReviewState, } from "./types.js"; export type ReviewServer = { id: string; url: string; result: Promise>; close(reason: CancelReason): void; }; type CancelReason = Extract["reason"]; type StartServerOptions = { diff: CollectedDiff; state: ReviewState; round: number; token?: string; timeoutMs?: number; refreshDiff?: () => Promise; onSubmit?: ( result: Extract, diff: CollectedDiff, ) => Promise | void; onHeartbeatLost?: () => void; }; type RouteContext = StartServerOptions & { token: string; diff: CollectedDiff; findings: FindingDraft[]; notes: string; finish(event: ServerEvent): void; }; type ServerEvent = Extract | "heartbeat"; type Route = { method: string; path: string; handle( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ): Promise | void; }; const REVIEW_CATEGORIES = new Set([ "bug", "style", "perf", "question", ]); const REVIEW_SEVERITIES = new Set(["high", "medium", "low"]); const REVIEW_SIDES = new Set(["additions", "deletions"]); const ROUTES: readonly Route[] = [ { method: "GET", path: "/api/review", handle: getReview }, { method: "POST", path: "/api/heartbeat", handle: heartbeat }, { method: "POST", path: "/api/cancel", handle: cancel }, { method: "POST", path: "/api/finding/validate", handle: validateFinding }, { method: "POST", path: "/api/submit", handle: submitReview }, { method: "POST", path: "/submit", handle: submitForm }, { method: "POST", path: "/cancel", handle: cancelForm }, { method: "POST", path: "/finding", handle: addFinding }, { method: "POST", path: "/finding/delete", handle: deleteFinding }, { method: "GET", path: "/search", handle: searchRoute }, ]; export async function startReviewServer( options: StartServerOptions, ): Promise { const token = options.token ?? randomBytes(32).toString("base64url"); const id = randomUUID(); let server: Server; let finished = false; let lastHeartbeatAt = Date.now(); let heartbeatWarned = false; let resolveResult!: ( result: Extract, ) => void; const result = new Promise>( (resolve) => { resolveResult = resolve; }, ); const finish = (event: ServerEvent) => { if (event === "heartbeat") { lastHeartbeatAt = Date.now(); heartbeatWarned = false; return; } if (finished) return; finished = true; clearInterval(heartbeatTimer); if (timeoutTimer) clearTimeout(timeoutTimer); server.close(); resolveResult(event); }; const ctx: RouteContext = { ...options, token, findings: [], notes: "", finish, }; const heartbeatTimer = setInterval(() => { if (heartbeatWarned || Date.now() - lastHeartbeatAt <= HEARTBEAT_LOST_MS) return; heartbeatWarned = true; options.onHeartbeatLost?.(); finish({ type: "cancel", reason: "browser" }); }, HEARTBEAT_CHECK_INTERVAL_MS); heartbeatTimer.unref(); const timeoutTimer = options.timeoutMs === undefined ? undefined : setTimeout( () => finish({ type: "cancel", reason: "timeout" }), options.timeoutMs, ); timeoutTimer?.unref(); server = createServer((req, res) => void dispatch(req, res, ctx)); try { await listen(server, REVIEW_PORT); } catch (err) { clearInterval(heartbeatTimer); if (timeoutTimer) clearTimeout(timeoutTimer); server.close(); throw err; } const address = server.address(); if (!address || typeof address === "string") throw new Error("Failed to bind review server"); return { id, url: `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`, result, close: (reason) => finish({ type: "cancel", reason }), }; } async function dispatch( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { try { const url = new URL(req.url ?? "/", "http://127.0.0.1"); if (req.method === "GET" && url.pathname === "/") return await serveIndex(res, ctx.token, url, ctx); if (!authorized(req, ctx.token)) return json(res, 401, { error: "unauthorized" }); const route = ROUTES.find( (candidate) => candidate.method === req.method && candidate.path === url.pathname, ); if (!route) return json(res, 404, { error: "not found" }); await route.handle(req, res, ctx); } catch (err) { const status = err instanceof HttpError ? err.status : 500; json(res, status, { error: errorMessage(err) }); } } async function getReview( _req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff(); json(res, 200, reviewPayload(ctx)); } function reviewPayload(ctx: RouteContext): ReviewPayload { return { round: ctx.round, source: ctx.diff.source, diffText: ctx.diff.diffText, files: ctx.diff.files, skippedFiles: ctx.diff.skippedFiles, carriedFindings: ctx.state.findings.filter( (finding) => finding.status === "open", ), }; } function heartbeat( _req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { ctx.finish("heartbeat"); json(res, 200, { ok: true }); } function cancel(_req: IncomingMessage, res: ServerResponse, ctx: RouteContext) { json(res, 200, { ok: true }); ctx.finish({ type: "cancel", reason: "browser" }); } async function validateFinding( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { const draft = await readJson(req, parseFindingDraft); json(res, 200, { ok: true, anchor: anchorForDraft(ctx.diff, draft) }); } async function submitReview( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff(); const body = await readJson<{ notes?: string; findings: FindingDraft[] }>( req, parseSubmitBody, ); const result: Extract = { type: "submit", notes: body.notes, findings: body.findings.map((draft) => findingFromDraft(ctx.round, ctx.diff, draft), ), }; await ctx.onSubmit?.(result, ctx.diff); json(res, 200, { ok: true }); } async function submitForm( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff(); const params = new URLSearchParams(await readBody(req)); const notes = (params.get("notes") ?? "").trim() || undefined; const result: Extract = { type: "submit", notes, findings: ctx.findings.map((draft) => findingFromDraft(ctx.round, ctx.diff, draft), ), }; await ctx.onSubmit?.(result, ctx.diff); ctx.findings.length = 0; ctx.notes = ""; html( res, 200, `

Review sent to Pi

${result.findings.length} finding${result.findings.length === 1 ? "" : "s"} submitted.

Continue reviewing or close this tab.

`, ); } async function cancelForm( _req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { ctx.finish({ type: "cancel", reason: "browser" }); html( res, 200, `

Review cancelled

You can close this tab and return to Pi.

`, ); } async function addFinding( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { const params = new URLSearchParams(await readBody(req)); const draft = parseFindingDraftFromForm(params); ctx.findings.push(draft); html(res, 200, renderFindings(ctx.findings)); } async function deleteFinding( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { const params = new URLSearchParams(await readBody(req)); const index = Number(params.get("index")); if (Number.isInteger(index) && index >= 0 && index < ctx.findings.length) { ctx.findings.splice(index, 1); } html(res, 200, renderFindings(ctx.findings)); } async function searchRoute( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ) { const url = new URL(req.url ?? "/", "http://127.0.0.1"); const query = url.searchParams.get("q") ?? ""; const { buildSearchIndex, searchCode } = await import("./search.js"); const index = buildSearchIndex(ctx.diff.diffText); const hits = searchCode(query, index); const { renderSearchResults } = await import("./render.js"); html(res, 200, renderSearchResults(query, hits)); } async function serveIndex( res: ServerResponse, token: string, url: URL, ctx: RouteContext, ) { if (url.searchParams.get("token") !== token) return json(res, 401, { error: "unauthorized" }); res.setHeader( "Set-Cookie", `${TOKEN_COOKIE}=${token}; SameSite=Strict; Path=/`, ); const { renderPage } = await import("./render.js"); const htmlBody = await renderPage({ diff: ctx.diff, round: ctx.round, findings: ctx.findings, notes: ctx.notes, carriedFindings: ctx.state.findings.filter((f) => f.status === "open"), }); html(res, 200, htmlBody); } function authorized(req: IncomingMessage, token: string) { return ( req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token) ); } function cookieAuthorized(req: IncomingMessage, token: string) { return (req.headers.cookie ?? "") .split(/;\s*/) .some((cookie) => cookie === `${TOKEN_COOKIE}=${token}`); } function json(res: ServerResponse, status: number, data: unknown) { if (res.writableEnded) return; res.statusCode = status; res.setHeader("Content-Type", "application/json; charset=utf-8"); res.end(JSON.stringify(data)); } function html(res: ServerResponse, status: number, body: string) { if (res.writableEnded) return; res.statusCode = status; res.setHeader("Content-Type", "text/html; charset=utf-8"); res.setHeader("Cache-Control", "no-store"); res.end(body); } async function readJson( req: IncomingMessage, parse: (value: unknown) => T, ): Promise { const body = await readBody(req); try { return parse(body ? JSON.parse(body) : {}); } catch (err) { if (err instanceof HttpError) throw err; throw new HttpError( 400, err instanceof SyntaxError ? "invalid JSON" : errorMessage(err), ); } } async function readBody(req: IncomingMessage) { let body = ""; for await (const chunk of req) { body += String(chunk); if (Buffer.byteLength(body, "utf8") > REQUEST_BODY_MAX_BYTES) throw new HttpError(413, "request body too large"); } return body; } function parseSubmitBody(value: unknown): { notes?: string; findings: FindingDraft[]; } { if (!isRecord(value)) throw new Error("request body must be an object"); const notes = optionalString(value.notes, "notes")?.trim(); const rawFindings = value.findings ?? []; if (!Array.isArray(rawFindings)) throw new Error("findings must be an array"); return { ...(notes && { notes }), findings: rawFindings.map(parseFindingDraft), }; } function parseFindingDraft(value: unknown): FindingDraft { if (!isRecord(value)) throw new Error("finding must be an object"); const startLine = positiveInteger(value.startLine, "startLine"); const endLine = positiveInteger(value.endLine, "endLine"); if (endLine < startLine) throw new Error("endLine must be >= startLine"); const comment = requiredString(value.comment, "comment").trim(); if (!comment) throw new Error("comment required"); const notes = optionalString(value.notes, "notes")?.trim(); const prevFile = optionalString(value.prevFile, "prevFile"); return { file: requiredString(value.file, "file"), ...(prevFile && { prevFile }), side: enumValue(value.side, REVIEW_SIDES, "side"), startLine, endLine, category: enumValue(value.category, REVIEW_CATEGORIES, "category"), severity: enumValue(value.severity, REVIEW_SEVERITIES, "severity"), comment, ...(notes && { notes }), }; } function parseFindingDraftFromForm(params: URLSearchParams): FindingDraft { const startLine = positiveInteger( Number(params.get("startLine")), "startLine", ); const endLine = positiveInteger(Number(params.get("endLine")), "endLine"); if (endLine < startLine) throw new Error("endLine must be >= startLine"); const comment = (params.get("comment") ?? "").trim(); if (!comment) throw new Error("comment required"); return { file: requiredString(params.get("file") ?? "", "file"), side: enumValue(params.get("side") ?? "", REVIEW_SIDES, "side"), startLine, endLine, category: enumValue( params.get("category") ?? "", REVIEW_CATEGORIES, "category", ), severity: enumValue( params.get("severity") ?? "", REVIEW_SEVERITIES, "severity", ), comment, }; } function findingFromDraft( round: number, diff: CollectedDiff, draft: FindingDraft, ): Finding { return { id: randomUUID(), round, file: draft.file, ...(draft.prevFile && { prevFile: draft.prevFile }), side: draft.side, startLine: draft.startLine, endLine: draft.endLine, category: draft.category, severity: draft.severity, comment: draft.comment, ...(draft.notes && { notes: draft.notes }), status: "open", anchor: anchorForDraft(diff, draft), }; } function anchorForDraft(diff: CollectedDiff, draft: FindingDraft) { const file = diff.diffIndex.get(draft.file); if (!file) throw new HttpError(400, `Unknown file: ${draft.file}`); const lines = draft.side === "additions" ? file.newLines : file.oldLines; return { before: nearby( lines, draft.startLine - ANCHOR_CONTEXT_LINES, draft.startLine - 1, ), selected: selectedLines(lines, draft), after: nearby( lines, draft.endLine + 1, draft.endLine + ANCHOR_CONTEXT_LINES, ), }; } function selectedLines(lines: Map, draft: FindingDraft) { const selected: string[] = []; for (let line = draft.startLine; line <= draft.endLine; line++) { const text = lines.get(line); if (text === undefined) throw new HttpError( 400, `Selected line is not in rendered diff context: ${draft.file}:${line}`, ); selected.push(text); } return selected.join("\n"); } function nearby(lines: Map, start: number, end: number) { const out: string[] = []; for (let line = start; line <= end; line++) { const text = lines.get(line); if (text !== undefined) out.push(text); } return out.join("\n"); } function requiredString(value: unknown, name: string) { if (typeof value !== "string") throw new Error(`${name} must be a string`); return value; } function optionalString(value: unknown, name: string) { if (value === undefined) return undefined; return requiredString(value, name); } function positiveInteger(value: unknown, name: string) { if (!Number.isInteger(value) || (value as number) < 1) throw new Error(`${name} must be a positive integer`); return value as number; } function enumValue( value: unknown, choices: ReadonlySet, name: string, ): T { if (typeof value === "string" && choices.has(value as T)) return value as T; throw new Error(`invalid ${name}`); } function isRecord(value: unknown): value is Record { return !!value && typeof value === "object" && !Array.isArray(value); } function listen(server: Server, preferredPort: number) { return new Promise((resolveListen, reject) => { const onError = (err: NodeJS.ErrnoException) => { server.off("error", onError); if (err.code !== "EADDRINUSE") return reject(err); server.listen(0, "127.0.0.1", () => resolveListen()); }; server.once("error", onError); server.listen(preferredPort, "127.0.0.1", () => { server.off("error", onError); resolveListen(); }); }); } function errorMessage(err: unknown) { return err instanceof Error ? err.message : String(err); } class HttpError extends Error { constructor( readonly status: number, message: string, ) { super(message); } }