@self-review/serve 2.0.4 → 2.1.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 (76) hide show
  1. package/README.md +297 -3
  2. package/dist/chunk-CDBNWCCT.js +71 -0
  3. package/dist/chunk-CDBNWCCT.js.map +1 -0
  4. package/dist/chunk-THN5XTYQ.js +151 -0
  5. package/dist/chunk-THN5XTYQ.js.map +1 -0
  6. package/dist/cli.js +2140 -489
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client/assets/{abnfDiagram-VCTEODGH-CRvWpEsk.js → abnfDiagram-VCTEODGH-Dxm_OGm7.js} +1 -1
  9. package/dist/client/assets/{arc-PsXBAWZS.js → arc-BkF-Cs_1.js} +1 -1
  10. package/dist/client/assets/{architectureDiagram-5GKGNRK7-C3DgmaC3.js → architectureDiagram-5GKGNRK7-zB4eyVpl.js} +1 -1
  11. package/dist/client/assets/{blockDiagram-I7D4REHJ-BUrTsHao.js → blockDiagram-I7D4REHJ-cinsJzJ1.js} +1 -1
  12. package/dist/client/assets/{c4Diagram-7LVT6UL2-CpZNs6lz.js → c4Diagram-7LVT6UL2-D4TGkD91.js} +1 -1
  13. package/dist/client/assets/channel-BsuWTbtj.js +1 -0
  14. package/dist/client/assets/{chunk-2Q5K7J3B-BcKcR0LE.js → chunk-2Q5K7J3B-C8HjvUMv.js} +1 -1
  15. package/dist/client/assets/{chunk-5VM5RSS4-C7oHjssV.js → chunk-5VM5RSS4-45fUpmT8.js} +1 -1
  16. package/dist/client/assets/{chunk-F27PBJKO-BlPczT9-.js → chunk-F27PBJKO-DObAqHRK.js} +1 -1
  17. package/dist/client/assets/{chunk-IMKFNOWR-JWhBhxWO.js → chunk-IMKFNOWR-DPvCBgjP.js} +1 -1
  18. package/dist/client/assets/{chunk-JWPE2WC7-BHqPUvha.js → chunk-JWPE2WC7-D3HxOmIl.js} +1 -1
  19. package/dist/client/assets/{chunk-POPQ4Y6H-F7oDRNF5.js → chunk-POPQ4Y6H-CeetmS6D.js} +1 -1
  20. package/dist/client/assets/{chunk-SVP7TREG-BXZpN96Q.js → chunk-SVP7TREG-BltjJmw4.js} +1 -1
  21. package/dist/client/assets/{chunk-TICWLB2K-DNvFXi10.js → chunk-TICWLB2K-CRp0Zdpy.js} +1 -1
  22. package/dist/client/assets/{chunk-XXDRQBXY-DOvXkBHK.js → chunk-XXDRQBXY-BhqJXAOb.js} +1 -1
  23. package/dist/client/assets/classDiagram-ZZMXUADV-CJ7wz9Pi.js +1 -0
  24. package/dist/client/assets/classDiagram-v2-VYDZK3BY-CJ7wz9Pi.js +1 -0
  25. package/dist/client/assets/{cose-bilkent-JH36ORCC-DPJK_EQL.js → cose-bilkent-JH36ORCC-D29IHBME.js} +1 -1
  26. package/dist/client/assets/{cynefin-OW5HDTMX-JBAmnTQp.js → cynefin-OW5HDTMX-DbO7Hdnr.js} +1 -1
  27. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-CsYygsrr.js → cynefinDiagram-5FMLGOSQ-AmW3TeXb.js} +1 -1
  28. package/dist/client/assets/{dagre-GXQ25YYZ-Dbz4M33p.js → dagre-GXQ25YYZ-BIyWjaCd.js} +1 -1
  29. package/dist/client/assets/{diagram-S7CK7UJ4-Biv-Q_jb.js → diagram-S7CK7UJ4-CBHWhWpQ.js} +1 -1
  30. package/dist/client/assets/{diagram-UQ7AKVKN-JRvoicym.js → diagram-UQ7AKVKN-DRTCWqRa.js} +1 -1
  31. package/dist/client/assets/{diagram-VSXAHHWV-VAXOLPk0.js → diagram-VSXAHHWV-GE0ZO13U.js} +1 -1
  32. package/dist/client/assets/{diagram-VX7I27RA-DRmE-ol9.js → diagram-VX7I27RA-BBp26skq.js} +1 -1
  33. package/dist/client/assets/{diagram-Z3DM3KII-CavqQl_8.js → diagram-Z3DM3KII-CSUSeDRk.js} +1 -1
  34. package/dist/client/assets/{ebnfDiagram-PWID7BFC-70cdWXxf.js → ebnfDiagram-PWID7BFC-2RgBVavT.js} +1 -1
  35. package/dist/client/assets/{erDiagram-RLTQ6QDP-Ha04LW0x.js → erDiagram-RLTQ6QDP-DoEVHzNL.js} +1 -1
  36. package/dist/client/assets/{flowDiagram-HODETNUW-BRLi1S7q.js → flowDiagram-HODETNUW-BLeHpICc.js} +1 -1
  37. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-BfBVCQ3A.js → ganttDiagram-EL5Y4UJY-BE4gCIyJ.js} +1 -1
  38. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-D-GiQOxC.js → gitGraphDiagram-WWUBYQGX-BuuJ4_PE.js} +1 -1
  39. package/dist/client/assets/index-D1YcCF2h.css +1 -0
  40. package/dist/client/assets/{index-vUb9LsiF.js → index-P5EmeykP.js} +247 -220
  41. package/dist/client/assets/{infoDiagram-27XIBGKW-KEMBoX9p.js → infoDiagram-27XIBGKW-Dj6SJlyc.js} +1 -1
  42. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-CBS0T3w-.js → ishikawaDiagram-5VMMS53U-BVxSH4Dd.js} +1 -1
  43. package/dist/client/assets/{journeyDiagram-3NMN7TZE-AN4puIAJ.js → journeyDiagram-3NMN7TZE-BQIb4zis.js} +1 -1
  44. package/dist/client/assets/{kanban-definition-UXKFOSKX-BWQivApD.js → kanban-definition-UXKFOSKX-zswZjsPL.js} +1 -1
  45. package/dist/client/assets/{layout-B7etliRi.js → layout-i9tH82X4.js} +1 -1
  46. package/dist/client/assets/{linear-DYVJ9r-o.js → linear-CGCu0_8r.js} +1 -1
  47. package/dist/client/assets/{mermaid.core-B9m3791z.js → mermaid.core-DGOIMnVG.js} +5 -5
  48. package/dist/client/assets/{mindmap-definition-YA3MSWOX-BwhaRhOg.js → mindmap-definition-YA3MSWOX-DXzfof8m.js} +1 -1
  49. package/dist/client/assets/{pegDiagram-XKGWAZYB-B6zVpKjE.js → pegDiagram-XKGWAZYB-CmhgC38j.js} +1 -1
  50. package/dist/client/assets/{pieDiagram-E7YTZNPT-DGmD4H1L.js → pieDiagram-E7YTZNPT-iiATrVql.js} +1 -1
  51. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-CrKpGbBm.js → quadrantDiagram-AXDQQJYC-eENXXuDO.js} +1 -1
  52. package/dist/client/assets/{railroadDiagram-O6MQD6OU-DLcnTQsv.js → railroadDiagram-O6MQD6OU-Ve9DVyyu.js} +1 -1
  53. package/dist/client/assets/{requirementDiagram-BXWQKSXE-bqG-UOfq.js → requirementDiagram-BXWQKSXE-Ds3SiU76.js} +1 -1
  54. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DGRQqw-s.js → sankeyDiagram-P5KCCOFB-Ca_9nHzQ.js} +1 -1
  55. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-CW-ivDp5.js → sequenceDiagram-WJ2MYXX4-YB9gvQgl.js} +1 -1
  56. package/dist/client/assets/{sizeCapture-INFHLROL-BbHjPnUF.js → sizeCapture-INFHLROL-CNrWHUe0.js} +1 -1
  57. package/dist/client/assets/{stateDiagram-D77RDMKH-BproWKBe.js → stateDiagram-D77RDMKH-MSnDTD49.js} +1 -1
  58. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-BqISu6Sp.js +1 -0
  59. package/dist/client/assets/{swimlanes-42K2YHIH-OG2jZQn8.js → swimlanes-42K2YHIH-DA1GpdIB.js} +1 -1
  60. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DSERx6Gl.js +8 -0
  61. package/dist/client/assets/{timeline-definition-24CTP7MA-DQeIsWHU.js → timeline-definition-24CTP7MA-CKkqwVz6.js} +1 -1
  62. package/dist/client/assets/{vennDiagram-4TSXK5OY-CzLpoCxP.js → vennDiagram-4TSXK5OY-Bu9SbqJ4.js} +1 -1
  63. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-Bga8iF2e.js → wardleyDiagram-VM6X3IG4-DCUikUwQ.js} +1 -1
  64. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-BMPq9UWm.js → xychartDiagram-S5SC5T6Z-DS3iQdcW.js} +1 -1
  65. package/dist/client/index.html +2 -2
  66. package/dist/json-body-worker.js +16 -0
  67. package/dist/json-body-worker.js.map +1 -0
  68. package/dist/resume-parser-worker.js +30 -0
  69. package/dist/resume-parser-worker.js.map +1 -0
  70. package/package.json +4 -3
  71. package/dist/client/assets/channel-mzvzhynH.js +0 -1
  72. package/dist/client/assets/classDiagram-ZZMXUADV-BAE1ijM-.js +0 -1
  73. package/dist/client/assets/classDiagram-v2-VYDZK3BY-BAE1ijM-.js +0 -1
  74. package/dist/client/assets/index-hcoT-WH0.css +0 -1
  75. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Ck8yo6ic.js +0 -1
  76. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-CgYw65ZN.js +0 -8
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/args.ts","../src/startup.ts","../src/lifecycle.ts","../src/server.ts","../src/validate.ts","../src/capability.ts","../src/protocol.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// The serve-mode entry point: resolve one review session, serve it on a\n// port, and stop when the review is complete.\n//\n// Composition only — argument parsing is ./args, session resolution is\n// ./startup, the routes are ./server and the completion is ./lifecycle. The\n// order below is the load-bearing part: the session is fully resolved, and\n// the completion hook attached, before the listener opens, so no request can\n// reach a half-built session and no submission can arrive unobserved.\n\nimport { createRequire } from 'node:module';\nimport { parseServeArgs } from './args';\nimport { resolveSession } from './startup';\nimport { completeReviewOnSubmit } from './lifecycle';\nimport { createReviewServer, listenLoopback } from './server';\nimport { generateCapability } from './capability';\nimport { formatLaunchUrl } from './protocol';\n\nconst HELP = `\nself-review-serve - Serve the self-review interface over HTTP\n\nUsage: self-review-serve [options] [<git-diff-args>...]\n\nOptions:\n -o, --output <file> Write the review to <file> (default: ./review.xml, or\n output-file from .self-review.yaml)\n --resume-from <file> Load a previous review XML file\n -h, --help Show this help message\n -v, --version Show version number\n\nAll other arguments are passed to git diff. With none, the unstaged working\ntree changes are reviewed. Outside a git repository, pass a directory or file.\n\nExamples:\n self-review-serve # unstaged changes\n self-review-serve --staged\n self-review-serve main..feature-branch\n self-review-serve --resume-from review.xml # resume a previous review\n\nThe URL is printed to stderr on start. Open exactly that URL: the part after\n'#' is this session's key, drawn fresh each start, and the browser keeps it\nout of the address bar once the page has loaded. A reloaded or retyped\naddress has no key and the page says so; if the URL is lost, stop this\nprocess and start it again. Over ssh, forward the port (ssh -L) and open the\nsame URL against the forwarded port, keeping the '#' part.\n\nThe output path is fixed by the arguments above and cannot be changed from\nthe browser. Completing the review writes that file and stops this process.\nNothing is saved before then, and closing the tab once you have written a\ncomment warns you first. If the file cannot be written, the browser says why\nand keeps the review; fix the problem and press Finish Review again.\n\nThe listener binds to 127.0.0.1, refuses any request that names another host\nor origin so a web page cannot reach it, and refuses any API request without\nthe key, so another account on the same host cannot either.\n`.trim();\n\nfunction printVersion(): void {\n try {\n // Read at runtime rather than imported, so the version is the installed\n // package's own. dist/cli.js sits one directory below package.json in\n // both the workspace and an installed tarball.\n const requireFromHere = createRequire(import.meta.url);\n const pkg = requireFromHere('../package.json') as { version: string };\n console.error(`self-review-serve v${pkg.version}`);\n } catch {\n console.error('self-review-serve (version unknown)');\n }\n}\n\nasync function main(): Promise<void> {\n const args = parseServeArgs(process.argv.slice(2));\n if (args.help) {\n console.error(HELP);\n return;\n }\n if (args.version) {\n printVersion();\n return;\n }\n\n const { session, output } = await resolveSession(args);\n\n // Leaves only in the printed URL's fragment; the server never sends it.\n const capability = generateCapability();\n const server = createReviewServer({ session, output, capability });\n completeReviewOnSubmit({ server });\n\n const { url } = await listenLoopback(server);\n console.error(`[serve] Review ready at ${formatLaunchUrl(url, capability)}`);\n console.error(`[serve] Completing the review writes ${output.path} and stops this process.`);\n console.error(\n '[serve] The listener is loopback-only. The part of the URL after # is this ' +\n \"session's key: open the URL exactly as printed, and do not share it.\"\n );\n}\n\nmain().catch(error => {\n console.error(`[serve] ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n});\n","// Mirrors src/main/cli.ts over core's extractor; the flag table is in packages/core/src/startup.ts.\n\nimport { extractApplicationOptions } from '@self-review/core';\n\nexport interface ServeArgs {\n /** Arguments passed through to `git diff`, in the order given. */\n gitDiffArgs: string[];\n /**\n * Output path exactly as typed, unresolved. `null` means the caller said\n * nothing and the configured `output-file` decides.\n */\n outputPath: string | null;\n /** Path of a prior review XML to resume from, as typed. `null` when unset. */\n resumeFrom: string | null;\n help: boolean;\n version: boolean;\n}\n\nconst VALUE_FLAGS = {\n '--output': 'outputPath',\n '-o': 'outputPath',\n '--resume-from': 'resumeFrom',\n} as const;\n\nconst BOOLEAN_FLAGS = {\n '--help': 'help',\n '-h': 'help',\n '--version': 'version',\n '-v': 'version',\n} as const;\n\n// Throws ApplicationOptionError on a value flag with no or an empty value: `--output=` would otherwise\n// resolve to the working directory and fail with EISDIR only at submit.\nexport function parseServeArgs(argv: string[]): ServeArgs {\n const { values, flags, rest } = extractApplicationOptions(argv, {\n valueFlags: VALUE_FLAGS,\n booleanFlags: BOOLEAN_FLAGS,\n });\n return {\n gitDiffArgs: rest,\n outputPath: values.outputPath,\n resumeFrom: values.resumeFrom,\n help: flags.help,\n version: flags.version,\n };\n}\n","// Resolve one review session the way the desktop does. Each phase below cites\n// the phase of `initializeApp` (src/main/main.ts) it mirrors; the shared decisions are core's startup module.\n//\n// Two orderings are load-bearing: everything resolves before the caller opens\n// the listener, so no request races a half-built session; and the guide lands\n// on the session during startup, since `GET /api/diff` answers from there.\n//\n// The desktop's large-payload prompt and directory picker are native dialogs\n// with no browser equivalent, so the first becomes automatic and the second\n// becomes a startup error.\n\nimport { resolve } from 'node:path';\nimport {\n commitDiffData,\n computePayloadStats,\n countTotalLines,\n createReviewSession,\n inspectOutputPath,\n loadConfigWithProvenance,\n loadGuide,\n loadLocalReview,\n loadResumeDocument,\n publishOptionsFor,\n resolveOutputTarget,\n resolveStartupDiffArgs,\n resolveStartupSource,\n} from '@self-review/core';\nimport type { ReviewOutputTarget, ReviewSession } from '@self-review/core';\nimport type { ServeArgs } from './args';\n\nexport interface ServeStartup {\n /** Carries the source identity every path-taking route authorizes against (audit A6). */\n session: ReviewSession;\n /** Fixed for the process lifetime. */\n output: ReviewOutputTarget;\n}\n\nconst log = (message: string) => console.error(`[serve] ${message}`);\n\n/** Throws when startup cannot produce a servable session; the caller reports and exits. */\nexport async function resolveSession(args: ServeArgs): Promise<ServeStartup> {\n // Phase 2 (main.ts): configuration and the output path.\n const cwd = process.cwd();\n const loadedConfig = loadConfigWithProvenance({ cwd });\n const output = resolveOutputTarget(args.outputPath, loadedConfig, cwd);\n // Advisory (the publisher re-checks at submit), but refusing an output that can never be written beats serving a review with no way out.\n const problem = inspectOutputPath(output.path, publishOptionsFor(output));\n if (problem) {\n throw new Error(\n `Output path is not writable (${problem.code}): ${problem.message} ` +\n 'Pass a writable path with --output, or set output-file in .self-review.yaml.'\n );\n }\n log(`Output path: ${output.path} (${output.origin})`);\n\n // Phase 3 (main.ts): git diff arguments.\n const { gitDiffArgs, config } = resolveStartupDiffArgs(args.gitDiffArgs, loadedConfig, cwd);\n\n // Phase 4 (main.ts): what to review. Welcome mode is refused: a browser has no directory picker.\n const source = resolveStartupSource(gitDiffArgs, cwd);\n log(`Startup mode: ${source.mode}`);\n if (source.mode === 'welcome') {\n throw new Error(\n 'Nothing to review: this is not a git repository and no path was given. ' +\n 'Run self-review-serve inside a git repository, or pass a directory or file to review.'\n );\n }\n const { payload: diffData, identity } = await loadLocalReview(\n source,\n gitDiffArgs,\n config,\n cwd,\n log\n );\n log(`Loaded ${diffData.files.length} files`);\n\n // Phase 4b (main.ts): large payload. Nobody to ask before the browser connects, so lazy loading just turns on.\n const stats = computePayloadStats(diffData.files.length, countTotalLines(diffData.files), config);\n if (stats.exceedsAny) {\n log(\n `Large payload: ${stats.fileCount} files, ${stats.totalLines} lines ` +\n `(thresholds ${config.maxFiles} files, ${config.maxTotalLines} lines) — ` +\n 'serving file contents on demand'\n );\n diffData.isLargePayload = true;\n }\n\n // Phase 5 (main.ts): resume.\n const session = createReviewSession();\n if (args.resumeFrom) {\n const resumePath = resolve(cwd, args.resumeFrom);\n try {\n loadResumeDocument(session, resumePath);\n } catch (error) {\n throw new Error(\n `Could not read the resume file ${resumePath}: ` +\n (error instanceof Error ? error.message : String(error))\n );\n }\n log(\n `Resumed ${session.resumeComments.length} comments and ` +\n `${session.resumeViewedFiles.length} viewed files from ${resumePath}`\n );\n for (const diagnostic of session.resumeImportDiagnostics) {\n log(`Resume import: ${diagnostic}`);\n }\n }\n\n // Phase 5b (main.ts): guide sidecar. It must be on the session before listening; GET /api/diff answers from there.\n const guideData = await loadGuide(\n output.path,\n config,\n diffData.files.map(f => f.newPath || f.oldPath)\n );\n if (guideData) {\n log(`Walkthrough guide loaded: ${guideData.groups.length} groups`);\n }\n\n // Phase 6 (main.ts) — assemble. Everything the routes read is on the\n // session before the caller opens the listener.\n // commitDiffData captures the reviewed paths that authorize every apply, and the source identity.\n commitDiffData(session, diffData, identity);\n session.guideData = guideData;\n session.config = config;\n session.outputPathInfo = { resolvedOutputPath: output.path, outputPathWritable: true };\n\n return { session, output };\n}\n","// A published review stops the process; nothing else does. `POST /api/review` (./server.ts) publishes before it answers, so a flushed 200 means the file is on disk.\n\nimport type * as http from 'node:http';\n\nexport interface CompletionOptions {\n server: http.Server;\n /** Injected so a test can observe the exit code. Defaults to `process.exit`. */\n exit?: (code: number) => void;\n}\n\n/**\n * Closes open connections too, or a browser's idle keep-alive socket holds the\n * port after the process is done with it.\n */\nfunction shutdown(server: http.Server, exit: (code: number) => void, code: number): void {\n server.closeAllConnections();\n server.close();\n exit(code);\n}\n\n/**\n * The hook is the response, not the route: `finish` fires once the response is\n * flushed, so the browser has its answer before the socket goes away. Only a\n * 200 is a completion.\n */\nexport function completeReviewOnSubmit(options: CompletionOptions): void {\n const { server, exit = process.exit } = options;\n let completing = false;\n\n server.on('request', (req, res) => {\n if (req.method !== 'POST' || pathnameOf(req.url) !== '/api/review') {\n return;\n }\n res.on('finish', () => {\n if (res.statusCode !== 200 || completing) {\n return;\n }\n completing = true;\n console.error('[serve] Review complete; stopping.');\n shutdown(server, exit, 0);\n });\n });\n}\n\nfunction pathnameOf(url: string | undefined): string | null {\n try {\n return new URL(url ?? '/', 'http://localhost').pathname;\n } catch {\n return null;\n }\n}\n","// Nine JSON routes over one ReviewSession, each a thin wrapper over a function\n// core already exports, plus static serving for the client bundle. node:http,\n// no framework.\n//\n// Three properties are load-bearing: every route validates before core runs; the listener both binds\n// to loopback and refuses requests that name anything else (a web page can reach loopback, and DNS\n// rebinding would make it same-origin); and every API route requires the session capability (see ./protocol.ts).\n// `POST /api/review` publishes before it answers.\n\nimport * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AddressInfo } from 'node:net';\nimport {\n authorizeReviewedPath,\n getDiffLoad,\n getConfigLoad,\n getResumeLoad,\n getFileHunks,\n loadImage,\n parseAttachmentReference,\n readAttachment,\n expandContext,\n submitReviewState,\n applySuggestionForSession,\n publishOptionsFor,\n publishReview,\n ReviewPublishError,\n} from '@self-review/core';\nimport type {\n ReviewOutputTarget as CoreReviewOutputTarget,\n ReviewPublishErrorCode,\n ReviewSession,\n ReviewState,\n} from '@self-review/core';\nimport {\n containPath,\n parseExpandContextBody,\n parseReviewStateBody,\n parseSuggestionApplyBody,\n} from './validate';\nimport { capabilityMatches } from './capability';\nimport { CAPABILITY_SCHEME, MAX_REVIEW_BODY_BYTES } from './protocol';\nimport type { ReviewSubmitAck, ReviewSubmitFailure } from './protocol';\n\nexport { MAX_REVIEW_BODY_BYTES } from './protocol';\n\n// Resolved on demand: `import.meta.url` is not a `file:` URL under the client suite's browser-like environment.\nexport function defaultClientDir(): string {\n return fileURLToPath(new URL('./client/', import.meta.url));\n}\n\n/** Upper bound on a `POST /api/expand-context` body: a path and an integer. */\nexport const MAX_EXPAND_CONTEXT_BODY_BYTES = 64 * 1024;\n\nexport type ReviewOutputTarget = CoreReviewOutputTarget;\n\nexport interface ReviewServerOptions {\n /** Every request-supplied diff path is authorized against this session's source identity by core (audit A6). */\n session: ReviewSession;\n output: ReviewOutputTarget;\n /** Bearer token every `/api/` request must present; the server never sends it. */\n capability: string;\n /** Directory of the client bundle. Defaults to `defaultClientDir()`; tests inject a fixture. */\n clientDir?: string;\n}\n\ninterface RouteContext {\n req: http.IncomingMessage;\n res: http.ServerResponse;\n url: URL;\n session: ReviewSession;\n output: ReviewOutputTarget;\n}\n\ntype RouteHandler = (ctx: RouteContext) => Promise<void>;\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.txt': 'text/plain; charset=utf-8',\n};\n\n/**\n * The page renders the diff under review, which is the least trusted input the\n * program handles. Rendered content is sanitized before it becomes elements;\n * this is the second line, for whatever gets past that.\n *\n * Inline styles are allowed because index.html carries a <style> block and\n * bundled libraries inject at runtime; blob: because attachments display\n * through createObjectURL.\n */\nconst CSP = [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob:\",\n \"font-src 'self' data:\",\n \"connect-src 'self'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"object-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"frame-ancestors 'none'\",\n].join('; ');\n\nconst SECURITY_HEADERS: http.OutgoingHttpHeaders = {\n 'content-security-policy': CSP,\n 'x-content-type-options': 'nosniff',\n 'x-frame-options': 'DENY',\n 'referrer-policy': 'no-referrer',\n};\n\n/** A browser may resolve the printed URL either way, or prefer IPv6. */\nconst LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(['127.0.0.1', 'localhost', '[::1]']);\n\n/** Lowercased, with an explicit `:80` dropped so it matches the bare host. */\nfunction normalizeHost(value: string): string {\n const lowered = value.toLowerCase();\n return lowered.endsWith(':80') ? lowered.slice(0, -3) : lowered;\n}\n\n/**\n * A rebound request — an attacker's name re-resolved to 127.0.0.1 after the\n * page loads — still carries that name in `Host`, which is what distinguishes\n * it from a real one.\n *\n * The port is deliberately not compared against the bound port: an `ssh -L`\n * forward arrives carrying the forward's port, and refusing that would break\n * the use case this package exists for. It would buy nothing either, since a\n * rebound request fails on the hostname first.\n *\n * A duplicate `Host` is refused, not resolved: Node reads the first, and an\n * intermediary forwarding the last would be reading a different request.\n */\nfunction hostIsLoopback(req: http.IncomingMessage): boolean {\n const host = req.headers.host;\n if (host === undefined) return false;\n\n let seen = 0;\n for (let i = 0; i < req.rawHeaders.length; i += 2) {\n if (req.rawHeaders[i].toLowerCase() === 'host') seen++;\n }\n if (seen !== 1) return false;\n\n // Split the optional port off, keeping an IPv6 literal's brackets.\n const match = /^(\\[[^\\]]*\\]|[^:]*)(?::(\\d+))?$/.exec(host);\n if (match === null) return false;\n return LOOPBACK_HOSTNAMES.has(match[1].toLowerCase());\n}\n\n/**\n * A missing `Origin` is allowed — navigations and curl send none. Rejected is\n * an `Origin` naming a different authority than `Host`, including the `null` a\n * sandboxed frame sends.\n *\n * Comparing against `Host` rather than a loopback allowlist is what survives a\n * port forward while still refusing another local page: a dev server on :3000\n * sends its own origin and this listener's host, and those differ.\n */\nfunction originMatchesHost(req: http.IncomingMessage): boolean {\n const origin = req.headers.origin;\n if (origin === undefined) return true;\n const host = req.headers.host;\n if (host === undefined) return false;\n let parsed: URL;\n try {\n parsed = new URL(origin);\n } catch {\n return false;\n }\n if (parsed.protocol !== 'http:') return false;\n // `new URL` parses away userinfo, paths and leading-zero ports, any of which\n // would compare equal to this authority. A browser sends none of them.\n if (origin !== `${parsed.protocol}//${parsed.host}`) return false;\n return normalizeHost(parsed.host) === normalizeHost(host);\n}\n\n/**\n * Set by the browser, unforgeable by page script. A cross-site *GET* — an <img>\n * aimed at this port — carries no `Origin`, so without this it would be served\n * and only the absence of CORS headers would stop the page reading it.\n *\n * Non-browser clients send no such header and are unaffected.\n */\nfunction fetchSiteIsSelf(req: http.IncomingMessage): boolean {\n const site = req.headers['sec-fetch-site'];\n if (site === undefined) return true;\n return site === 'same-origin' || site === 'none';\n}\n\nfunction sendJson(\n res: http.ServerResponse,\n status: number,\n value: unknown,\n headers: http.OutgoingHttpHeaders = {}\n): void {\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...SECURITY_HEADERS,\n ...headers,\n });\n // `JSON.stringify(undefined)` is undefined; a void core result becomes `null`.\n res.end(JSON.stringify(value ?? null));\n}\n\nfunction sendError(res: http.ServerResponse, status: number, error: string): void {\n // A body that blew the cap is not read further; close the connection rather\n // than let the rest of it be reinterpreted as a next request.\n sendJson(res, status, { error }, status === 413 ? { connection: 'close' } : {});\n}\n\n// Header only: a token in the query string would land in history and logs.\nfunction presentsCapability(req: http.IncomingMessage, capability: string): boolean {\n const header = req.headers.authorization;\n if (header === undefined) return false;\n const space = header.indexOf(' ');\n if (space === -1) return false;\n if (header.slice(0, space).toLowerCase() !== CAPABILITY_SCHEME.toLowerCase()) return false;\n return capabilityMatches(capability, header.slice(space + 1).trim());\n}\n\nfunction sendUnauthorized(res: http.ServerResponse): void {\n sendJson(res, 401, { error: 'unauthorized' }, { 'www-authenticate': CAPABILITY_SCHEME });\n}\n\nconst REVIEWED_PATH_ERROR = 'path must name a file in the reviewed diff';\n\n/** Core's authorization; answers 400 and returns false when `filePath` is not a reviewed path. */\nfunction requireReviewedPath(ctx: RouteContext, filePath: string, what = 'path'): boolean {\n if (authorizeReviewedPath(ctx.session, filePath).ok) return true;\n sendError(\n ctx.res,\n 400,\n what === 'path' ? REVIEWED_PATH_ERROR : `${what} must name a file in the reviewed diff`\n );\n return false;\n}\n\nfunction requireReviewedQueryPath(ctx: RouteContext): string | null {\n const raw = ctx.url.searchParams.get('path');\n if (raw === null) {\n sendError(ctx.res, 400, REVIEWED_PATH_ERROR);\n return null;\n }\n return requireReviewedPath(ctx, raw) ? raw : null;\n}\n\ntype BodyResult = { ok: true; value: unknown } | { ok: false; status: number; error: string };\n\n/**\n * The declared length is checked before a byte is read and the running total\n * during it, so a chunked body without a length is capped too.\n */\nfunction readJsonBody(req: http.IncomingMessage, maxBytes: number): Promise<BodyResult> {\n const contentType = req.headers['content-type'] ?? '';\n if (!contentType.toLowerCase().startsWith('application/json')) {\n return Promise.resolve({\n ok: false,\n status: 415,\n error: 'content-type must be application/json',\n });\n }\n const declared = Number(req.headers['content-length']);\n if (Number.isFinite(declared) && declared > maxBytes) {\n return Promise.resolve({ ok: false, status: 413, error: 'request body too large' });\n }\n\n return new Promise(resolve => {\n const chunks: Buffer[] = [];\n let received = 0;\n req.on('data', (chunk: Buffer) => {\n received += chunk.length;\n if (received > maxBytes) {\n chunks.length = 0;\n req.removeAllListeners('data');\n req.removeAllListeners('end');\n resolve({ ok: false, status: 413, error: 'request body too large' });\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n try {\n resolve({ ok: true, value: JSON.parse(Buffer.concat(chunks).toString('utf-8')) });\n } catch {\n resolve({ ok: false, status: 400, error: 'body must be valid JSON' });\n }\n });\n req.on('error', () => {\n resolve({ ok: false, status: 400, error: 'request body could not be read' });\n });\n });\n}\n\n// Each route validates, calls exactly one core function, and sends its result.\n\nconst routes: Record<string, RouteHandler> = {\n 'GET /api/diff': async ({ res, session }) => {\n // The guide rides with the diff, so the client needs no push channel.\n sendJson(res, 200, getDiffLoad(session));\n },\n\n 'GET /api/config': async ({ res, session }) => {\n sendJson(res, 200, getConfigLoad(session));\n },\n\n 'GET /api/resume': async ({ res, session }) => {\n sendJson(res, 200, getResumeLoad(session));\n },\n\n 'GET /api/file': async ctx => {\n const filePath = requireReviewedQueryPath(ctx);\n if (filePath === null) return;\n // Diff paths are source-relative strings; core matches on them as sent.\n sendJson(ctx.res, 200, getFileHunks(ctx.session, filePath));\n },\n\n 'GET /api/image': async ctx => {\n const filePath = requireReviewedQueryPath(ctx);\n if (filePath === null) return;\n // Core reads the reviewed snapshot under the same identity it just authorized.\n sendJson(ctx.res, 200, await loadImage(ctx.session, filePath));\n },\n\n 'GET /api/attachment': async ctx => {\n // Not a diff path: a `.self-review-assets/<name>` reference core resolves itself; only its shape is checked here.\n const raw = ctx.url.searchParams.get('path');\n if (raw === null || parseAttachmentReference(raw) === null) {\n sendError(ctx.res, 400, 'path must name a file in the .self-review-assets directory');\n return;\n }\n const result = await readAttachment(ctx.session, raw);\n if (!result.ok) {\n const status =\n result.reason === 'not-authorized' ? 400 : result.reason === 'too-large' ? 413 : 404;\n sendError(ctx.res, status, status === 404 ? 'attachment not found' : result.message);\n return;\n }\n const { res } = ctx;\n res.writeHead(200, {\n 'content-type': 'application/octet-stream',\n 'cache-control': 'no-store',\n ...SECURITY_HEADERS,\n });\n res.end(Buffer.from(result.data));\n },\n\n 'POST /api/expand-context': async ctx => {\n const { req, res, session } = ctx;\n const body = await readJsonBody(req, MAX_EXPAND_CONTEXT_BODY_BYTES);\n if (!body.ok) {\n sendError(res, body.status, body.error);\n return;\n }\n const parsed = parseExpandContextBody(body.value);\n if (!parsed.ok) {\n sendError(res, 400, parsed.error);\n return;\n }\n // Becomes a git pathspec; authorized as a reviewed path, then passed through as sent.\n if (!requireReviewedPath(ctx, parsed.value.filePath, 'filePath')) return;\n sendJson(res, 200, await expandContext(session, parsed.value));\n },\n\n // The one route that rewrites a file in the reviewed tree. Core refuses unless the anchored lines still\n // match the suggestion's recorded original byte for byte, and resolves the destination itself.\n 'POST /api/apply-suggestion': async ctx => {\n const { req, res, session } = ctx;\n const body = await readJsonBody(req, MAX_EXPAND_CONTEXT_BODY_BYTES);\n if (!body.ok) {\n sendError(res, body.status, body.error);\n return;\n }\n const parsed = parseSuggestionApplyBody(body.value);\n if (!parsed.ok) {\n sendError(res, 400, parsed.error);\n return;\n }\n if (!requireReviewedPath(ctx, parsed.value.filePath, 'filePath')) return;\n sendJson(res, 200, applySuggestionForSession(session, parsed.value));\n },\n\n // The completion: a 200 means the file is on disk; a failure leaves the server up for a retry.\n 'POST /api/review': async ({ req, res, session, output }) => {\n const body = await readJsonBody(req, MAX_REVIEW_BODY_BYTES);\n if (!body.ok) {\n sendError(res, body.status, body.error);\n return;\n }\n const parsed = parseReviewStateBody(body.value);\n if (!parsed.ok) {\n sendError(res, 400, parsed.error);\n return;\n }\n submitReviewState(session, parsed.value);\n const outcome = await publishSubmittedReview(parsed.value, output, session);\n if (outcome.ok) {\n sendJson(res, 200, outcome);\n } else {\n sendJson(res, publishFailureStatus(outcome.code), outcome);\n }\n },\n};\n\n// Publisher failures are returned, not thrown, so the route answers and keeps serving.\nasync function publishSubmittedReview(\n state: ReviewState,\n output: ReviewOutputTarget,\n session: ReviewSession\n): Promise<ReviewSubmitAck | ReviewSubmitFailure> {\n const options = publishOptionsFor(output, session.attachmentOrigins);\n try {\n const { outputPath } = await publishReview(state, output.path, options);\n console.error(`[serve] Review written to ${outputPath}`);\n return { ok: true, outputPath };\n } catch (error) {\n if (!(error instanceof ReviewPublishError)) throw error;\n console.error(`[serve] Review not saved (${error.code}): ${error.message}`);\n for (const detail of error.details) {\n console.error(`[serve] ${detail}`);\n }\n console.error(\n '[serve] The review is still open in the browser. Fix the problem and press Finish Review again.'\n );\n return { ok: false, code: error.code, message: error.message, details: [...error.details] };\n }\n}\n\nconst DOCUMENT_ERROR_CODES: ReadonlySet<ReviewPublishErrorCode> = new Set([\n 'validation-failed',\n 'xml-illegal-character',\n]);\n\nfunction publishFailureStatus(code: ReviewPublishErrorCode): number {\n return DOCUMENT_ERROR_CODES.has(code) ? 422 : 500;\n}\n\nconst ROUTE_PATHS = new Set(Object.keys(routes).map(key => key.split(' ')[1]));\n\n/**\n * `/` is index.html; everything else is contained under the client directory.\n * Anything that is not a regular file under it is a 404.\n */\nasync function serveStatic(\n res: http.ServerResponse,\n clientDir: string,\n pathname: string\n): Promise<void> {\n let decoded: string;\n try {\n decoded = decodeURIComponent(pathname);\n } catch {\n sendError(res, 404, 'not found');\n return;\n }\n const relative = decoded === '/' ? 'index.html' : decoded.replace(/^\\/+/, '');\n const resolved = containPath(clientDir, relative);\n if (resolved === null) {\n sendError(res, 404, 'not found');\n return;\n }\n\n let data: Buffer;\n try {\n const stat = await fs.promises.stat(resolved);\n if (!stat.isFile()) {\n sendError(res, 404, 'not found');\n return;\n }\n data = await fs.promises.readFile(resolved);\n } catch {\n sendError(res, 404, 'not found');\n return;\n }\n res.writeHead(200, {\n 'content-type':\n CONTENT_TYPES[path.extname(resolved).toLowerCase()] ?? 'application/octet-stream',\n 'content-length': data.length,\n ...SECURITY_HEADERS,\n });\n res.end(data);\n}\n\n/**\n * Taking the session explicitly rather than reading module state mirrors the\n * core handlers and lets a test drive this without a repository. Not yet\n * listening: bind it with `listenLoopback`.\n */\nexport function createReviewServer(options: ReviewServerOptions): http.Server {\n const { session, output, capability, clientDir = defaultClientDir() } = options;\n\n return http.createServer(async (req, res) => {\n const method = req.method ?? 'GET';\n let url: URL;\n try {\n url = new URL(req.url ?? '/', 'http://localhost');\n } catch {\n sendError(res, 400, 'malformed request URL');\n return;\n }\n\n // Before anything is routed: this listener answers only to itself.\n if (!hostIsLoopback(req) || !originMatchesHost(req) || !fetchSiteIsSelf(req)) {\n sendError(res, 403, 'forbidden');\n return;\n }\n\n // Assets are served to anyone; every /api/ route is refused before lookup, so the route table does not leak.\n if (url.pathname.startsWith('/api/') && !presentsCapability(req, capability)) {\n sendUnauthorized(res);\n return;\n }\n\n try {\n const handler = routes[`${method} ${url.pathname}`];\n if (handler) {\n await handler({ req, res, url, session, output });\n } else if (ROUTE_PATHS.has(url.pathname)) {\n sendError(res, 405, 'method not allowed');\n } else if (url.pathname.startsWith('/api/')) {\n sendError(res, 404, 'not found');\n } else if (method === 'GET') {\n await serveStatic(res, clientDir, url.pathname);\n } else {\n sendError(res, 404, 'not found');\n }\n } catch (error) {\n console.error(`[serve] ${method} ${url.pathname} failed:`, error);\n if (!res.headersSent) {\n sendError(res, 500, 'internal error');\n } else {\n res.end();\n }\n }\n });\n}\n\n/**\n * The address is fixed here, not left to the caller: never `0.0.0.0`, never the\n * default. Port 0 asks the OS for an ephemeral one.\n */\nexport function listenLoopback(\n server: http.Server,\n port = 0\n): Promise<{ port: number; url: string }> {\n return new Promise((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, '127.0.0.1', () => {\n server.off('error', reject);\n const address = server.address() as AddressInfo;\n resolve({ port: address.port, url: `http://127.0.0.1:${address.port}/` });\n });\n });\n}\n","// Request validation for the serve package. Core's handlers assume a caller the\n// compiler checked; over HTTP the body is whatever the socket delivered.\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { ExpandContextRequest, ReviewState, SuggestionApplyRequest } from '@self-review/core';\n\n/** Realpath the deepest existing ancestor, so a deleted file still resolves. */\nfunction realpathDeepestExisting(absolute: string): string | null {\n const missing: string[] = [];\n let current = absolute;\n for (;;) {\n try {\n const real = fs.realpathSync(current);\n return missing.length === 0 ? real : path.join(real, ...missing);\n } catch {\n const parent = path.dirname(current);\n if (parent === current) {\n return null;\n }\n missing.unshift(path.basename(current));\n current = parent;\n }\n }\n}\n\n/**\n * Resolve `candidate` under `root`, or null if it escapes. For the client bundle and attachments only;\n * reviewed diff paths go through core's `authorizeReviewedPath`.\n *\n * Never decode here: callers pass a value `searchParams` already decoded once,\n * and decoding again turns `%2E%2E%2F` inside a filename into a real traversal.\n */\nexport function containPath(root: string, candidate: string): string | null {\n let resolvedRoot: string;\n try {\n resolvedRoot = fs.realpathSync(root);\n } catch {\n return null;\n }\n\n // Realpath both sides so a symlink inside the repository cannot escape it.\n const resolved = realpathDeepestExisting(path.resolve(resolvedRoot, candidate));\n if (resolved === null) {\n return null;\n }\n\n if (resolved === resolvedRoot) {\n return resolved;\n }\n // Root plus separator, not a bare prefix: `/repo-evil` is not under `/repo`.\n const rootWithSep = resolvedRoot.endsWith(path.sep) ? resolvedRoot : resolvedRoot + path.sep;\n return resolved.startsWith(rootWithSep) ? resolved : null;\n}\n\n/**\n * Reaches git as `-U${contextLines}`, so it must be bounded. Matches\n * `MAX_CONTEXT` in useExpandContext.ts; keep the two in step.\n */\nexport const MAX_CONTEXT_LINES = 99_999;\n\nexport type ParseResult<T> = { ok: true; value: T } | { ok: false; error: string };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nconst EXPAND_CONTEXT_KEYS: ReadonlySet<string> = new Set(['filePath', 'contextLines']);\n\n/**\n * Accepts exactly `{ filePath, contextLines }`. Unknown keys are rejected, not\n * ignored. The route authorizes `filePath` as a reviewed path before git sees it.\n */\nexport function parseExpandContextBody(body: unknown): ParseResult<ExpandContextRequest> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return { ok: false, error: 'body must be a JSON object' };\n }\n const record = body as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (!EXPAND_CONTEXT_KEYS.has(key)) {\n return { ok: false, error: `unknown field: ${key}` };\n }\n }\n\n const { filePath, contextLines } = record;\n if (typeof filePath !== 'string') {\n return { ok: false, error: 'filePath must be a string' };\n }\n if (\n typeof contextLines !== 'number' ||\n !Number.isInteger(contextLines) ||\n contextLines < 0 ||\n contextLines > MAX_CONTEXT_LINES\n ) {\n return {\n ok: false,\n error: `contextLines must be an integer between 0 and ${MAX_CONTEXT_LINES}`,\n };\n }\n\n return { ok: true, value: { filePath, contextLines } };\n}\n\nconst APPLY_KEYS: ReadonlySet<string> = new Set(['filePath', 'lineRange', 'suggestion']);\nconst LINE_RANGE_KEYS: ReadonlySet<string> = new Set(['side', 'start', 'end']);\nconst SUGGESTION_KEYS: ReadonlySet<string> = new Set(['originalCode', 'proposedCode']);\n\n/**\n * Validate the body of `POST /api/apply-suggestion`.\n *\n * This is the one route that rewrites a file in the reviewed tree, so the shape\n * is checked exactly rather than deferred. Core refuses anything whose anchored\n * lines do not still match `originalCode` byte for byte, but it should never be\n * asked a question this malformed in the first place.\n */\nexport function parseSuggestionApplyBody(body: unknown): ParseResult<SuggestionApplyRequest> {\n if (!isRecord(body)) {\n return { ok: false, error: 'body must be a JSON object' };\n }\n for (const key of Object.keys(body)) {\n if (!APPLY_KEYS.has(key)) return { ok: false, error: `unknown field: ${key}` };\n }\n\n const { filePath, lineRange, suggestion } = body;\n if (typeof filePath !== 'string' || filePath === '') {\n return { ok: false, error: 'filePath must be a non-empty string' };\n }\n\n // A file-level comment has no anchor, and core refuses it. Accept the null so\n // the refusal comes back in core's vocabulary rather than as a 400.\n if (lineRange !== null) {\n if (!isRecord(lineRange)) {\n return { ok: false, error: 'lineRange must be an object or null' };\n }\n for (const key of Object.keys(lineRange)) {\n if (!LINE_RANGE_KEYS.has(key)) {\n return { ok: false, error: `unknown lineRange field: ${key}` };\n }\n }\n if (lineRange.side !== 'old' && lineRange.side !== 'new') {\n return { ok: false, error: \"lineRange.side must be 'old' or 'new'\" };\n }\n for (const key of ['start', 'end'] as const) {\n const value = lineRange[key];\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {\n return { ok: false, error: `lineRange.${key} must be a positive integer` };\n }\n }\n if ((lineRange.end as number) < (lineRange.start as number)) {\n return { ok: false, error: 'lineRange.end must not precede lineRange.start' };\n }\n }\n\n if (!isRecord(suggestion)) {\n return { ok: false, error: 'suggestion must be an object' };\n }\n for (const key of Object.keys(suggestion)) {\n if (!SUGGESTION_KEYS.has(key)) {\n return { ok: false, error: `unknown suggestion field: ${key}` };\n }\n }\n for (const key of ['originalCode', 'proposedCode'] as const) {\n if (typeof suggestion[key] !== 'string') {\n return { ok: false, error: `suggestion.${key} must be a string` };\n }\n }\n\n return { ok: true, value: body as unknown as SuggestionApplyRequest };\n}\n\nconst REVIEW_STATE_KEYS: ReadonlySet<string> = new Set(['timestamp', 'source', 'files']);\n\n/**\n * Accepts exactly `{ timestamp, source, files }`. Remote provenance is never\n * taken from the client; the process injects it after submission.\n *\n * Structural only — the XSD checks nested fields at serialization time. The\n * exception is `id`, checked below, because the serializer turns an id into a\n * file name *before* it validates anything.\n */\nexport function parseReviewStateBody(body: unknown): ParseResult<ReviewState> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return { ok: false, error: 'body must be a JSON object' };\n }\n const record = body as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (!REVIEW_STATE_KEYS.has(key)) {\n return { ok: false, error: `unknown field: ${key}` };\n }\n }\n\n const { timestamp, source, files } = record;\n if (typeof timestamp !== 'string') {\n return { ok: false, error: 'timestamp must be a string' };\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return { ok: false, error: 'source must be an object' };\n }\n if (!Array.isArray(files)) {\n return { ok: false, error: 'files must be an array' };\n }\n\n const decoded = decodeFileAttachments(files);\n if (!decoded.ok) {\n return decoded;\n }\n\n return { ok: true, value: { timestamp, source, files: decoded.value } as ReviewState };\n}\n\n// Attachment blobs on the wire. `JSON.stringify` renders an ArrayBuffer as\n// `{}`, which would write a zero-byte image with a 200 and no error anywhere,\n// so the client sends base64 in `dataBase64` and a raw `data` field is refused.\n\n/** Canonical base64: full quartets, with at most one padded tail group. */\nconst BASE64_PATTERN =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)$/;\n\nconst RAW_DATA_ERROR =\n 'attachment data must be sent base64-encoded as dataBase64, never as a serialized ArrayBuffer';\n\n/** Every id this app makes: a randomUUID, or generateId's `${ms}-${base36}`. */\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/**\n * An id becomes an attachment's file name, so `../../x` was a path. Core\n * contains that write too; refusing here fails with a 400 at the door rather\n * than midway through saving, once the review has left the session.\n */\nfunction checkId(entry: Record<string, unknown>, what: string): string | null {\n if (entry.id === undefined) return null;\n if (typeof entry.id !== 'string' || !ID_PATTERN.test(entry.id)) {\n return `${what} id must match ${ID_PATTERN.source}`;\n }\n return null;\n}\n\n/**\n * The slice is load-bearing: `Buffer.from` returns a view into Node's shared\n * pool, so handing `.buffer` over whole writes unrelated memory to disk.\n */\nfunction base64ToArrayBuffer(value: string): ArrayBuffer {\n const buffer = Buffer.from(value, 'base64');\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n ) as ArrayBuffer;\n}\n\n/** Decode each blob. A resumed attachment carries none and passes through. */\nfunction decodeAttachmentList(list: unknown[]): ParseResult<unknown[]> {\n const decoded: unknown[] = [];\n for (const entry of list) {\n if (!isRecord(entry)) {\n decoded.push(entry);\n continue;\n }\n if (entry.data !== undefined) {\n return { ok: false, error: RAW_DATA_ERROR };\n }\n if (entry.dataBase64 === undefined) {\n decoded.push(entry);\n continue;\n }\n const encoded = entry.dataBase64;\n if (typeof encoded !== 'string' || !BASE64_PATTERN.test(encoded)) {\n // The empty string fails the pattern too: an attachment with no bytes\n // is a zero-byte file on disk, which is the failure being guarded.\n return { ok: false, error: 'attachment dataBase64 must be non-empty base64' };\n }\n const { dataBase64: _encoded, ...rest } = entry;\n decoded.push({ ...rest, data: base64ToArrayBuffer(encoded) });\n }\n return { ok: true, value: decoded };\n}\n\n/**\n * Walk the files, decoding blobs and checking every id that becomes a file\n * name. Tolerant of anything it does not recognise, since the XSD checks the\n * document later; strict about the encoding, which the XSD cannot see.\n */\nfunction decodeFileAttachments(files: unknown[]): ParseResult<unknown[]> {\n const decodedFiles: unknown[] = [];\n for (const file of files) {\n if (!isRecord(file) || !Array.isArray(file.comments)) {\n decodedFiles.push(file);\n continue;\n }\n const decodedComments: unknown[] = [];\n for (const comment of file.comments) {\n if (!isRecord(comment)) {\n decodedComments.push(comment);\n continue;\n }\n const commentIdError = checkId(comment, 'comment');\n if (commentIdError) return { ok: false, error: commentIdError };\n const next: Record<string, unknown> = { ...comment };\n\n if (Array.isArray(comment.attachments)) {\n const result = decodeAttachmentList(comment.attachments);\n if (!result.ok) return result;\n next.attachments = result.value;\n }\n\n if (Array.isArray(comment.replies)) {\n const decodedReplies: unknown[] = [];\n for (const reply of comment.replies) {\n if (!isRecord(reply)) {\n decodedReplies.push(reply);\n continue;\n }\n const replyIdError = checkId(reply, 'reply');\n if (replyIdError) return { ok: false, error: replyIdError };\n if (!Array.isArray(reply.attachments)) {\n decodedReplies.push(reply);\n continue;\n }\n const result = decodeAttachmentList(reply.attachments);\n if (!result.ok) return result;\n decodedReplies.push({ ...reply, attachments: result.value });\n }\n next.replies = decodedReplies;\n }\n\n decodedComments.push(next);\n }\n decodedFiles.push({ ...file, comments: decodedComments });\n }\n return { ok: true, value: decodedFiles };\n}\n","// The session capability. Host/Origin checks cannot tell the reviewer from another local account\n// (loopback is shared and a local client can send no browser headers); this secret can.\n// The browser side of the contract is in ./protocol.ts.\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\n\nexport function generateCapability(): string {\n return randomBytes(32).toString('base64url');\n}\n\n// Constant-time once lengths agree; every capability has the same length, so the length check leaks nothing.\nexport function capabilityMatches(expected: string, presented: string): boolean {\n const a = Buffer.from(expected, 'utf-8');\n const b = Buffer.from(presented, 'utf-8');\n return a.length === b.length && timingSafeEqual(a, b);\n}\n","// The HTTP contract both ends share; no Node dependency so the browser bundle can import it.\n\nimport type { ReviewPublishErrorCode } from '@self-review/core';\n\n/**\n * Upper bound on a `POST /api/review` body. The client checks it too, so an oversized review is\n * refused with the work still in the page. Attachments ride base64, about 4/3 of their bytes.\n */\nexport const MAX_REVIEW_BODY_BYTES = 32 * 1024 * 1024;\n\n/** A 200 from `POST /api/review`, sent only after the document is published. */\nexport interface ReviewSubmitAck {\n ok: true;\n /** The absolute path the review was written to. */\n outputPath: string;\n}\n\n/** `POST /api/review` when publishing failed; the server stays up for a retry. */\nexport interface ReviewSubmitFailure {\n ok: false;\n /** The publisher's code; `details` has one rendered line per problem. */\n code: ReviewPublishErrorCode;\n message: string;\n details: string[];\n}\n\n/** The client's own code for a body it refused to send, and for the server's 413. */\nexport const REVIEW_TOO_LARGE_CODE = 'review-too-large';\n\n// The capability travels only in the launch URL's fragment (`/#cap=<token>`), which a browser never sends\n// (not even in `Referer`). The page moves it into `Authorization: Bearer` on every API request.\nexport const CAPABILITY_FRAGMENT_KEY = 'cap';\n\nexport const CAPABILITY_SCHEME = 'Bearer';\n\nexport function formatLaunchUrl(listenerUrl: string, capability: string): string {\n return `${listenerUrl}#${CAPABILITY_FRAGMENT_KEY}=${capability}`;\n}\n\n// Parsed as URL parameters so a browser that re-encodes the fragment is still read.\nexport function parseCapabilityFragment(hash: string): string | null {\n const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n const value = params.get(CAPABILITY_FRAGMENT_KEY);\n return value ? value : null;\n}\n\nexport function capabilityAuthorization(capability: string): string {\n return `${CAPABILITY_SCHEME} ${capability}`;\n}\n\nexport function formatMegabytes(bytes: number): string {\n return (bytes / (1024 * 1024)).toFixed(1);\n}\n"],"mappings":";;;AAWA,SAAS,qBAAqB;;;ACT9B,SAAS,iCAAiC;AAgB1C,IAAM,cAAc;AAAA,EAClB,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,iBAAiB;AACnB;AAEA,IAAM,gBAAgB;AAAA,EACpB,UAAU;AAAA,EACV,MAAM;AAAA,EACN,aAAa;AAAA,EACb,MAAM;AACR;AAIO,SAAS,eAAe,MAA2B;AACxD,QAAM,EAAE,QAAQ,OAAO,KAAK,IAAI,0BAA0B,MAAM;AAAA,IAC9D,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB,CAAC;AACD,SAAO;AAAA,IACL,aAAa;AAAA,IACb,YAAY,OAAO;AAAA,IACnB,YAAY,OAAO;AAAA,IACnB,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM;AAAA,EACjB;AACF;;;AClCA,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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AClB;AAAA,EACF;AACA,MAAI,KAAK,SAAS;AAChB,iBAAa;AACb;AAAA,EACF;AAEA,QAAM,EAAE,SAAS,OAAO,IAAI,MAAM,eAAe,IAAI;AAGrD,QAAM,aAAa,mBAAmB;AACtC,QAAM,SAAS,mBAAmB,EAAE,SAAS,QAAQ,WAAW,CAAC;AACjE,yBAAuB,EAAE,OAAO,CAAC;AAEjC,QAAM,EAAE,IAAI,IAAI,MAAM,eAAe,MAAM;AAC3C,UAAQ,MAAM,2BAA2B,gBAAgB,KAAK,UAAU,CAAC,EAAE;AAC3E,UAAQ,MAAM,wCAAwC,OAAO,IAAI,0BAA0B;AAC3F,UAAQ;AAAA,IACN;AAAA,EAEF;AACF;AAEA,KAAK,EAAE,MAAM,WAAS;AACpB,UAAQ,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACjF,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["fs","path","publishOptionsFor","resolve","publishOptionsFor"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/args.ts","../src/startup-composition.ts","../../core/src/anchor-validation.ts","../../core/src/xml-errors.ts","../../core/src/input-budgets.ts","../../core/src/review-state-validation.ts","../../core/src/unicode-text.ts","../../core/src/review-request-validation.ts","../../core/src/same-diff-source.ts","../../config/src/index.ts","../../core/src/config-font-size.ts","../../core/src/publication-ownership.ts","../src/engine-contract.ts","../../core/src/attachment-origin-plan.ts","../../core/src/attachment-planner.ts","../src/resume-adoption-compatibility.ts","../src/resume-document-loader.ts","../src/resume-worker-lifetime.ts","../src/diagnostic-reporter.ts","../src/startup-resolver.ts","../src/startup.ts","../src/core-capabilities.ts","../src/protocol.ts","../src/request-admission.ts","../src/lifecycle.ts","../src/bound-server.ts","../src/json-body-processing.ts","../src/capability.ts","../src/http-transport.ts","../src/static-assets.ts","../src/contained-path.ts","../src/review-submission.ts","../src/legacy-submission.ts","../src/bound-api-routes.ts","../src/json-response.ts","../src/attachment-codec.ts","../src/validate.ts","../src/route-composition.ts","../src/source-ownership.ts","../src/review-operations.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// The serve-mode entry point: resolve one review session, serve it on a\n// port, and stop when the review is complete.\n//\n// Composition only — argument parsing is ./args, session resolution is\n// ./startup, the routes are ./server and the completion is ./lifecycle. The\n// order below is the load-bearing part: the session is fully resolved, and\n// the completion hook attached, before the listener opens, so no request can\n// reach a half-built session and no submission can arrive unobserved.\n\nimport { createRequire } from 'node:module';\nimport { parseServeArgs } from './args';\nimport { resolveSession } from './startup';\nimport { createStartupHost } from './startup-composition';\nimport { reportCoreCompatibility } from './core-capabilities';\nimport { createServeLifecycle } from './lifecycle';\nimport { createValidatedReviewServer, listenLoopback } from './bound-server';\nimport { createValidatedPublicationOperations } from './review-operations';\nimport { installedServeEngine } from './engine-contract';\nimport { generateCapability } from './capability';\nimport { formatLaunchUrl } from './protocol';\n\nconst HELP = `\nself-review-serve - Serve the self-review interface over HTTP\n\nUsage: self-review-serve [options] [<git-diff-args>...]\n\nOptions:\n -o, --output <file> Write the review to <file> (default: ./review.xml, or\n output-file from .self-review.yaml)\n --resume-from <file> Load a previous review XML file\n -h, --help Show this help message\n -v, --version Show version number\n\nAll other arguments are passed to git diff. With none, the unstaged working\ntree changes are reviewed. Outside a git repository, pass a directory or file.\n\nExamples:\n self-review-serve # unstaged changes\n self-review-serve --staged\n self-review-serve main..feature-branch\n self-review-serve --resume-from review.xml # resume a previous review\n\nThe URL is printed to stderr on start. Open exactly that URL: the part after\n'#' is this session's key, drawn fresh each start, and the browser keeps it\nout of the address bar once the page has loaded. A reloaded or retyped\naddress has no key and the page says so; if the URL is lost, stop this\nprocess and start it again. Over ssh, forward the port (ssh -L) and open the\nsame URL against the forwarded port, keeping the '#' part.\n\nThe output path is fixed by the arguments above and cannot be changed from\nthe browser. Completing the review writes that file and stops this process.\nNothing is saved before then, and closing the tab once you have written a\ncomment warns you first. If the file cannot be written, the browser says why\nand keeps the review; fix the problem and press Finish Review again.\n\nThe listener binds to 127.0.0.1, refuses any request that names another host\nor origin so a web page cannot reach it, and refuses any API request without\nthe key, so another account on the same host cannot either.\n`.trim();\n\nfunction printVersion(): void {\n try {\n // Read at runtime rather than imported, so the version is the installed\n // package's own. dist/cli.js sits one directory below package.json in\n // both the workspace and an installed tarball.\n const requireFromHere = createRequire(import.meta.url);\n const pkg = requireFromHere('../package.json') as { version: string };\n console.error(`self-review-serve v${pkg.version}`);\n } catch {\n console.error('self-review-serve (version unknown)');\n }\n}\n\nasync function main(): Promise<void> {\n const args = parseServeArgs(process.argv.slice(2));\n if (args.help) {\n console.error(HELP);\n return;\n }\n if (args.version) {\n printVersion();\n return;\n }\n\n const host = createStartupHost(process.cwd(), message => console.error(message));\n reportCoreCompatibility(host.reportDiagnostic);\n const lifetime = createServeLifecycle({\n signals: process,\n reportDiagnostic: host.reportDiagnostic,\n });\n const startupTimer = setTimeout(() => {\n console.error('[serve] Startup deadline reached; stopping.');\n lifetime.stop(1);\n }, 45_000);\n try {\n await lifetime.track(\n (async () => {\n const { session, output } = await resolveSession(\n args,\n {\n signal: lifetime.signal,\n timeoutMs: 30_000,\n },\n host\n );\n if (lifetime.signal.aborted) throw lifetime.signal.reason;\n const capability = generateCapability();\n const operations = createValidatedPublicationOperations(\n session,\n output,\n installedServeEngine,\n host.reportDiagnostic\n );\n const server = createValidatedReviewServer({\n capability,\n operations,\n publication: operations,\n reportDiagnostic: host.reportDiagnostic,\n });\n lifetime.attach(server);\n const { url } = await listenLoopback(server, 0, { signal: lifetime.signal });\n if (lifetime.signal.aborted) throw lifetime.signal.reason;\n console.error(`[serve] Review ready at ${formatLaunchUrl(url, capability)}`);\n console.error(\n `[serve] Completing the review writes ${output.path} and stops this process.`\n );\n console.error(\n '[serve] The listener is loopback-only. The part of the URL after # is this ' +\n \"session's key: open the URL exactly as printed, and do not share it.\"\n );\n })()\n );\n } catch (error) {\n if (!lifetime.signal.aborted)\n console.error(`[serve] ${error instanceof Error ? error.message : String(error)}`);\n lifetime.stop(1);\n } finally {\n clearTimeout(startupTimer);\n }\n}\n\nmain().catch(error => {\n console.error(`[serve] ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n});\n","// Mirrors src/main/cli.ts over core's extractor; the flag table is in packages/core/src/startup.ts.\n\nimport { extractApplicationOptions } from '@self-review/core';\n\nexport interface ServeArgs {\n /** Arguments passed through to `git diff`, in the order given. */\n gitDiffArgs: string[];\n /**\n * Output path exactly as typed, unresolved. `null` means the caller said\n * nothing and the configured `output-file` decides.\n */\n outputPath: string | null;\n /** Path of a prior review XML to resume from, as typed. `null` when unset. */\n resumeFrom: string | null;\n help: boolean;\n version: boolean;\n}\n\nconst VALUE_FLAGS = {\n '--output': 'outputPath',\n '-o': 'outputPath',\n '--resume-from': 'resumeFrom',\n} as const;\n\nconst BOOLEAN_FLAGS = {\n '--help': 'help',\n '-h': 'help',\n '--version': 'version',\n '-v': 'version',\n} as const;\n\n// Throws ApplicationOptionError on a value flag with no or an empty value: `--output=` would otherwise\n// resolve to the working directory and fail with EISDIR only at submit.\nexport function parseServeArgs(argv: string[]): ServeArgs {\n const { values, flags, rest } = extractApplicationOptions(argv, {\n valueFlags: VALUE_FLAGS,\n booleanFlags: BOOLEAN_FLAGS,\n });\n return {\n gitDiffArgs: rest,\n outputPath: values.outputPath,\n resumeFrom: values.resumeFrom,\n help: flags.help,\n version: flags.version,\n };\n}\n","// Environment and installed-engine choices for the CLI and legacy programmatic defaults.\nimport { resolve } from 'node:path';\nimport { normalizeConfigFontSize } from '@self-review/core/validation';\nimport { installedServeEngine } from './engine-contract';\nimport { loadResumeDocumentAsync } from './resume-document-loader';\nimport { nonThrowingReporter } from './diagnostic-reporter';\nimport type { StartupHost } from './startup-resolver';\n\nexport function createStartupHost(\n cwd = process.cwd(),\n reportDiagnostic: (message: string) => void = message => console.error(message)\n): StartupHost {\n const { core, resolveSource } = installedServeEngine;\n return {\n cwd,\n reportDiagnostic,\n operations: {\n loadConfigWithProvenance: options => {\n const loaded = core.loadConfigWithProvenance(options);\n const normalized = normalizeConfigFontSize(loaded.config);\n if (!normalized.diagnostic) return loaded;\n nonThrowingReporter(options?.reportDiagnostic ?? reportDiagnostic)(normalized.diagnostic);\n return {\n ...loaded,\n config: normalized.config,\n provenance: { ...loaded.provenance, fontSize: 'default' },\n };\n },\n inspectOutput: output => core.inspectOutputPath(output.path, core.publishOptionsFor(output)),\n resolveSource,\n loadLocalReview: core.loadLocalReview,\n commitLoadedReview: installedServeEngine.commitLoadedReview,\n loadResumeDocument: core.loadResumeDocument,\n loadResumeDocumentAsync,\n loadGuide: (output, config, files, options) =>\n // Core 2.0.4 ignores the fourth argument. Resolve the configured path here\n // as well, so that peer still reads the host's guide without changing cwd.\n core.loadGuide(\n output,\n config.guideFile\n ? { ...config, guideFile: resolve(options?.cwd ?? cwd, config.guideFile) }\n : config,\n files,\n options\n ),\n },\n };\n}\n","// Line-anchor validation shared by the resume importer and Apply, both untrusted input.\n\nimport type { LineRange } from './types';\n\nexport type AnchorSide = 'old' | 'new';\n\nexport interface LineAnchor {\n side: AnchorSide;\n start: number;\n end: number;\n}\n\nexport type AnchorCheck = { ok: true; anchor: LineAnchor } | { ok: false; reason: string };\n\n/** The four raw line fields; `unknown` because XML gives strings and JSON gives anything. */\nexport interface AnchorFields {\n oldLineStart?: unknown;\n oldLineEnd?: unknown;\n newLineStart?: unknown;\n newLineEnd?: unknown;\n}\n\n/**\n * Returns `null` when no field is present (a file-level comment), else the first\n * rule broken: positive safe integers (digit strings accepted), exactly one\n * complete side, start <= end, end <= `maxLine`. `reason` is embedded in diagnostics.\n */\nexport function validateLineAnchor(fields: AnchorFields, maxLine?: number): AnchorCheck | null {\n const old = sideFields('old', fields.oldLineStart, fields.oldLineEnd);\n const next = sideFields('new', fields.newLineStart, fields.newLineEnd);\n\n if (!old.present && !next.present) return null;\n if (old.present && next.present) {\n return { ok: false, reason: 'carries both old and new line ranges' };\n }\n\n const side = old.present ? old : next;\n if (side.start === undefined || side.end === undefined) {\n return { ok: false, reason: `${side.name}-line range is incomplete (start and end required)` };\n }\n\n const start = toPositiveSafeInteger(side.start);\n if (start === null) {\n return {\n ok: false,\n reason: `${side.name}-line-start is not a positive integer (${describe(side.start)})`,\n };\n }\n const end = toPositiveSafeInteger(side.end);\n if (end === null) {\n return {\n ok: false,\n reason: `${side.name}-line-end is not a positive integer (${describe(side.end)})`,\n };\n }\n\n return checkRange({ side: side.name, start, end }, maxLine);\n}\n\n/**\n * Same rules as {@link validateLineAnchor} for a typed range; `NaN`, `0`, `1.5` and `Infinity` are\n * still numbers.\n */\nexport function validateLineRange(range: LineRange, maxLine?: number): AnchorCheck {\n const start = toPositiveSafeInteger(range.start);\n if (start === null) {\n return {\n ok: false,\n reason: `${range.side}-line-start is not a positive integer (${describe(range.start)})`,\n };\n }\n const end = toPositiveSafeInteger(range.end);\n if (end === null) {\n return {\n ok: false,\n reason: `${range.side}-line-end is not a positive integer (${describe(range.end)})`,\n };\n }\n return checkRange({ side: range.side, start, end }, maxLine);\n}\n\nfunction checkRange(anchor: LineAnchor, maxLine: number | undefined): AnchorCheck {\n if (anchor.start > anchor.end) {\n return {\n ok: false,\n reason: `${anchor.side}-line range is reversed (${anchor.start} > ${anchor.end})`,\n };\n }\n if (maxLine !== undefined && anchor.end > maxLine) {\n return {\n ok: false,\n reason: `${anchor.side}-line range ends beyond line ${maxLine} (${anchor.end})`,\n };\n }\n return { ok: true, anchor };\n}\n\ninterface SideFields {\n name: AnchorSide;\n present: boolean;\n start: unknown;\n end: unknown;\n}\n\nfunction sideFields(name: AnchorSide, start: unknown, end: unknown): SideFields {\n const s = isAbsent(start) ? undefined : start;\n const e = isAbsent(end) ? undefined : end;\n return { name, present: s !== undefined || e !== undefined, start: s, end: e };\n}\n\nfunction isAbsent(value: unknown): boolean {\n return value === undefined || value === null;\n}\n\n/**\n * A positive safe integer from a number or decimal digit string; anything else (`1e3`, `NaN`,\n * booleans) is `null`.\n */\nfunction toPositiveSafeInteger(value: unknown): number | null {\n let n: number;\n if (typeof value === 'number') {\n n = value;\n } else if (typeof value === 'string' && /^\\d+$/.test(value)) {\n n = Number(value);\n } else {\n return null;\n }\n return Number.isSafeInteger(n) && n > 0 ? n : null;\n}\n\nfunction describe(value: unknown): string {\n return typeof value === 'string' ? JSON.stringify(value) : String(value);\n}\n","// Typed failures of review XML reading and writing. Library code throws, hosts print\n// `.message` and choose their exit; nothing here calls `process.exit`.\n\nexport type ReviewXmlErrorCode =\n | 'read-failed'\n /** Over a safety budget (input-budgets.ts): byte size or attachment count. */\n | 'input-too-large'\n | 'parse-failed'\n /** Well-formed, but with no `<review>` root element. */\n | 'missing-root'\n /** The generated document does not validate against the v3 XSD. */\n | 'schema-invalid'\n /** The in-memory review DTO is malformed or has an unusable anchor. */\n | 'invalid-state'\n | 'xml-illegal-character';\n\nexport class ReviewXmlError extends Error {\n readonly code: ReviewXmlErrorCode;\n readonly cause?: unknown;\n /** One rendered line per problem (e.g. a schema violation with its line number). */\n readonly details: readonly string[];\n\n constructor(\n code: ReviewXmlErrorCode,\n message: string,\n options?: { cause?: unknown; details?: readonly string[] }\n ) {\n // Assigned, not passed to `super`: the app's tsconfig lib lacks `ErrorOptions`.\n super(message);\n this.name = 'ReviewXmlError';\n this.code = code;\n this.details = options?.details ?? [];\n if (options?.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport interface XmlIllegalCharacterLocation {\n /** e.g. `body`, `original-code`, `path`, `author`. */\n field: string;\n filePath?: string;\n commentId?: string;\n replyId?: string;\n}\n\n/**\n * Thrown before anything is written: no escaped form exists, and dropping the character would\n * change the reviewer's text or a suggestion's code.\n */\nexport class XmlIllegalCharacterError extends ReviewXmlError {\n readonly codePoint: number;\n readonly field: string;\n readonly filePath?: string;\n readonly commentId?: string;\n readonly replyId?: string;\n\n constructor(codePoint: number, location: XmlIllegalCharacterLocation) {\n super('xml-illegal-character', describeIllegalCharacter(codePoint, location));\n this.name = 'XmlIllegalCharacterError';\n this.codePoint = codePoint;\n this.field = location.field;\n this.filePath = location.filePath;\n this.commentId = location.commentId;\n this.replyId = location.replyId;\n }\n}\n\nfunction describeIllegalCharacter(\n codePoint: number,\n location: XmlIllegalCharacterLocation\n): string {\n const hex = codePoint.toString(16).toUpperCase().padStart(4, '0');\n const where = [\n location.filePath !== undefined ? `file \"${location.filePath}\"` : null,\n location.commentId !== undefined ? `comment ${location.commentId}` : null,\n location.replyId !== undefined ? `reply ${location.replyId}` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(', ');\n return (\n `Cannot write review XML: ${location.field}${where ? ` of ${where}` : ''} contains ` +\n `U+${hex}, which XML 1.0 cannot represent. Remove the character and save again.`\n );\n}\n","// Safety budgets, checked before the expensive step. Unlike the transport thresholds\n// (`max-files`, `max-total-lines`), these are deliberately not configurable.\n// Exceeding one surfaces as a diagnostic, a guide warning or `input-too-large`.\n\nconst KIB = 1024;\nconst MIB = 1024 * KIB;\n\n/**\n * Entries one directory walk (or untracked-file listing) may examine; ignored directories are\n * pruned first.\n */\nexport const MAX_SOURCE_ENTRIES = 50_000;\n\n/** Prefix sampled for a NUL byte to decide a file is binary. */\nexport const BINARY_SNIFF_BYTES = 8 * KIB;\n\n/**\n * Largest text file read into a synthetic diff; a larger one is listed without content and named in\n * a diagnostic.\n */\nexport const MAX_SOURCE_FILE_BYTES = 5 * MIB;\n\n/** Total bytes one synthetic-diff build may read, binary sniffs included. */\nexport const MAX_SOURCE_TOTAL_BYTES = 64 * MIB;\n\n/** Most bytes of `git diff` output captured from one invocation (the child process `maxBuffer`). */\nexport const MAX_GIT_DIFF_OUTPUT_BYTES = 50 * MIB;\n\n/** Largest guide sidecar the loader will read. */\nexport const MAX_GUIDE_BYTES = 1 * MIB;\n\n/**\n * Largest review document `--resume-from` will read (text and attachment references, never bytes).\n */\nexport const MAX_RESUME_XML_BYTES = 16 * MIB;\n\n/** Most attachment occurrences in a review document, including replies and repeated references. */\nexport const MAX_REVIEW_ATTACHMENTS = 1_000;\n\n/** Backwards-compatible name for the same reader/writer document contract. */\nexport const MAX_RESUME_ATTACHMENTS = MAX_REVIEW_ATTACHMENTS;\n\n/** Total newly staged asset bytes per publication. Existing references require no copy or read. */\nexport const MAX_PUBLICATION_ASSET_BYTES = 64 * MIB;\n\n/** Largest image read for a rendered preview or a comment attachment. */\nexport const MAX_IMAGE_BYTES = 10 * MIB;\n\n/**\n * The source-loading budgets as one value; overrides are for tests and embedders, never user\n * config.\n */\nexport interface SourceBudgets {\n maxEntries: number;\n maxFileBytes: number;\n maxTotalBytes: number;\n maxGitDiffOutputBytes: number;\n /** Representation limits are independent of bytes and transport/lazy thresholds. */\n maxFileLines?: number;\n maxTotalLines?: number;\n maxDiffFiles?: number;\n maxDiffHunks?: number;\n maxDiagnostics?: number;\n}\n\n/** Bounds retained objects even for empty lines, empty hunks and metadata-only files. */\nexport const MAX_SOURCE_FILE_LINES = 100_000;\nexport const MAX_SOURCE_TOTAL_LINES = 250_000;\nexport const MAX_DIFF_FILES = 10_000;\nexport const MAX_DIFF_HUNKS = 50_000;\nexport const MAX_DIFF_DIAGNOSTICS = 1_000;\n/** Avoid repeating an enormous malicious header in each diagnostic. */\nexport const MAX_DIFF_DIAGNOSTIC_CHARS = 8 * KIB;\n\nexport type ResolvedSourceBudgets = Required<SourceBudgets>;\n\nexport const DEFAULT_SOURCE_BUDGETS: Readonly<ResolvedSourceBudgets> = Object.freeze({\n maxEntries: MAX_SOURCE_ENTRIES,\n maxFileBytes: MAX_SOURCE_FILE_BYTES,\n maxTotalBytes: MAX_SOURCE_TOTAL_BYTES,\n maxGitDiffOutputBytes: MAX_GIT_DIFF_OUTPUT_BYTES,\n maxFileLines: MAX_SOURCE_FILE_LINES,\n maxTotalLines: MAX_SOURCE_TOTAL_LINES,\n maxDiffFiles: MAX_DIFF_FILES,\n maxDiffHunks: MAX_DIFF_HUNKS,\n maxDiagnostics: MAX_DIFF_DIAGNOSTICS,\n});\n\nexport function resolveSourceBudgets(\n overrides: Partial<SourceBudgets> = {}\n): ResolvedSourceBudgets {\n const budgets = { ...DEFAULT_SOURCE_BUDGETS };\n for (const name of Object.keys(budgets) as (keyof SourceBudgets)[]) {\n const value = overrides[name];\n if (value !== undefined) budgets[name] = value;\n }\n for (const [name, value] of Object.entries(budgets)) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a nonnegative safe integer`);\n }\n }\n return budgets;\n}\n\n/** `5 MiB`, `7.3 MiB`, `812 KiB`, `100 bytes`. */\nexport function formatBytes(bytes: number): string {\n if (bytes >= MIB) return `${trimFixed(bytes / MIB)} MiB`;\n if (bytes >= KIB) return `${trimFixed(bytes / KIB)} KiB`;\n return `${bytes} bytes`;\n}\n\nfunction trimFixed(value: number): string {\n return value.toFixed(1).replace(/\\.0$/, '');\n}\n\n/** Internal refusal shared by patch parsing and direct projection. */\nexport class RepresentationLimitError extends Error {\n constructor(\n readonly aggregate: boolean,\n detail: string\n ) {\n super(`Not loaded: ${detail} representation budget exceeded.`);\n this.name = 'RepresentationLimitError';\n }\n}\n\n/** Charge before allocating. Discarded objects still count toward this operation's work. */\nexport function createRepresentationBudget(budgets: ResolvedSourceBudgets) {\n let files = 0;\n let hunks = 0;\n let lines = 0;\n let fileLines = 0;\n return {\n beginFile() {\n if (files >= budgets.maxDiffFiles)\n throw new RepresentationLimitError(true, `${budgets.maxDiffFiles}-file`);\n files++;\n fileLines = 0;\n },\n addHunk() {\n if (hunks >= budgets.maxDiffHunks)\n throw new RepresentationLimitError(true, `${budgets.maxDiffHunks}-hunk total`);\n hunks++;\n },\n addLines(count: number) {\n if (count > budgets.maxFileLines - fileLines)\n throw new RepresentationLimitError(false, `${budgets.maxFileLines}-line per-file`);\n if (count > budgets.maxTotalLines - lines)\n throw new RepresentationLimitError(true, `${budgets.maxTotalLines}-line total`);\n fileLines += count;\n lines += count;\n },\n };\n}\n","// Runtime boundary for review DTOs, shared by transports and XML publication.\n// Validated DTOs retain supported optional metadata, extension fields and binary assets.\n\nimport type { ReviewState } from './types';\nimport { validateLineRange } from './anchor-validation';\nimport { ReviewXmlError } from './xml-errors';\nimport {\n MAX_IMAGE_BYTES,\n MAX_REVIEW_ATTACHMENTS,\n MAX_PUBLICATION_ASSET_BYTES,\n formatBytes,\n} from './input-budgets';\n\n/**\n * Validate the complete in-memory DTO without I/O. Unknown extension fields are retained.\n * Historical submissions may omit nullable anchors/suggestions; the returned DTO defaults them to null.\n * Already complete DTOs are returned unchanged.\n * Hosts can catch ReviewXmlError (`invalid-state`) before accepting a submission. Serialization and\n * publication use the same boundary, including when the XSD validator is unavailable.\n */\nexport function validateReviewState(value: unknown): ReviewState {\n validateState(value, true);\n return normalizeNullableFields(value as ReviewState);\n}\n\n/** Existing serializers accept a missing transient comment id and use an empty asset prefix. */\nexport function validateReviewForSerialization(state: ReviewState): ReviewState {\n validateState(state, false);\n return normalizeNullableFields(state);\n}\n\nfunction validateState(value: unknown, requireCommentIds: boolean): void {\n const state = record(value, 'review');\n const budget = { attachments: 0, bytes: 0 };\n string(state.timestamp, 'review.timestamp');\n const source = record(state.source, 'review.source');\n switch (source.type) {\n case 'git':\n string(source.gitDiffArgs, 'review.source.gitDiffArgs');\n string(source.repository, 'review.source.repository');\n break;\n case 'directory':\n case 'file':\n string(source.sourcePath, 'review.source.sourcePath');\n break;\n case 'welcome':\n case 'loading':\n break;\n default:\n invalid('review.source.type', 'must be git, directory, file, welcome or loading');\n }\n for (const key of ['remoteUrl', 'remoteBaseSha', 'remoteHeadSha'])\n optionalString(state, key, 'review');\n optionalEnum(state, 'remoteForge', ['github', 'gitlab'], 'review');\n array(state.files, 'review.files').forEach((value, index) => {\n const at = `review.files[${index}]`;\n const file = record(value, at);\n string(file.path, `${at}.path`);\n enumValue(\n file.changeType,\n ['added', 'modified', 'deleted', 'renamed', 'copied'],\n `${at}.changeType`\n );\n boolean(file.viewed, `${at}.viewed`);\n array(file.comments, `${at}.comments`).forEach((comment, index) =>\n validateComment(\n comment,\n `${at}.comments[${index}]`,\n file.path as string,\n requireCommentIds,\n budget\n )\n );\n });\n}\n\nfunction validateComment(\n value: unknown,\n at: string,\n ownerPath: string,\n requireId: boolean,\n budget: AttachmentBudget\n): void {\n const comment = record(value, at);\n if (requireId || comment.id !== undefined) string(comment.id, `${at}.id`);\n for (const key of ['filePath', 'body', 'category']) string(comment[key], `${at}.${key}`);\n if (comment.filePath !== ownerPath)\n invalid(`${at}.filePath`, 'must match its containing file path');\n for (const key of ['author', 'remoteId']) optionalString(comment, key, at);\n optionalEnum(comment, 'severity', ['critical', 'major', 'minor', 'info'], at);\n optionalEnum(comment, 'confidence', ['high', 'medium', 'low'], at);\n if (comment.orphaned !== undefined) boolean(comment.orphaned, `${at}.orphaned`);\n if (comment.lineRange !== null && comment.lineRange !== undefined) {\n const range = record(comment.lineRange, `${at}.lineRange`);\n enumValue(range.side, ['old', 'new'], `${at}.lineRange.side`);\n if (typeof range.start !== 'number' || typeof range.end !== 'number')\n invalid(`${at}.lineRange`, 'bounds must be numbers');\n const checked = validateLineRange({\n side: range.side as 'old' | 'new',\n start: range.start as number,\n end: range.end as number,\n });\n if (!checked.ok) invalid(`${at}.lineRange`, checked.reason);\n }\n if (comment.suggestion !== null && comment.suggestion !== undefined) {\n const suggestion = record(comment.suggestion, `${at}.suggestion`);\n string(suggestion.originalCode, `${at}.suggestion.originalCode`);\n string(suggestion.proposedCode, `${at}.suggestion.proposedCode`);\n if (comment.lineRange === null || comment.lineRange === undefined)\n invalid(`${at}.suggestion`, 'requires a line anchor');\n }\n validateAttachments(comment.attachments, `${at}.attachments`, budget);\n if (comment.replies !== undefined) {\n array(comment.replies, `${at}.replies`).forEach((value, index) => {\n const replyAt = `${at}.replies[${index}]`;\n const reply = record(value, replyAt);\n string(reply.id, `${replyAt}.id`);\n string(reply.body, `${replyAt}.body`);\n for (const key of ['author', 'remoteId']) optionalString(reply, key, replyAt);\n validateAttachments(reply.attachments, `${replyAt}.attachments`, budget);\n });\n }\n}\n\ninterface AttachmentBudget {\n attachments: number;\n bytes: number;\n}\n\nfunction validateAttachments(value: unknown, at: string, budget: AttachmentBudget): void {\n if (value === undefined) return;\n const attachments = array(value, at);\n budget.attachments += attachments.length;\n if (budget.attachments > MAX_REVIEW_ATTACHMENTS)\n invalid(at, `exceeds the ${MAX_REVIEW_ATTACHMENTS} attachment limit for a review document`);\n attachments.forEach((value, index) => {\n const attachmentAt = `${at}[${index}]`;\n const attachment = record(value, attachmentAt);\n for (const key of ['id', 'fileName', 'mediaType'])\n string(attachment[key], `${attachmentAt}.${key}`);\n if (attachment.data !== undefined && !isReadableArrayBuffer(attachment.data))\n invalid(`${attachmentAt}.data`, 'must be a readable ArrayBuffer');\n if (attachment.data !== undefined) {\n const bytes = new Uint8Array(attachment.data as ArrayBuffer).byteLength;\n if (bytes > MAX_IMAGE_BYTES)\n invalid(\n `${attachmentAt}.data`,\n `exceeds the ${formatBytes(MAX_IMAGE_BYTES)} attachment limit`\n );\n budget.bytes += bytes;\n if (budget.bytes > MAX_PUBLICATION_ASSET_BYTES)\n invalid(\n at,\n `exceeds the ${formatBytes(MAX_PUBLICATION_ASSET_BYTES)} publication asset limit`\n );\n }\n });\n}\n\nfunction record(value: unknown, at: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n invalid(at, 'must be an object');\n return value as Record<string, unknown>;\n}\n\nfunction array(value: unknown, at: string): unknown[] {\n if (!Array.isArray(value)) invalid(at, 'must be an array');\n for (let index = 0; index < value.length; index++) {\n if (!(index in value)) invalid(`${at}[${index}]`, 'must be present');\n }\n return value;\n}\n\nfunction string(value: unknown, at: string): void {\n if (typeof value !== 'string') invalid(at, 'must be a string');\n}\n\nfunction boolean(value: unknown, at: string): void {\n if (typeof value !== 'boolean') invalid(at, 'must be a boolean');\n}\n\nfunction optionalString(node: Record<string, unknown>, key: string, at: string): void {\n if (node[key] !== undefined) string(node[key], `${at}.${key}`);\n}\n\nfunction enumValue(value: unknown, allowed: readonly string[], at: string): void {\n if (typeof value !== 'string' || !allowed.includes(value))\n invalid(at, `must be one of ${allowed.join(', ')}`);\n}\n\nfunction optionalEnum(\n node: Record<string, unknown>,\n key: string,\n allowed: readonly string[],\n at: string\n): void {\n if (node[key] !== undefined) enumValue(node[key], allowed, `${at}.${key}`);\n}\n\nfunction invalid(at: string, reason: string): never {\n const message = `Invalid review state: ${at} ${reason}`;\n throw new ReviewXmlError('invalid-state', message, { details: [message] });\n}\n\n/** Only copy branches with historical omissions; buffers and extension fields keep their identity. */\nfunction normalizeNullableFields(state: ReviewState): ReviewState {\n const files = state.files.map(file => {\n const comments = file.comments.map(comment =>\n comment.lineRange === undefined || comment.suggestion === undefined\n ? {\n ...comment,\n lineRange: comment.lineRange ?? null,\n suggestion: comment.suggestion ?? null,\n }\n : comment\n );\n return comments.some((comment, index) => comment !== file.comments[index])\n ? { ...file, comments }\n : file;\n });\n return files.some((file, index) => file !== state.files[index]) ? { ...state, files } : state;\n}\n\n/** Intrinsic slot checks accept buffers across realms and refuse detached buffers before staging. */\nfunction isReadableArrayBuffer(value: unknown): value is ArrayBuffer {\n try {\n const getLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')!.get!;\n getLength.call(value);\n return new Uint8Array(value as ArrayBuffer).buffer === value;\n } catch {\n return false;\n }\n}\n","/** Lone UTF-16 surrogates cannot round-trip through UTF-8 without replacement. */\nexport function isWellFormedUnicode(value: string): boolean {\n return !/[\\uD800-\\uDFFF]/u.test(value);\n}\n","// Transport-neutral request structure. Anchor usability belongs to the engine,\n// which returns typed refusals before reading or changing reviewed source.\nimport type { SuggestionApplyRequest } from './types';\nimport { isWellFormedUnicode } from './unicode-text';\n\nexport const MAX_CONTEXT_LINES = 99_999;\nexport type RequestDecodeResult<T> = { ok: true; value: T } | { ok: false; error: string };\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Preserves extension fields; each transport decides its own unknown-key policy. */\nexport function decodeSuggestionApplyRequest(\n value: unknown\n): RequestDecodeResult<SuggestionApplyRequest> {\n if (!record(value)) return { ok: false, error: 'body must be a JSON object' };\n if (typeof value.filePath !== 'string') return { ok: false, error: 'filePath must be a string' };\n const range = value.lineRange;\n if (range !== null) {\n if (!record(range)) return { ok: false, error: 'lineRange must be an object or null' };\n if (range.side !== 'old' && range.side !== 'new')\n return { ok: false, error: \"lineRange.side must be 'old' or 'new'\" };\n for (const key of ['start', 'end'] as const) {\n if (typeof range[key] !== 'number')\n return { ok: false, error: `lineRange.${key} must be a number` };\n }\n }\n if (!record(value.suggestion)) return { ok: false, error: 'suggestion must be an object' };\n for (const key of ['originalCode', 'proposedCode'] as const) {\n if (typeof value.suggestion[key] !== 'string')\n return { ok: false, error: `suggestion.${key} must be a string` };\n }\n if (!isWellFormedUnicode(value.suggestion.proposedCode as string))\n return { ok: false, error: 'suggestion.proposedCode must be well-formed Unicode text' };\n return { ok: true, value: value as unknown as SuggestionApplyRequest };\n}\n","import type { DiffSource } from './types';\n\n/** Compare only canonical source fields, without normalizing their exact string values.\n * This is DTO equality, not permission to publish a welcome/loading source or provenance.\n */\nexport function sameDiffSource(loaded: DiffSource, submitted: DiffSource): boolean {\n if (loaded.type !== submitted.type) return false;\n switch (loaded.type) {\n case 'git':\n return (\n submitted.type === 'git' &&\n loaded.repository === submitted.repository &&\n loaded.gitDiffArgs === submitted.gitDiffArgs\n );\n case 'directory':\n case 'file':\n return (\n (submitted.type === 'directory' || submitted.type === 'file') &&\n loaded.sourcePath === submitted.sourcePath\n );\n case 'welcome':\n case 'loading':\n return true;\n }\n}\n","import type { AppConfig, CategoryDef } from '@self-review/types';\n\nconst categoryTemplate: readonly Readonly<CategoryDef>[] = Object.freeze(\n [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ].map(category => Object.freeze(category))\n);\n\n/** Only core's directory scanner reads these; the renderer carries them so the defaults stay one. */\nconst ignoreTemplate: readonly string[] = Object.freeze([\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n]);\n\nexport const DEFAULT_FONT_SIZE = 14;\n\nexport const DEFAULT_MAX_FILES = 500;\nexport const DEFAULT_MAX_TOTAL_LINES = 100000;\n\n/** `guideFile` is absent on purpose: the loader derives it from the output path. */\nconst configTemplate = Object.freeze({\n theme: 'system',\n diffView: 'split',\n fontSize: DEFAULT_FONT_SIZE,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: ignoreTemplate,\n categories: categoryTemplate,\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: DEFAULT_MAX_FILES,\n maxTotalLines: DEFAULT_MAX_TOTAL_LINES,\n} satisfies Omit<AppConfig, 'ignore' | 'categories'> & {\n ignore: readonly string[];\n categories: readonly Readonly<CategoryDef>[];\n});\n\n/** Return mutable defaults with independently owned arrays and category objects. */\nexport function createDefaultConfig(): AppConfig {\n return {\n ...configTemplate,\n ignore: [...configTemplate.ignore],\n categories: configTemplate.categories.map(category => ({ ...category })),\n };\n}\n\n/** Copy caller-owned nested configuration before retaining it. */\nexport function cloneConfig(config: AppConfig): AppConfig {\n return {\n ...config,\n // Partial configuration can explicitly replace a default with undefined.\n ignore: config.ignore && [...config.ignore],\n categories: config.categories && config.categories.map(category => ({ ...category })),\n };\n}\n\n// Compatibility snapshots remain mutable at runtime. Internal factories never read them.\nexport const DEFAULT_CATEGORIES: readonly CategoryDef[] = categoryTemplate.map(category => ({\n ...category,\n}));\nexport const DEFAULT_IGNORE_PATTERNS: readonly string[] = [...ignoreTemplate];\nexport const DEFAULT_CONFIG: Readonly<AppConfig> = createDefaultConfig();\n","// Pure policy shared by the YAML loader and hosts adapting older Core configuration.\nimport { createDefaultConfig } from '../../config/src/index';\n\nexport function normalizeConfigFontSize<T extends { fontSize: number }>(\n config: T,\n fallback: number = createDefaultConfig().fontSize\n): { config: T; diagnostic?: string } {\n if (Number.isFinite(config.fontSize)) return { config };\n return {\n config: { ...config, fontSize: fallback },\n diagnostic: `Warning: Invalid font-size value \"${String(config.fontSize)}\", expected a finite number; using a finite fallback`,\n };\n}\n","// Pure publication ownership policy. Hosts translate refusal with their installed error classes.\nimport type { DiffLoadPayload, DiffSource, RemoteSessionInfo, ReviewState } from './types';\nimport { sameDiffSource } from './same-diff-source';\n\ntype LoadedReview = Pick<DiffLoadPayload, 'source' | 'remote'>;\ntype Provenance = Pick<\n RemoteSessionInfo,\n 'remoteUrl' | 'remoteForge' | 'remoteBaseSha' | 'remoteHeadSha'\n>;\n\nexport interface PublicationOwnership {\n readonly loaded: LoadedReview;\n readonly source: DiffSource;\n readonly remote: Provenance | undefined;\n}\n\nfunction provenance(remote: RemoteSessionInfo | undefined): Provenance | undefined {\n if (!remote) return undefined;\n return {\n remoteUrl: remote.remoteUrl,\n remoteForge: remote.remoteForge,\n remoteBaseSha: remote.remoteBaseSha,\n remoteHeadSha: remote.remoteHeadSha,\n };\n}\n\n/** Capture before asynchronous admission work; preserve the loaded object's public reference alias. */\nexport function capturePublicationOwnership(\n loaded: LoadedReview | null\n): PublicationOwnership | null {\n if (!loaded || loaded.source.type === 'welcome' || loaded.source.type === 'loading') return null;\n return { loaded, source: { ...loaded.source }, remote: provenance(loaded.remote) };\n}\n\n/** Refuse absent, foreign or replaced loads, including in-place canonical source/provenance changes.\n * Keep legitimate state/source extensions; only the four host-owned provenance fields are replaced.\n */\nexport function normalizePublicationState(\n state: ReviewState,\n current: LoadedReview | null,\n admitted: PublicationOwnership | null\n): ReviewState | null {\n if (\n !admitted ||\n !current ||\n current !== admitted.loaded ||\n !state.source ||\n !sameDiffSource(admitted.source, current.source) ||\n !sameDiffSource(admitted.source, state.source)\n )\n return null;\n const remote = provenance(current.remote);\n if (\n remote?.remoteUrl !== admitted.remote?.remoteUrl ||\n remote?.remoteForge !== admitted.remote?.remoteForge ||\n remote?.remoteBaseSha !== admitted.remote?.remoteBaseSha ||\n remote?.remoteHeadSha !== admitted.remote?.remoteHeadSha\n )\n return null;\n const {\n remoteUrl: _url,\n remoteForge: _forge,\n remoteBaseSha: _base,\n remoteHeadSha: _head,\n ...local\n } = state;\n return { ...local, ...admitted.remote };\n}\n","// Installed-engine selection occurs once at composition. The 2.0.4 fallbacks\n// remain supported; their weaker interruption guarantees are reported by the CLI.\n// Remove fallback policies only when the supported Core minimum provides every\n// selected capability; preserve the original compatibility entry-point exports.\nimport * as core from '@self-review/core';\nimport { ReviewXmlError } from '@self-review/core';\nimport type {\n GitExecutionOptions,\n ReviewSession,\n SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ReviewState,\n} from '@self-review/core';\nimport {\n validateReviewState,\n ReviewXmlError as BundledXmlError,\n decodeSuggestionApplyRequest,\n MAX_CONTEXT_LINES,\n} from '@self-review/core/validation';\nimport { resumeAdopterFor } from './resume-adoption-compatibility';\nexport interface ApplyOptions {\n signal?: AbortSignal;\n}\ninterface ApplyEngine {\n applySuggestionForSession(\n session: ReviewSession,\n request: SuggestionApplyRequest\n ): SuggestionApplyOutcome;\n applySuggestionForSessionAsync?: (\n session: ReviewSession,\n request: SuggestionApplyRequest,\n options?: ApplyOptions\n ) => Promise<SuggestionApplyOutcome>;\n}\n\n/** The legacy path blocks the event loop; it cannot interrupt an in-progress write. */\nexport function applyFor(engine: ApplyEngine) {\n const applyAsync = engine.applySuggestionForSessionAsync?.bind(engine);\n const applySync = engine.applySuggestionForSession.bind(engine);\n return async (\n session: ReviewSession,\n request: SuggestionApplyRequest,\n options: ApplyOptions = {}\n ): Promise<SuggestionApplyOutcome> => {\n if (applyAsync) return applyAsync(session, request, options);\n if (options.signal?.aborted) throw options.signal.reason;\n return applySync(session, request);\n };\n}\ntype Source = ReturnType<typeof core.resolveStartupSource>;\ninterface StartupEngine {\n resolveStartupSource: typeof core.resolveStartupSource;\n resolveStartupSourceAsync?: (\n args: string[],\n cwd?: string,\n options?: GitExecutionOptions\n ) => Promise<Source>;\n}\nexport function startupSourceFor(engine: StartupEngine) {\n const resolveAsync = engine.resolveStartupSourceAsync?.bind(engine);\n const resolveSync = engine.resolveStartupSource.bind(engine);\n return async (args: string[], cwd: string, options: GitExecutionOptions): Promise<Source> => {\n if (options.signal?.aborted) throw options.signal.reason;\n return resolveAsync ? resolveAsync(args, cwd, options) : resolveSync(args, cwd);\n };\n}\ntype ReviewStateValidator = (value: unknown) => ReviewState;\n\nexport function reviewStateValidatorFor(engine: {\n validateReviewState?: ReviewStateValidator;\n ReviewXmlError?: typeof ReviewXmlError;\n}): ReviewStateValidator {\n if (engine.validateReviewState) return engine.validateReviewState;\n const ErrorType = engine.ReviewXmlError ?? ReviewXmlError;\n return value => validateBundledReviewState(value, ErrorType);\n}\n\nfunction validateBundledReviewState(value: unknown, ErrorType: typeof ReviewXmlError): ReviewState {\n try {\n return validateReviewState(value);\n } catch (error) {\n // The bundled subpath has its own class in published serve. Keep callers'\n // instanceof checks tied to the installed root, in both ESM and CommonJS.\n if (error instanceof BundledXmlError) {\n throw new ErrorType(error.code, error.message, {\n details: error.details,\n cause: error.cause,\n });\n }\n throw error;\n }\n}\n\ninterface RequestContract {\n decodeSuggestionApplyRequest?: typeof decodeSuggestionApplyRequest;\n MAX_CONTEXT_LINES?: number;\n}\n\nexport function requestContractFor(engine: RequestContract) {\n return {\n decode: engine.decodeSuggestionApplyRequest ?? decodeSuggestionApplyRequest,\n maxContextLines: engine.MAX_CONTEXT_LINES ?? MAX_CONTEXT_LINES,\n };\n}\n\n/** Only capabilities selected here are required. Extra root members retain their\n * inferred types and identity, including the original complete Core namespace. */\nexport type ServeEngineCapabilities = ApplyEngine &\n StartupEngine &\n RequestContract & {\n ReviewXmlError: typeof core.ReviewXmlError;\n recordResumedAttachments: typeof core.recordResumedAttachments;\n validateReviewState?: ReviewStateValidator;\n adoptResumeDocument?: typeof core.adoptResumeDocument;\n commitLoadedReview?: typeof core.commitLoadedReview;\n } & CoreCapabilityShape;\n\nfunction selectServeEngine<T extends ServeEngineCapabilities>(engine: T) {\n return {\n core: engine,\n commitLoadedReview:\n typeof engine.commitLoadedReview === 'function' ? engine.commitLoadedReview : undefined,\n compatibilityDiagnostics: coreCompatibilityDiagnostics(engine),\n resolveSource: startupSourceFor(engine),\n applySuggestion: applyFor(engine),\n validateReviewState: reviewStateValidatorFor(engine),\n requestContract: requestContractFor(engine),\n adoptResume: resumeAdopterFor(engine),\n };\n}\n// The final overload preserves the original ReturnType as well as call-site\n// inference. The alias adds no forwarding call or runtime ownership.\nexport const resolveServeEngine: {\n <T extends ServeEngineCapabilities>(engine: T): ReturnType<typeof selectServeEngine<T>>;\n (engine: typeof core): ReturnType<typeof selectServeEngine<typeof core>>;\n} = selectServeEngine;\n\n/** Original complete-root type remains available for existing consumers. */\nexport type ServeEngine = ReturnType<typeof resolveServeEngine<typeof core>>;\nexport const installedServeEngine = resolveServeEngine(core);\n\nexport interface CoreCapabilityShape {\n resolveStartupSourceAsync?: unknown;\n applySuggestionForSessionAsync?: unknown;\n loadSyntheticFilesAsync?: unknown;\n MAX_PUBLICATION_ASSET_BYTES?: unknown;\n}\n\nexport function coreCompatibilityDiagnostics(engine: CoreCapabilityShape): readonly string[] {\n const messages: string[] = [];\n if (typeof engine.resolveStartupSourceAsync !== 'function')\n messages.push(\n '[serve] Installed core uses a synchronous startup probe; it blocks the event loop and cannot be interrupted.'\n );\n if (typeof engine.applySuggestionForSessionAsync !== 'function')\n messages.push(\n '[serve] Installed core uses synchronous Apply; deadlines and shutdown may be delayed during a write. Check the destination after a lost response; never replay automatically.'\n );\n if (typeof engine.loadSyntheticFilesAsync !== 'function')\n messages.push(\n '[serve] Installed core local loading does not support the startup signal; cancellation may wait for filesystem work.'\n );\n if (typeof engine.MAX_PUBLICATION_ASSET_BYTES !== 'number')\n messages.push(\n '[serve] Installed core publication lacks the aggregate asset budget and cooperative staging cancellation. The HTTP body limit does not bound resumed assets read from disk.'\n );\n return messages;\n}\n","// Pure attachment reference policy and origin planning. No filesystem acquisition or runtime Core classes.\nimport * as path from 'node:path';\nimport type { ReviewComment } from './types';\nimport { ASSET_DIR_NAME } from './attachment-planner';\n\n/** The bare name in `.self-review-assets/<name>`; null for any other shape. */\nexport function parseAttachmentReference(reference: unknown): string | null {\n if (typeof reference !== 'string') return null;\n const prefix = `${ASSET_DIR_NAME}/`;\n if (!reference.startsWith(prefix)) return null;\n const name = reference.slice(prefix.length);\n if (name === '' || name === '.' || name === '..') return null;\n if (/[/\\\\\\0]/.test(name)) return null;\n return name;\n}\n\nexport function* attachmentLists(comments: readonly ReviewComment[]) {\n for (const comment of comments) {\n if (comment.attachments) yield { comment, attachments: comment.attachments };\n for (const reply of comment.replies ?? []) {\n if (reply.attachments) yield { comment, attachments: reply.attachments };\n }\n }\n}\n\n/** The caller supplies a physically resolved directory from its own filesystem. No lookup occurs. */\nexport function resolveAttachmentOriginsAtDirectory(\n comments: readonly ReviewComment[],\n directory: string\n): { origins: Map<string, string>; diagnostics: string[] } {\n if (!path.isAbsolute(directory))\n throw new TypeError('Attachment document directory must be absolute');\n const assetDir = path.join(directory, ASSET_DIR_NAME);\n const origins = new Map<string, string>();\n const diagnostics: string[] = [];\n for (const { comment, attachments } of attachmentLists(comments)) {\n for (const attachment of attachments) {\n const name = parseAttachmentReference(attachment.fileName);\n if (name === null) {\n diagnostics.push(\n `${comment.filePath || '(review)'}: attachment \"${attachment.fileName}\" is not in the ` +\n `document's ${ASSET_DIR_NAME} directory; it will not be loaded`\n );\n continue;\n }\n origins.set(attachment.fileName, path.join(assetDir, name));\n }\n }\n return { origins, diagnostics };\n}\n","// Pure attachment naming and document planning. Never reads or writes files.\nimport * as path from 'node:path';\nimport type { Attachment, ReviewState } from './types';\n\nfunction extFromMediaType(mediaType: string): string {\n // Same reasoning as `assetNameComponent`: anything not in the map falls\n // back to png, including a value that is not a string at all.\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\n/**\n * Reduce an id to something that can only ever name a file *inside* the asset\n * directory.\n *\n * A comment id is not trusted input. The desktop gets its ReviewState from its\n * own renderer, but the serve front end accepts a whole document over HTTP, so\n * `../../x` in an id would walk this function's write out of the asset\n * directory and onto an arbitrary path. Every id this app generates is a UUID,\n * so restricting the prefix to the URL-safe alphabet renames nothing in\n * practice and leaves existing asset names byte-identical.\n */\nfunction assetNameComponent(idPrefix: string): string {\n // Coerced rather than assumed: this runs before the document is validated\n // against anything, so a caller that omits an id reaches here with\n // `undefined`, and a bare `.replace` would turn that into a crash *after*\n // the review has already been taken off the session — losing it. The\n // serializer's job here is to name a file, not to police the document.\n return String(idPrefix ?? '').replace(/[^A-Za-z0-9_-]/g, '_');\n}\n\nexport const ASSET_DIR_NAME = '.self-review-assets';\n\nexport interface PlannedAsset {\n /** As emitted in the document: `.self-review-assets/<name>`. */\n relativePath: string;\n absolutePath: string;\n data: ArrayBuffer;\n}\n\n/**\n * `idPrefix` is already URL-safe; the result must be a bare file name. The publisher injects unique\n * names so a new document never overwrites an asset the previous one references.\n */\nexport type AssetNamer = (idPrefix: string, index: number, ext: string) => string;\n\nexport interface SerializedReview {\n /** Validated, without a trailing newline. */\n xml: string;\n /** Blobs the document references that nothing has written yet. */\n assets: PlannedAsset[];\n}\n\nexport const defaultAssetName: AssetNamer = (idPrefix, index, ext) => `${idPrefix}-${index}.${ext}`;\n\ninterface AssetLocation {\n relativePath: string;\n absolutePath: string;\n}\n\ntype AssetSource = { data: ArrayBuffer } | { origin: string; reference: string };\nexport type PublicationAsset = AssetLocation & AssetSource;\n\n/** Public serialization keeps its existing in-memory planned-asset result. */\nexport function planAttachments(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer\n): { state: ReviewState; assets: PlannedAsset[] } {\n return planDocument(state, outputFilePath, assetName, attachment =>\n attachment.data ? { data: attachment.data } : null\n );\n}\n\n/** Plan imported references without loading their bytes. Repeated origins share one new asset. */\nexport function planPublicationAttachments(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer,\n origins: ReadonlyMap<string, string>,\n targetAssetDir: string\n): { state: ReviewState; assets: PublicationAsset[] } {\n return planDocument<AssetSource>(state, outputFilePath, assetName, attachment => {\n if (attachment.data) return { data: attachment.data };\n const origin = origins.get(attachment.fileName);\n return origin === undefined || path.dirname(origin) === targetAssetDir\n ? null\n : { origin, reference: attachment.fileName };\n });\n}\n\nfunction planDocument<T extends AssetSource>(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer,\n sourceFor: (attachment: Attachment) => T | null\n): { state: ReviewState; assets: (AssetLocation & T)[] } {\n const assetDir = path.join(path.dirname(outputFilePath), ASSET_DIR_NAME);\n const assets: (AssetLocation & T)[] = [];\n const imported = new Map<string, AssetLocation & T>();\n const planList = (attachments: Attachment[] | undefined, idPrefix: string) =>\n attachments?.map((attachment, index) => {\n const source = sourceFor(attachment);\n if (source === null) return attachment;\n let asset = 'origin' in source ? imported.get(source.origin) : undefined;\n if (!asset) {\n const name = assetName(\n assetNameComponent(idPrefix),\n index,\n extFromMediaType(attachment.mediaType)\n );\n const absolutePath = path.join(assetDir, name);\n if (path.dirname(path.resolve(absolutePath)) !== path.resolve(assetDir)) {\n throw new Error(`Refusing to write an attachment outside ${assetDir}: ${name}`);\n }\n asset = { ...source, absolutePath, relativePath: `${ASSET_DIR_NAME}/${name}` };\n assets.push(asset);\n if ('origin' in source) imported.set(source.origin, asset);\n }\n return { ...attachment, fileName: asset.relativePath, data: undefined };\n });\n const files = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => ({\n ...comment,\n attachments: planList(comment.attachments, comment.id),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: planList(reply.attachments, `${comment.id}-r-${reply.id}`),\n })),\n }\n : {}),\n })),\n }));\n return { state: { ...state, files }, assets };\n}\n","// Core 2.0.4 exposes parsing and origin recording but predates adoption.\n// Remove this fallback only when every supported Core exposes adoptResumeDocument.\n// Project its public loadResumeDocument assignment contract after worker parsing.\n// Authorization and path policy remain solely in recordResumedAttachments.\nimport type * as core from '@self-review/core';\nimport type { ParsedReview, ReviewSession } from '@self-review/core';\nimport { resolveAttachmentOriginsAtDirectory } from '../../core/src/attachment-origin-plan';\n\nfunction adoptFields(\n session: ReviewSession,\n parsed: ParsedReview,\n origins: ReviewSession['attachmentOrigins'],\n diagnostics: string[]\n): ParsedReview {\n session.attachmentOrigins = origins;\n session.resumeComments = parsed.comments;\n session.resumeViewedFiles = parsed.viewedFiles;\n session.resumeImportDiagnostics = [...parsed.importDiagnostics, ...diagnostics];\n return parsed;\n}\n\n/** Pure adoption also supports installed peers without the resolved-location overload. */\nexport function adoptResumeAtDirectory(\n session: ReviewSession,\n parsed: ParsedReview,\n directory: string\n): ParsedReview {\n const { origins, diagnostics } = resolveAttachmentOriginsAtDirectory(parsed.comments, directory);\n return adoptFields(session, parsed, origins, diagnostics);\n}\n\ninterface ResumeEngine {\n adoptResumeDocument?: typeof core.adoptResumeDocument;\n recordResumedAttachments: typeof core.recordResumedAttachments;\n}\nexport function resumeAdopterFor(engine: ResumeEngine) {\n if (engine.adoptResumeDocument) return engine.adoptResumeDocument;\n const record = engine.recordResumedAttachments;\n return (session: ReviewSession, parsed: ParsedReview, path: string): ParsedReview => {\n const attachments = { attachmentOrigins: session.attachmentOrigins };\n const diagnostics = record(attachments, parsed.comments, path);\n return adoptFields(session, parsed, attachments.attachmentOrigins, diagnostics);\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { realpath } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport type { ReviewSession } from '@self-review/core';\nimport { installedServeEngine } from './engine-contract';\nimport { checkResumeOwnership, runResumeWorker } from './resume-worker-lifetime';\nimport type { ResumeWorkerOptions } from './resume-worker-lifetime';\nimport type { LocalSourcePaths } from '../../core/src/source-identity';\nimport { adoptResumeAtDirectory } from './resume-adoption-compatibility';\n\nconst nativePaths: LocalSourcePaths = {\n async realpath(directory) {\n const absolute = resolve(directory);\n // Preserve the original native canonicalization's lexical fallback.\n return realpath(absolute).catch(() => absolute);\n },\n};\nconst createParserWorker = () => new Worker(new URL('./resume-parser-worker.js', import.meta.url));\n\nasync function parseResume(path: string, options: ResumeWorkerOptions, worker: () => Worker) {\n checkResumeOwnership(options);\n const parsed = await runResumeWorker(worker(), { id: randomUUID(), path }, options);\n checkResumeOwnership(options);\n return parsed;\n}\n\n/** The entry is emitted beside cli.js; no cwd or desktop dependency. */\nexport function createResumeLoader(\n adopt = installedServeEngine.adoptResume,\n createWorker = createParserWorker\n) {\n return async (session: ReviewSession, path: string, options: ResumeWorkerOptions = {}) => {\n const parsed = await parseResume(path, options, createWorker);\n checkResumeOwnership(options);\n return adopt(session, parsed, path);\n };\n}\n\nexport function loadResumeDocumentAsync(\n session: ReviewSession,\n path: string,\n options: ResumeWorkerOptions & { paths: LocalSourcePaths }\n): Promise<Awaited<ReturnType<typeof parseResume>>>;\nexport function loadResumeDocumentAsync(\n session: ReviewSession,\n path: string,\n options?: ResumeWorkerOptions\n): Promise<Awaited<ReturnType<typeof parseResume>>>;\nexport async function loadResumeDocumentAsync(\n session: ReviewSession,\n path: string,\n options: ResumeWorkerOptions & { paths?: LocalSourcePaths } = {}\n) {\n const parsed = await parseResume(path, options, createParserWorker);\n let directory: string;\n try {\n directory = await (options.paths ?? nativePaths).realpath(dirname(path));\n } catch (error) {\n checkResumeOwnership(options);\n throw error;\n }\n checkResumeOwnership(options);\n return adoptResumeAtDirectory(session, parsed, directory);\n}\n","import type { Worker } from 'node:worker_threads';\nimport { ReviewXmlError } from '@self-review/core';\nimport type { ParsedReview, ReviewXmlErrorCode } from '@self-review/core';\nimport {\n runResumeWorker as runOwnedResumeWorker,\n restoreResumeFailure,\n} from '@self-review/core/resume-worker';\nimport type { ResumeWorkerOptions, ResumeParseRequest } from '@self-review/core/resume-worker';\nexport { checkResumeOwnership } from '@self-review/core/resume-worker';\nexport type { ResumeWorkerOptions, ResumeParseRequest } from '@self-review/core/resume-worker';\n\n// Keep the original mutable serve details field; additional diagnostics are optional.\nexport type ResumeParseReply =\n | { id: string; kind: 'parsed'; parsed: ParsedReview }\n | {\n id: string;\n kind: 'failed';\n error: {\n message: string;\n code?: string;\n details?: string[];\n name?: string;\n stack?: string;\n cause?: unknown;\n };\n };\n\nexport function runResumeWorker(\n worker: Pick<Worker, 'on' | 'off' | 'postMessage' | 'terminate'>,\n request: ResumeParseRequest,\n options: ResumeWorkerOptions = {}\n): Promise<ParsedReview> {\n return runOwnedResumeWorker(worker, request, options, failure =>\n restoreResumeFailure(\n failure,\n (code, message, options) => new ReviewXmlError(code as ReviewXmlErrorCode, message, options)\n )\n );\n}\n","import { format } from 'node:util';\n\n/** Reporter failures never change publication, transport responses or cleanup. */\nexport function nonThrowingReporter(report?: (message: string) => void) {\n return (message: string, ...details: unknown[]): void => {\n try {\n const result = report\n ? report(format(message, ...details))\n : console.error(message, ...details);\n void Promise.resolve(result).catch(() => {});\n } catch {\n // Diagnostics are observational, including asynchronously rejecting hosts.\n }\n };\n}\n","// Resolve one review session the way the desktop does. Each phase below cites\n// the phase of `initializeApp` (src/main/main.ts) it mirrors; the shared decisions are core's startup module.\n//\n// Two orderings are load-bearing: everything resolves before the caller opens\n// the listener, so no request races a half-built session; and the guide lands\n// on the session during startup, since `GET /api/diff` answers from there.\n//\n// The desktop's large-payload prompt and directory picker are native dialogs\n// with no browser equivalent, so the first becomes automatic and the second\n// becomes a startup error.\n\nimport { nonThrowingReporter } from './diagnostic-reporter';\nimport { resolve } from 'node:path';\nimport {\n commitDiffData,\n computePayloadStats,\n countTotalLines,\n createReviewSession,\n resolveOutputTarget,\n resolveStartupDiffArgs,\n} from '@self-review/core';\nimport type * as core from '@self-review/core';\nimport type { resolveCompatibleStartupSource } from './startup-compatibility';\nimport type { GitExecutionOptions, ReviewOutputTarget, ReviewSession } from '@self-review/core';\nimport type { ServeArgs } from './args';\nimport type { loadResumeDocumentAsync } from './resume-document-loader';\n\nexport interface ServeStartup {\n /** Carries the source identity every path-taking route authorizes against (audit A6). */\n session: ReviewSession;\n /** Fixed for the process lifetime. */\n output: ReviewOutputTarget;\n}\n\n/** The effects startup uses, independent of the process environment and transport. */\nexport interface StartupOperations {\n loadConfigWithProvenance: typeof core.loadConfigWithProvenance;\n inspectOutput: (output: ReviewOutputTarget) => ReturnType<typeof core.inspectOutputPath>;\n resolveSource: typeof resolveCompatibleStartupSource;\n loadLocalReview: typeof core.loadLocalReview;\n /** Selected once at composition; absent with Core 2.0.4 or original injected operations. */\n commitLoadedReview?: typeof core.commitLoadedReview;\n loadResumeDocument: typeof core.loadResumeDocument;\n /** First-party cancellable parsing. Omitted by original injected operation sets. */\n loadResumeDocumentAsync?: typeof loadResumeDocumentAsync;\n loadGuide: typeof core.loadGuide;\n}\n\nexport interface StartupHost {\n cwd: string;\n reportDiagnostic: (message: string) => void;\n operations: StartupOperations;\n}\n\n/** Throws when startup cannot produce a servable session; the caller reports and exits. */\nexport async function resolveSessionWithHost(\n args: ServeArgs,\n options: GitExecutionOptions,\n host: StartupHost\n): Promise<ServeStartup> {\n options.signal?.throwIfAborted();\n // Phase 2 (main.ts): configuration and the output path.\n const { cwd, operations, reportDiagnostic } = host;\n const report = nonThrowingReporter(reportDiagnostic);\n const log = (message: string) => report(`[serve] ${message}`);\n const loadedConfig = operations.loadConfigWithProvenance({ cwd, reportDiagnostic: report });\n const output = resolveOutputTarget(args.outputPath, loadedConfig, cwd);\n // Advisory (the publisher re-checks at submit), but refusing an output that can never be written beats serving a review with no way out.\n const problem = operations.inspectOutput(output);\n if (problem) {\n throw new Error(\n `Output path is not writable (${problem.code}): ${problem.message} ` +\n 'Pass a writable path with --output, or set output-file in .self-review.yaml.'\n );\n }\n log(`Output path: ${output.path} (${output.origin})`);\n\n // Phase 3 (main.ts): git diff arguments.\n const { gitDiffArgs, config } = resolveStartupDiffArgs(args.gitDiffArgs, loadedConfig, cwd);\n\n // Phase 4 (main.ts): what to review. Welcome mode is refused: a browser has no directory picker.\n const source = await operations.resolveSource(gitDiffArgs, cwd, options);\n log(`Startup mode: ${source.mode}`);\n if (source.mode === 'welcome') {\n throw new Error(\n 'Nothing to review: this is not a git repository and no path was given. ' +\n 'Run self-review-serve inside a git repository, or pass a directory or file to review.'\n );\n }\n const loadedReview = await operations.loadLocalReview(\n source,\n gitDiffArgs,\n config,\n cwd,\n log,\n options\n );\n const { payload: diffData, identity } = loadedReview;\n log(`Loaded ${diffData.files.length} files`);\n\n // Phase 4b (main.ts): large payload. Nobody to ask before the browser connects, so lazy loading just turns on.\n const stats = computePayloadStats(diffData.files.length, countTotalLines(diffData.files), config);\n if (stats.exceedsAny) {\n log(\n `Large payload: ${stats.fileCount} files, ${stats.totalLines} lines ` +\n `(thresholds ${config.maxFiles} files, ${config.maxTotalLines} lines) — ` +\n 'serving file contents on demand'\n );\n diffData.isLargePayload = true;\n }\n\n // Phase 5 (main.ts): resume.\n const session = createReviewSession();\n if (args.resumeFrom) {\n const resumePath = resolve(cwd, args.resumeFrom);\n try {\n if (operations.loadResumeDocumentAsync)\n await operations.loadResumeDocumentAsync(session, resumePath, options);\n else operations.loadResumeDocument(session, resumePath);\n } catch (error) {\n throw new Error(\n `Could not read the resume file ${resumePath}: ` +\n (error instanceof Error ? error.message : String(error))\n );\n }\n log(\n `Resumed ${session.resumeComments.length} comments and ` +\n `${session.resumeViewedFiles.length} viewed files from ${resumePath}`\n );\n for (const diagnostic of session.resumeImportDiagnostics) {\n log(`Resume import: ${diagnostic}`);\n }\n }\n\n // Phase 5b (main.ts): guide sidecar. It must be on the session before listening; GET /api/diff answers from there.\n const guideData = await operations.loadGuide(\n output.path,\n config,\n diffData.files.map(f => f.newPath || f.oldPath),\n { cwd, reportDiagnostic, signal: options.signal }\n );\n if (guideData) {\n log(`Walkthrough guide loaded: ${guideData.groups.length} groups`);\n }\n\n if (options.signal?.aborted) throw options.signal.reason;\n\n // Phase 6 (main.ts) — assemble. Everything the routes read is on the\n // session before the caller opens the listener.\n // commitDiffData captures the reviewed paths that authorize every apply, and the source identity.\n if (loadedReview.loadedReview && operations.commitLoadedReview)\n operations.commitLoadedReview(session, diffData, loadedReview.loadedReview);\n else commitDiffData(session, diffData, identity);\n session.guideData = guideData;\n session.config = config;\n session.outputPathInfo = { resolvedOutputPath: output.path, outputPathWritable: true };\n\n return { session, output };\n}\n","// Compatibility entry: defaults belong at the host composition edge.\nimport type { GitExecutionOptions } from '@self-review/core';\nimport type { ServeArgs } from './args';\nimport { createStartupHost } from './startup-composition';\nimport { resolveSessionWithHost, type StartupHost } from './startup-resolver';\nexport type { ServeStartup, StartupHost, StartupOperations } from './startup-resolver';\n\nexport function resolveSession(\n args: ServeArgs,\n options: GitExecutionOptions = {},\n host: StartupHost = createStartupHost()\n) {\n return resolveSessionWithHost(args, options, host);\n}\n","// Report supported installed-engine limitations without disabling capabilities.\nimport {\n installedServeEngine,\n coreCompatibilityDiagnostics,\n type CoreCapabilityShape,\n} from './engine-contract';\n\nexport function reportCoreCompatibility(\n report: (message: string) => void,\n engine?: CoreCapabilityShape\n): void {\n const messages = engine\n ? coreCompatibilityDiagnostics(engine)\n : installedServeEngine.compatibilityDiagnostics;\n for (const message of messages) report(message);\n}\n","// The HTTP contract both ends share; no Node dependency so the browser bundle can import it.\n\nimport type { ReviewPublishErrorCode } from '@self-review/core';\n\n/**\n * Upper bound on a `POST /api/review` body. The client checks it too, so an oversized review is\n * refused with the work still in the page. Attachments ride base64, about 4/3 of their bytes.\n */\nexport const MAX_REVIEW_BODY_BYTES = 32 * 1024 * 1024;\n\n/** Original plus proposed code, measured as JSON UTF-8 bytes by both ends. */\nexport const MAX_APPLY_BODY_BYTES = MAX_REVIEW_BODY_BYTES;\nexport const SUGGESTION_TOO_LARGE_CODE = 'suggestion-too-large';\n\n/** A 200 from `POST /api/review`, sent only after the document is published. */\nexport interface ReviewSubmitAck {\n ok: true;\n /** The absolute path the review was written to. */\n outputPath: string;\n}\n\n/** `POST /api/review` when publishing failed; the server stays up for a retry. */\nexport interface ReviewSubmitFailure {\n ok: false;\n /** The publisher's code; `details` has one rendered line per problem. */\n code: ReviewPublishErrorCode;\n message: string;\n details: string[];\n}\n\n/** The client's own code for a body it refused to send, and for the server's 413. */\nexport const REVIEW_TOO_LARGE_CODE = 'review-too-large';\n\n// The capability travels only in the launch URL's fragment (`/#cap=<token>`), which a browser never sends\n// (not even in `Referer`). The page moves it into `Authorization: Bearer` on every API request.\nexport const CAPABILITY_FRAGMENT_KEY = 'cap';\n\nexport const CAPABILITY_SCHEME = 'Bearer';\n\nexport function formatLaunchUrl(listenerUrl: string, capability: string): string {\n return `${listenerUrl}#${CAPABILITY_FRAGMENT_KEY}=${capability}`;\n}\n\n// Parsed as URL parameters so a browser that re-encodes the fragment is still read.\nexport function parseCapabilityFragment(hash: string): string | null {\n const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n const value = params.get(CAPABILITY_FRAGMENT_KEY);\n return value ? value : null;\n}\n\nexport function capabilityAuthorization(capability: string): string {\n return `${CAPABILITY_SCHEME} ${capability}`;\n}\n\nexport function formatMegabytes(bytes: number): string {\n return (bytes / (1024 * 1024)).toFixed(1);\n}\n\n/** Admission refuses before starting any engine operation, so retry is safe. */\nexport const SERVER_BUSY_ERROR = 'review server busy; retry after pending requests finish';\n\n/** Stable pre-admission refusal; diagnostic wording is not the modern classifier. */\nexport const SERVER_BUSY_CODE = 'server-busy';\n","// Bounded ownership of admitted work and its response. A disconnected response\n// does not release a slot until its underlying operation also settles.\nimport type * as http from 'node:http';\nimport { SERVER_BUSY_ERROR, SERVER_BUSY_CODE } from './protocol';\n\nexport const REQUEST_SHUTDOWN = Symbol('review-request-shutdown');\nexport interface ManagedReviewServer extends http.Server {\n [REQUEST_SHUTDOWN](): Promise<void>;\n}\nexport type RequestKind = 'read' | 'expensive-read' | 'mutation' | 'publication';\nexport interface AdmissionOptions {\n maxRequests?: number;\n maxExpensiveReads?: number;\n requestTimeoutMs?: number;\n}\ninterface Admitted {\n controller: AbortController;\n done: Promise<void>;\n cancelDeadline(): void;\n}\n\nexport class RequestAdmission {\n private readonly active = new Set<Admitted>();\n private expensiveReads = 0;\n private exclusive = false;\n private stopping = false;\n\n constructor(private readonly options: AdmissionOptions = {}) {\n for (const value of Object.values(options)) {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new Error('Request admission limits must be positive safe integers.');\n }\n }\n }\n\n rejection(kind: RequestKind): { status: number; error: string; code?: string } | null {\n if (this.stopping) return { status: 503, error: 'review complete; server is stopping' };\n if ((kind === 'publication' || kind === 'mutation') && this.exclusive) {\n return {\n status: 409,\n error:\n kind === 'publication'\n ? 'review submission already in progress or complete'\n : 'review source mutation or publication already in progress',\n };\n }\n if (\n this.active.size >= (this.options.maxRequests ?? 32) ||\n (kind === 'expensive-read' && this.expensiveReads >= (this.options.maxExpensiveReads ?? 8))\n ) {\n return { status: 503, error: SERVER_BUSY_ERROR, code: SERVER_BUSY_CODE };\n }\n return null;\n }\n\n run(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n kind: RequestKind,\n work: (signal: AbortSignal) => Promise<void>,\n timeout: (elapsedMs?: number) => void\n ): void {\n const started = performance.now();\n const controller = new AbortController();\n const exclusive = kind === 'publication' || kind === 'mutation';\n if (exclusive) this.exclusive = true;\n if (kind === 'expensive-read') this.expensiveReads++;\n const abort = () => controller.abort(new Error('Review request disconnected.'));\n const onClose = () => {\n if (!res.writableFinished) abort();\n };\n req.once('aborted', abort);\n res.once('close', onClose);\n const timer = setTimeout(() => {\n // Disconnect and shutdown already own cancellation; they are not deadlines.\n if (controller.signal.aborted) return;\n controller.abort(new Error('Review request deadline exceeded.'));\n timeout(Math.max(0, Math.round(performance.now() - started)));\n }, this.options.requestTimeoutMs ?? 60_000);\n const flushed = new Promise<void>(resolve => {\n const finish = () => {\n res.off('finish', finish);\n res.off('close', finish);\n resolve();\n };\n res.once('finish', finish);\n res.once('close', finish);\n });\n // Defer execution until this admission is visible to shutdown.\n const done = Promise.allSettled([\n Promise.resolve().then(() => work(controller.signal)),\n flushed,\n ]).then(() => {\n clearTimeout(timer);\n req.off('aborted', abort);\n res.off('close', onClose);\n this.active.delete(entry);\n if (exclusive) this.exclusive = false;\n if (kind === 'expensive-read') this.expensiveReads--;\n });\n const entry = { controller, done, cancelDeadline: () => clearTimeout(timer) };\n this.active.add(entry);\n }\n\n drain(): Promise<void> {\n return Promise.allSettled([...this.active].map(entry => entry.done)).then(() => {});\n }\n\n shutdown(): Promise<void> {\n this.stopping = true;\n for (const entry of this.active) {\n entry.cancelDeadline();\n entry.controller.abort(new Error('Review server is stopping.'));\n }\n return this.drain();\n }\n}\n","// One shutdown owner for startup, publication and signals. Publication is an\n// explicit event; a response status cannot prove that a file was committed.\nimport type * as http from 'node:http';\nimport { nonThrowingReporter } from './diagnostic-reporter';\nimport { REQUEST_SHUTDOWN, type ManagedReviewServer } from './request-admission';\n\nexport const REVIEW_PUBLISHED = 'review-published';\nconst SHUTDOWN_GRACE_MS = 5_000;\ntype ScheduleDeadline = (expire: () => void) => () => void;\nconst scheduleDeadline: ScheduleDeadline = expire => {\n const timer = setTimeout(expire, SHUTDOWN_GRACE_MS);\n return () => clearTimeout(timer);\n};\ninterface SignalSource {\n on(signal: 'SIGINT' | 'SIGTERM', listener: () => void): unknown;\n off(signal: 'SIGINT' | 'SIGTERM', listener: () => void): unknown;\n}\nexport interface LifecycleOptions {\n /** Observational only. Throws and rejected or pending promises never delay cleanup. */\n reportDiagnostic?: (message: string) => void;\n exit?: (code: number) => void;\n scheduleDeadline?: ScheduleDeadline;\n signals?: SignalSource;\n}\nexport interface CompletionOptions extends LifecycleOptions {\n server: http.Server;\n}\n\nexport function createServeLifecycle(options: LifecycleOptions = {}) {\n const { exit = process.exit, scheduleDeadline: schedule = scheduleDeadline, signals } = options;\n const report = nonThrowingReporter(options.reportDiagnostic);\n const controller = new AbortController();\n const pending = new Set<Promise<unknown>>();\n let server: http.Server | undefined;\n let stopping = false;\n let exited = false;\n let exitCode = 0;\n let interrupted = false;\n let cancelDeadline = () => {};\n const cleanupResponses = new Set<() => void>();\n\n const finish = () => {\n if (exited) return;\n exited = true;\n cancelDeadline();\n signals?.off('SIGINT', onInterrupt);\n signals?.off('SIGTERM', onTerminate);\n server?.off(REVIEW_PUBLISHED, onPublished);\n server?.off('listening', onListening);\n for (const cleanup of cleanupResponses) cleanup();\n cleanupResponses.clear();\n server?.closeAllConnections();\n exit(exitCode);\n };\n const maybeFinish = () => {\n if (stopping && pending.size === 0) finish();\n };\n const track = <T>(work: Promise<T>): Promise<T> => {\n pending.add(work);\n void work.then(\n () => {\n pending.delete(work);\n maybeFinish();\n },\n () => {\n pending.delete(work);\n maybeFinish();\n }\n );\n return work;\n };\n const drainServer = () => {\n server?.close();\n const managed = server as Partial<ManagedReviewServer> | undefined;\n if (managed?.[REQUEST_SHUTDOWN]) track(managed[REQUEST_SHUTDOWN]());\n };\n const stop = (code: number) => {\n if (exited) return;\n if (code === 130 || code === 143) {\n interrupted = true;\n exitCode = code;\n } else if (!interrupted) exitCode = code;\n if (stopping) return;\n stopping = true;\n // Cancellation never rolls back a publication that has already committed.\n controller.abort(new Error('Review server is stopping.'));\n cancelDeadline = schedule(() => {\n report(\n '[serve] Shutdown deadline reached; closing remaining connections and waiting for owned work.'\n );\n server?.closeAllConnections();\n maybeFinish();\n });\n drainServer();\n maybeFinish();\n };\n function onInterrupt() {\n stop(130);\n }\n function onTerminate() {\n stop(143);\n }\n function onListening() {\n if (stopping) server?.close();\n }\n function onPublished(response: http.ServerResponse, drain?: () => Promise<void>) {\n const cleanup = () => {\n response.off('finish', complete);\n response.off('close', complete);\n cleanupResponses.delete(cleanup);\n };\n const complete = () => {\n cleanup();\n report('[serve] Review complete; stopping.');\n // Older servers hand ownership over through the event instead of the symbol.\n if (drain && !(server as Partial<ManagedReviewServer> | undefined)?.[REQUEST_SHUTDOWN])\n track(drain());\n stop(0);\n };\n cleanupResponses.add(cleanup);\n response.once('finish', complete);\n response.once('close', complete);\n if (response.writableFinished || response.destroyed) complete();\n }\n signals?.on('SIGINT', onInterrupt);\n signals?.on('SIGTERM', onTerminate);\n return {\n signal: controller.signal,\n track,\n stop,\n attach(value: http.Server) {\n server = value;\n server.on(REVIEW_PUBLISHED, onPublished);\n server.on('listening', onListening);\n if (stopping) drainServer();\n },\n };\n}\n\n/** Compatibility call form for embedders that attach completion after construction. */\nexport function completeReviewOnSubmit(options: CompletionOptions): void {\n createServeLifecycle(options).attach(options.server);\n}\n","// Nine JSON routes over one ReviewSession, each a thin wrapper over a function\n// core already exports, plus static serving for the client bundle. node:http,\n// no framework.\n//\n// Three properties are load-bearing: every route validates before core runs; the listener both binds\n// to loopback and refuses requests that name anything else (a web page can reach loopback, and DNS\n// rebinding would make it same-origin); and every API route requires the session capability (see ./protocol.ts).\n// `POST /api/review` publishes before it answers.\n\nimport * as http from 'node:http';\nimport { fileURLToPath } from 'node:url';\nimport type { AddressInfo } from 'node:net';\nimport { allowRequest, sendJson, sendError } from './http-transport';\nimport { serveStatic } from './static-assets';\nimport type { ReviewTransportOperations } from './review-operations';\nimport { nonThrowingReporter } from './diagnostic-reporter';\nimport { ReviewSubmission } from './review-submission';\nimport { createBoundApiRoutes } from './bound-api-routes';\nimport { bindRouteValidation, bindSelectedRouteValidation } from './route-composition';\nexport { MAX_EXPAND_CONTEXT_BODY_BYTES } from './api-routes';\nimport {\n RequestAdmission,\n REQUEST_SHUTDOWN,\n type AdmissionOptions,\n type ManagedReviewServer,\n type RequestKind,\n} from './request-admission';\nimport { JsonResponseLimitError } from './json-response';\nimport { JsonBodyProcessing } from './json-body-processing';\nimport { REVIEW_PUBLISHED } from './lifecycle';\n\nexport { MAX_REVIEW_BODY_BYTES } from './protocol';\n\n// Resolved on demand: import.meta.url is not a file URL in the browser-like test environment.\nexport function defaultClientDir(): string {\n return fileURLToPath(new URL('./client/', import.meta.url));\n}\n\nexport interface ReviewTransportOptions extends AdmissionOptions {\n /** Bearer token required on every API request; never returned by the server. */\n capability: string;\n /** Host-owned byte decoder. The default uses the bundled Node worker. */\n jsonBodyProcessing?: JsonBodyProcessing;\n clientDir?: string;\n /** Accepted sockets, including idle peers and incomplete HTTP headers. */\n maxConnections?: number;\n /** Transport and submission messages; defaults to stderr. Reporter failures do not change outcomes. */\n reportDiagnostic?: (message: string) => void;\n}\n/** Transport accepts already bound reads and an explicit publication role. */\nexport interface PublicationReviewServerOptions extends ReviewTransportOptions {\n operations: ReviewTransportOperations;\n publication: import('./review-submission').PublicationOperations;\n}\n\n/** No session, output path or engine construction belongs to this transport. */\nexport function createBoundReviewServer(\n options: PublicationReviewServerOptions\n): ManagedReviewServer {\n return serveBoundReview(options, bindRouteValidation(options.operations));\n}\n\n/** Complete first-party composition, with no unrelated-engine validation fallback. */\nexport function createValidatedReviewServer(\n options: Omit<PublicationReviewServerOptions, 'operations'> & {\n operations: import('./review-operations').ValidatedReviewOperations;\n }\n): ManagedReviewServer {\n return serveBoundReview(options, bindSelectedRouteValidation(options.operations));\n}\n\nfunction serveBoundReview(\n options: PublicationReviewServerOptions,\n validation: import('./validate').RequestValidation\n): ManagedReviewServer {\n const { capability, clientDir = defaultClientDir(), operations } = options;\n const report = nonThrowingReporter(options.reportDiagnostic);\n const maxConnections = options.maxConnections ?? 64;\n if (!Number.isSafeInteger(maxConnections) || maxConnections < 1) {\n throw new Error('Connection limit must be a positive safe integer.');\n }\n const submission = new ReviewSubmission(\n { publication: options.publication },\n options.reportDiagnostic\n );\n const admission = new RequestAdmission({\n maxRequests: options.maxRequests,\n maxExpensiveReads: options.maxExpensiveReads,\n requestTimeoutMs: options.requestTimeoutMs,\n });\n const published = (response: http.ServerResponse) =>\n server.emit(REVIEW_PUBLISHED, response, () => admission.drain());\n\n const processing = options.jsonBodyProcessing ?? new JsonBodyProcessing();\n const routes = createBoundApiRoutes(operations, submission, published, validation, processing);\n const routeMethods = new Map<string, string[]>();\n for (const key of Object.keys(routes)) {\n const [method, path] = key.split(' ');\n const methods = routeMethods.get(path) ?? [];\n methods.push(method);\n routeMethods.set(path, methods);\n }\n const reportDeadline = (kind: RequestKind, elapsedMs: number) =>\n report(`[serve] Request deadline exceeded: kind=${kind} elapsedMs=${elapsedMs}`);\n\n const dispatch = async (req: http.IncomingMessage, res: http.ServerResponse) => {\n const method = req.method ?? 'GET';\n let url: URL;\n try {\n url = new URL(req.url ?? '/', 'http://localhost');\n } catch {\n sendError(res, 400, 'malformed request URL');\n return;\n }\n\n if (!allowRequest(req, res, url, capability)) return;\n if (submission.completed) {\n sendError(res, 503, 'review complete; server is stopping');\n return;\n }\n\n try {\n const route = routes[`${method} ${url.pathname}`];\n if (route) {\n const { kind, handle } = route;\n const rejection = admission.rejection(kind);\n if (rejection) {\n sendJson(\n res,\n rejection.status,\n { error: rejection.error, ...(rejection.code ? { code: rejection.code } : {}) },\n { connection: 'close' }\n );\n return;\n }\n admission.run(\n req,\n res,\n kind,\n async signal => {\n try {\n await handle({ req, res, url, signal });\n } catch (error) {\n if (!signal.aborted) report(`[serve] ${method} ${url.pathname} failed:`, error);\n if (!res.headersSent && !res.destroyed)\n sendError(\n res,\n error instanceof JsonResponseLimitError ? 413 : 500,\n error instanceof JsonResponseLimitError ? error.message : 'internal error'\n );\n else if (!res.writableEnded) res.destroy();\n }\n },\n (elapsedMs = 0) => {\n reportDeadline(kind, elapsedMs);\n if (!res.headersSent && !res.destroyed)\n sendJson(\n res,\n 503,\n { error: 'request deadline exceeded; operation outcome may be unknown' },\n { connection: 'close' }\n );\n else if (!res.writableEnded) res.destroy();\n }\n );\n } else if (routeMethods.has(url.pathname)) {\n sendJson(\n res,\n 405,\n { error: 'method not allowed' },\n { allow: routeMethods.get(url.pathname)!.join(', ') }\n );\n } else if (url.pathname.startsWith('/api/')) {\n sendError(res, 404, 'not found');\n } else if (method === 'GET') {\n const rejection = admission.rejection('read');\n if (rejection) {\n sendJson(\n res,\n rejection.status,\n { error: rejection.error, ...(rejection.code ? { code: rejection.code } : {}) },\n { connection: 'close' }\n );\n return;\n }\n admission.run(\n req,\n res,\n 'read',\n async signal => {\n try {\n await serveStatic(res, clientDir, url.pathname, { signal });\n } catch (error) {\n if (!signal.aborted) report(`[serve] ${method} ${url.pathname} failed:`, error);\n if (!res.headersSent && !res.destroyed) sendError(res, 500, 'internal error');\n else res.destroy();\n }\n },\n (elapsedMs = 0) => {\n reportDeadline('read', elapsedMs);\n res.destroy();\n }\n );\n } else {\n sendError(res, 404, 'not found');\n }\n } catch (error) {\n report(`[serve] ${method} ${url.pathname} failed:`, error);\n if (!res.headersSent) {\n sendError(res, 500, 'internal error');\n } else {\n res.end();\n }\n }\n };\n\n const server = http.createServer((req, res) => {\n void dispatch(req, res);\n }) as ManagedReviewServer;\n server[REQUEST_SHUTDOWN] = () =>\n Promise.all([admission.shutdown(), processing.shutdown()]).then(() => {});\n // node:net closes excess sockets before HTTP parses any request bytes.\n server.maxConnections = maxConnections;\n server.headersTimeout = 15_000;\n server.requestTimeout = 60_000;\n return server;\n}\n\n/**\n * The address is fixed here, not left to the caller: never `0.0.0.0`, never the\n * default. Port 0 asks the OS for an ephemeral one.\n */\nexport function listenLoopback(\n server: http.Server,\n port = 0,\n options: { signal?: AbortSignal } = {}\n): Promise<{ port: number; url: string }> {\n return new Promise((resolve, reject) => {\n const { signal } = options;\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const cleanup = () => {\n signal?.removeEventListener('abort', onAbort);\n server.off('error', onError);\n server.off('listening', onListening);\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onAbort = () => {\n cleanup();\n server.close();\n reject(signal?.reason);\n };\n const onListening = () => {\n cleanup();\n if (signal?.aborted) {\n server.close();\n reject(signal.reason);\n return;\n }\n const address = server.address() as AddressInfo;\n resolve({ port: address.port, url: `http://127.0.0.1:${address.port}/` });\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen({ port, host: '127.0.0.1', signal });\n });\n}\n","import { Worker } from 'node:worker_threads';\nimport type { JsonBodyResult } from './json-body-codec';\nimport { decodeJsonWorkerReply, type JsonWorkerReply } from './json-body-transfer';\nimport { MAX_REVIEW_BODY_BYTES } from './protocol';\n\nexport const INLINE_JSON_BODY_BYTES = 128 * 1024;\nfunction unreadableBody(): JsonBodyResult {\n return { ok: false, status: 400, error: 'request body could not be read' };\n}\nexport interface JsonBodyLease {\n signal: AbortSignal;\n parse(chunks: ArrayBuffer[], signal: AbortSignal): Promise<JsonBodyResult>;\n release(): void;\n}\n/** A worker owns decoding/parsing only. Its host joins termination before releasing admission. */\nexport type JsonParserWorker = Pick<Worker, 'on' | 'off' | 'postMessage' | 'terminate'>;\nexport async function parseInJsonWorker(\n worker: JsonParserWorker,\n chunks: ArrayBuffer[],\n signal: AbortSignal\n): Promise<JsonBodyResult> {\n let reply!: (value: JsonWorkerReply) => void;\n const outcome = new Promise<JsonWorkerReply>(resolve => {\n reply = resolve;\n });\n let exited!: () => void;\n const exit = new Promise<void>(resolve => {\n exited = resolve;\n });\n const onMessage = (result: JsonWorkerReply) => reply(result);\n const onError = () => reply(unreadableBody());\n const onExit = () => {\n exited();\n reply(unreadableBody());\n };\n const onAbort = () => reply(unreadableBody());\n worker.on('message', onMessage);\n worker.on('error', onError);\n worker.on('exit', onExit);\n signal.addEventListener('abort', onAbort, { once: true });\n try {\n if (signal.aborted) onAbort();\n else {\n try {\n worker.postMessage(chunks, chunks);\n } catch {\n onError();\n }\n }\n const result = await outcome;\n try {\n await worker.terminate();\n } catch {\n // A failed terminate does not prove the worker stopped. Retain ownership until exit.\n await exit;\n return unreadableBody();\n }\n return signal.aborted ? unreadableBody() : decodeJsonWorkerReply(result);\n } finally {\n worker.off('message', onMessage);\n worker.off('error', onError);\n worker.off('exit', onExit);\n signal.removeEventListener('abort', onAbort);\n }\n}\n\n/** Two reservations, at most 64 MiB of admitted input, and no waiting queue.\n * Reservations include collecting bodies and workers whose termination is still pending.\n */\nexport class JsonBodyProcessing {\n private readonly active = new Set<{\n controller: AbortController;\n done: Promise<void>;\n }>();\n private reservedBytes = 0;\n private stopping = false;\n constructor(\n private readonly createWorker: () => JsonParserWorker = () =>\n new Worker(new URL('./json-body-worker.js', import.meta.url))\n ) {}\n\n reserve(maxBytes: number): JsonBodyLease | null {\n if (\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 1 ||\n this.stopping ||\n this.active.size >= 2 ||\n this.reservedBytes + maxBytes > 2 * MAX_REVIEW_BODY_BYTES\n )\n return null;\n const controller = new AbortController();\n let releaseDone!: () => void;\n const done = new Promise<void>(resolve => {\n releaseDone = resolve;\n });\n const entry = { controller, done };\n this.active.add(entry);\n this.reservedBytes += maxBytes;\n let parsing = false;\n let released = false;\n const release = () => {\n if (released || parsing) return;\n released = true;\n this.active.delete(entry);\n this.reservedBytes -= maxBytes;\n releaseDone();\n };\n return {\n signal: controller.signal,\n parse: async (chunks, signal) => {\n if (released || parsing) throw new Error('JSON body reservation is no longer available.');\n parsing = true;\n try {\n const combined = AbortSignal.any([controller.signal, signal]);\n if (combined.aborted) return unreadableBody();\n return await parseInJsonWorker(this.createWorker(), chunks, combined);\n } finally {\n parsing = false;\n release();\n }\n },\n release,\n };\n }\n\n shutdown(): Promise<void> {\n this.stopping = true;\n for (const entry of this.active) entry.controller.abort();\n return Promise.all([...this.active].map(entry => entry.done)).then(() => {});\n }\n}\n\nexport const defaultJsonBodyProcessing = new JsonBodyProcessing();\n","// The session capability. Host/Origin checks cannot tell the reviewer from another local account\n// (loopback is shared and a local client can send no browser headers); this secret can.\n// The browser side of the contract is in ./protocol.ts.\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\n\nexport function generateCapability(): string {\n return randomBytes(32).toString('base64url');\n}\n\n// Constant-time once lengths agree; every capability has the same length, so the length check leaks nothing.\nexport function capabilityMatches(expected: string, presented: string): boolean {\n const a = Buffer.from(expected, 'utf-8');\n const b = Buffer.from(presented, 'utf-8');\n return a.length === b.length && timingSafeEqual(a, b);\n}\n","// HTTP security, responses and bounded JSON decoding. No review policy lives here.\n\nimport { decodeJsonBody, type JsonBodyResult } from './json-body-codec';\nimport {\n defaultJsonBodyProcessing,\n INLINE_JSON_BODY_BYTES,\n type JsonBodyProcessing,\n type JsonBodyLease,\n} from './json-body-processing';\nimport { SERVER_BUSY_ERROR } from './protocol';\nimport type * as http from 'node:http';\nimport { capabilityMatches } from './capability';\nimport { CAPABILITY_SCHEME } from './protocol';\n\n/**\n * The page renders the diff under review, which is the least trusted input the\n * program handles. Rendered content is sanitized before it becomes elements;\n * this is the second line, for whatever gets past that.\n *\n * Inline styles are allowed because index.html carries a <style> block and\n * bundled libraries inject at runtime; blob: because attachments display\n * through createObjectURL.\n */\nconst CSP = [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob:\",\n \"font-src 'self' data:\",\n \"connect-src 'self'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"object-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"frame-ancestors 'none'\",\n].join('; ');\n\nexport const SECURITY_HEADERS: http.OutgoingHttpHeaders = {\n 'content-security-policy': CSP,\n 'x-content-type-options': 'nosniff',\n 'x-frame-options': 'DENY',\n 'referrer-policy': 'no-referrer',\n};\n\n/** A browser may resolve the printed URL either way, or prefer IPv6. */\nconst LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(['127.0.0.1', 'localhost', '[::1]']);\n\n/** Lowercased, with an explicit `:80` dropped so it matches the bare host. */\nfunction normalizeHost(value: string): string {\n const lowered = value.toLowerCase();\n return lowered.endsWith(':80') ? lowered.slice(0, -3) : lowered;\n}\n\n/**\n * A rebound request — an attacker's name re-resolved to 127.0.0.1 after the\n * page loads — still carries that name in `Host`, which is what distinguishes\n * it from a real one.\n *\n * The port is deliberately not compared against the bound port: an `ssh -L`\n * forward arrives carrying the forward's port, and refusing that would break\n * the use case this package exists for. It would buy nothing either, since a\n * rebound request fails on the hostname first.\n *\n * A duplicate `Host` is refused, not resolved: Node reads the first, and an\n * intermediary forwarding the last would be reading a different request.\n */\nfunction hostIsLoopback(req: http.IncomingMessage): boolean {\n const host = req.headers.host;\n if (host === undefined) return false;\n\n let seen = 0;\n for (let i = 0; i < req.rawHeaders.length; i += 2) {\n if (req.rawHeaders[i].toLowerCase() === 'host') seen++;\n }\n if (seen !== 1) return false;\n\n // Split the optional port off, keeping an IPv6 literal's brackets.\n const match = /^(\\[[^\\]]*\\]|[^:]*)(?::(\\d+))?$/.exec(host);\n if (match === null) return false;\n return LOOPBACK_HOSTNAMES.has(match[1].toLowerCase());\n}\n\n/**\n * A missing `Origin` is allowed — navigations and curl send none. Rejected is\n * an `Origin` naming a different authority than `Host`, including the `null` a\n * sandboxed frame sends.\n *\n * Comparing against `Host` rather than a loopback allowlist is what survives a\n * port forward while still refusing another local page: a dev server on :3000\n * sends its own origin and this listener's host, and those differ.\n */\nfunction originMatchesHost(req: http.IncomingMessage): boolean {\n const origin = req.headers.origin;\n if (origin === undefined) return true;\n const host = req.headers.host;\n if (host === undefined) return false;\n let parsed: URL;\n try {\n parsed = new URL(origin);\n } catch {\n return false;\n }\n if (parsed.protocol !== 'http:') return false;\n // `new URL` parses away userinfo, paths and leading-zero ports, any of which\n // would compare equal to this authority. A browser sends none of them.\n if (origin !== `${parsed.protocol}//${parsed.host}`) return false;\n return normalizeHost(parsed.host) === normalizeHost(host);\n}\n\n/**\n * Set by the browser, unforgeable by page script. A cross-site *GET* — an <img>\n * aimed at this port — carries no `Origin`, so without this it would be served\n * and only the absence of CORS headers would stop the page reading it.\n *\n * Non-browser clients send no such header and are unaffected.\n */\nfunction fetchSiteIsSelf(req: http.IncomingMessage): boolean {\n const site = req.headers['sec-fetch-site'];\n if (site === undefined) return true;\n return site === 'same-origin' || site === 'none';\n}\n\nexport function sendJson(\n res: http.ServerResponse,\n status: number,\n value: unknown,\n headers: http.OutgoingHttpHeaders = {}\n): void {\n // Serialize before headers so a failure can still produce a useful error.\n const text = JSON.stringify(value ?? null);\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...SECURITY_HEADERS,\n ...headers,\n });\n // `JSON.stringify(undefined)` is undefined; a void core result becomes `null`.\n res.end(text);\n}\n\nexport function sendError(res: http.ServerResponse, status: number, error: string): void {\n // A body that blew the cap is not read further; close the connection rather\n // than let the rest of it be reinterpreted as a next request.\n sendJson(res, status, { error }, status === 413 ? { connection: 'close' } : {});\n}\n\n// Header only: a token in the query string would land in history and logs.\nfunction presentsCapability(req: http.IncomingMessage, capability: string): boolean {\n const header = req.headers.authorization;\n if (header === undefined) return false;\n const space = header.indexOf(' ');\n if (space === -1) return false;\n if (header.slice(0, space).toLowerCase() !== CAPABILITY_SCHEME.toLowerCase()) return false;\n return capabilityMatches(capability, header.slice(space + 1).trim());\n}\n\nfunction sendUnauthorized(res: http.ServerResponse): void {\n sendJson(res, 401, { error: 'unauthorized' }, { 'www-authenticate': CAPABILITY_SCHEME });\n}\n\n/** Security checks precede route lookup and operation admission. */\nexport function allowRequest(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n url: URL,\n capability: string\n): boolean {\n if (!hostIsLoopback(req) || !originMatchesHost(req) || !fetchSiteIsSelf(req)) {\n sendError(res, 403, 'forbidden');\n return false;\n }\n if (url.pathname.startsWith('/api/') && !presentsCapability(req, capability)) {\n sendUnauthorized(res);\n return false;\n }\n return true;\n}\n\ntype BodyResult = JsonBodyResult;\n\n/** Original reflected call contract remains the three-argument form. */\nexport function readJsonBody(\n req: http.IncomingMessage,\n maxBytes: number,\n signal: AbortSignal | undefined,\n processing: JsonBodyProcessing\n): Promise<BodyResult>;\nexport function readJsonBody(\n req: http.IncomingMessage,\n maxBytes: number,\n signal?: AbortSignal\n): Promise<BodyResult>;\n/** Length checks precede allocation; large bodies reserve worker ownership while collecting. */\nexport async function readJsonBody(\n req: http.IncomingMessage,\n maxBytes: number,\n signal?: AbortSignal,\n processing: JsonBodyProcessing = defaultJsonBodyProcessing\n): Promise<BodyResult> {\n const contentType = req.headers['content-type'] ?? '';\n if (contentType.split(';', 1)[0].trim().toLowerCase() !== 'application/json') {\n return { ok: false, status: 415, error: 'content-type must be application/json' };\n }\n const declared = Number(req.headers['content-length']);\n if (Number.isFinite(declared) && declared > maxBytes) {\n return { ok: false, status: 413, error: 'request body too large' };\n }\n const chunks: Uint8Array<ArrayBuffer>[] = [];\n let received = 0;\n let tailBytes = 0;\n const ownership: { lease: JsonBodyLease | null } = { lease: null };\n const cancelled = new AbortController();\n const unreadable: BodyResult = {\n ok: false,\n status: 400,\n error: 'request body could not be read',\n };\n let collected!: (result: BodyResult | null) => void;\n const collection = new Promise<BodyResult | null>(resolve => {\n collected = resolve;\n });\n let reading = true;\n const finishCollection = (result: BodyResult | null) => {\n if (!reading) return;\n reading = false;\n req.off('data', onData);\n req.off('end', onEnd);\n collected(result);\n };\n const onError = () => {\n cancelled.abort();\n finishCollection(unreadable);\n };\n const onData = (chunk: Buffer) => {\n received += chunk.length;\n if (received > maxBytes) {\n finishCollection({ ok: false, status: 413, error: 'request body too large' });\n return;\n }\n if (!ownership.lease && received > INLINE_JSON_BODY_BYTES) {\n ownership.lease = processing.reserve(maxBytes);\n if (!ownership.lease) {\n finishCollection({ ok: false, status: 503, error: SERVER_BUSY_ERROR });\n return;\n }\n ownership.lease.signal.addEventListener('abort', onError, { once: true });\n if (ownership.lease.signal.aborted) {\n onError();\n return;\n }\n }\n // Fixed-size owned blocks bound the transfer list even for one-byte stream chunks.\n // Copies are incremental; there is no main-thread full-body concatenation or clone.\n let offset = 0;\n while (offset < chunk.length) {\n let tail = chunks[chunks.length - 1];\n if (!tail || tailBytes === tail.length) {\n tail = new Uint8Array(64 * 1024);\n chunks.push(tail);\n tailBytes = 0;\n }\n const length = Math.min(tail.length - tailBytes, chunk.length - offset);\n tail.set(chunk.subarray(offset, offset + length), tailBytes);\n tailBytes += length;\n offset += length;\n }\n };\n const onEnd = () => finishCollection(null);\n try {\n if (signal?.aborted) return unreadable;\n req.on('data', onData);\n req.once('end', onEnd);\n req.on('error', onError);\n req.once('aborted', onError);\n signal?.addEventListener('abort', onError, { once: true });\n const failure = await collection;\n if (failure) return failure;\n if (cancelled.signal.aborted) return unreadable;\n const last = chunks.length - 1;\n if (last >= 0 && tailBytes < chunks[last].length)\n chunks[last] = chunks[last].slice(0, tailBytes);\n const result = ownership.lease\n ? await ownership.lease.parse(\n chunks.map(chunk => chunk.buffer),\n cancelled.signal\n )\n : decodeJsonBody(chunks);\n return cancelled.signal.aborted ? unreadable : result;\n } finally {\n req.off('data', onData);\n req.off('end', onEnd);\n req.off('error', onError);\n req.off('aborted', onError);\n signal?.removeEventListener('abort', onError);\n ownership.lease?.signal.removeEventListener('abort', onError);\n ownership.lease?.release();\n chunks.length = 0;\n }\n}\n","// Contained static bundle delivery.\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type * as http from 'node:http';\nimport { once } from 'node:events';\nimport { containPathAsync, isUnavailablePathError } from './contained-path';\nimport { SECURITY_HEADERS, sendError } from './http-transport';\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.txt': 'text/plain; charset=utf-8',\n};\n\n// Bundled scripts, styles and fonts fit comfortably within this per-file limit.\nexport const MAX_STATIC_ASSET_BYTES = 32 * 1024 * 1024;\nexport const STATIC_READ_CHUNK_BYTES = 64 * 1024;\n\n/**\n * `/` is index.html; everything else is contained under the client directory.\n * Anything that is not a regular file under it is a 404.\n */\nexport async function serveStatic(\n res: http.ServerResponse,\n clientDir: string,\n pathname: string,\n options: { signal?: AbortSignal } = {}\n): Promise<void> {\n let decoded: string;\n try {\n decoded = decodeURIComponent(pathname);\n } catch {\n sendError(res, 404, 'not found');\n return;\n }\n if (decoded.includes('\\0')) {\n sendError(res, 404, 'not found');\n return;\n }\n const relative = decoded === '/' ? 'index.html' : decoded.replace(/^\\/+/, '');\n const controller = new AbortController();\n const abort = () => controller.abort(new Error('Static delivery cancelled.'));\n options.signal?.addEventListener('abort', abort, { once: true });\n res.once('close', abort);\n if (options.signal?.aborted || res.destroyed) abort();\n const { signal } = controller;\n let file: fs.promises.FileHandle | undefined;\n try {\n signal.throwIfAborted();\n const resolved = await containPathAsync(clientDir, relative, { signal });\n signal.throwIfAborted();\n if (resolved === null) {\n sendError(res, 404, 'not found');\n return;\n }\n file = await fs.promises.open(\n resolved,\n fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK\n );\n signal.throwIfAborted();\n const stat = await file.stat();\n signal.throwIfAborted();\n const named = await fs.promises.lstat(resolved);\n signal.throwIfAborted();\n // Recheck containment and inode after opening. Never reopen the file for reading.\n if (\n !stat.isFile() ||\n stat.dev !== named.dev ||\n stat.ino !== named.ino ||\n named.isSymbolicLink() ||\n (await containPathAsync(clientDir, relative, { signal })) !== resolved ||\n (await fs.promises.realpath(resolved)) !== resolved\n ) {\n sendError(res, 404, 'not found');\n return;\n }\n signal.throwIfAborted();\n if (stat.size > MAX_STATIC_ASSET_BYTES) {\n sendError(res, 413, 'static asset exceeds 32 MiB limit');\n return;\n }\n\n let position = 0;\n // Read only the original range: growth cannot exceed Content-Length or the size policy.\n while (position < stat.size) {\n signal.throwIfAborted();\n const buffer = Buffer.allocUnsafe(Math.min(STATIC_READ_CHUNK_BYTES, stat.size - position));\n const { bytesRead } = await file.read({ buffer, position });\n signal.throwIfAborted();\n if (bytesRead === 0) throw new Error('Static asset shortened during delivery.');\n if (!res.headersSent) writeHeaders();\n position += bytesRead;\n if (!res.write(buffer.subarray(0, bytesRead))) await once(res, 'drain', { signal });\n }\n signal.throwIfAborted();\n if (!res.headersSent) writeHeaders();\n res.end();\n\n function writeHeaders() {\n res.writeHead(200, {\n 'content-type':\n CONTENT_TYPES[path.extname(resolved!).toLowerCase()] ?? 'application/octet-stream',\n 'content-length': stat.size,\n ...SECURITY_HEADERS,\n });\n }\n } catch (error) {\n // A failed stream must never end as a successful, truncated response.\n if (signal.aborted) res.destroy();\n else if (isUnavailablePathError(error)) {\n if (res.headersSent) res.destroy();\n else sendError(res, 404, 'not found');\n } else {\n // The transport owns reporting and its generic 500 response.\n throw error;\n }\n } finally {\n options.signal?.removeEventListener('abort', abort);\n res.off('close', abort);\n // Admission retains the work slot until this close has completed.\n await file?.close();\n }\n}\n","// Filesystem containment for static bundle delivery. Reviewed paths use core authorization.\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/** Missing names and invalid path components are ordinary unavailable assets. */\nexport function isUnavailablePathError(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n return code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP' || code === 'ENAMETOOLONG';\n}\n\n/** Realpath the deepest existing ancestor, so a deleted file still resolves. */\nfunction realpathDeepestExisting(absolute: string): string | null {\n const missing: string[] = [];\n let current = absolute;\n for (;;) {\n try {\n const real = fs.realpathSync(current);\n return missing.length === 0 ? real : path.join(real, ...missing);\n } catch (error) {\n if (!isUnavailablePathError(error)) throw error;\n if ((error as NodeJS.ErrnoException).code === 'ELOOP') return null;\n const parent = path.dirname(current);\n if (parent === current) {\n return null;\n }\n missing.unshift(path.basename(current));\n current = parent;\n }\n }\n}\n\n/**\n * Resolve `candidate` under `root`, or null if it escapes. For the client bundle and attachments only;\n * reviewed diff paths go through core's `authorizeReviewedPath`.\n *\n * Never decode here: callers pass a value `searchParams` already decoded once,\n * and decoding again turns `%2E%2E%2F` inside a filename into a real traversal.\n */\nexport function containPath(root: string, candidate: string): string | null {\n let resolvedRoot: string;\n try {\n resolvedRoot = fs.realpathSync(root);\n } catch (error) {\n if (!isUnavailablePathError(error)) throw error;\n return null;\n }\n\n // Realpath both sides so a symlink inside the repository cannot escape it.\n const resolved = realpathDeepestExisting(path.resolve(resolvedRoot, candidate));\n if (resolved === null) {\n return null;\n }\n\n if (resolved === resolvedRoot) {\n return resolved;\n }\n // Root plus separator, not a bare prefix: `/repo-evil` is not under `/repo`.\n const rootWithSep = resolvedRoot.endsWith(path.sep) ? resolvedRoot : resolvedRoot + path.sep;\n return resolved.startsWith(rootWithSep) ? resolved : null;\n}\n\n/** Async static-request inspection. Each failed lookup removes one path component;\n * no directory enumeration or detached I/O. Cancellation joins the pending syscall.\n * Native metadata work itself is not preemptible.\n */\nexport async function containPathAsync(\n root: string,\n candidate: string,\n options: { signal?: AbortSignal } = {}\n): Promise<string | null> {\n const { signal } = options;\n async function realpath(name: string): Promise<string> {\n signal?.throwIfAborted();\n const resolved = await fs.promises.realpath(name);\n signal?.throwIfAborted();\n return resolved;\n }\n let resolvedRoot: string;\n try {\n resolvedRoot = await realpath(root);\n } catch (error) {\n signal?.throwIfAborted();\n if (!isUnavailablePathError(error)) throw error;\n return null;\n }\n const missing: string[] = [];\n let current = path.resolve(resolvedRoot, candidate);\n for (;;) {\n signal?.throwIfAborted();\n try {\n const ancestor = await realpath(current);\n const resolved = path.join(ancestor, ...missing.reverse());\n const rootWithSep = resolvedRoot.endsWith(path.sep) ? resolvedRoot : resolvedRoot + path.sep;\n return resolved === resolvedRoot || resolved.startsWith(rootWithSep) ? resolved : null;\n } catch (error) {\n signal?.throwIfAborted();\n if (!isUnavailablePathError(error)) throw error;\n if ((error as NodeJS.ErrnoException).code === 'ELOOP') return null;\n const parent = path.dirname(current);\n if (parent === current) return null;\n missing.push(path.basename(current));\n current = parent;\n }\n }\n}\n","// One-shot publication admission and recoverable error policy, independent of HTTP.\n\nimport { ReviewPublishError } from '@self-review/core';\nimport type { ReviewState, ReviewPublishErrorCode } from '@self-review/core';\nimport type { ReviewSubmitAck, ReviewSubmitFailure } from './protocol';\nimport { legacyPublication } from './legacy-submission';\nimport { nonThrowingReporter } from './diagnostic-reporter';\n\n/** A publisher resolves only after commit; a refusal throws without replacing the previous file. */\nexport interface PublicationOperations {\n /** Optional for original operation sets; selected with the engine that publishes. */\n publicationError?: typeof ReviewPublishError;\n publishReview: (\n state: ReviewState,\n options?: { signal?: AbortSignal }\n ) => Promise<{ outputPath: string }>;\n}\n\n/** Original handoff/publication contract, including handoff side effects and ordering. */\nexport interface SubmissionOperations extends PublicationOperations {\n submitReviewState: (state: ReviewState) => void;\n}\nexport interface PublicationRole {\n publication: PublicationOperations;\n}\n\nexport class ReviewSubmission {\n private state: 'open' | 'publishing' | 'published' = 'open';\n\n private readonly operations: PublicationOperations;\n private readonly report: ReturnType<typeof nonThrowingReporter>;\n\n constructor(operations: SubmissionOperations, reportDiagnostic?: (message: string) => void);\n constructor(role: PublicationRole, reportDiagnostic?: (message: string) => void);\n constructor(\n input: SubmissionOperations | PublicationRole,\n reportDiagnostic?: (message: string) => void\n ) {\n this.operations = 'submitReviewState' in input ? legacyPublication(input) : input.publication;\n this.report = nonThrowingReporter(reportDiagnostic);\n }\n\n get completed(): boolean {\n return this.state === 'published';\n }\n\n /** Reserve before reading the body, so overlapping uploads cannot both enter publication. */\n begin(): boolean {\n if (this.state !== 'open') return false;\n this.state = 'publishing';\n return true;\n }\n\n /** Failed parsing, publication or unexpected errors all permit a repaired submission. */\n release(): void {\n if (this.state === 'publishing') this.state = 'open';\n }\n\n async publish(\n state: ReviewState,\n options?: { signal?: AbortSignal }\n ): Promise<ReviewSubmitAck | ReviewSubmitFailure> {\n try {\n const { outputPath } = await this.operations.publishReview(state, options);\n this.state = 'published';\n this.report(`[serve] Review written to ${outputPath}`);\n return { ok: true, outputPath };\n } catch (error) {\n if (!(error instanceof (this.operations.publicationError ?? ReviewPublishError))) throw error;\n this.report(`[serve] Review not saved (${error.code}): ${error.message}`);\n for (const detail of error.details) this.report(`[serve] ${detail}`);\n this.report(\n '[serve] The review is still open in the browser. Fix the problem and press Finish Review again.'\n );\n return { ok: false, code: error.code, message: error.message, details: [...error.details] };\n }\n }\n}\n\nconst DOCUMENT_ERROR_CODES: ReadonlySet<ReviewPublishErrorCode> = new Set([\n 'validation-failed',\n 'xml-illegal-character',\n]);\n\nexport function publishFailureStatus(code: ReviewPublishErrorCode): number {\n return DOCUMENT_ERROR_CODES.has(code) ? 422 : 500;\n}\n","import type { PublicationOperations, SubmissionOperations } from './review-submission';\n\n/** Original injected operations may populate a dependent cache during handoff.\n * Retain this ordering while the original SubmissionOperations API is supported.\n */\nexport function legacyPublication(operations: SubmissionOperations): PublicationOperations {\n return {\n publicationError: operations.publicationError,\n publishReview: async (state, options) => {\n operations.submitReviewState(state);\n return operations.publishReview(state, options);\n },\n };\n}\n","// API handlers bind only their own engine capabilities. Admission is mandatory at registration.\nimport type * as http from 'node:http';\nimport { parseAttachmentReference } from '@self-review/core';\nimport type { RequestValidation } from './validate';\nimport { MAX_REVIEW_BODY_BYTES, MAX_APPLY_BODY_BYTES } from './protocol';\nimport { readJsonBody, sendJson, sendError, SECURITY_HEADERS } from './http-transport';\nimport type { ReviewTransportOperations as ReviewOperations } from './review-operations';\nimport { ReviewSubmission, publishFailureStatus } from './review-submission';\nimport { sendLargeJson } from './json-response';\nimport { defaultJsonBodyProcessing, type JsonBodyProcessing } from './json-body-processing';\nimport type { RequestKind } from './request-admission';\n\nexport const MAX_EXPAND_CONTEXT_BODY_BYTES = 64 * 1024;\nexport interface RouteContext {\n req: http.IncomingMessage;\n res: http.ServerResponse;\n url: URL;\n signal: AbortSignal;\n}\n\nexport type RouteHandler = (ctx: RouteContext) => Promise<void>;\n\nconst REVIEWED_PATH_ERROR = 'path must name a file in the reviewed diff';\n\n/** Core's authorization; answers 400 and returns false when `filePath` is not a reviewed path. */\nfunction requireReviewedPath(\n ctx: RouteContext,\n authorize: ReviewOperations['authorizeReviewedPath'],\n filePath: string,\n what = 'path'\n): boolean {\n if (authorize(filePath).ok) return true;\n sendError(\n ctx.res,\n 400,\n what === 'path' ? REVIEWED_PATH_ERROR : `${what} must name a file in the reviewed diff`\n );\n return false;\n}\n\nfunction requireReviewedQueryPath(\n ctx: RouteContext,\n authorize: ReviewOperations['authorizeReviewedPath']\n): string | null {\n const raw = ctx.url.searchParams.get('path');\n if (raw === null) {\n sendError(ctx.res, 400, REVIEWED_PATH_ERROR);\n return null;\n }\n return requireReviewedPath(ctx, authorize, raw) ? raw : null;\n}\n\nfunction createFileRoute({\n authorizeReviewedPath,\n getFileHunks,\n}: Pick<ReviewOperations, 'authorizeReviewedPath' | 'getFileHunks'>): RouteHandler {\n return async ctx => {\n const filePath = requireReviewedQueryPath(ctx, authorizeReviewedPath);\n if (filePath === null) return;\n // Diff paths are source-relative strings; core matches on them as sent.\n await sendLargeJson(ctx.res, getFileHunks(filePath), { signal: ctx.signal });\n };\n}\n\nfunction createImageRoute({\n authorizeReviewedPath,\n loadImage,\n}: Pick<ReviewOperations, 'authorizeReviewedPath' | 'loadImage'>): RouteHandler {\n return async ctx => {\n const filePath = requireReviewedQueryPath(ctx, authorizeReviewedPath);\n if (filePath === null) return;\n // Core reads the reviewed snapshot under the same identity it just authorized.\n await sendLargeJson(ctx.res, await loadImage(filePath, { signal: ctx.signal }), {\n signal: ctx.signal,\n });\n };\n}\n\nfunction createAttachmentRoute({\n readAttachment,\n}: Pick<ReviewOperations, 'readAttachment'>): RouteHandler {\n return async ctx => {\n // Not a diff path: a `.self-review-assets/<name>` reference core resolves itself; only its shape is checked here.\n const raw = ctx.url.searchParams.get('path');\n if (raw === null || parseAttachmentReference(raw) === null) {\n sendError(ctx.res, 400, 'path must name a file in the .self-review-assets directory');\n return;\n }\n const result = await readAttachment(raw, { signal: ctx.signal });\n if (!result.ok) {\n const status =\n result.reason === 'not-found'\n ? 404\n : result.reason === 'too-large'\n ? 413\n : result.reason === 'io-error'\n ? 500\n : 400;\n sendError(ctx.res, status, status === 404 ? 'attachment not found' : result.message);\n return;\n }\n const { res } = ctx;\n res.writeHead(200, {\n 'content-type': 'application/octet-stream',\n 'cache-control': 'no-store',\n ...SECURITY_HEADERS,\n });\n res.end(Buffer.from(result.data));\n };\n}\n\nfunction createExpansionRoute(\n {\n authorizeReviewedPath,\n expandContext,\n }: Pick<ReviewOperations, 'authorizeReviewedPath' | 'expandContext'>,\n parseExpandContextBody: RequestValidation['parseExpandContextBody'],\n processing: JsonBodyProcessing\n): RouteHandler {\n return async ctx => {\n const { req, res } = ctx;\n const body = await readJsonBody(req, MAX_EXPAND_CONTEXT_BODY_BYTES, ctx.signal, processing);\n if (!body.ok) {\n sendError(res, body.status, body.error);\n return;\n }\n const parsed = parseExpandContextBody(body.value);\n if (!parsed.ok) {\n sendError(res, 400, parsed.error);\n return;\n }\n // Becomes a git pathspec; authorized as a reviewed path, then passed through as sent.\n if (!requireReviewedPath(ctx, authorizeReviewedPath, parsed.value.filePath, 'filePath')) return;\n await sendLargeJson(res, await expandContext(parsed.value, { signal: ctx.signal }), {\n signal: ctx.signal,\n });\n };\n}\n\nfunction createApplyRoute(\n {\n authorizeReviewedPath,\n applySuggestionForSession,\n }: Pick<ReviewOperations, 'authorizeReviewedPath' | 'applySuggestionForSession'>,\n parseSuggestionApplyBody: RequestValidation['parseSuggestionApplyBody'],\n processing: JsonBodyProcessing\n): RouteHandler {\n return async ctx => {\n const { req, res } = ctx;\n const body = await readJsonBody(req, MAX_APPLY_BODY_BYTES, ctx.signal, processing);\n if (!body.ok) {\n sendError(res, body.status, body.error);\n return;\n }\n const parsed = parseSuggestionApplyBody(body.value);\n if (!parsed.ok) {\n sendError(res, 400, parsed.error);\n return;\n }\n if (!requireReviewedPath(ctx, authorizeReviewedPath, parsed.value.filePath, 'filePath')) return;\n sendJson(res, 200, await applySuggestionForSession(parsed.value, { signal: ctx.signal }));\n };\n}\n\nfunction createSubmissionRoute(\n submission: Pick<ReviewSubmission, 'begin' | 'publish' | 'release'>,\n published: (response: http.ServerResponse) => void,\n parseReviewStateBody: RequestValidation['parseReviewStateBody'],\n processing: JsonBodyProcessing\n): RouteHandler {\n return async ({ req, res, signal }) => {\n if (!submission.begin()) {\n sendError(res, 409, 'review submission already in progress or complete');\n return;\n }\n try {\n const body = await readJsonBody(req, MAX_REVIEW_BODY_BYTES, signal, processing);\n if (!body.ok) {\n sendError(res, body.status, body.error);\n return;\n }\n const parsed = parseReviewStateBody(body.value);\n if (!parsed.ok) {\n sendError(res, 400, parsed.error);\n return;\n }\n if (signal.aborted) throw signal.reason;\n const outcome = await submission.publish(parsed.value, { signal });\n if (outcome.ok) {\n published(res);\n sendJson(res, 200, outcome);\n } else {\n sendJson(res, publishFailureStatus(outcome.code), outcome);\n }\n } finally {\n submission.release();\n }\n };\n}\nexport interface ApiRoute {\n kind: RequestKind;\n handle: RouteHandler;\n}\n\nfunction createJsonReadRoute(read: () => unknown): ApiRoute {\n return {\n kind: 'expensive-read',\n handle: async ({ res, signal }) => {\n await sendLargeJson(res, read(), { signal });\n },\n };\n}\n\n/** Composition is the only place with access to the full operation bundle. */\nexport function createBoundApiRoutes(\n operations: ReviewOperations,\n submission: ReviewSubmission,\n published: (response: http.ServerResponse) => void,\n validation: RequestValidation,\n processing: JsonBodyProcessing\n): Record<string, ApiRoute>;\nexport function createBoundApiRoutes(\n operations: ReviewOperations,\n submission: ReviewSubmission,\n published: (response: http.ServerResponse) => void,\n validation: RequestValidation\n): Record<string, ApiRoute>;\nexport function createBoundApiRoutes(\n operations: ReviewOperations,\n submission: ReviewSubmission,\n published: (response: http.ServerResponse) => void,\n validation: RequestValidation,\n processing: JsonBodyProcessing = defaultJsonBodyProcessing\n): Record<string, ApiRoute> {\n // Keep operation replacement observable for hosts using the existing injected test seam.\n const authorizeReviewedPath: ReviewOperations['authorizeReviewedPath'] = path =>\n operations.authorizeReviewedPath(path);\n return {\n 'GET /api/diff': createJsonReadRoute(() => operations.getDiffLoad()),\n 'GET /api/config': createJsonReadRoute(() => operations.getConfigLoad()),\n 'GET /api/resume': createJsonReadRoute(() => operations.getResumeLoad()),\n 'GET /api/file': {\n kind: 'expensive-read',\n handle: createFileRoute({\n authorizeReviewedPath,\n getFileHunks: (...args) => operations.getFileHunks(...args),\n }),\n },\n 'GET /api/image': {\n kind: 'expensive-read',\n handle: createImageRoute({\n authorizeReviewedPath,\n loadImage: (...args) => operations.loadImage(...args),\n }),\n },\n 'GET /api/attachment': {\n kind: 'expensive-read',\n handle: createAttachmentRoute({\n readAttachment: (...args) => operations.readAttachment(...args),\n }),\n },\n 'POST /api/expand-context': {\n kind: 'mutation',\n handle: createExpansionRoute(\n {\n authorizeReviewedPath,\n expandContext: (...args) => operations.expandContext(...args),\n },\n validation.parseExpandContextBody,\n processing\n ),\n },\n 'POST /api/apply-suggestion': {\n kind: 'mutation',\n handle: createApplyRoute(\n {\n authorizeReviewedPath,\n applySuggestionForSession: (...args) => operations.applySuggestionForSession(...args),\n },\n validation.parseSuggestionApplyBody,\n processing\n ),\n },\n 'POST /api/review': {\n kind: 'publication',\n handle: createSubmissionRoute(\n submission,\n published,\n validation.parseReviewStateBody,\n processing\n ),\n },\n };\n}\n","// Two bounded, cooperative passes over data-only DTOs: measure before headers,\n// then encode into small chunks, waiting for the socket whenever it backs up.\nimport type { ServerResponse } from 'node:http';\nimport { setImmediate } from 'node:timers/promises';\nimport { SECURITY_HEADERS } from './http-transport';\n\nexport const MAX_JSON_RESPONSE_BYTES = 64 * 1024 * 1024;\nexport const MAX_JSON_RESPONSE_NODES = 2_000_000;\nconst MAX_DEPTH = 128;\nconst CHUNK_CHARS = 16 * 1024;\n\nexport class JsonResponseLimitError extends Error {}\nexport interface JsonResponseOptions {\n signal: AbortSignal;\n maxBytes?: number;\n maxNodes?: number;\n}\n\nfunction* quoted(text: string): Generator<string> {\n yield '\"';\n for (let start = 0; start < text.length; ) {\n let end = Math.min(text.length, start + CHUNK_CHARS);\n // JSON.stringify escapes lone surrogates; never split an intact pair.\n if (\n end < text.length &&\n text.charCodeAt(end - 1) >= 0xd800 &&\n text.charCodeAt(end - 1) <= 0xdbff\n )\n end--;\n yield JSON.stringify(text.slice(start, end)).slice(1, -1);\n start = end;\n }\n yield '\"';\n}\n\nfunction* tokens(value: unknown, maxNodes: number): Generator<string> {\n let nodes = 0;\n const ancestors = new Set<object>();\n function* visit(value: unknown, depth: number): Generator<string> {\n if (++nodes > maxNodes || depth > MAX_DEPTH)\n throw new JsonResponseLimitError('JSON response exceeds the serialization work limit');\n if (typeof value === 'string') {\n yield* quoted(value);\n return;\n }\n if (value === null || value === undefined) {\n yield 'null';\n return;\n }\n if (typeof value === 'boolean' || typeof value === 'number') {\n yield JSON.stringify(value);\n return;\n }\n if (typeof value !== 'object') throw new TypeError('Response must be a JSON DTO');\n if (ancestors.has(value)) throw new TypeError('Response contains a cycle');\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n const length = value.length;\n if (length > maxNodes - nodes)\n throw new JsonResponseLimitError('JSON response exceeds the serialization work limit');\n yield '[';\n for (let i = 0; i < length; i++) {\n if (i) yield ',';\n const descriptor = Object.getOwnPropertyDescriptor(value, String(i));\n if (descriptor && !('value' in descriptor))\n throw new TypeError('Response contains an accessor');\n yield* visit(descriptor?.value, depth + 1);\n }\n yield ']';\n } else {\n const keys = Object.keys(value);\n if (keys.length > maxNodes - nodes)\n throw new JsonResponseLimitError('JSON response exceeds the serialization work limit');\n yield '{';\n let first = true;\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !('value' in descriptor))\n throw new TypeError('Response contains an accessor');\n if (descriptor.value === undefined) {\n if (++nodes > maxNodes)\n throw new JsonResponseLimitError(\n 'JSON response exceeds the serialization work limit'\n );\n continue;\n }\n if (!first) yield ',';\n first = false;\n yield* quoted(key);\n yield ':';\n yield* visit(descriptor.value, depth + 1);\n }\n yield '}';\n }\n } finally {\n ancestors.delete(value);\n }\n }\n yield* visit(value, 0);\n}\n\nasync function* chunks(value: unknown, options: JsonResponseOptions): AsyncGenerator<string> {\n let bytes = 0;\n let steps = 0;\n let checkpointBytes = 0;\n let pending = '';\n for (const token of tokens(value, options.maxNodes ?? MAX_JSON_RESPONSE_NODES)) {\n options.signal.throwIfAborted();\n const tokenBytes = Buffer.byteLength(token);\n bytes += tokenBytes;\n checkpointBytes += tokenBytes;\n if (bytes > (options.maxBytes ?? MAX_JSON_RESPONSE_BYTES))\n throw new JsonResponseLimitError('JSON response exceeds the output byte limit');\n pending += token;\n if (pending.length >= CHUNK_CHARS) {\n yield pending;\n pending = '';\n }\n if (++steps % 2048 === 0 || checkpointBytes >= 256 * 1024) {\n await setImmediate(undefined, { signal: options.signal });\n checkpointBytes = 0;\n }\n }\n if (pending) yield pending;\n}\n\nfunction drain(res: ServerResponse, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n res.off('drain', ready);\n res.off('close', closed);\n res.off('error', failed);\n signal.removeEventListener('abort', aborted);\n };\n const ready = () => {\n cleanup();\n resolve();\n };\n const failed = (error: Error) => {\n cleanup();\n reject(error);\n };\n const closed = () => failed(new Error('JSON response disconnected'));\n const aborted = () => failed(signal.reason);\n res.once('drain', ready);\n res.once('close', closed);\n res.once('error', failed);\n signal.addEventListener('abort', aborted, { once: true });\n if (signal.aborted) aborted();\n else if (res.destroyed) closed();\n });\n}\n\nexport async function sendLargeJson(\n res: ServerResponse,\n value: unknown,\n options: JsonResponseOptions\n): Promise<void> {\n // No header or partial success for a preventable serialization refusal.\n for await (const _chunk of chunks(value, options)) {\n /* measure, without retaining */\n }\n options.signal.throwIfAborted();\n res.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n ...SECURITY_HEADERS,\n });\n for await (const chunk of chunks(value, options)) {\n if (!res.write(chunk)) await drain(res, options.signal);\n }\n res.end();\n}\n","// Decode HTTP attachment bytes without applying review DTO policy.\n\ntype ParseResult<T> = { ok: true; value: T } | { ok: false; error: string };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// Attachment blobs on the wire. `JSON.stringify` renders an ArrayBuffer as\n// `{}`, which would write a zero-byte image with a 200 and no error anywhere,\n// so the client sends base64 in `dataBase64` and a raw `data` field is refused.\n\n/** Canonical base64: full quartets, with at most one padded tail group. */\nconst BASE64_PATTERN =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)$/;\n\nconst RAW_DATA_ERROR =\n 'attachment data must be sent base64-encoded as dataBase64, never as a serialized ArrayBuffer';\n\n/** Every id this app makes: a randomUUID, or generateId's `${ms}-${base36}`. */\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/**\n * An id becomes an attachment's file name, so `../../x` was a path. Core\n * contains that write too; refusing here fails with a 400 at the door rather\n * than midway through saving, once the review has left the session.\n */\nfunction checkId(entry: Record<string, unknown>, what: string): string | null {\n if (entry.id === undefined) return null;\n if (typeof entry.id !== 'string' || !ID_PATTERN.test(entry.id)) {\n return `${what} id must match ${ID_PATTERN.source}`;\n }\n return null;\n}\n\n/**\n * The slice is load-bearing: `Buffer.from` returns a view into Node's shared\n * pool, so handing `.buffer` over whole writes unrelated memory to disk.\n */\nfunction base64ToArrayBuffer(value: string): ArrayBuffer {\n const buffer = Buffer.from(value, 'base64');\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n ) as ArrayBuffer;\n}\n\n/** Decode each blob. A resumed attachment carries none and passes through. */\nfunction decodeAttachmentList(list: unknown[]): ParseResult<unknown[]> {\n const decoded: unknown[] = [];\n for (const entry of list) {\n if (!isRecord(entry)) {\n decoded.push(entry);\n continue;\n }\n if (entry.data !== undefined) {\n return { ok: false, error: RAW_DATA_ERROR };\n }\n if (entry.dataBase64 === undefined) {\n decoded.push(entry);\n continue;\n }\n const encoded = entry.dataBase64;\n if (typeof encoded !== 'string' || !BASE64_PATTERN.test(encoded)) {\n // The empty string fails the pattern too: an attachment with no bytes\n // is a zero-byte file on disk, which is the failure being guarded.\n return { ok: false, error: 'attachment dataBase64 must be non-empty base64' };\n }\n const { dataBase64: _encoded, ...rest } = entry;\n decoded.push({ ...rest, data: base64ToArrayBuffer(encoded) });\n }\n return { ok: true, value: decoded };\n}\n\n/**\n * Walk the files, decoding blobs and checking every id that becomes a file\n * name. Leave other nested values for the shared runtime validator; only this\n * transport understands base64 fields and serialized ArrayBuffer mistakes.\n */\nexport function decodeFileAttachments(files: unknown[]): ParseResult<unknown[]> {\n const decodedFiles: unknown[] = [];\n for (const file of files) {\n if (!isRecord(file) || !Array.isArray(file.comments)) {\n decodedFiles.push(file);\n continue;\n }\n const decodedComments: unknown[] = [];\n for (const comment of file.comments) {\n if (!isRecord(comment)) {\n decodedComments.push(comment);\n continue;\n }\n const commentIdError = checkId(comment, 'comment');\n if (commentIdError) return { ok: false, error: commentIdError };\n const next: Record<string, unknown> = { ...comment };\n\n if (Array.isArray(comment.attachments)) {\n const result = decodeAttachmentList(comment.attachments);\n if (!result.ok) return result;\n next.attachments = result.value;\n }\n\n if (Array.isArray(comment.replies)) {\n const decodedReplies: unknown[] = [];\n for (const reply of comment.replies) {\n if (!isRecord(reply)) {\n decodedReplies.push(reply);\n continue;\n }\n const replyIdError = checkId(reply, 'reply');\n if (replyIdError) return { ok: false, error: replyIdError };\n if (!Array.isArray(reply.attachments)) {\n decodedReplies.push(reply);\n continue;\n }\n const result = decodeAttachmentList(reply.attachments);\n if (!result.ok) return result;\n decodedReplies.push({ ...reply, attachments: result.value });\n }\n next.replies = decodedReplies;\n }\n\n decodedComments.push(next);\n }\n decodedFiles.push({ ...file, comments: decodedComments });\n }\n return { ok: true, value: decodedFiles };\n}\n","// Request validation for the serve package. Core's handlers assume a caller the\n// compiler checked; over HTTP the body is whatever the socket delivered.\n\nimport { installedServeEngine, type ServeEngine } from './engine-contract';\nimport { decodeFileAttachments } from './attachment-codec';\n\n// Compatibility for callers that imported containment from this module.\nexport { containPath } from './contained-path';\nimport type { ExpandContextRequest, ReviewState, SuggestionApplyRequest } from '@self-review/core';\n\n/**\n * Reaches git as `-U${contextLines}`, so it must be bounded. Matches\n * `MAX_CONTEXT` in useExpandContext.ts; keep the two in step.\n */\nexport const MAX_CONTEXT_LINES = installedServeEngine.requestContract.maxContextLines;\n\nexport type RequestValidationRole = Pick<ServeEngine, 'requestContract' | 'validateReviewState'> & {\n core: Pick<ServeEngine['core'], 'ReviewXmlError'>;\n};\n\nexport type ParseResult<T> = { ok: true; value: T } | { ok: false; error: string };\n\n/** The same peer supplies validation, decode policy and its error identity. */\nexport function createRequestValidation(engine: RequestValidationRole) {\n const { requestContract, validateReviewState: validateCompatibleReviewState } = engine;\n const { ReviewXmlError } = engine.core;\n const maxContextLines = requestContract.maxContextLines;\n\n function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n\n const EXPAND_CONTEXT_KEYS: ReadonlySet<string> = new Set(['filePath', 'contextLines']);\n\n /**\n * Accepts exactly `{ filePath, contextLines }`. Unknown keys are rejected, not\n * ignored. The route authorizes `filePath` as a reviewed path before git sees it.\n */\n function parseExpandContextBody(body: unknown): ParseResult<ExpandContextRequest> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return { ok: false, error: 'body must be a JSON object' };\n }\n const record = body as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (!EXPAND_CONTEXT_KEYS.has(key)) {\n return { ok: false, error: `unknown field: ${key}` };\n }\n }\n\n const { filePath, contextLines } = record;\n if (typeof filePath !== 'string') {\n return { ok: false, error: 'filePath must be a string' };\n }\n if (\n typeof contextLines !== 'number' ||\n !Number.isInteger(contextLines) ||\n contextLines < 0 ||\n contextLines > maxContextLines\n ) {\n return {\n ok: false,\n error: `contextLines must be an integer between 0 and ${maxContextLines}`,\n };\n }\n\n return { ok: true, value: { filePath, contextLines } };\n }\n\n const APPLY_KEYS: ReadonlySet<string> = new Set(['filePath', 'lineRange', 'suggestion']);\n const LINE_RANGE_KEYS: ReadonlySet<string> = new Set(['side', 'start', 'end']);\n const SUGGESTION_KEYS: ReadonlySet<string> = new Set(['originalCode', 'proposedCode']);\n\n /**\n * Validate the body of `POST /api/apply-suggestion`.\n *\n * This is the one route that rewrites a file in the reviewed tree, so the shape\n * is checked exactly rather than deferred. Core refuses anything whose anchored\n * lines do not still match `originalCode` byte for byte, but it should never be\n * asked a question this malformed in the first place.\n */\n function parseSuggestionApplyBody(body: unknown): ParseResult<SuggestionApplyRequest> {\n if (!isRecord(body)) {\n return { ok: false, error: 'body must be a JSON object' };\n }\n for (const key of Object.keys(body)) {\n if (!APPLY_KEYS.has(key)) return { ok: false, error: `unknown field: ${key}` };\n }\n\n const { filePath, lineRange, suggestion } = body;\n if (typeof filePath !== 'string' || filePath === '') {\n return { ok: false, error: 'filePath must be a non-empty string' };\n }\n\n // A file-level comment has no anchor, and core refuses it. Accept the null so\n // the refusal comes back in core's vocabulary rather than as a 400.\n if (lineRange !== null) {\n if (!isRecord(lineRange)) {\n return { ok: false, error: 'lineRange must be an object or null' };\n }\n for (const key of Object.keys(lineRange)) {\n if (!LINE_RANGE_KEYS.has(key)) {\n return { ok: false, error: `unknown lineRange field: ${key}` };\n }\n }\n }\n\n if (!isRecord(suggestion)) {\n return { ok: false, error: 'suggestion must be an object' };\n }\n for (const key of Object.keys(suggestion)) {\n if (!SUGGESTION_KEYS.has(key)) {\n return { ok: false, error: `unknown suggestion field: ${key}` };\n }\n }\n for (const key of ['originalCode', 'proposedCode'] as const) {\n if (typeof suggestion[key] !== 'string') {\n return { ok: false, error: `suggestion.${key} must be a string` };\n }\n }\n\n return requestContract.decode(body);\n }\n\n const REVIEW_STATE_KEYS: ReadonlySet<string> = new Set(['timestamp', 'source', 'files']);\n\n /**\n * Accepts exactly `{ timestamp, source, files }`. Remote provenance is never\n * taken from the client; the process injects it after submission.\n *\n * Decode transport-only attachment fields, then validate the complete runtime\n * DTO before it reaches session storage. XSD validation still checks publication.\n */\n function parseReviewStateBody(body: unknown): ParseResult<ReviewState> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return { ok: false, error: 'body must be a JSON object' };\n }\n const record = body as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (!REVIEW_STATE_KEYS.has(key)) {\n return { ok: false, error: `unknown field: ${key}` };\n }\n }\n\n const { timestamp, source, files } = record;\n if (typeof timestamp !== 'string') {\n return { ok: false, error: 'timestamp must be a string' };\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return { ok: false, error: 'source must be an object' };\n }\n if (!Array.isArray(files)) {\n return { ok: false, error: 'files must be an array' };\n }\n\n const decoded = decodeFileAttachments(files);\n if (!decoded.ok) {\n return decoded;\n }\n\n try {\n return {\n ok: true,\n value: validateCompatibleReviewState({ timestamp, source, files: decoded.value }),\n };\n } catch (error) {\n if (!(error instanceof ReviewXmlError)) throw error;\n return { ok: false, error: error.message };\n }\n }\n\n return { parseExpandContextBody, parseSuggestionApplyBody, parseReviewStateBody };\n}\nexport type RequestValidation = ReturnType<typeof createRequestValidation>;\n// Original exports remain default compatibility facades.\nconst defaults = createRequestValidation(installedServeEngine);\nexport const parseExpandContextBody = defaults.parseExpandContextBody;\nexport const parseSuggestionApplyBody = defaults.parseSuggestionApplyBody;\nexport const parseReviewStateBody = defaults.parseReviewStateBody;\n","// Legacy operation bundles may omit validation. Only composition selects that default.\nimport { installedServeEngine } from './engine-contract';\nimport { createRequestValidation, type RequestValidation } from './validate';\nimport type { ReviewTransportOperations } from './review-operations';\n\nexport function bindRouteValidation(\n operations: Pick<ReviewTransportOperations, 'requestValidation'>,\n validation?: RequestValidation\n): RequestValidation {\n return (\n validation ?? operations.requestValidation ?? createRequestValidation(installedServeEngine)\n );\n}\n\n/** Modern composition never borrows validation from the installed default peer. */\nexport function bindSelectedRouteValidation(\n operations: import('./review-operations').ValidatedReviewOperations\n): RequestValidation {\n return {\n parseExpandContextBody: body => operations.requestValidation.parseExpandContextBody(body),\n parseSuggestionApplyBody: body => operations.requestValidation.parseSuggestionApplyBody(body),\n parseReviewStateBody: body => operations.requestValidation.parseReviewStateBody(body),\n };\n}\n","// A submission describes the loaded review; the browser cannot select a new source.\nimport {\n capturePublicationOwnership,\n normalizePublicationState,\n} from '@self-review/core/validation';\nimport { ReviewPublishError } from '@self-review/core';\nimport type { ReviewSession, ReviewState } from '@self-review/core';\n\nexport function ownedReviewState(\n session: ReviewSession,\n state: ReviewState,\n outputPath: string,\n ErrorType: typeof ReviewPublishError = ReviewPublishError\n): ReviewState {\n const owned = normalizePublicationState(\n state,\n session.diffData,\n capturePublicationOwnership(session.diffData)\n );\n if (!owned)\n throw new ErrorType(\n 'validation-failed',\n outputPath,\n 'The submitted source does not match the loaded review.'\n );\n return owned;\n}\n","// Composition of the core engine for one HTTP session. Tests can replace individual\n// operations with deferred or failing implementations without patching package imports.\n\nimport type * as core from '@self-review/core';\nimport { installedServeEngine, type ServeEngine } from './engine-contract';\nimport type {\n ReviewSession,\n ReviewState,\n ReviewOutputTarget,\n ExpandContextRequest,\n SuggestionApplyRequest,\n} from '@self-review/core';\nimport { ownedReviewState } from './source-ownership';\nimport type { SubmissionOperations, PublicationOperations } from './review-submission';\nimport { createRequestValidation, type RequestValidation } from './validate';\nimport { nonThrowingReporter } from './diagnostic-reporter';\n\nexport interface OperationOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\n/** Bound to one session; results and errors retain the core operation's contract. */\nexport interface ReviewOperations extends SubmissionOperations {\n /** Optional for original operation sets. Bound together with the selected engine. */\n requestValidation?: RequestValidation;\n authorizeReviewedPath: (path: string) => ReturnType<typeof core.authorizeReviewedPath>;\n getDiffLoad: () => ReturnType<typeof core.getDiffLoad>;\n getConfigLoad: () => ReturnType<typeof core.getConfigLoad>;\n getResumeLoad: () => ReturnType<typeof core.getResumeLoad>;\n getFileHunks: (path: string) => ReturnType<typeof core.getFileHunks>;\n loadImage: (path: string, options?: OperationOptions) => ReturnType<typeof core.loadImage>;\n readAttachment: (\n path: string,\n options?: OperationOptions\n ) => ReturnType<typeof core.readAttachment>;\n expandContext: (\n request: ExpandContextRequest,\n options?: OperationOptions\n ) => ReturnType<typeof core.expandContext>;\n applySuggestionForSession: (\n request: SuggestionApplyRequest,\n options?: OperationOptions\n ) =>\n | ReturnType<typeof core.applySuggestionForSession>\n | Promise<ReturnType<typeof core.applySuggestionForSession>>;\n}\n\nexport type ReviewTransportOperations = Omit<ReviewOperations, keyof SubmissionOperations>;\nexport type PublicationReviewOperations = ReviewTransportOperations & PublicationOperations;\n\n/** Complete first-party role. Original operation roles retain their optional validator. */\nexport type ValidatedReviewOperations = ReviewTransportOperations & {\n requestValidation: RequestValidation;\n};\nexport type ValidatedPublicationOperations = ValidatedReviewOperations & PublicationOperations;\n\n/** The publication consumer needs reads, one writer and its peer's validation. */\nexport type PublicationEngine = Pick<\n ServeEngine,\n 'applySuggestion' | 'requestContract' | 'validateReviewState'\n> & {\n core: Pick<\n typeof core,\n | 'authorizeReviewedPath'\n | 'getDiffLoad'\n | 'getConfigLoad'\n | 'getResumeLoad'\n | 'getFileHunks'\n | 'loadImage'\n | 'readAttachment'\n | 'expandContext'\n | 'publishReview'\n | 'publishOptionsFor'\n | 'ReviewXmlError'\n | 'ReviewPublishError'\n >;\n};\n\n/** First-party operations publish the supplied state without a redundant handoff. */\nexport function createPublicationOperations(\n session: ReviewSession,\n output: ReviewOutputTarget,\n engine?: PublicationEngine,\n reportDiagnostic?: (message: string) => void\n): PublicationReviewOperations;\n/** Retain the original reflected parameter type for existing consumers. */\nexport function createPublicationOperations(\n session: ReviewSession,\n output: ReviewOutputTarget,\n engine?: ServeEngine,\n reportDiagnostic?: (message: string) => void\n): PublicationReviewOperations;\nexport function createPublicationOperations(\n session: ReviewSession,\n output: ReviewOutputTarget,\n engine: PublicationEngine = installedServeEngine,\n reportDiagnostic?: (message: string) => void\n): PublicationReviewOperations {\n return createValidatedPublicationOperations(session, output, engine, reportDiagnostic);\n}\n\n/** Bind validation and effects from exactly the same selected peer. */\nexport function createValidatedPublicationOperations(\n session: ReviewSession,\n output: ReviewOutputTarget,\n engine: PublicationEngine = installedServeEngine,\n reportDiagnostic?: (message: string) => void\n): ValidatedPublicationOperations {\n const { core, applySuggestion } = engine;\n const report = reportDiagnostic && nonThrowingReporter(reportDiagnostic);\n return {\n requestValidation: createRequestValidation(engine),\n publicationError: core.ReviewPublishError,\n authorizeReviewedPath: path => core.authorizeReviewedPath(session, path),\n getDiffLoad: () => core.getDiffLoad(session),\n getConfigLoad: () => core.getConfigLoad(session),\n getResumeLoad: () => core.getResumeLoad(session),\n getFileHunks: path => core.getFileHunks(session, path),\n loadImage: (path, options) =>\n core.loadImage(session, path, report ? { ...options, reportDiagnostic: report } : options),\n readAttachment: (path, options) =>\n core.readAttachment(\n session,\n path,\n report ? { ...options, reportDiagnostic: report } : options\n ),\n expandContext: (request, options) => core.expandContext(session, request, undefined, options),\n applySuggestionForSession: (request, options) => applySuggestion(session, request, options),\n publishReview: (state: ReviewState, options) => {\n const owned = ownedReviewState(session, state, output.path, core.ReviewPublishError);\n // Preserve the CLI diagnostic without recreating the handoff cache mutation.\n if (report)\n report(\n '[review] Review state submitted:',\n JSON.stringify({\n timestamp: owned.timestamp,\n source: owned.source,\n fileCount: owned.files.length,\n })\n );\n return core.publishReview(owned, output.path, {\n ...core.publishOptionsFor(output, session.attachmentOrigins),\n signal: options?.signal,\n reportDiagnostic: report,\n });\n },\n };\n}\n\n/** Compatibility factory retains the original state-handoff operation. */\nexport function createReviewOperations(\n session: ReviewSession,\n output: ReviewOutputTarget\n): ReviewOperations {\n return {\n ...createPublicationOperations(session, output),\n submitReviewState: state =>\n installedServeEngine.core.submitReviewState(\n session,\n ownedReviewState(session, state, output.path)\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAS,qBAAqB;;;ACT9B,SAAS,iCAAiC;AAgB1C,IAAM,cAAc;AAAA,EAClB,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,iBAAiB;AACnB;AAEA,IAAM,gBAAgB;AAAA,EACpB,UAAU;AAAA,EACV,MAAM;AAAA,EACN,aAAa;AAAA,EACb,MAAM;AACR;AAIO,SAAS,eAAe,MAA2B;AACxD,QAAM,EAAE,QAAQ,OAAO,KAAK,IAAI,0BAA0B,MAAM;AAAA,IAC9D,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB,CAAC;AACD,SAAO;AAAA,IACL,aAAa;AAAA,IACb,YAAY,OAAO;AAAA,IACnB,YAAY,OAAO;AAAA,IACnB,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM;AAAA,EACjB;AACF;;;AC5CA,SAAS,WAAAA,gBAAe;;;AC8DjB,SAAS,kBAAkB,OAAkB,SAA+B;AACjF,QAAM,QAAQ,sBAAsB,MAAM,KAAK;AAC/C,MAAI,UAAU,MAAM;AAClB,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,GAAG,MAAM,IAAI,0CAA0C,SAAS,MAAM,KAAK,CAAC;AAAA,IACtF;AAAA,EACF;AACA,QAAM,MAAM,sBAAsB,MAAM,GAAG;AAC3C,MAAI,QAAQ,MAAM;AAChB,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,GAAG,MAAM,IAAI,wCAAwC,SAAS,MAAM,GAAG,CAAC;AAAA,IAClF;AAAA,EACF;AACA,SAAO,WAAW,EAAE,MAAM,MAAM,MAAM,OAAO,IAAI,GAAG,OAAO;AAC7D;AAEA,S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ACtC,cAAM,aAAa;AAAA,UACjB;AAAA,UACA;AAAA,UACA;AAAA,UACA,KAAK;AAAA,QACP;AACA,cAAM,SAAS,4BAA4B;AAAA,UACzC;AAAA,UACA;AAAA,UACA,aAAa;AAAA,UACb,kBAAkB,KAAK;AAAA,QACzB,CAAC;AACD,iBAAS,OAAO,MAAM;AACtB,cAAM,EAAE,IAAI,IAAI,MAAM,eAAe,QAAQ,GAAG,EAAE,QAAQ,SAAS,OAAO,CAAC;AAC3E,YAAI,SAAS,OAAO,QAAS,OAAM,SAAS,OAAO;AACnD,gBAAQ,MAAM,2BAA2B,gBAAgB,KAAK,UAAU,CAAC,EAAE;AAC3E,gBAAQ;AAAA,UACN,wCAAwC,OAAO,IAAI;AAAA,QACrD;AACA,gBAAQ;AAAA,UACN;AAAA,QAEF;AAAA,MACF,GAAG;AAAA,IACL;AAAA,EACF,SAAS,OAAO;AACd,QAAI,CAAC,SAAS,OAAO;AACnB,cAAQ,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACnF,aAAS,KAAK,CAAC;AAAA,EACjB,UAAE;AACA,iBAAa,YAAY;AAAA,EAC3B;AACF;AAEA,KAAK,EAAE,MAAM,WAAS;AACpB,UAAQ,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACjF,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["resolve","value","index","record","ReviewXmlError","path","record","path","ReviewXmlError","dirname","resolve","ReviewXmlError","runResumeWorker","options","ReviewXmlError","resolve","path","runResumeWorker","path","dirname","core","resolve","resolve","resolve","drain","Worker","chunks","resolve","Worker","chunks","resolve","fs","path","path","realpath","writeHeaders","parseAttachmentReference","value","resolve","parseAttachmentReference","parseExpandContextBody","parseSuggestionApplyBody","parseReviewStateBody","path","MAX_CONTEXT_LINES","ReviewXmlError","isRecord","parseExpandContextBody","record","parseSuggestionApplyBody","parseReviewStateBody","path","resolve","ReviewPublishError","core","path"]}