@self-review/serve 2.0.3 → 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 CHANGED
@@ -1,4 +1,13 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ decodeJsonBody,
4
+ decodeJsonWorkerReply
5
+ } from "./chunk-CDBNWCCT.js";
6
+ import {
7
+ checkResumeOwnership,
8
+ restoreResumeFailure,
9
+ runResumeWorker
10
+ } from "./chunk-THN5XTYQ.js";
2
11
 
3
12
  // src/cli.ts
4
13
  import { createRequire } from "module";
@@ -30,29 +39,725 @@ function parseServeArgs(argv) {
30
39
  };
31
40
  }
32
41
 
33
- // src/startup.ts
34
- import { resolve } from "path";
42
+ // src/startup-composition.ts
43
+ import { resolve as resolve3 } from "path";
44
+
45
+ // ../core/src/anchor-validation.ts
46
+ function validateLineRange(range, maxLine) {
47
+ const start = toPositiveSafeInteger(range.start);
48
+ if (start === null) {
49
+ return {
50
+ ok: false,
51
+ reason: `${range.side}-line-start is not a positive integer (${describe(range.start)})`
52
+ };
53
+ }
54
+ const end = toPositiveSafeInteger(range.end);
55
+ if (end === null) {
56
+ return {
57
+ ok: false,
58
+ reason: `${range.side}-line-end is not a positive integer (${describe(range.end)})`
59
+ };
60
+ }
61
+ return checkRange({ side: range.side, start, end }, maxLine);
62
+ }
63
+ function checkRange(anchor, maxLine) {
64
+ if (anchor.start > anchor.end) {
65
+ return {
66
+ ok: false,
67
+ reason: `${anchor.side}-line range is reversed (${anchor.start} > ${anchor.end})`
68
+ };
69
+ }
70
+ if (maxLine !== void 0 && anchor.end > maxLine) {
71
+ return {
72
+ ok: false,
73
+ reason: `${anchor.side}-line range ends beyond line ${maxLine} (${anchor.end})`
74
+ };
75
+ }
76
+ return { ok: true, anchor };
77
+ }
78
+ function toPositiveSafeInteger(value) {
79
+ let n;
80
+ if (typeof value === "number") {
81
+ n = value;
82
+ } else if (typeof value === "string" && /^\d+$/.test(value)) {
83
+ n = Number(value);
84
+ } else {
85
+ return null;
86
+ }
87
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
88
+ }
89
+ function describe(value) {
90
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
91
+ }
92
+
93
+ // ../core/src/xml-errors.ts
94
+ var ReviewXmlError = class extends Error {
95
+ constructor(code, message, options) {
96
+ super(message);
97
+ this.name = "ReviewXmlError";
98
+ this.code = code;
99
+ this.details = options?.details ?? [];
100
+ if (options?.cause !== void 0) this.cause = options.cause;
101
+ }
102
+ };
103
+
104
+ // ../core/src/input-budgets.ts
105
+ var KIB = 1024;
106
+ var MIB = 1024 * KIB;
107
+ var MAX_SOURCE_ENTRIES = 5e4;
108
+ var BINARY_SNIFF_BYTES = 8 * KIB;
109
+ var MAX_SOURCE_FILE_BYTES = 5 * MIB;
110
+ var MAX_SOURCE_TOTAL_BYTES = 64 * MIB;
111
+ var MAX_GIT_DIFF_OUTPUT_BYTES = 50 * MIB;
112
+ var MAX_GUIDE_BYTES = 1 * MIB;
113
+ var MAX_RESUME_XML_BYTES = 16 * MIB;
114
+ var MAX_REVIEW_ATTACHMENTS = 1e3;
115
+ var MAX_PUBLICATION_ASSET_BYTES = 64 * MIB;
116
+ var MAX_IMAGE_BYTES = 10 * MIB;
117
+ var MAX_SOURCE_FILE_LINES = 1e5;
118
+ var MAX_SOURCE_TOTAL_LINES = 25e4;
119
+ var MAX_DIFF_FILES = 1e4;
120
+ var MAX_DIFF_HUNKS = 5e4;
121
+ var MAX_DIFF_DIAGNOSTICS = 1e3;
122
+ var MAX_DIFF_DIAGNOSTIC_CHARS = 8 * KIB;
123
+ var DEFAULT_SOURCE_BUDGETS = Object.freeze({
124
+ maxEntries: MAX_SOURCE_ENTRIES,
125
+ maxFileBytes: MAX_SOURCE_FILE_BYTES,
126
+ maxTotalBytes: MAX_SOURCE_TOTAL_BYTES,
127
+ maxGitDiffOutputBytes: MAX_GIT_DIFF_OUTPUT_BYTES,
128
+ maxFileLines: MAX_SOURCE_FILE_LINES,
129
+ maxTotalLines: MAX_SOURCE_TOTAL_LINES,
130
+ maxDiffFiles: MAX_DIFF_FILES,
131
+ maxDiffHunks: MAX_DIFF_HUNKS,
132
+ maxDiagnostics: MAX_DIFF_DIAGNOSTICS
133
+ });
134
+ function formatBytes(bytes) {
135
+ if (bytes >= MIB) return `${trimFixed(bytes / MIB)} MiB`;
136
+ if (bytes >= KIB) return `${trimFixed(bytes / KIB)} KiB`;
137
+ return `${bytes} bytes`;
138
+ }
139
+ function trimFixed(value) {
140
+ return value.toFixed(1).replace(/\.0$/, "");
141
+ }
142
+
143
+ // ../core/src/review-state-validation.ts
144
+ function validateReviewState(value) {
145
+ validateState(value, true);
146
+ return normalizeNullableFields(value);
147
+ }
148
+ function validateState(value, requireCommentIds) {
149
+ const state = record(value, "review");
150
+ const budget = { attachments: 0, bytes: 0 };
151
+ string(state.timestamp, "review.timestamp");
152
+ const source = record(state.source, "review.source");
153
+ switch (source.type) {
154
+ case "git":
155
+ string(source.gitDiffArgs, "review.source.gitDiffArgs");
156
+ string(source.repository, "review.source.repository");
157
+ break;
158
+ case "directory":
159
+ case "file":
160
+ string(source.sourcePath, "review.source.sourcePath");
161
+ break;
162
+ case "welcome":
163
+ case "loading":
164
+ break;
165
+ default:
166
+ invalid("review.source.type", "must be git, directory, file, welcome or loading");
167
+ }
168
+ for (const key of ["remoteUrl", "remoteBaseSha", "remoteHeadSha"])
169
+ optionalString(state, key, "review");
170
+ optionalEnum(state, "remoteForge", ["github", "gitlab"], "review");
171
+ array(state.files, "review.files").forEach((value2, index) => {
172
+ const at = `review.files[${index}]`;
173
+ const file = record(value2, at);
174
+ string(file.path, `${at}.path`);
175
+ enumValue(
176
+ file.changeType,
177
+ ["added", "modified", "deleted", "renamed", "copied"],
178
+ `${at}.changeType`
179
+ );
180
+ boolean(file.viewed, `${at}.viewed`);
181
+ array(file.comments, `${at}.comments`).forEach(
182
+ (comment, index2) => validateComment(
183
+ comment,
184
+ `${at}.comments[${index2}]`,
185
+ file.path,
186
+ requireCommentIds,
187
+ budget
188
+ )
189
+ );
190
+ });
191
+ }
192
+ function validateComment(value, at, ownerPath, requireId, budget) {
193
+ const comment = record(value, at);
194
+ if (requireId || comment.id !== void 0) string(comment.id, `${at}.id`);
195
+ for (const key of ["filePath", "body", "category"]) string(comment[key], `${at}.${key}`);
196
+ if (comment.filePath !== ownerPath)
197
+ invalid(`${at}.filePath`, "must match its containing file path");
198
+ for (const key of ["author", "remoteId"]) optionalString(comment, key, at);
199
+ optionalEnum(comment, "severity", ["critical", "major", "minor", "info"], at);
200
+ optionalEnum(comment, "confidence", ["high", "medium", "low"], at);
201
+ if (comment.orphaned !== void 0) boolean(comment.orphaned, `${at}.orphaned`);
202
+ if (comment.lineRange !== null && comment.lineRange !== void 0) {
203
+ const range = record(comment.lineRange, `${at}.lineRange`);
204
+ enumValue(range.side, ["old", "new"], `${at}.lineRange.side`);
205
+ if (typeof range.start !== "number" || typeof range.end !== "number")
206
+ invalid(`${at}.lineRange`, "bounds must be numbers");
207
+ const checked = validateLineRange({
208
+ side: range.side,
209
+ start: range.start,
210
+ end: range.end
211
+ });
212
+ if (!checked.ok) invalid(`${at}.lineRange`, checked.reason);
213
+ }
214
+ if (comment.suggestion !== null && comment.suggestion !== void 0) {
215
+ const suggestion = record(comment.suggestion, `${at}.suggestion`);
216
+ string(suggestion.originalCode, `${at}.suggestion.originalCode`);
217
+ string(suggestion.proposedCode, `${at}.suggestion.proposedCode`);
218
+ if (comment.lineRange === null || comment.lineRange === void 0)
219
+ invalid(`${at}.suggestion`, "requires a line anchor");
220
+ }
221
+ validateAttachments(comment.attachments, `${at}.attachments`, budget);
222
+ if (comment.replies !== void 0) {
223
+ array(comment.replies, `${at}.replies`).forEach((value2, index) => {
224
+ const replyAt = `${at}.replies[${index}]`;
225
+ const reply = record(value2, replyAt);
226
+ string(reply.id, `${replyAt}.id`);
227
+ string(reply.body, `${replyAt}.body`);
228
+ for (const key of ["author", "remoteId"]) optionalString(reply, key, replyAt);
229
+ validateAttachments(reply.attachments, `${replyAt}.attachments`, budget);
230
+ });
231
+ }
232
+ }
233
+ function validateAttachments(value, at, budget) {
234
+ if (value === void 0) return;
235
+ const attachments = array(value, at);
236
+ budget.attachments += attachments.length;
237
+ if (budget.attachments > MAX_REVIEW_ATTACHMENTS)
238
+ invalid(at, `exceeds the ${MAX_REVIEW_ATTACHMENTS} attachment limit for a review document`);
239
+ attachments.forEach((value2, index) => {
240
+ const attachmentAt = `${at}[${index}]`;
241
+ const attachment = record(value2, attachmentAt);
242
+ for (const key of ["id", "fileName", "mediaType"])
243
+ string(attachment[key], `${attachmentAt}.${key}`);
244
+ if (attachment.data !== void 0 && !isReadableArrayBuffer(attachment.data))
245
+ invalid(`${attachmentAt}.data`, "must be a readable ArrayBuffer");
246
+ if (attachment.data !== void 0) {
247
+ const bytes = new Uint8Array(attachment.data).byteLength;
248
+ if (bytes > MAX_IMAGE_BYTES)
249
+ invalid(
250
+ `${attachmentAt}.data`,
251
+ `exceeds the ${formatBytes(MAX_IMAGE_BYTES)} attachment limit`
252
+ );
253
+ budget.bytes += bytes;
254
+ if (budget.bytes > MAX_PUBLICATION_ASSET_BYTES)
255
+ invalid(
256
+ at,
257
+ `exceeds the ${formatBytes(MAX_PUBLICATION_ASSET_BYTES)} publication asset limit`
258
+ );
259
+ }
260
+ });
261
+ }
262
+ function record(value, at) {
263
+ if (value === null || typeof value !== "object" || Array.isArray(value))
264
+ invalid(at, "must be an object");
265
+ return value;
266
+ }
267
+ function array(value, at) {
268
+ if (!Array.isArray(value)) invalid(at, "must be an array");
269
+ for (let index = 0; index < value.length; index++) {
270
+ if (!(index in value)) invalid(`${at}[${index}]`, "must be present");
271
+ }
272
+ return value;
273
+ }
274
+ function string(value, at) {
275
+ if (typeof value !== "string") invalid(at, "must be a string");
276
+ }
277
+ function boolean(value, at) {
278
+ if (typeof value !== "boolean") invalid(at, "must be a boolean");
279
+ }
280
+ function optionalString(node, key, at) {
281
+ if (node[key] !== void 0) string(node[key], `${at}.${key}`);
282
+ }
283
+ function enumValue(value, allowed, at) {
284
+ if (typeof value !== "string" || !allowed.includes(value))
285
+ invalid(at, `must be one of ${allowed.join(", ")}`);
286
+ }
287
+ function optionalEnum(node, key, allowed, at) {
288
+ if (node[key] !== void 0) enumValue(node[key], allowed, `${at}.${key}`);
289
+ }
290
+ function invalid(at, reason) {
291
+ const message = `Invalid review state: ${at} ${reason}`;
292
+ throw new ReviewXmlError("invalid-state", message, { details: [message] });
293
+ }
294
+ function normalizeNullableFields(state) {
295
+ const files = state.files.map((file) => {
296
+ const comments = file.comments.map(
297
+ (comment) => comment.lineRange === void 0 || comment.suggestion === void 0 ? {
298
+ ...comment,
299
+ lineRange: comment.lineRange ?? null,
300
+ suggestion: comment.suggestion ?? null
301
+ } : comment
302
+ );
303
+ return comments.some((comment, index) => comment !== file.comments[index]) ? { ...file, comments } : file;
304
+ });
305
+ return files.some((file, index) => file !== state.files[index]) ? { ...state, files } : state;
306
+ }
307
+ function isReadableArrayBuffer(value) {
308
+ try {
309
+ const getLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
310
+ getLength.call(value);
311
+ return new Uint8Array(value).buffer === value;
312
+ } catch {
313
+ return false;
314
+ }
315
+ }
316
+
317
+ // ../core/src/unicode-text.ts
318
+ function isWellFormedUnicode(value) {
319
+ return !/[\uD800-\uDFFF]/u.test(value);
320
+ }
321
+
322
+ // ../core/src/review-request-validation.ts
323
+ var MAX_CONTEXT_LINES = 99999;
324
+ function record2(value) {
325
+ return value !== null && typeof value === "object" && !Array.isArray(value);
326
+ }
327
+ function decodeSuggestionApplyRequest(value) {
328
+ if (!record2(value)) return { ok: false, error: "body must be a JSON object" };
329
+ if (typeof value.filePath !== "string") return { ok: false, error: "filePath must be a string" };
330
+ const range = value.lineRange;
331
+ if (range !== null) {
332
+ if (!record2(range)) return { ok: false, error: "lineRange must be an object or null" };
333
+ if (range.side !== "old" && range.side !== "new")
334
+ return { ok: false, error: "lineRange.side must be 'old' or 'new'" };
335
+ for (const key of ["start", "end"]) {
336
+ if (typeof range[key] !== "number")
337
+ return { ok: false, error: `lineRange.${key} must be a number` };
338
+ }
339
+ }
340
+ if (!record2(value.suggestion)) return { ok: false, error: "suggestion must be an object" };
341
+ for (const key of ["originalCode", "proposedCode"]) {
342
+ if (typeof value.suggestion[key] !== "string")
343
+ return { ok: false, error: `suggestion.${key} must be a string` };
344
+ }
345
+ if (!isWellFormedUnicode(value.suggestion.proposedCode))
346
+ return { ok: false, error: "suggestion.proposedCode must be well-formed Unicode text" };
347
+ return { ok: true, value };
348
+ }
349
+
350
+ // ../core/src/same-diff-source.ts
351
+ function sameDiffSource(loaded, submitted) {
352
+ if (loaded.type !== submitted.type) return false;
353
+ switch (loaded.type) {
354
+ case "git":
355
+ return submitted.type === "git" && loaded.repository === submitted.repository && loaded.gitDiffArgs === submitted.gitDiffArgs;
356
+ case "directory":
357
+ case "file":
358
+ return (submitted.type === "directory" || submitted.type === "file") && loaded.sourcePath === submitted.sourcePath;
359
+ case "welcome":
360
+ case "loading":
361
+ return true;
362
+ }
363
+ }
364
+
365
+ // ../config/src/index.ts
366
+ var categoryTemplate = Object.freeze(
367
+ [
368
+ {
369
+ name: "question",
370
+ description: "Clarification needed \u2014 not necessarily a problem",
371
+ color: "#805ad5"
372
+ },
373
+ {
374
+ name: "bug",
375
+ description: "Likely defect or incorrect behavior",
376
+ color: "#e53e3e"
377
+ },
378
+ {
379
+ name: "security",
380
+ description: "Security vulnerability or concern",
381
+ color: "#dd6b20"
382
+ },
383
+ {
384
+ name: "style",
385
+ description: "Code style, naming, or formatting issue",
386
+ color: "#3182ce"
387
+ },
388
+ {
389
+ name: "task",
390
+ description: "Action item or follow-up task",
391
+ color: "#38a169"
392
+ },
393
+ {
394
+ name: "nit",
395
+ description: "Minor nitpick, low priority",
396
+ color: "#718096"
397
+ }
398
+ ].map((category) => Object.freeze(category))
399
+ );
400
+ var ignoreTemplate = Object.freeze([
401
+ ".git",
402
+ "node_modules",
403
+ "vendor",
404
+ ".vendor",
405
+ "__pycache__",
406
+ ".venv",
407
+ "venv",
408
+ ".env",
409
+ "dist",
410
+ "build",
411
+ ".next",
412
+ ".nuxt",
413
+ ".svelte-kit",
414
+ "target",
415
+ "*.min.js",
416
+ "*.min.css",
417
+ "package-lock.json",
418
+ "yarn.lock",
419
+ "pnpm-lock.yaml",
420
+ "composer.lock",
421
+ "Gemfile.lock",
422
+ "Cargo.lock",
423
+ "poetry.lock",
424
+ "go.sum"
425
+ ]);
426
+ var DEFAULT_FONT_SIZE = 14;
427
+ var DEFAULT_MAX_FILES = 500;
428
+ var DEFAULT_MAX_TOTAL_LINES = 1e5;
429
+ var configTemplate = Object.freeze({
430
+ theme: "system",
431
+ diffView: "split",
432
+ fontSize: DEFAULT_FONT_SIZE,
433
+ outputFormat: "xml",
434
+ outputFile: "./review.xml",
435
+ ignore: ignoreTemplate,
436
+ categories: categoryTemplate,
437
+ defaultDiffArgs: "",
438
+ showUntracked: true,
439
+ showUntrackedExplicit: false,
440
+ wordWrap: true,
441
+ maxFiles: DEFAULT_MAX_FILES,
442
+ maxTotalLines: DEFAULT_MAX_TOTAL_LINES
443
+ });
444
+ function createDefaultConfig() {
445
+ return {
446
+ ...configTemplate,
447
+ ignore: [...configTemplate.ignore],
448
+ categories: configTemplate.categories.map((category) => ({ ...category }))
449
+ };
450
+ }
451
+ var DEFAULT_CATEGORIES = categoryTemplate.map((category) => ({
452
+ ...category
453
+ }));
454
+ var DEFAULT_IGNORE_PATTERNS = [...ignoreTemplate];
455
+ var DEFAULT_CONFIG = createDefaultConfig();
456
+
457
+ // ../core/src/config-font-size.ts
458
+ function normalizeConfigFontSize(config, fallback = createDefaultConfig().fontSize) {
459
+ if (Number.isFinite(config.fontSize)) return { config };
460
+ return {
461
+ config: { ...config, fontSize: fallback },
462
+ diagnostic: `Warning: Invalid font-size value "${String(config.fontSize)}", expected a finite number; using a finite fallback`
463
+ };
464
+ }
465
+
466
+ // ../core/src/publication-ownership.ts
467
+ function provenance(remote) {
468
+ if (!remote) return void 0;
469
+ return {
470
+ remoteUrl: remote.remoteUrl,
471
+ remoteForge: remote.remoteForge,
472
+ remoteBaseSha: remote.remoteBaseSha,
473
+ remoteHeadSha: remote.remoteHeadSha
474
+ };
475
+ }
476
+ function capturePublicationOwnership(loaded) {
477
+ if (!loaded || loaded.source.type === "welcome" || loaded.source.type === "loading") return null;
478
+ return { loaded, source: { ...loaded.source }, remote: provenance(loaded.remote) };
479
+ }
480
+ function normalizePublicationState(state, current, admitted) {
481
+ if (!admitted || !current || current !== admitted.loaded || !state.source || !sameDiffSource(admitted.source, current.source) || !sameDiffSource(admitted.source, state.source))
482
+ return null;
483
+ const remote = provenance(current.remote);
484
+ if (remote?.remoteUrl !== admitted.remote?.remoteUrl || remote?.remoteForge !== admitted.remote?.remoteForge || remote?.remoteBaseSha !== admitted.remote?.remoteBaseSha || remote?.remoteHeadSha !== admitted.remote?.remoteHeadSha)
485
+ return null;
486
+ const {
487
+ remoteUrl: _url,
488
+ remoteForge: _forge,
489
+ remoteBaseSha: _base,
490
+ remoteHeadSha: _head,
491
+ ...local
492
+ } = state;
493
+ return { ...local, ...admitted.remote };
494
+ }
495
+
496
+ // src/engine-contract.ts
497
+ import * as core from "@self-review/core";
498
+ import { ReviewXmlError as ReviewXmlError2 } from "@self-review/core";
499
+
500
+ // ../core/src/attachment-origin-plan.ts
501
+ import * as path2 from "path";
502
+
503
+ // ../core/src/attachment-planner.ts
504
+ import * as path from "path";
505
+ var ASSET_DIR_NAME = ".self-review-assets";
506
+
507
+ // ../core/src/attachment-origin-plan.ts
508
+ function parseAttachmentReference(reference) {
509
+ if (typeof reference !== "string") return null;
510
+ const prefix = `${ASSET_DIR_NAME}/`;
511
+ if (!reference.startsWith(prefix)) return null;
512
+ const name = reference.slice(prefix.length);
513
+ if (name === "" || name === "." || name === "..") return null;
514
+ if (/[/\\\0]/.test(name)) return null;
515
+ return name;
516
+ }
517
+ function* attachmentLists(comments) {
518
+ for (const comment of comments) {
519
+ if (comment.attachments) yield { comment, attachments: comment.attachments };
520
+ for (const reply of comment.replies ?? []) {
521
+ if (reply.attachments) yield { comment, attachments: reply.attachments };
522
+ }
523
+ }
524
+ }
525
+ function resolveAttachmentOriginsAtDirectory(comments, directory) {
526
+ if (!path2.isAbsolute(directory))
527
+ throw new TypeError("Attachment document directory must be absolute");
528
+ const assetDir = path2.join(directory, ASSET_DIR_NAME);
529
+ const origins = /* @__PURE__ */ new Map();
530
+ const diagnostics = [];
531
+ for (const { comment, attachments } of attachmentLists(comments)) {
532
+ for (const attachment of attachments) {
533
+ const name = parseAttachmentReference(attachment.fileName);
534
+ if (name === null) {
535
+ diagnostics.push(
536
+ `${comment.filePath || "(review)"}: attachment "${attachment.fileName}" is not in the document's ${ASSET_DIR_NAME} directory; it will not be loaded`
537
+ );
538
+ continue;
539
+ }
540
+ origins.set(attachment.fileName, path2.join(assetDir, name));
541
+ }
542
+ }
543
+ return { origins, diagnostics };
544
+ }
545
+
546
+ // src/resume-adoption-compatibility.ts
547
+ function adoptFields(session, parsed, origins, diagnostics) {
548
+ session.attachmentOrigins = origins;
549
+ session.resumeComments = parsed.comments;
550
+ session.resumeViewedFiles = parsed.viewedFiles;
551
+ session.resumeImportDiagnostics = [...parsed.importDiagnostics, ...diagnostics];
552
+ return parsed;
553
+ }
554
+ function adoptResumeAtDirectory(session, parsed, directory) {
555
+ const { origins, diagnostics } = resolveAttachmentOriginsAtDirectory(parsed.comments, directory);
556
+ return adoptFields(session, parsed, origins, diagnostics);
557
+ }
558
+ function resumeAdopterFor(engine) {
559
+ if (engine.adoptResumeDocument) return engine.adoptResumeDocument;
560
+ const record3 = engine.recordResumedAttachments;
561
+ return (session, parsed, path5) => {
562
+ const attachments = { attachmentOrigins: session.attachmentOrigins };
563
+ const diagnostics = record3(attachments, parsed.comments, path5);
564
+ return adoptFields(session, parsed, attachments.attachmentOrigins, diagnostics);
565
+ };
566
+ }
567
+
568
+ // src/engine-contract.ts
569
+ function applyFor(engine) {
570
+ const applyAsync = engine.applySuggestionForSessionAsync?.bind(engine);
571
+ const applySync = engine.applySuggestionForSession.bind(engine);
572
+ return async (session, request, options = {}) => {
573
+ if (applyAsync) return applyAsync(session, request, options);
574
+ if (options.signal?.aborted) throw options.signal.reason;
575
+ return applySync(session, request);
576
+ };
577
+ }
578
+ function startupSourceFor(engine) {
579
+ const resolveAsync = engine.resolveStartupSourceAsync?.bind(engine);
580
+ const resolveSync = engine.resolveStartupSource.bind(engine);
581
+ return async (args, cwd, options) => {
582
+ if (options.signal?.aborted) throw options.signal.reason;
583
+ return resolveAsync ? resolveAsync(args, cwd, options) : resolveSync(args, cwd);
584
+ };
585
+ }
586
+ function reviewStateValidatorFor(engine) {
587
+ if (engine.validateReviewState) return engine.validateReviewState;
588
+ const ErrorType = engine.ReviewXmlError ?? ReviewXmlError2;
589
+ return (value) => validateBundledReviewState(value, ErrorType);
590
+ }
591
+ function validateBundledReviewState(value, ErrorType) {
592
+ try {
593
+ return validateReviewState(value);
594
+ } catch (error) {
595
+ if (error instanceof ReviewXmlError) {
596
+ throw new ErrorType(error.code, error.message, {
597
+ details: error.details,
598
+ cause: error.cause
599
+ });
600
+ }
601
+ throw error;
602
+ }
603
+ }
604
+ function requestContractFor(engine) {
605
+ return {
606
+ decode: engine.decodeSuggestionApplyRequest ?? decodeSuggestionApplyRequest,
607
+ maxContextLines: engine.MAX_CONTEXT_LINES ?? MAX_CONTEXT_LINES
608
+ };
609
+ }
610
+ function selectServeEngine(engine) {
611
+ return {
612
+ core: engine,
613
+ commitLoadedReview: typeof engine.commitLoadedReview === "function" ? engine.commitLoadedReview : void 0,
614
+ compatibilityDiagnostics: coreCompatibilityDiagnostics(engine),
615
+ resolveSource: startupSourceFor(engine),
616
+ applySuggestion: applyFor(engine),
617
+ validateReviewState: reviewStateValidatorFor(engine),
618
+ requestContract: requestContractFor(engine),
619
+ adoptResume: resumeAdopterFor(engine)
620
+ };
621
+ }
622
+ var resolveServeEngine = selectServeEngine;
623
+ var installedServeEngine = resolveServeEngine(core);
624
+ function coreCompatibilityDiagnostics(engine) {
625
+ const messages = [];
626
+ if (typeof engine.resolveStartupSourceAsync !== "function")
627
+ messages.push(
628
+ "[serve] Installed core uses a synchronous startup probe; it blocks the event loop and cannot be interrupted."
629
+ );
630
+ if (typeof engine.applySuggestionForSessionAsync !== "function")
631
+ messages.push(
632
+ "[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."
633
+ );
634
+ if (typeof engine.loadSyntheticFilesAsync !== "function")
635
+ messages.push(
636
+ "[serve] Installed core local loading does not support the startup signal; cancellation may wait for filesystem work."
637
+ );
638
+ if (typeof engine.MAX_PUBLICATION_ASSET_BYTES !== "number")
639
+ messages.push(
640
+ "[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."
641
+ );
642
+ return messages;
643
+ }
644
+
645
+ // src/resume-document-loader.ts
646
+ import { randomUUID } from "crypto";
647
+ import { realpath } from "fs/promises";
648
+ import { dirname as dirname2, resolve as resolve2 } from "path";
649
+ import { Worker } from "worker_threads";
650
+
651
+ // src/resume-worker-lifetime.ts
652
+ import { ReviewXmlError as ReviewXmlError3 } from "@self-review/core";
653
+ function runResumeWorker2(worker, request, options = {}) {
654
+ return runResumeWorker(
655
+ worker,
656
+ request,
657
+ options,
658
+ (failure) => restoreResumeFailure(
659
+ failure,
660
+ (code, message, options2) => new ReviewXmlError3(code, message, options2)
661
+ )
662
+ );
663
+ }
664
+
665
+ // src/resume-document-loader.ts
666
+ var nativePaths = {
667
+ async realpath(directory) {
668
+ const absolute = resolve2(directory);
669
+ return realpath(absolute).catch(() => absolute);
670
+ }
671
+ };
672
+ var createParserWorker = () => new Worker(new URL("./resume-parser-worker.js", import.meta.url));
673
+ async function parseResume(path5, options, worker) {
674
+ checkResumeOwnership(options);
675
+ const parsed = await runResumeWorker2(worker(), { id: randomUUID(), path: path5 }, options);
676
+ checkResumeOwnership(options);
677
+ return parsed;
678
+ }
679
+ async function loadResumeDocumentAsync(session, path5, options = {}) {
680
+ const parsed = await parseResume(path5, options, createParserWorker);
681
+ let directory;
682
+ try {
683
+ directory = await (options.paths ?? nativePaths).realpath(dirname2(path5));
684
+ } catch (error) {
685
+ checkResumeOwnership(options);
686
+ throw error;
687
+ }
688
+ checkResumeOwnership(options);
689
+ return adoptResumeAtDirectory(session, parsed, directory);
690
+ }
691
+
692
+ // src/diagnostic-reporter.ts
693
+ import { format } from "util";
694
+ function nonThrowingReporter(report) {
695
+ return (message, ...details) => {
696
+ try {
697
+ const result = report ? report(format(message, ...details)) : console.error(message, ...details);
698
+ void Promise.resolve(result).catch(() => {
699
+ });
700
+ } catch {
701
+ }
702
+ };
703
+ }
704
+
705
+ // src/startup-composition.ts
706
+ function createStartupHost(cwd = process.cwd(), reportDiagnostic = (message) => console.error(message)) {
707
+ const { core: core2, resolveSource } = installedServeEngine;
708
+ return {
709
+ cwd,
710
+ reportDiagnostic,
711
+ operations: {
712
+ loadConfigWithProvenance: (options) => {
713
+ const loaded = core2.loadConfigWithProvenance(options);
714
+ const normalized = normalizeConfigFontSize(loaded.config);
715
+ if (!normalized.diagnostic) return loaded;
716
+ nonThrowingReporter(options?.reportDiagnostic ?? reportDiagnostic)(normalized.diagnostic);
717
+ return {
718
+ ...loaded,
719
+ config: normalized.config,
720
+ provenance: { ...loaded.provenance, fontSize: "default" }
721
+ };
722
+ },
723
+ inspectOutput: (output) => core2.inspectOutputPath(output.path, core2.publishOptionsFor(output)),
724
+ resolveSource,
725
+ loadLocalReview: core2.loadLocalReview,
726
+ commitLoadedReview: installedServeEngine.commitLoadedReview,
727
+ loadResumeDocument: core2.loadResumeDocument,
728
+ loadResumeDocumentAsync,
729
+ loadGuide: (output, config, files, options) => (
730
+ // Core 2.0.4 ignores the fourth argument. Resolve the configured path here
731
+ // as well, so that peer still reads the host's guide without changing cwd.
732
+ core2.loadGuide(
733
+ output,
734
+ config.guideFile ? { ...config, guideFile: resolve3(options?.cwd ?? cwd, config.guideFile) } : config,
735
+ files,
736
+ options
737
+ )
738
+ )
739
+ }
740
+ };
741
+ }
742
+
743
+ // src/startup-resolver.ts
744
+ import { resolve as resolve4 } from "path";
35
745
  import {
36
746
  commitDiffData,
37
747
  computePayloadStats,
38
748
  countTotalLines,
39
749
  createReviewSession,
40
- inspectOutputPath,
41
- loadConfigWithProvenance,
42
- loadGuide,
43
- loadLocalReview,
44
- loadResumeDocument,
45
- publishOptionsFor,
46
750
  resolveOutputTarget,
47
- resolveStartupDiffArgs,
48
- resolveStartupSource
751
+ resolveStartupDiffArgs
49
752
  } from "@self-review/core";
50
- var log = (message) => console.error(`[serve] ${message}`);
51
- async function resolveSession(args) {
52
- const cwd = process.cwd();
53
- const loadedConfig = loadConfigWithProvenance({ cwd });
753
+ async function resolveSessionWithHost(args, options, host) {
754
+ options.signal?.throwIfAborted();
755
+ const { cwd, operations, reportDiagnostic } = host;
756
+ const report = nonThrowingReporter(reportDiagnostic);
757
+ const log = (message) => report(`[serve] ${message}`);
758
+ const loadedConfig = operations.loadConfigWithProvenance({ cwd, reportDiagnostic: report });
54
759
  const output = resolveOutputTarget(args.outputPath, loadedConfig, cwd);
55
- const problem = inspectOutputPath(output.path, publishOptionsFor(output));
760
+ const problem = operations.inspectOutput(output);
56
761
  if (problem) {
57
762
  throw new Error(
58
763
  `Output path is not writable (${problem.code}): ${problem.message} Pass a writable path with --output, or set output-file in .self-review.yaml.`
@@ -60,20 +765,22 @@ async function resolveSession(args) {
60
765
  }
61
766
  log(`Output path: ${output.path} (${output.origin})`);
62
767
  const { gitDiffArgs, config } = resolveStartupDiffArgs(args.gitDiffArgs, loadedConfig, cwd);
63
- const source = resolveStartupSource(gitDiffArgs, cwd);
768
+ const source = await operations.resolveSource(gitDiffArgs, cwd, options);
64
769
  log(`Startup mode: ${source.mode}`);
65
770
  if (source.mode === "welcome") {
66
771
  throw new Error(
67
772
  "Nothing to review: this is not a git repository and no path was given. Run self-review-serve inside a git repository, or pass a directory or file to review."
68
773
  );
69
774
  }
70
- const { payload: diffData, identity } = await loadLocalReview(
775
+ const loadedReview = await operations.loadLocalReview(
71
776
  source,
72
777
  gitDiffArgs,
73
778
  config,
74
779
  cwd,
75
- log
780
+ log,
781
+ options
76
782
  );
783
+ const { payload: diffData, identity } = loadedReview;
77
784
  log(`Loaded ${diffData.files.length} files`);
78
785
  const stats = computePayloadStats(diffData.files.length, countTotalLines(diffData.files), config);
79
786
  if (stats.exceedsAny) {
@@ -84,9 +791,11 @@ async function resolveSession(args) {
84
791
  }
85
792
  const session = createReviewSession();
86
793
  if (args.resumeFrom) {
87
- const resumePath = resolve(cwd, args.resumeFrom);
794
+ const resumePath = resolve4(cwd, args.resumeFrom);
88
795
  try {
89
- loadResumeDocument(session, resumePath);
796
+ if (operations.loadResumeDocumentAsync)
797
+ await operations.loadResumeDocumentAsync(session, resumePath, options);
798
+ else operations.loadResumeDocument(session, resumePath);
90
799
  } catch (error) {
91
800
  throw new Error(
92
801
  `Could not read the resume file ${resumePath}: ` + (error instanceof Error ? error.message : String(error))
@@ -99,302 +808,351 @@ async function resolveSession(args) {
99
808
  log(`Resume import: ${diagnostic}`);
100
809
  }
101
810
  }
102
- const guideData = await loadGuide(
811
+ const guideData = await operations.loadGuide(
103
812
  output.path,
104
813
  config,
105
- diffData.files.map((f) => f.newPath || f.oldPath)
814
+ diffData.files.map((f) => f.newPath || f.oldPath),
815
+ { cwd, reportDiagnostic, signal: options.signal }
106
816
  );
107
817
  if (guideData) {
108
818
  log(`Walkthrough guide loaded: ${guideData.groups.length} groups`);
109
819
  }
110
- commitDiffData(session, diffData, identity);
820
+ if (options.signal?.aborted) throw options.signal.reason;
821
+ if (loadedReview.loadedReview && operations.commitLoadedReview)
822
+ operations.commitLoadedReview(session, diffData, loadedReview.loadedReview);
823
+ else commitDiffData(session, diffData, identity);
111
824
  session.guideData = guideData;
112
825
  session.config = config;
113
826
  session.outputPathInfo = { resolvedOutputPath: output.path, outputPathWritable: true };
114
827
  return { session, output };
115
828
  }
116
829
 
117
- // src/lifecycle.ts
118
- function shutdown(server, exit, code) {
119
- server.closeAllConnections();
120
- server.close();
121
- exit(code);
122
- }
123
- function completeReviewOnSubmit(options) {
124
- const { server, exit = process.exit } = options;
125
- let completing = false;
126
- server.on("request", (req, res) => {
127
- if (req.method !== "POST" || pathnameOf(req.url) !== "/api/review") {
128
- return;
129
- }
130
- res.on("finish", () => {
131
- if (res.statusCode !== 200 || completing) {
132
- return;
133
- }
134
- completing = true;
135
- console.error("[serve] Review complete; stopping.");
136
- shutdown(server, exit, 0);
137
- });
138
- });
830
+ // src/startup.ts
831
+ function resolveSession(args, options = {}, host = createStartupHost()) {
832
+ return resolveSessionWithHost(args, options, host);
139
833
  }
140
- function pathnameOf(url) {
141
- try {
142
- return new URL(url ?? "/", "http://localhost").pathname;
143
- } catch {
144
- return null;
145
- }
834
+
835
+ // src/core-capabilities.ts
836
+ function reportCoreCompatibility(report, engine) {
837
+ const messages = engine ? coreCompatibilityDiagnostics(engine) : installedServeEngine.compatibilityDiagnostics;
838
+ for (const message of messages) report(message);
146
839
  }
147
840
 
148
- // src/server.ts
149
- import * as fs2 from "fs";
150
- import * as http from "http";
151
- import * as path2 from "path";
152
- import { fileURLToPath } from "url";
153
- import {
154
- authorizeReviewedPath,
155
- getDiffLoad,
156
- getConfigLoad,
157
- getResumeLoad,
158
- getFileHunks,
159
- loadImage,
160
- parseAttachmentReference,
161
- readAttachment,
162
- expandContext,
163
- submitReviewState,
164
- applySuggestionForSession,
165
- publishOptionsFor as publishOptionsFor2,
166
- publishReview,
167
- ReviewPublishError
168
- } from "@self-review/core";
841
+ // src/protocol.ts
842
+ var MAX_REVIEW_BODY_BYTES = 32 * 1024 * 1024;
843
+ var MAX_APPLY_BODY_BYTES = MAX_REVIEW_BODY_BYTES;
844
+ var CAPABILITY_FRAGMENT_KEY = "cap";
845
+ var CAPABILITY_SCHEME = "Bearer";
846
+ function formatLaunchUrl(listenerUrl, capability) {
847
+ return `${listenerUrl}#${CAPABILITY_FRAGMENT_KEY}=${capability}`;
848
+ }
849
+ var SERVER_BUSY_ERROR = "review server busy; retry after pending requests finish";
850
+ var SERVER_BUSY_CODE = "server-busy";
169
851
 
170
- // src/validate.ts
171
- import * as fs from "fs";
172
- import * as path from "path";
173
- function realpathDeepestExisting(absolute) {
174
- const missing = [];
175
- let current = absolute;
176
- for (; ; ) {
177
- try {
178
- const real = fs.realpathSync(current);
179
- return missing.length === 0 ? real : path.join(real, ...missing);
180
- } catch {
181
- const parent = path.dirname(current);
182
- if (parent === current) {
183
- return null;
852
+ // src/request-admission.ts
853
+ var REQUEST_SHUTDOWN = /* @__PURE__ */ Symbol("review-request-shutdown");
854
+ var RequestAdmission = class {
855
+ constructor(options = {}) {
856
+ this.options = options;
857
+ this.active = /* @__PURE__ */ new Set();
858
+ this.expensiveReads = 0;
859
+ this.exclusive = false;
860
+ this.stopping = false;
861
+ for (const value of Object.values(options)) {
862
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1)) {
863
+ throw new Error("Request admission limits must be positive safe integers.");
184
864
  }
185
- missing.unshift(path.basename(current));
186
- current = parent;
187
865
  }
188
866
  }
189
- }
190
- function containPath(root, candidate) {
191
- let resolvedRoot;
192
- try {
193
- resolvedRoot = fs.realpathSync(root);
194
- } catch {
195
- return null;
196
- }
197
- const resolved = realpathDeepestExisting(path.resolve(resolvedRoot, candidate));
198
- if (resolved === null) {
867
+ rejection(kind) {
868
+ if (this.stopping) return { status: 503, error: "review complete; server is stopping" };
869
+ if ((kind === "publication" || kind === "mutation") && this.exclusive) {
870
+ return {
871
+ status: 409,
872
+ error: kind === "publication" ? "review submission already in progress or complete" : "review source mutation or publication already in progress"
873
+ };
874
+ }
875
+ if (this.active.size >= (this.options.maxRequests ?? 32) || kind === "expensive-read" && this.expensiveReads >= (this.options.maxExpensiveReads ?? 8)) {
876
+ return { status: 503, error: SERVER_BUSY_ERROR, code: SERVER_BUSY_CODE };
877
+ }
199
878
  return null;
200
879
  }
201
- if (resolved === resolvedRoot) {
202
- return resolved;
880
+ run(req, res, kind, work, timeout) {
881
+ const started = performance.now();
882
+ const controller = new AbortController();
883
+ const exclusive = kind === "publication" || kind === "mutation";
884
+ if (exclusive) this.exclusive = true;
885
+ if (kind === "expensive-read") this.expensiveReads++;
886
+ const abort = () => controller.abort(new Error("Review request disconnected."));
887
+ const onClose = () => {
888
+ if (!res.writableFinished) abort();
889
+ };
890
+ req.once("aborted", abort);
891
+ res.once("close", onClose);
892
+ const timer = setTimeout(() => {
893
+ if (controller.signal.aborted) return;
894
+ controller.abort(new Error("Review request deadline exceeded."));
895
+ timeout(Math.max(0, Math.round(performance.now() - started)));
896
+ }, this.options.requestTimeoutMs ?? 6e4);
897
+ const flushed = new Promise((resolve6) => {
898
+ const finish = () => {
899
+ res.off("finish", finish);
900
+ res.off("close", finish);
901
+ resolve6();
902
+ };
903
+ res.once("finish", finish);
904
+ res.once("close", finish);
905
+ });
906
+ const done = Promise.allSettled([
907
+ Promise.resolve().then(() => work(controller.signal)),
908
+ flushed
909
+ ]).then(() => {
910
+ clearTimeout(timer);
911
+ req.off("aborted", abort);
912
+ res.off("close", onClose);
913
+ this.active.delete(entry);
914
+ if (exclusive) this.exclusive = false;
915
+ if (kind === "expensive-read") this.expensiveReads--;
916
+ });
917
+ const entry = { controller, done, cancelDeadline: () => clearTimeout(timer) };
918
+ this.active.add(entry);
203
919
  }
204
- const rootWithSep = resolvedRoot.endsWith(path.sep) ? resolvedRoot : resolvedRoot + path.sep;
205
- return resolved.startsWith(rootWithSep) ? resolved : null;
206
- }
207
- var MAX_CONTEXT_LINES = 99999;
208
- function isRecord(value) {
209
- return typeof value === "object" && value !== null && !Array.isArray(value);
210
- }
211
- var EXPAND_CONTEXT_KEYS = /* @__PURE__ */ new Set(["filePath", "contextLines"]);
212
- function parseExpandContextBody(body) {
213
- if (typeof body !== "object" || body === null || Array.isArray(body)) {
214
- return { ok: false, error: "body must be a JSON object" };
920
+ drain() {
921
+ return Promise.allSettled([...this.active].map((entry) => entry.done)).then(() => {
922
+ });
215
923
  }
216
- const record = body;
217
- for (const key of Object.keys(record)) {
218
- if (!EXPAND_CONTEXT_KEYS.has(key)) {
219
- return { ok: false, error: `unknown field: ${key}` };
924
+ shutdown() {
925
+ this.stopping = true;
926
+ for (const entry of this.active) {
927
+ entry.cancelDeadline();
928
+ entry.controller.abort(new Error("Review server is stopping."));
220
929
  }
930
+ return this.drain();
221
931
  }
222
- const { filePath, contextLines } = record;
223
- if (typeof filePath !== "string") {
224
- return { ok: false, error: "filePath must be a string" };
225
- }
226
- if (typeof contextLines !== "number" || !Number.isInteger(contextLines) || contextLines < 0 || contextLines > MAX_CONTEXT_LINES) {
227
- return {
228
- ok: false,
229
- error: `contextLines must be an integer between 0 and ${MAX_CONTEXT_LINES}`
230
- };
932
+ };
933
+
934
+ // src/lifecycle.ts
935
+ var REVIEW_PUBLISHED = "review-published";
936
+ var SHUTDOWN_GRACE_MS = 5e3;
937
+ var scheduleDeadline = (expire) => {
938
+ const timer = setTimeout(expire, SHUTDOWN_GRACE_MS);
939
+ return () => clearTimeout(timer);
940
+ };
941
+ function createServeLifecycle(options = {}) {
942
+ const { exit = process.exit, scheduleDeadline: schedule = scheduleDeadline, signals } = options;
943
+ const report = nonThrowingReporter(options.reportDiagnostic);
944
+ const controller = new AbortController();
945
+ const pending = /* @__PURE__ */ new Set();
946
+ let server;
947
+ let stopping = false;
948
+ let exited = false;
949
+ let exitCode = 0;
950
+ let interrupted = false;
951
+ let cancelDeadline = () => {
952
+ };
953
+ const cleanupResponses = /* @__PURE__ */ new Set();
954
+ const finish = () => {
955
+ if (exited) return;
956
+ exited = true;
957
+ cancelDeadline();
958
+ signals?.off("SIGINT", onInterrupt);
959
+ signals?.off("SIGTERM", onTerminate);
960
+ server?.off(REVIEW_PUBLISHED, onPublished);
961
+ server?.off("listening", onListening);
962
+ for (const cleanup of cleanupResponses) cleanup();
963
+ cleanupResponses.clear();
964
+ server?.closeAllConnections();
965
+ exit(exitCode);
966
+ };
967
+ const maybeFinish = () => {
968
+ if (stopping && pending.size === 0) finish();
969
+ };
970
+ const track = (work) => {
971
+ pending.add(work);
972
+ void work.then(
973
+ () => {
974
+ pending.delete(work);
975
+ maybeFinish();
976
+ },
977
+ () => {
978
+ pending.delete(work);
979
+ maybeFinish();
980
+ }
981
+ );
982
+ return work;
983
+ };
984
+ const drainServer = () => {
985
+ server?.close();
986
+ const managed = server;
987
+ if (managed?.[REQUEST_SHUTDOWN]) track(managed[REQUEST_SHUTDOWN]());
988
+ };
989
+ const stop = (code) => {
990
+ if (exited) return;
991
+ if (code === 130 || code === 143) {
992
+ interrupted = true;
993
+ exitCode = code;
994
+ } else if (!interrupted) exitCode = code;
995
+ if (stopping) return;
996
+ stopping = true;
997
+ controller.abort(new Error("Review server is stopping."));
998
+ cancelDeadline = schedule(() => {
999
+ report(
1000
+ "[serve] Shutdown deadline reached; closing remaining connections and waiting for owned work."
1001
+ );
1002
+ server?.closeAllConnections();
1003
+ maybeFinish();
1004
+ });
1005
+ drainServer();
1006
+ maybeFinish();
1007
+ };
1008
+ function onInterrupt() {
1009
+ stop(130);
231
1010
  }
232
- return { ok: true, value: { filePath, contextLines } };
233
- }
234
- var APPLY_KEYS = /* @__PURE__ */ new Set(["filePath", "lineRange", "suggestion"]);
235
- var LINE_RANGE_KEYS = /* @__PURE__ */ new Set(["side", "start", "end"]);
236
- var SUGGESTION_KEYS = /* @__PURE__ */ new Set(["originalCode", "proposedCode"]);
237
- function parseSuggestionApplyBody(body) {
238
- if (!isRecord(body)) {
239
- return { ok: false, error: "body must be a JSON object" };
1011
+ function onTerminate() {
1012
+ stop(143);
240
1013
  }
241
- for (const key of Object.keys(body)) {
242
- if (!APPLY_KEYS.has(key)) return { ok: false, error: `unknown field: ${key}` };
1014
+ function onListening() {
1015
+ if (stopping) server?.close();
243
1016
  }
244
- const { filePath, lineRange, suggestion } = body;
245
- if (typeof filePath !== "string" || filePath === "") {
246
- return { ok: false, error: "filePath must be a non-empty string" };
1017
+ function onPublished(response, drain2) {
1018
+ const cleanup = () => {
1019
+ response.off("finish", complete);
1020
+ response.off("close", complete);
1021
+ cleanupResponses.delete(cleanup);
1022
+ };
1023
+ const complete = () => {
1024
+ cleanup();
1025
+ report("[serve] Review complete; stopping.");
1026
+ if (drain2 && !server?.[REQUEST_SHUTDOWN])
1027
+ track(drain2());
1028
+ stop(0);
1029
+ };
1030
+ cleanupResponses.add(cleanup);
1031
+ response.once("finish", complete);
1032
+ response.once("close", complete);
1033
+ if (response.writableFinished || response.destroyed) complete();
247
1034
  }
248
- if (lineRange !== null) {
249
- if (!isRecord(lineRange)) {
250
- return { ok: false, error: "lineRange must be an object or null" };
1035
+ signals?.on("SIGINT", onInterrupt);
1036
+ signals?.on("SIGTERM", onTerminate);
1037
+ return {
1038
+ signal: controller.signal,
1039
+ track,
1040
+ stop,
1041
+ attach(value) {
1042
+ server = value;
1043
+ server.on(REVIEW_PUBLISHED, onPublished);
1044
+ server.on("listening", onListening);
1045
+ if (stopping) drainServer();
251
1046
  }
252
- for (const key of Object.keys(lineRange)) {
253
- if (!LINE_RANGE_KEYS.has(key)) {
254
- return { ok: false, error: `unknown lineRange field: ${key}` };
1047
+ };
1048
+ }
1049
+
1050
+ // src/bound-server.ts
1051
+ import * as http from "http";
1052
+ import { fileURLToPath } from "url";
1053
+
1054
+ // src/json-body-processing.ts
1055
+ import { Worker as Worker2 } from "worker_threads";
1056
+ var INLINE_JSON_BODY_BYTES = 128 * 1024;
1057
+ function unreadableBody() {
1058
+ return { ok: false, status: 400, error: "request body could not be read" };
1059
+ }
1060
+ async function parseInJsonWorker(worker, chunks2, signal) {
1061
+ let reply;
1062
+ const outcome = new Promise((resolve6) => {
1063
+ reply = resolve6;
1064
+ });
1065
+ let exited;
1066
+ const exit = new Promise((resolve6) => {
1067
+ exited = resolve6;
1068
+ });
1069
+ const onMessage = (result) => reply(result);
1070
+ const onError = () => reply(unreadableBody());
1071
+ const onExit = () => {
1072
+ exited();
1073
+ reply(unreadableBody());
1074
+ };
1075
+ const onAbort = () => reply(unreadableBody());
1076
+ worker.on("message", onMessage);
1077
+ worker.on("error", onError);
1078
+ worker.on("exit", onExit);
1079
+ signal.addEventListener("abort", onAbort, { once: true });
1080
+ try {
1081
+ if (signal.aborted) onAbort();
1082
+ else {
1083
+ try {
1084
+ worker.postMessage(chunks2, chunks2);
1085
+ } catch {
1086
+ onError();
255
1087
  }
256
1088
  }
257
- if (lineRange.side !== "old" && lineRange.side !== "new") {
258
- return { ok: false, error: "lineRange.side must be 'old' or 'new'" };
259
- }
260
- for (const key of ["start", "end"]) {
261
- const value = lineRange[key];
262
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
263
- return { ok: false, error: `lineRange.${key} must be a positive integer` };
264
- }
265
- }
266
- if (lineRange.end < lineRange.start) {
267
- return { ok: false, error: "lineRange.end must not precede lineRange.start" };
268
- }
269
- }
270
- if (!isRecord(suggestion)) {
271
- return { ok: false, error: "suggestion must be an object" };
272
- }
273
- for (const key of Object.keys(suggestion)) {
274
- if (!SUGGESTION_KEYS.has(key)) {
275
- return { ok: false, error: `unknown suggestion field: ${key}` };
276
- }
277
- }
278
- for (const key of ["originalCode", "proposedCode"]) {
279
- if (typeof suggestion[key] !== "string") {
280
- return { ok: false, error: `suggestion.${key} must be a string` };
281
- }
282
- }
283
- return { ok: true, value: body };
284
- }
285
- var REVIEW_STATE_KEYS = /* @__PURE__ */ new Set(["timestamp", "source", "files"]);
286
- function parseReviewStateBody(body) {
287
- if (typeof body !== "object" || body === null || Array.isArray(body)) {
288
- return { ok: false, error: "body must be a JSON object" };
289
- }
290
- const record = body;
291
- for (const key of Object.keys(record)) {
292
- if (!REVIEW_STATE_KEYS.has(key)) {
293
- return { ok: false, error: `unknown field: ${key}` };
1089
+ const result = await outcome;
1090
+ try {
1091
+ await worker.terminate();
1092
+ } catch {
1093
+ await exit;
1094
+ return unreadableBody();
294
1095
  }
1096
+ return signal.aborted ? unreadableBody() : decodeJsonWorkerReply(result);
1097
+ } finally {
1098
+ worker.off("message", onMessage);
1099
+ worker.off("error", onError);
1100
+ worker.off("exit", onExit);
1101
+ signal.removeEventListener("abort", onAbort);
295
1102
  }
296
- const { timestamp, source, files } = record;
297
- if (typeof timestamp !== "string") {
298
- return { ok: false, error: "timestamp must be a string" };
299
- }
300
- if (typeof source !== "object" || source === null || Array.isArray(source)) {
301
- return { ok: false, error: "source must be an object" };
302
- }
303
- if (!Array.isArray(files)) {
304
- return { ok: false, error: "files must be an array" };
305
- }
306
- const decoded = decodeFileAttachments(files);
307
- if (!decoded.ok) {
308
- return decoded;
309
- }
310
- return { ok: true, value: { timestamp, source, files: decoded.value } };
311
1103
  }
312
- var BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)$/;
313
- var RAW_DATA_ERROR = "attachment data must be sent base64-encoded as dataBase64, never as a serialized ArrayBuffer";
314
- var ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
315
- function checkId(entry, what) {
316
- if (entry.id === void 0) return null;
317
- if (typeof entry.id !== "string" || !ID_PATTERN.test(entry.id)) {
318
- return `${what} id must match ${ID_PATTERN.source}`;
1104
+ var JsonBodyProcessing = class {
1105
+ constructor(createWorker = () => new Worker2(new URL("./json-body-worker.js", import.meta.url))) {
1106
+ this.createWorker = createWorker;
1107
+ this.active = /* @__PURE__ */ new Set();
1108
+ this.reservedBytes = 0;
1109
+ this.stopping = false;
319
1110
  }
320
- return null;
321
- }
322
- function base64ToArrayBuffer(value) {
323
- const buffer = Buffer.from(value, "base64");
324
- return buffer.buffer.slice(
325
- buffer.byteOffset,
326
- buffer.byteOffset + buffer.byteLength
327
- );
328
- }
329
- function decodeAttachmentList(list) {
330
- const decoded = [];
331
- for (const entry of list) {
332
- if (!isRecord(entry)) {
333
- decoded.push(entry);
334
- continue;
335
- }
336
- if (entry.data !== void 0) {
337
- return { ok: false, error: RAW_DATA_ERROR };
338
- }
339
- if (entry.dataBase64 === void 0) {
340
- decoded.push(entry);
341
- continue;
342
- }
343
- const encoded = entry.dataBase64;
344
- if (typeof encoded !== "string" || !BASE64_PATTERN.test(encoded)) {
345
- return { ok: false, error: "attachment dataBase64 must be non-empty base64" };
346
- }
347
- const { dataBase64: _encoded, ...rest } = entry;
348
- decoded.push({ ...rest, data: base64ToArrayBuffer(encoded) });
349
- }
350
- return { ok: true, value: decoded };
351
- }
352
- function decodeFileAttachments(files) {
353
- const decodedFiles = [];
354
- for (const file of files) {
355
- if (!isRecord(file) || !Array.isArray(file.comments)) {
356
- decodedFiles.push(file);
357
- continue;
358
- }
359
- const decodedComments = [];
360
- for (const comment of file.comments) {
361
- if (!isRecord(comment)) {
362
- decodedComments.push(comment);
363
- continue;
364
- }
365
- const commentIdError = checkId(comment, "comment");
366
- if (commentIdError) return { ok: false, error: commentIdError };
367
- const next = { ...comment };
368
- if (Array.isArray(comment.attachments)) {
369
- const result = decodeAttachmentList(comment.attachments);
370
- if (!result.ok) return result;
371
- next.attachments = result.value;
372
- }
373
- if (Array.isArray(comment.replies)) {
374
- const decodedReplies = [];
375
- for (const reply of comment.replies) {
376
- if (!isRecord(reply)) {
377
- decodedReplies.push(reply);
378
- continue;
379
- }
380
- const replyIdError = checkId(reply, "reply");
381
- if (replyIdError) return { ok: false, error: replyIdError };
382
- if (!Array.isArray(reply.attachments)) {
383
- decodedReplies.push(reply);
384
- continue;
385
- }
386
- const result = decodeAttachmentList(reply.attachments);
387
- if (!result.ok) return result;
388
- decodedReplies.push({ ...reply, attachments: result.value });
1111
+ reserve(maxBytes) {
1112
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || this.stopping || this.active.size >= 2 || this.reservedBytes + maxBytes > 2 * MAX_REVIEW_BODY_BYTES)
1113
+ return null;
1114
+ const controller = new AbortController();
1115
+ let releaseDone;
1116
+ const done = new Promise((resolve6) => {
1117
+ releaseDone = resolve6;
1118
+ });
1119
+ const entry = { controller, done };
1120
+ this.active.add(entry);
1121
+ this.reservedBytes += maxBytes;
1122
+ let parsing = false;
1123
+ let released = false;
1124
+ const release = () => {
1125
+ if (released || parsing) return;
1126
+ released = true;
1127
+ this.active.delete(entry);
1128
+ this.reservedBytes -= maxBytes;
1129
+ releaseDone();
1130
+ };
1131
+ return {
1132
+ signal: controller.signal,
1133
+ parse: async (chunks2, signal) => {
1134
+ if (released || parsing) throw new Error("JSON body reservation is no longer available.");
1135
+ parsing = true;
1136
+ try {
1137
+ const combined = AbortSignal.any([controller.signal, signal]);
1138
+ if (combined.aborted) return unreadableBody();
1139
+ return await parseInJsonWorker(this.createWorker(), chunks2, combined);
1140
+ } finally {
1141
+ parsing = false;
1142
+ release();
389
1143
  }
390
- next.replies = decodedReplies;
391
- }
392
- decodedComments.push(next);
393
- }
394
- decodedFiles.push({ ...file, comments: decodedComments });
1144
+ },
1145
+ release
1146
+ };
395
1147
  }
396
- return { ok: true, value: decodedFiles };
397
- }
1148
+ shutdown() {
1149
+ this.stopping = true;
1150
+ for (const entry of this.active) entry.controller.abort();
1151
+ return Promise.all([...this.active].map((entry) => entry.done)).then(() => {
1152
+ });
1153
+ }
1154
+ };
1155
+ var defaultJsonBodyProcessing = new JsonBodyProcessing();
398
1156
 
399
1157
  // src/capability.ts
400
1158
  import { randomBytes, timingSafeEqual } from "crypto";
@@ -407,33 +1165,7 @@ function capabilityMatches(expected, presented) {
407
1165
  return a.length === b.length && timingSafeEqual(a, b);
408
1166
  }
409
1167
 
410
- // src/protocol.ts
411
- var MAX_REVIEW_BODY_BYTES = 32 * 1024 * 1024;
412
- var CAPABILITY_FRAGMENT_KEY = "cap";
413
- var CAPABILITY_SCHEME = "Bearer";
414
- function formatLaunchUrl(listenerUrl, capability) {
415
- return `${listenerUrl}#${CAPABILITY_FRAGMENT_KEY}=${capability}`;
416
- }
417
-
418
- // src/server.ts
419
- function defaultClientDir() {
420
- return fileURLToPath(new URL("./client/", import.meta.url));
421
- }
422
- var MAX_EXPAND_CONTEXT_BODY_BYTES = 64 * 1024;
423
- var CONTENT_TYPES = {
424
- ".html": "text/html; charset=utf-8",
425
- ".js": "text/javascript; charset=utf-8",
426
- ".mjs": "text/javascript; charset=utf-8",
427
- ".css": "text/css; charset=utf-8",
428
- ".map": "application/json; charset=utf-8",
429
- ".json": "application/json; charset=utf-8",
430
- ".svg": "image/svg+xml",
431
- ".png": "image/png",
432
- ".ico": "image/x-icon",
433
- ".woff": "font/woff",
434
- ".woff2": "font/woff2",
435
- ".txt": "text/plain; charset=utf-8"
436
- };
1168
+ // src/http-transport.ts
437
1169
  var CSP = [
438
1170
  "default-src 'self'",
439
1171
  "script-src 'self'",
@@ -492,13 +1224,14 @@ function fetchSiteIsSelf(req) {
492
1224
  return site === "same-origin" || site === "none";
493
1225
  }
494
1226
  function sendJson(res, status, value, headers = {}) {
1227
+ const text = JSON.stringify(value ?? null);
495
1228
  res.writeHead(status, {
496
1229
  "content-type": "application/json; charset=utf-8",
497
1230
  "cache-control": "no-store",
498
1231
  ...SECURITY_HEADERS,
499
1232
  ...headers
500
1233
  });
501
- res.end(JSON.stringify(value ?? null));
1234
+ res.end(text);
502
1235
  }
503
1236
  function sendError(res, status, error) {
504
1237
  sendJson(res, status, { error }, status === 413 ? { connection: "close" } : {});
@@ -511,12 +1244,484 @@ function presentsCapability(req, capability) {
511
1244
  if (header.slice(0, space).toLowerCase() !== CAPABILITY_SCHEME.toLowerCase()) return false;
512
1245
  return capabilityMatches(capability, header.slice(space + 1).trim());
513
1246
  }
514
- function sendUnauthorized(res) {
515
- sendJson(res, 401, { error: "unauthorized" }, { "www-authenticate": CAPABILITY_SCHEME });
1247
+ function sendUnauthorized(res) {
1248
+ sendJson(res, 401, { error: "unauthorized" }, { "www-authenticate": CAPABILITY_SCHEME });
1249
+ }
1250
+ function allowRequest(req, res, url, capability) {
1251
+ if (!hostIsLoopback(req) || !originMatchesHost(req) || !fetchSiteIsSelf(req)) {
1252
+ sendError(res, 403, "forbidden");
1253
+ return false;
1254
+ }
1255
+ if (url.pathname.startsWith("/api/") && !presentsCapability(req, capability)) {
1256
+ sendUnauthorized(res);
1257
+ return false;
1258
+ }
1259
+ return true;
1260
+ }
1261
+ async function readJsonBody(req, maxBytes, signal, processing = defaultJsonBodyProcessing) {
1262
+ const contentType = req.headers["content-type"] ?? "";
1263
+ if (contentType.split(";", 1)[0].trim().toLowerCase() !== "application/json") {
1264
+ return { ok: false, status: 415, error: "content-type must be application/json" };
1265
+ }
1266
+ const declared = Number(req.headers["content-length"]);
1267
+ if (Number.isFinite(declared) && declared > maxBytes) {
1268
+ return { ok: false, status: 413, error: "request body too large" };
1269
+ }
1270
+ const chunks2 = [];
1271
+ let received = 0;
1272
+ let tailBytes = 0;
1273
+ const ownership = { lease: null };
1274
+ const cancelled = new AbortController();
1275
+ const unreadable = {
1276
+ ok: false,
1277
+ status: 400,
1278
+ error: "request body could not be read"
1279
+ };
1280
+ let collected;
1281
+ const collection = new Promise((resolve6) => {
1282
+ collected = resolve6;
1283
+ });
1284
+ let reading = true;
1285
+ const finishCollection = (result) => {
1286
+ if (!reading) return;
1287
+ reading = false;
1288
+ req.off("data", onData);
1289
+ req.off("end", onEnd);
1290
+ collected(result);
1291
+ };
1292
+ const onError = () => {
1293
+ cancelled.abort();
1294
+ finishCollection(unreadable);
1295
+ };
1296
+ const onData = (chunk) => {
1297
+ received += chunk.length;
1298
+ if (received > maxBytes) {
1299
+ finishCollection({ ok: false, status: 413, error: "request body too large" });
1300
+ return;
1301
+ }
1302
+ if (!ownership.lease && received > INLINE_JSON_BODY_BYTES) {
1303
+ ownership.lease = processing.reserve(maxBytes);
1304
+ if (!ownership.lease) {
1305
+ finishCollection({ ok: false, status: 503, error: SERVER_BUSY_ERROR });
1306
+ return;
1307
+ }
1308
+ ownership.lease.signal.addEventListener("abort", onError, { once: true });
1309
+ if (ownership.lease.signal.aborted) {
1310
+ onError();
1311
+ return;
1312
+ }
1313
+ }
1314
+ let offset = 0;
1315
+ while (offset < chunk.length) {
1316
+ let tail = chunks2[chunks2.length - 1];
1317
+ if (!tail || tailBytes === tail.length) {
1318
+ tail = new Uint8Array(64 * 1024);
1319
+ chunks2.push(tail);
1320
+ tailBytes = 0;
1321
+ }
1322
+ const length = Math.min(tail.length - tailBytes, chunk.length - offset);
1323
+ tail.set(chunk.subarray(offset, offset + length), tailBytes);
1324
+ tailBytes += length;
1325
+ offset += length;
1326
+ }
1327
+ };
1328
+ const onEnd = () => finishCollection(null);
1329
+ try {
1330
+ if (signal?.aborted) return unreadable;
1331
+ req.on("data", onData);
1332
+ req.once("end", onEnd);
1333
+ req.on("error", onError);
1334
+ req.once("aborted", onError);
1335
+ signal?.addEventListener("abort", onError, { once: true });
1336
+ const failure = await collection;
1337
+ if (failure) return failure;
1338
+ if (cancelled.signal.aborted) return unreadable;
1339
+ const last = chunks2.length - 1;
1340
+ if (last >= 0 && tailBytes < chunks2[last].length)
1341
+ chunks2[last] = chunks2[last].slice(0, tailBytes);
1342
+ const result = ownership.lease ? await ownership.lease.parse(
1343
+ chunks2.map((chunk) => chunk.buffer),
1344
+ cancelled.signal
1345
+ ) : decodeJsonBody(chunks2);
1346
+ return cancelled.signal.aborted ? unreadable : result;
1347
+ } finally {
1348
+ req.off("data", onData);
1349
+ req.off("end", onEnd);
1350
+ req.off("error", onError);
1351
+ req.off("aborted", onError);
1352
+ signal?.removeEventListener("abort", onError);
1353
+ ownership.lease?.signal.removeEventListener("abort", onError);
1354
+ ownership.lease?.release();
1355
+ chunks2.length = 0;
1356
+ }
1357
+ }
1358
+
1359
+ // src/static-assets.ts
1360
+ import * as fs2 from "fs";
1361
+ import * as path4 from "path";
1362
+ import { once } from "events";
1363
+
1364
+ // src/contained-path.ts
1365
+ import * as fs from "fs";
1366
+ import * as path3 from "path";
1367
+ function isUnavailablePathError(error) {
1368
+ const code = error?.code;
1369
+ return code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP" || code === "ENAMETOOLONG";
1370
+ }
1371
+ async function containPathAsync(root, candidate, options = {}) {
1372
+ const { signal } = options;
1373
+ async function realpath2(name) {
1374
+ signal?.throwIfAborted();
1375
+ const resolved = await fs.promises.realpath(name);
1376
+ signal?.throwIfAborted();
1377
+ return resolved;
1378
+ }
1379
+ let resolvedRoot;
1380
+ try {
1381
+ resolvedRoot = await realpath2(root);
1382
+ } catch (error) {
1383
+ signal?.throwIfAborted();
1384
+ if (!isUnavailablePathError(error)) throw error;
1385
+ return null;
1386
+ }
1387
+ const missing = [];
1388
+ let current = path3.resolve(resolvedRoot, candidate);
1389
+ for (; ; ) {
1390
+ signal?.throwIfAborted();
1391
+ try {
1392
+ const ancestor = await realpath2(current);
1393
+ const resolved = path3.join(ancestor, ...missing.reverse());
1394
+ const rootWithSep = resolvedRoot.endsWith(path3.sep) ? resolvedRoot : resolvedRoot + path3.sep;
1395
+ return resolved === resolvedRoot || resolved.startsWith(rootWithSep) ? resolved : null;
1396
+ } catch (error) {
1397
+ signal?.throwIfAborted();
1398
+ if (!isUnavailablePathError(error)) throw error;
1399
+ if (error.code === "ELOOP") return null;
1400
+ const parent = path3.dirname(current);
1401
+ if (parent === current) return null;
1402
+ missing.push(path3.basename(current));
1403
+ current = parent;
1404
+ }
1405
+ }
1406
+ }
1407
+
1408
+ // src/static-assets.ts
1409
+ var CONTENT_TYPES = {
1410
+ ".html": "text/html; charset=utf-8",
1411
+ ".js": "text/javascript; charset=utf-8",
1412
+ ".mjs": "text/javascript; charset=utf-8",
1413
+ ".css": "text/css; charset=utf-8",
1414
+ ".map": "application/json; charset=utf-8",
1415
+ ".json": "application/json; charset=utf-8",
1416
+ ".svg": "image/svg+xml",
1417
+ ".png": "image/png",
1418
+ ".ico": "image/x-icon",
1419
+ ".woff": "font/woff",
1420
+ ".woff2": "font/woff2",
1421
+ ".txt": "text/plain; charset=utf-8"
1422
+ };
1423
+ var MAX_STATIC_ASSET_BYTES = 32 * 1024 * 1024;
1424
+ var STATIC_READ_CHUNK_BYTES = 64 * 1024;
1425
+ async function serveStatic(res, clientDir, pathname, options = {}) {
1426
+ let decoded;
1427
+ try {
1428
+ decoded = decodeURIComponent(pathname);
1429
+ } catch {
1430
+ sendError(res, 404, "not found");
1431
+ return;
1432
+ }
1433
+ if (decoded.includes("\0")) {
1434
+ sendError(res, 404, "not found");
1435
+ return;
1436
+ }
1437
+ const relative = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
1438
+ const controller = new AbortController();
1439
+ const abort = () => controller.abort(new Error("Static delivery cancelled."));
1440
+ options.signal?.addEventListener("abort", abort, { once: true });
1441
+ res.once("close", abort);
1442
+ if (options.signal?.aborted || res.destroyed) abort();
1443
+ const { signal } = controller;
1444
+ let file;
1445
+ try {
1446
+ let writeHeaders2 = function() {
1447
+ res.writeHead(200, {
1448
+ "content-type": CONTENT_TYPES[path4.extname(resolved).toLowerCase()] ?? "application/octet-stream",
1449
+ "content-length": stat.size,
1450
+ ...SECURITY_HEADERS
1451
+ });
1452
+ };
1453
+ var writeHeaders = writeHeaders2;
1454
+ signal.throwIfAborted();
1455
+ const resolved = await containPathAsync(clientDir, relative, { signal });
1456
+ signal.throwIfAborted();
1457
+ if (resolved === null) {
1458
+ sendError(res, 404, "not found");
1459
+ return;
1460
+ }
1461
+ file = await fs2.promises.open(
1462
+ resolved,
1463
+ fs2.constants.O_RDONLY | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK
1464
+ );
1465
+ signal.throwIfAborted();
1466
+ const stat = await file.stat();
1467
+ signal.throwIfAborted();
1468
+ const named = await fs2.promises.lstat(resolved);
1469
+ signal.throwIfAborted();
1470
+ if (!stat.isFile() || stat.dev !== named.dev || stat.ino !== named.ino || named.isSymbolicLink() || await containPathAsync(clientDir, relative, { signal }) !== resolved || await fs2.promises.realpath(resolved) !== resolved) {
1471
+ sendError(res, 404, "not found");
1472
+ return;
1473
+ }
1474
+ signal.throwIfAborted();
1475
+ if (stat.size > MAX_STATIC_ASSET_BYTES) {
1476
+ sendError(res, 413, "static asset exceeds 32 MiB limit");
1477
+ return;
1478
+ }
1479
+ let position = 0;
1480
+ while (position < stat.size) {
1481
+ signal.throwIfAborted();
1482
+ const buffer = Buffer.allocUnsafe(Math.min(STATIC_READ_CHUNK_BYTES, stat.size - position));
1483
+ const { bytesRead } = await file.read({ buffer, position });
1484
+ signal.throwIfAborted();
1485
+ if (bytesRead === 0) throw new Error("Static asset shortened during delivery.");
1486
+ if (!res.headersSent) writeHeaders2();
1487
+ position += bytesRead;
1488
+ if (!res.write(buffer.subarray(0, bytesRead))) await once(res, "drain", { signal });
1489
+ }
1490
+ signal.throwIfAborted();
1491
+ if (!res.headersSent) writeHeaders2();
1492
+ res.end();
1493
+ } catch (error) {
1494
+ if (signal.aborted) res.destroy();
1495
+ else if (isUnavailablePathError(error)) {
1496
+ if (res.headersSent) res.destroy();
1497
+ else sendError(res, 404, "not found");
1498
+ } else {
1499
+ throw error;
1500
+ }
1501
+ } finally {
1502
+ options.signal?.removeEventListener("abort", abort);
1503
+ res.off("close", abort);
1504
+ await file?.close();
1505
+ }
1506
+ }
1507
+
1508
+ // src/review-submission.ts
1509
+ import { ReviewPublishError } from "@self-review/core";
1510
+
1511
+ // src/legacy-submission.ts
1512
+ function legacyPublication(operations) {
1513
+ return {
1514
+ publicationError: operations.publicationError,
1515
+ publishReview: async (state, options) => {
1516
+ operations.submitReviewState(state);
1517
+ return operations.publishReview(state, options);
1518
+ }
1519
+ };
1520
+ }
1521
+
1522
+ // src/review-submission.ts
1523
+ var ReviewSubmission = class {
1524
+ constructor(input, reportDiagnostic) {
1525
+ this.state = "open";
1526
+ this.operations = "submitReviewState" in input ? legacyPublication(input) : input.publication;
1527
+ this.report = nonThrowingReporter(reportDiagnostic);
1528
+ }
1529
+ get completed() {
1530
+ return this.state === "published";
1531
+ }
1532
+ /** Reserve before reading the body, so overlapping uploads cannot both enter publication. */
1533
+ begin() {
1534
+ if (this.state !== "open") return false;
1535
+ this.state = "publishing";
1536
+ return true;
1537
+ }
1538
+ /** Failed parsing, publication or unexpected errors all permit a repaired submission. */
1539
+ release() {
1540
+ if (this.state === "publishing") this.state = "open";
1541
+ }
1542
+ async publish(state, options) {
1543
+ try {
1544
+ const { outputPath } = await this.operations.publishReview(state, options);
1545
+ this.state = "published";
1546
+ this.report(`[serve] Review written to ${outputPath}`);
1547
+ return { ok: true, outputPath };
1548
+ } catch (error) {
1549
+ if (!(error instanceof (this.operations.publicationError ?? ReviewPublishError))) throw error;
1550
+ this.report(`[serve] Review not saved (${error.code}): ${error.message}`);
1551
+ for (const detail of error.details) this.report(`[serve] ${detail}`);
1552
+ this.report(
1553
+ "[serve] The review is still open in the browser. Fix the problem and press Finish Review again."
1554
+ );
1555
+ return { ok: false, code: error.code, message: error.message, details: [...error.details] };
1556
+ }
1557
+ }
1558
+ };
1559
+ var DOCUMENT_ERROR_CODES = /* @__PURE__ */ new Set([
1560
+ "validation-failed",
1561
+ "xml-illegal-character"
1562
+ ]);
1563
+ function publishFailureStatus(code) {
1564
+ return DOCUMENT_ERROR_CODES.has(code) ? 422 : 500;
1565
+ }
1566
+
1567
+ // src/bound-api-routes.ts
1568
+ import { parseAttachmentReference as parseAttachmentReference2 } from "@self-review/core";
1569
+
1570
+ // src/json-response.ts
1571
+ import { setImmediate } from "timers/promises";
1572
+ var MAX_JSON_RESPONSE_BYTES = 64 * 1024 * 1024;
1573
+ var MAX_JSON_RESPONSE_NODES = 2e6;
1574
+ var MAX_DEPTH = 128;
1575
+ var CHUNK_CHARS = 16 * 1024;
1576
+ var JsonResponseLimitError = class extends Error {
1577
+ };
1578
+ function* quoted(text) {
1579
+ yield '"';
1580
+ for (let start = 0; start < text.length; ) {
1581
+ let end = Math.min(text.length, start + CHUNK_CHARS);
1582
+ if (end < text.length && text.charCodeAt(end - 1) >= 55296 && text.charCodeAt(end - 1) <= 56319)
1583
+ end--;
1584
+ yield JSON.stringify(text.slice(start, end)).slice(1, -1);
1585
+ start = end;
1586
+ }
1587
+ yield '"';
1588
+ }
1589
+ function* tokens(value, maxNodes) {
1590
+ let nodes = 0;
1591
+ const ancestors = /* @__PURE__ */ new Set();
1592
+ function* visit(value2, depth) {
1593
+ if (++nodes > maxNodes || depth > MAX_DEPTH)
1594
+ throw new JsonResponseLimitError("JSON response exceeds the serialization work limit");
1595
+ if (typeof value2 === "string") {
1596
+ yield* quoted(value2);
1597
+ return;
1598
+ }
1599
+ if (value2 === null || value2 === void 0) {
1600
+ yield "null";
1601
+ return;
1602
+ }
1603
+ if (typeof value2 === "boolean" || typeof value2 === "number") {
1604
+ yield JSON.stringify(value2);
1605
+ return;
1606
+ }
1607
+ if (typeof value2 !== "object") throw new TypeError("Response must be a JSON DTO");
1608
+ if (ancestors.has(value2)) throw new TypeError("Response contains a cycle");
1609
+ ancestors.add(value2);
1610
+ try {
1611
+ if (Array.isArray(value2)) {
1612
+ const length = value2.length;
1613
+ if (length > maxNodes - nodes)
1614
+ throw new JsonResponseLimitError("JSON response exceeds the serialization work limit");
1615
+ yield "[";
1616
+ for (let i = 0; i < length; i++) {
1617
+ if (i) yield ",";
1618
+ const descriptor = Object.getOwnPropertyDescriptor(value2, String(i));
1619
+ if (descriptor && !("value" in descriptor))
1620
+ throw new TypeError("Response contains an accessor");
1621
+ yield* visit(descriptor?.value, depth + 1);
1622
+ }
1623
+ yield "]";
1624
+ } else {
1625
+ const keys = Object.keys(value2);
1626
+ if (keys.length > maxNodes - nodes)
1627
+ throw new JsonResponseLimitError("JSON response exceeds the serialization work limit");
1628
+ yield "{";
1629
+ let first = true;
1630
+ for (const key of keys) {
1631
+ const descriptor = Object.getOwnPropertyDescriptor(value2, key);
1632
+ if (!descriptor || !("value" in descriptor))
1633
+ throw new TypeError("Response contains an accessor");
1634
+ if (descriptor.value === void 0) {
1635
+ if (++nodes > maxNodes)
1636
+ throw new JsonResponseLimitError(
1637
+ "JSON response exceeds the serialization work limit"
1638
+ );
1639
+ continue;
1640
+ }
1641
+ if (!first) yield ",";
1642
+ first = false;
1643
+ yield* quoted(key);
1644
+ yield ":";
1645
+ yield* visit(descriptor.value, depth + 1);
1646
+ }
1647
+ yield "}";
1648
+ }
1649
+ } finally {
1650
+ ancestors.delete(value2);
1651
+ }
1652
+ }
1653
+ yield* visit(value, 0);
1654
+ }
1655
+ async function* chunks(value, options) {
1656
+ let bytes = 0;
1657
+ let steps = 0;
1658
+ let checkpointBytes = 0;
1659
+ let pending = "";
1660
+ for (const token of tokens(value, options.maxNodes ?? MAX_JSON_RESPONSE_NODES)) {
1661
+ options.signal.throwIfAborted();
1662
+ const tokenBytes = Buffer.byteLength(token);
1663
+ bytes += tokenBytes;
1664
+ checkpointBytes += tokenBytes;
1665
+ if (bytes > (options.maxBytes ?? MAX_JSON_RESPONSE_BYTES))
1666
+ throw new JsonResponseLimitError("JSON response exceeds the output byte limit");
1667
+ pending += token;
1668
+ if (pending.length >= CHUNK_CHARS) {
1669
+ yield pending;
1670
+ pending = "";
1671
+ }
1672
+ if (++steps % 2048 === 0 || checkpointBytes >= 256 * 1024) {
1673
+ await setImmediate(void 0, { signal: options.signal });
1674
+ checkpointBytes = 0;
1675
+ }
1676
+ }
1677
+ if (pending) yield pending;
1678
+ }
1679
+ function drain(res, signal) {
1680
+ return new Promise((resolve6, reject) => {
1681
+ const cleanup = () => {
1682
+ res.off("drain", ready);
1683
+ res.off("close", closed);
1684
+ res.off("error", failed);
1685
+ signal.removeEventListener("abort", aborted);
1686
+ };
1687
+ const ready = () => {
1688
+ cleanup();
1689
+ resolve6();
1690
+ };
1691
+ const failed = (error) => {
1692
+ cleanup();
1693
+ reject(error);
1694
+ };
1695
+ const closed = () => failed(new Error("JSON response disconnected"));
1696
+ const aborted = () => failed(signal.reason);
1697
+ res.once("drain", ready);
1698
+ res.once("close", closed);
1699
+ res.once("error", failed);
1700
+ signal.addEventListener("abort", aborted, { once: true });
1701
+ if (signal.aborted) aborted();
1702
+ else if (res.destroyed) closed();
1703
+ });
1704
+ }
1705
+ async function sendLargeJson(res, value, options) {
1706
+ for await (const _chunk of chunks(value, options)) {
1707
+ }
1708
+ options.signal.throwIfAborted();
1709
+ res.writeHead(200, {
1710
+ "content-type": "application/json; charset=utf-8",
1711
+ "cache-control": "no-store",
1712
+ ...SECURITY_HEADERS
1713
+ });
1714
+ for await (const chunk of chunks(value, options)) {
1715
+ if (!res.write(chunk)) await drain(res, options.signal);
1716
+ }
1717
+ res.end();
516
1718
  }
1719
+
1720
+ // src/bound-api-routes.ts
1721
+ var MAX_EXPAND_CONTEXT_BODY_BYTES = 64 * 1024;
517
1722
  var REVIEWED_PATH_ERROR = "path must name a file in the reviewed diff";
518
- function requireReviewedPath(ctx, filePath, what = "path") {
519
- if (authorizeReviewedPath(ctx.session, filePath).ok) return true;
1723
+ function requireReviewedPath(ctx, authorize, filePath, what = "path") {
1724
+ if (authorize(filePath).ok) return true;
520
1725
  sendError(
521
1726
  ctx.res,
522
1727
  400,
@@ -524,82 +1729,48 @@ function requireReviewedPath(ctx, filePath, what = "path") {
524
1729
  );
525
1730
  return false;
526
1731
  }
527
- function requireReviewedQueryPath(ctx) {
1732
+ function requireReviewedQueryPath(ctx, authorize) {
528
1733
  const raw = ctx.url.searchParams.get("path");
529
1734
  if (raw === null) {
530
1735
  sendError(ctx.res, 400, REVIEWED_PATH_ERROR);
531
1736
  return null;
532
1737
  }
533
- return requireReviewedPath(ctx, raw) ? raw : null;
534
- }
535
- function readJsonBody(req, maxBytes) {
536
- const contentType = req.headers["content-type"] ?? "";
537
- if (!contentType.toLowerCase().startsWith("application/json")) {
538
- return Promise.resolve({
539
- ok: false,
540
- status: 415,
541
- error: "content-type must be application/json"
542
- });
543
- }
544
- const declared = Number(req.headers["content-length"]);
545
- if (Number.isFinite(declared) && declared > maxBytes) {
546
- return Promise.resolve({ ok: false, status: 413, error: "request body too large" });
547
- }
548
- return new Promise((resolve3) => {
549
- const chunks = [];
550
- let received = 0;
551
- req.on("data", (chunk) => {
552
- received += chunk.length;
553
- if (received > maxBytes) {
554
- chunks.length = 0;
555
- req.removeAllListeners("data");
556
- req.removeAllListeners("end");
557
- resolve3({ ok: false, status: 413, error: "request body too large" });
558
- return;
559
- }
560
- chunks.push(chunk);
561
- });
562
- req.on("end", () => {
563
- try {
564
- resolve3({ ok: true, value: JSON.parse(Buffer.concat(chunks).toString("utf-8")) });
565
- } catch {
566
- resolve3({ ok: false, status: 400, error: "body must be valid JSON" });
567
- }
568
- });
569
- req.on("error", () => {
570
- resolve3({ ok: false, status: 400, error: "request body could not be read" });
571
- });
572
- });
1738
+ return requireReviewedPath(ctx, authorize, raw) ? raw : null;
573
1739
  }
574
- var routes = {
575
- "GET /api/diff": async ({ res, session }) => {
576
- sendJson(res, 200, getDiffLoad(session));
577
- },
578
- "GET /api/config": async ({ res, session }) => {
579
- sendJson(res, 200, getConfigLoad(session));
580
- },
581
- "GET /api/resume": async ({ res, session }) => {
582
- sendJson(res, 200, getResumeLoad(session));
583
- },
584
- "GET /api/file": async (ctx) => {
585
- const filePath = requireReviewedQueryPath(ctx);
1740
+ function createFileRoute({
1741
+ authorizeReviewedPath,
1742
+ getFileHunks
1743
+ }) {
1744
+ return async (ctx) => {
1745
+ const filePath = requireReviewedQueryPath(ctx, authorizeReviewedPath);
586
1746
  if (filePath === null) return;
587
- sendJson(ctx.res, 200, getFileHunks(ctx.session, filePath));
588
- },
589
- "GET /api/image": async (ctx) => {
590
- const filePath = requireReviewedQueryPath(ctx);
1747
+ await sendLargeJson(ctx.res, getFileHunks(filePath), { signal: ctx.signal });
1748
+ };
1749
+ }
1750
+ function createImageRoute({
1751
+ authorizeReviewedPath,
1752
+ loadImage
1753
+ }) {
1754
+ return async (ctx) => {
1755
+ const filePath = requireReviewedQueryPath(ctx, authorizeReviewedPath);
591
1756
  if (filePath === null) return;
592
- sendJson(ctx.res, 200, await loadImage(ctx.session, filePath));
593
- },
594
- "GET /api/attachment": async (ctx) => {
1757
+ await sendLargeJson(ctx.res, await loadImage(filePath, { signal: ctx.signal }), {
1758
+ signal: ctx.signal
1759
+ });
1760
+ };
1761
+ }
1762
+ function createAttachmentRoute({
1763
+ readAttachment
1764
+ }) {
1765
+ return async (ctx) => {
595
1766
  const raw = ctx.url.searchParams.get("path");
596
- if (raw === null || parseAttachmentReference(raw) === null) {
1767
+ if (raw === null || parseAttachmentReference2(raw) === null) {
597
1768
  sendError(ctx.res, 400, "path must name a file in the .self-review-assets directory");
598
1769
  return;
599
1770
  }
600
- const result = await readAttachment(ctx.session, raw);
1771
+ const result = await readAttachment(raw, { signal: ctx.signal });
601
1772
  if (!result.ok) {
602
- const status = result.reason === "not-authorized" ? 400 : result.reason === "too-large" ? 413 : 404;
1773
+ const status = result.reason === "not-found" ? 404 : result.reason === "too-large" ? 413 : result.reason === "io-error" ? 500 : 400;
603
1774
  sendError(ctx.res, status, status === 404 ? "attachment not found" : result.message);
604
1775
  return;
605
1776
  }
@@ -610,122 +1781,396 @@ var routes = {
610
1781
  ...SECURITY_HEADERS
611
1782
  });
612
1783
  res.end(Buffer.from(result.data));
613
- },
614
- "POST /api/expand-context": async (ctx) => {
615
- const { req, res, session } = ctx;
616
- const body = await readJsonBody(req, MAX_EXPAND_CONTEXT_BODY_BYTES);
1784
+ };
1785
+ }
1786
+ function createExpansionRoute({
1787
+ authorizeReviewedPath,
1788
+ expandContext
1789
+ }, parseExpandContextBody2, processing) {
1790
+ return async (ctx) => {
1791
+ const { req, res } = ctx;
1792
+ const body = await readJsonBody(req, MAX_EXPAND_CONTEXT_BODY_BYTES, ctx.signal, processing);
617
1793
  if (!body.ok) {
618
1794
  sendError(res, body.status, body.error);
619
1795
  return;
620
1796
  }
621
- const parsed = parseExpandContextBody(body.value);
1797
+ const parsed = parseExpandContextBody2(body.value);
622
1798
  if (!parsed.ok) {
623
1799
  sendError(res, 400, parsed.error);
624
1800
  return;
625
1801
  }
626
- if (!requireReviewedPath(ctx, parsed.value.filePath, "filePath")) return;
627
- sendJson(res, 200, await expandContext(session, parsed.value));
628
- },
629
- // The one route that rewrites a file in the reviewed tree. Core refuses unless the anchored lines still
630
- // match the suggestion's recorded original byte for byte, and resolves the destination itself.
631
- "POST /api/apply-suggestion": async (ctx) => {
632
- const { req, res, session } = ctx;
633
- const body = await readJsonBody(req, MAX_EXPAND_CONTEXT_BODY_BYTES);
1802
+ if (!requireReviewedPath(ctx, authorizeReviewedPath, parsed.value.filePath, "filePath")) return;
1803
+ await sendLargeJson(res, await expandContext(parsed.value, { signal: ctx.signal }), {
1804
+ signal: ctx.signal
1805
+ });
1806
+ };
1807
+ }
1808
+ function createApplyRoute({
1809
+ authorizeReviewedPath,
1810
+ applySuggestionForSession
1811
+ }, parseSuggestionApplyBody2, processing) {
1812
+ return async (ctx) => {
1813
+ const { req, res } = ctx;
1814
+ const body = await readJsonBody(req, MAX_APPLY_BODY_BYTES, ctx.signal, processing);
634
1815
  if (!body.ok) {
635
1816
  sendError(res, body.status, body.error);
636
1817
  return;
637
1818
  }
638
- const parsed = parseSuggestionApplyBody(body.value);
1819
+ const parsed = parseSuggestionApplyBody2(body.value);
639
1820
  if (!parsed.ok) {
640
1821
  sendError(res, 400, parsed.error);
641
1822
  return;
642
1823
  }
643
- if (!requireReviewedPath(ctx, parsed.value.filePath, "filePath")) return;
644
- sendJson(res, 200, applySuggestionForSession(session, parsed.value));
645
- },
646
- // The completion: a 200 means the file is on disk; a failure leaves the server up for a retry.
647
- "POST /api/review": async ({ req, res, session, output }) => {
648
- const body = await readJsonBody(req, MAX_REVIEW_BODY_BYTES);
649
- if (!body.ok) {
650
- sendError(res, body.status, body.error);
1824
+ if (!requireReviewedPath(ctx, authorizeReviewedPath, parsed.value.filePath, "filePath")) return;
1825
+ sendJson(res, 200, await applySuggestionForSession(parsed.value, { signal: ctx.signal }));
1826
+ };
1827
+ }
1828
+ function createSubmissionRoute(submission, published, parseReviewStateBody2, processing) {
1829
+ return async ({ req, res, signal }) => {
1830
+ if (!submission.begin()) {
1831
+ sendError(res, 409, "review submission already in progress or complete");
651
1832
  return;
652
1833
  }
653
- const parsed = parseReviewStateBody(body.value);
654
- if (!parsed.ok) {
655
- sendError(res, 400, parsed.error);
656
- return;
1834
+ try {
1835
+ const body = await readJsonBody(req, MAX_REVIEW_BODY_BYTES, signal, processing);
1836
+ if (!body.ok) {
1837
+ sendError(res, body.status, body.error);
1838
+ return;
1839
+ }
1840
+ const parsed = parseReviewStateBody2(body.value);
1841
+ if (!parsed.ok) {
1842
+ sendError(res, 400, parsed.error);
1843
+ return;
1844
+ }
1845
+ if (signal.aborted) throw signal.reason;
1846
+ const outcome = await submission.publish(parsed.value, { signal });
1847
+ if (outcome.ok) {
1848
+ published(res);
1849
+ sendJson(res, 200, outcome);
1850
+ } else {
1851
+ sendJson(res, publishFailureStatus(outcome.code), outcome);
1852
+ }
1853
+ } finally {
1854
+ submission.release();
657
1855
  }
658
- submitReviewState(session, parsed.value);
659
- const outcome = await publishSubmittedReview(parsed.value, output, session);
660
- if (outcome.ok) {
661
- sendJson(res, 200, outcome);
662
- } else {
663
- sendJson(res, publishFailureStatus(outcome.code), outcome);
1856
+ };
1857
+ }
1858
+ function createJsonReadRoute(read) {
1859
+ return {
1860
+ kind: "expensive-read",
1861
+ handle: async ({ res, signal }) => {
1862
+ await sendLargeJson(res, read(), { signal });
1863
+ }
1864
+ };
1865
+ }
1866
+ function createBoundApiRoutes(operations, submission, published, validation, processing = defaultJsonBodyProcessing) {
1867
+ const authorizeReviewedPath = (path5) => operations.authorizeReviewedPath(path5);
1868
+ return {
1869
+ "GET /api/diff": createJsonReadRoute(() => operations.getDiffLoad()),
1870
+ "GET /api/config": createJsonReadRoute(() => operations.getConfigLoad()),
1871
+ "GET /api/resume": createJsonReadRoute(() => operations.getResumeLoad()),
1872
+ "GET /api/file": {
1873
+ kind: "expensive-read",
1874
+ handle: createFileRoute({
1875
+ authorizeReviewedPath,
1876
+ getFileHunks: (...args) => operations.getFileHunks(...args)
1877
+ })
1878
+ },
1879
+ "GET /api/image": {
1880
+ kind: "expensive-read",
1881
+ handle: createImageRoute({
1882
+ authorizeReviewedPath,
1883
+ loadImage: (...args) => operations.loadImage(...args)
1884
+ })
1885
+ },
1886
+ "GET /api/attachment": {
1887
+ kind: "expensive-read",
1888
+ handle: createAttachmentRoute({
1889
+ readAttachment: (...args) => operations.readAttachment(...args)
1890
+ })
1891
+ },
1892
+ "POST /api/expand-context": {
1893
+ kind: "mutation",
1894
+ handle: createExpansionRoute(
1895
+ {
1896
+ authorizeReviewedPath,
1897
+ expandContext: (...args) => operations.expandContext(...args)
1898
+ },
1899
+ validation.parseExpandContextBody,
1900
+ processing
1901
+ )
1902
+ },
1903
+ "POST /api/apply-suggestion": {
1904
+ kind: "mutation",
1905
+ handle: createApplyRoute(
1906
+ {
1907
+ authorizeReviewedPath,
1908
+ applySuggestionForSession: (...args) => operations.applySuggestionForSession(...args)
1909
+ },
1910
+ validation.parseSuggestionApplyBody,
1911
+ processing
1912
+ )
1913
+ },
1914
+ "POST /api/review": {
1915
+ kind: "publication",
1916
+ handle: createSubmissionRoute(
1917
+ submission,
1918
+ published,
1919
+ validation.parseReviewStateBody,
1920
+ processing
1921
+ )
664
1922
  }
1923
+ };
1924
+ }
1925
+
1926
+ // src/attachment-codec.ts
1927
+ function isRecord(value) {
1928
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1929
+ }
1930
+ var BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)$/;
1931
+ var RAW_DATA_ERROR = "attachment data must be sent base64-encoded as dataBase64, never as a serialized ArrayBuffer";
1932
+ var ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
1933
+ function checkId(entry, what) {
1934
+ if (entry.id === void 0) return null;
1935
+ if (typeof entry.id !== "string" || !ID_PATTERN.test(entry.id)) {
1936
+ return `${what} id must match ${ID_PATTERN.source}`;
665
1937
  }
666
- };
667
- async function publishSubmittedReview(state, output, session) {
668
- const options = publishOptionsFor2(output, session.attachmentOrigins);
669
- try {
670
- const { outputPath } = await publishReview(state, output.path, options);
671
- console.error(`[serve] Review written to ${outputPath}`);
672
- return { ok: true, outputPath };
673
- } catch (error) {
674
- if (!(error instanceof ReviewPublishError)) throw error;
675
- console.error(`[serve] Review not saved (${error.code}): ${error.message}`);
676
- for (const detail of error.details) {
677
- console.error(`[serve] ${detail}`);
1938
+ return null;
1939
+ }
1940
+ function base64ToArrayBuffer(value) {
1941
+ const buffer = Buffer.from(value, "base64");
1942
+ return buffer.buffer.slice(
1943
+ buffer.byteOffset,
1944
+ buffer.byteOffset + buffer.byteLength
1945
+ );
1946
+ }
1947
+ function decodeAttachmentList(list) {
1948
+ const decoded = [];
1949
+ for (const entry of list) {
1950
+ if (!isRecord(entry)) {
1951
+ decoded.push(entry);
1952
+ continue;
678
1953
  }
679
- console.error(
680
- "[serve] The review is still open in the browser. Fix the problem and press Finish Review again."
681
- );
682
- return { ok: false, code: error.code, message: error.message, details: [...error.details] };
1954
+ if (entry.data !== void 0) {
1955
+ return { ok: false, error: RAW_DATA_ERROR };
1956
+ }
1957
+ if (entry.dataBase64 === void 0) {
1958
+ decoded.push(entry);
1959
+ continue;
1960
+ }
1961
+ const encoded = entry.dataBase64;
1962
+ if (typeof encoded !== "string" || !BASE64_PATTERN.test(encoded)) {
1963
+ return { ok: false, error: "attachment dataBase64 must be non-empty base64" };
1964
+ }
1965
+ const { dataBase64: _encoded, ...rest } = entry;
1966
+ decoded.push({ ...rest, data: base64ToArrayBuffer(encoded) });
683
1967
  }
1968
+ return { ok: true, value: decoded };
684
1969
  }
685
- var DOCUMENT_ERROR_CODES = /* @__PURE__ */ new Set([
686
- "validation-failed",
687
- "xml-illegal-character"
688
- ]);
689
- function publishFailureStatus(code) {
690
- return DOCUMENT_ERROR_CODES.has(code) ? 422 : 500;
1970
+ function decodeFileAttachments(files) {
1971
+ const decodedFiles = [];
1972
+ for (const file of files) {
1973
+ if (!isRecord(file) || !Array.isArray(file.comments)) {
1974
+ decodedFiles.push(file);
1975
+ continue;
1976
+ }
1977
+ const decodedComments = [];
1978
+ for (const comment of file.comments) {
1979
+ if (!isRecord(comment)) {
1980
+ decodedComments.push(comment);
1981
+ continue;
1982
+ }
1983
+ const commentIdError = checkId(comment, "comment");
1984
+ if (commentIdError) return { ok: false, error: commentIdError };
1985
+ const next = { ...comment };
1986
+ if (Array.isArray(comment.attachments)) {
1987
+ const result = decodeAttachmentList(comment.attachments);
1988
+ if (!result.ok) return result;
1989
+ next.attachments = result.value;
1990
+ }
1991
+ if (Array.isArray(comment.replies)) {
1992
+ const decodedReplies = [];
1993
+ for (const reply of comment.replies) {
1994
+ if (!isRecord(reply)) {
1995
+ decodedReplies.push(reply);
1996
+ continue;
1997
+ }
1998
+ const replyIdError = checkId(reply, "reply");
1999
+ if (replyIdError) return { ok: false, error: replyIdError };
2000
+ if (!Array.isArray(reply.attachments)) {
2001
+ decodedReplies.push(reply);
2002
+ continue;
2003
+ }
2004
+ const result = decodeAttachmentList(reply.attachments);
2005
+ if (!result.ok) return result;
2006
+ decodedReplies.push({ ...reply, attachments: result.value });
2007
+ }
2008
+ next.replies = decodedReplies;
2009
+ }
2010
+ decodedComments.push(next);
2011
+ }
2012
+ decodedFiles.push({ ...file, comments: decodedComments });
2013
+ }
2014
+ return { ok: true, value: decodedFiles };
691
2015
  }
692
- var ROUTE_PATHS = new Set(Object.keys(routes).map((key) => key.split(" ")[1]));
693
- async function serveStatic(res, clientDir, pathname) {
694
- let decoded;
695
- try {
696
- decoded = decodeURIComponent(pathname);
697
- } catch {
698
- sendError(res, 404, "not found");
699
- return;
2016
+
2017
+ // src/validate.ts
2018
+ var MAX_CONTEXT_LINES2 = installedServeEngine.requestContract.maxContextLines;
2019
+ function createRequestValidation(engine) {
2020
+ const { requestContract, validateReviewState: validateCompatibleReviewState } = engine;
2021
+ const { ReviewXmlError: ReviewXmlError4 } = engine.core;
2022
+ const maxContextLines = requestContract.maxContextLines;
2023
+ function isRecord2(value) {
2024
+ return typeof value === "object" && value !== null && !Array.isArray(value);
700
2025
  }
701
- const relative = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
702
- const resolved = containPath(clientDir, relative);
703
- if (resolved === null) {
704
- sendError(res, 404, "not found");
705
- return;
2026
+ const EXPAND_CONTEXT_KEYS = /* @__PURE__ */ new Set(["filePath", "contextLines"]);
2027
+ function parseExpandContextBody2(body) {
2028
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
2029
+ return { ok: false, error: "body must be a JSON object" };
2030
+ }
2031
+ const record3 = body;
2032
+ for (const key of Object.keys(record3)) {
2033
+ if (!EXPAND_CONTEXT_KEYS.has(key)) {
2034
+ return { ok: false, error: `unknown field: ${key}` };
2035
+ }
2036
+ }
2037
+ const { filePath, contextLines } = record3;
2038
+ if (typeof filePath !== "string") {
2039
+ return { ok: false, error: "filePath must be a string" };
2040
+ }
2041
+ if (typeof contextLines !== "number" || !Number.isInteger(contextLines) || contextLines < 0 || contextLines > maxContextLines) {
2042
+ return {
2043
+ ok: false,
2044
+ error: `contextLines must be an integer between 0 and ${maxContextLines}`
2045
+ };
2046
+ }
2047
+ return { ok: true, value: { filePath, contextLines } };
706
2048
  }
707
- let data;
708
- try {
709
- const stat = await fs2.promises.stat(resolved);
710
- if (!stat.isFile()) {
711
- sendError(res, 404, "not found");
712
- return;
2049
+ const APPLY_KEYS = /* @__PURE__ */ new Set(["filePath", "lineRange", "suggestion"]);
2050
+ const LINE_RANGE_KEYS = /* @__PURE__ */ new Set(["side", "start", "end"]);
2051
+ const SUGGESTION_KEYS = /* @__PURE__ */ new Set(["originalCode", "proposedCode"]);
2052
+ function parseSuggestionApplyBody2(body) {
2053
+ if (!isRecord2(body)) {
2054
+ return { ok: false, error: "body must be a JSON object" };
713
2055
  }
714
- data = await fs2.promises.readFile(resolved);
715
- } catch {
716
- sendError(res, 404, "not found");
717
- return;
2056
+ for (const key of Object.keys(body)) {
2057
+ if (!APPLY_KEYS.has(key)) return { ok: false, error: `unknown field: ${key}` };
2058
+ }
2059
+ const { filePath, lineRange, suggestion } = body;
2060
+ if (typeof filePath !== "string" || filePath === "") {
2061
+ return { ok: false, error: "filePath must be a non-empty string" };
2062
+ }
2063
+ if (lineRange !== null) {
2064
+ if (!isRecord2(lineRange)) {
2065
+ return { ok: false, error: "lineRange must be an object or null" };
2066
+ }
2067
+ for (const key of Object.keys(lineRange)) {
2068
+ if (!LINE_RANGE_KEYS.has(key)) {
2069
+ return { ok: false, error: `unknown lineRange field: ${key}` };
2070
+ }
2071
+ }
2072
+ }
2073
+ if (!isRecord2(suggestion)) {
2074
+ return { ok: false, error: "suggestion must be an object" };
2075
+ }
2076
+ for (const key of Object.keys(suggestion)) {
2077
+ if (!SUGGESTION_KEYS.has(key)) {
2078
+ return { ok: false, error: `unknown suggestion field: ${key}` };
2079
+ }
2080
+ }
2081
+ for (const key of ["originalCode", "proposedCode"]) {
2082
+ if (typeof suggestion[key] !== "string") {
2083
+ return { ok: false, error: `suggestion.${key} must be a string` };
2084
+ }
2085
+ }
2086
+ return requestContract.decode(body);
718
2087
  }
719
- res.writeHead(200, {
720
- "content-type": CONTENT_TYPES[path2.extname(resolved).toLowerCase()] ?? "application/octet-stream",
721
- "content-length": data.length,
722
- ...SECURITY_HEADERS
723
- });
724
- res.end(data);
2088
+ const REVIEW_STATE_KEYS = /* @__PURE__ */ new Set(["timestamp", "source", "files"]);
2089
+ function parseReviewStateBody2(body) {
2090
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
2091
+ return { ok: false, error: "body must be a JSON object" };
2092
+ }
2093
+ const record3 = body;
2094
+ for (const key of Object.keys(record3)) {
2095
+ if (!REVIEW_STATE_KEYS.has(key)) {
2096
+ return { ok: false, error: `unknown field: ${key}` };
2097
+ }
2098
+ }
2099
+ const { timestamp, source, files } = record3;
2100
+ if (typeof timestamp !== "string") {
2101
+ return { ok: false, error: "timestamp must be a string" };
2102
+ }
2103
+ if (typeof source !== "object" || source === null || Array.isArray(source)) {
2104
+ return { ok: false, error: "source must be an object" };
2105
+ }
2106
+ if (!Array.isArray(files)) {
2107
+ return { ok: false, error: "files must be an array" };
2108
+ }
2109
+ const decoded = decodeFileAttachments(files);
2110
+ if (!decoded.ok) {
2111
+ return decoded;
2112
+ }
2113
+ try {
2114
+ return {
2115
+ ok: true,
2116
+ value: validateCompatibleReviewState({ timestamp, source, files: decoded.value })
2117
+ };
2118
+ } catch (error) {
2119
+ if (!(error instanceof ReviewXmlError4)) throw error;
2120
+ return { ok: false, error: error.message };
2121
+ }
2122
+ }
2123
+ return { parseExpandContextBody: parseExpandContextBody2, parseSuggestionApplyBody: parseSuggestionApplyBody2, parseReviewStateBody: parseReviewStateBody2 };
2124
+ }
2125
+ var defaults = createRequestValidation(installedServeEngine);
2126
+ var parseExpandContextBody = defaults.parseExpandContextBody;
2127
+ var parseSuggestionApplyBody = defaults.parseSuggestionApplyBody;
2128
+ var parseReviewStateBody = defaults.parseReviewStateBody;
2129
+
2130
+ // src/route-composition.ts
2131
+ function bindSelectedRouteValidation(operations) {
2132
+ return {
2133
+ parseExpandContextBody: (body) => operations.requestValidation.parseExpandContextBody(body),
2134
+ parseSuggestionApplyBody: (body) => operations.requestValidation.parseSuggestionApplyBody(body),
2135
+ parseReviewStateBody: (body) => operations.requestValidation.parseReviewStateBody(body)
2136
+ };
2137
+ }
2138
+
2139
+ // src/bound-server.ts
2140
+ function defaultClientDir() {
2141
+ return fileURLToPath(new URL("./client/", import.meta.url));
2142
+ }
2143
+ function createValidatedReviewServer(options) {
2144
+ return serveBoundReview(options, bindSelectedRouteValidation(options.operations));
725
2145
  }
726
- function createReviewServer(options) {
727
- const { session, output, capability, clientDir = defaultClientDir() } = options;
728
- return http.createServer(async (req, res) => {
2146
+ function serveBoundReview(options, validation) {
2147
+ const { capability, clientDir = defaultClientDir(), operations } = options;
2148
+ const report = nonThrowingReporter(options.reportDiagnostic);
2149
+ const maxConnections = options.maxConnections ?? 64;
2150
+ if (!Number.isSafeInteger(maxConnections) || maxConnections < 1) {
2151
+ throw new Error("Connection limit must be a positive safe integer.");
2152
+ }
2153
+ const submission = new ReviewSubmission(
2154
+ { publication: options.publication },
2155
+ options.reportDiagnostic
2156
+ );
2157
+ const admission = new RequestAdmission({
2158
+ maxRequests: options.maxRequests,
2159
+ maxExpensiveReads: options.maxExpensiveReads,
2160
+ requestTimeoutMs: options.requestTimeoutMs
2161
+ });
2162
+ const published = (response) => server.emit(REVIEW_PUBLISHED, response, () => admission.drain());
2163
+ const processing = options.jsonBodyProcessing ?? new JsonBodyProcessing();
2164
+ const routes = createBoundApiRoutes(operations, submission, published, validation, processing);
2165
+ const routeMethods = /* @__PURE__ */ new Map();
2166
+ for (const key of Object.keys(routes)) {
2167
+ const [method, path5] = key.split(" ");
2168
+ const methods = routeMethods.get(path5) ?? [];
2169
+ methods.push(method);
2170
+ routeMethods.set(path5, methods);
2171
+ }
2172
+ const reportDeadline = (kind, elapsedMs) => report(`[serve] Request deadline exceeded: kind=${kind} elapsedMs=${elapsedMs}`);
2173
+ const dispatch = async (req, res) => {
729
2174
  const method = req.method ?? "GET";
730
2175
  let url;
731
2176
  try {
@@ -734,48 +2179,210 @@ function createReviewServer(options) {
734
2179
  sendError(res, 400, "malformed request URL");
735
2180
  return;
736
2181
  }
737
- if (!hostIsLoopback(req) || !originMatchesHost(req) || !fetchSiteIsSelf(req)) {
738
- sendError(res, 403, "forbidden");
739
- return;
740
- }
741
- if (url.pathname.startsWith("/api/") && !presentsCapability(req, capability)) {
742
- sendUnauthorized(res);
2182
+ if (!allowRequest(req, res, url, capability)) return;
2183
+ if (submission.completed) {
2184
+ sendError(res, 503, "review complete; server is stopping");
743
2185
  return;
744
2186
  }
745
2187
  try {
746
- const handler = routes[`${method} ${url.pathname}`];
747
- if (handler) {
748
- await handler({ req, res, url, session, output });
749
- } else if (ROUTE_PATHS.has(url.pathname)) {
750
- sendError(res, 405, "method not allowed");
2188
+ const route = routes[`${method} ${url.pathname}`];
2189
+ if (route) {
2190
+ const { kind, handle } = route;
2191
+ const rejection = admission.rejection(kind);
2192
+ if (rejection) {
2193
+ sendJson(
2194
+ res,
2195
+ rejection.status,
2196
+ { error: rejection.error, ...rejection.code ? { code: rejection.code } : {} },
2197
+ { connection: "close" }
2198
+ );
2199
+ return;
2200
+ }
2201
+ admission.run(
2202
+ req,
2203
+ res,
2204
+ kind,
2205
+ async (signal) => {
2206
+ try {
2207
+ await handle({ req, res, url, signal });
2208
+ } catch (error) {
2209
+ if (!signal.aborted) report(`[serve] ${method} ${url.pathname} failed:`, error);
2210
+ if (!res.headersSent && !res.destroyed)
2211
+ sendError(
2212
+ res,
2213
+ error instanceof JsonResponseLimitError ? 413 : 500,
2214
+ error instanceof JsonResponseLimitError ? error.message : "internal error"
2215
+ );
2216
+ else if (!res.writableEnded) res.destroy();
2217
+ }
2218
+ },
2219
+ (elapsedMs = 0) => {
2220
+ reportDeadline(kind, elapsedMs);
2221
+ if (!res.headersSent && !res.destroyed)
2222
+ sendJson(
2223
+ res,
2224
+ 503,
2225
+ { error: "request deadline exceeded; operation outcome may be unknown" },
2226
+ { connection: "close" }
2227
+ );
2228
+ else if (!res.writableEnded) res.destroy();
2229
+ }
2230
+ );
2231
+ } else if (routeMethods.has(url.pathname)) {
2232
+ sendJson(
2233
+ res,
2234
+ 405,
2235
+ { error: "method not allowed" },
2236
+ { allow: routeMethods.get(url.pathname).join(", ") }
2237
+ );
751
2238
  } else if (url.pathname.startsWith("/api/")) {
752
2239
  sendError(res, 404, "not found");
753
2240
  } else if (method === "GET") {
754
- await serveStatic(res, clientDir, url.pathname);
2241
+ const rejection = admission.rejection("read");
2242
+ if (rejection) {
2243
+ sendJson(
2244
+ res,
2245
+ rejection.status,
2246
+ { error: rejection.error, ...rejection.code ? { code: rejection.code } : {} },
2247
+ { connection: "close" }
2248
+ );
2249
+ return;
2250
+ }
2251
+ admission.run(
2252
+ req,
2253
+ res,
2254
+ "read",
2255
+ async (signal) => {
2256
+ try {
2257
+ await serveStatic(res, clientDir, url.pathname, { signal });
2258
+ } catch (error) {
2259
+ if (!signal.aborted) report(`[serve] ${method} ${url.pathname} failed:`, error);
2260
+ if (!res.headersSent && !res.destroyed) sendError(res, 500, "internal error");
2261
+ else res.destroy();
2262
+ }
2263
+ },
2264
+ (elapsedMs = 0) => {
2265
+ reportDeadline("read", elapsedMs);
2266
+ res.destroy();
2267
+ }
2268
+ );
755
2269
  } else {
756
2270
  sendError(res, 404, "not found");
757
2271
  }
758
2272
  } catch (error) {
759
- console.error(`[serve] ${method} ${url.pathname} failed:`, error);
2273
+ report(`[serve] ${method} ${url.pathname} failed:`, error);
760
2274
  if (!res.headersSent) {
761
2275
  sendError(res, 500, "internal error");
762
2276
  } else {
763
2277
  res.end();
764
2278
  }
765
2279
  }
2280
+ };
2281
+ const server = http.createServer((req, res) => {
2282
+ void dispatch(req, res);
2283
+ });
2284
+ server[REQUEST_SHUTDOWN] = () => Promise.all([admission.shutdown(), processing.shutdown()]).then(() => {
766
2285
  });
2286
+ server.maxConnections = maxConnections;
2287
+ server.headersTimeout = 15e3;
2288
+ server.requestTimeout = 6e4;
2289
+ return server;
767
2290
  }
768
- function listenLoopback(server, port = 0) {
769
- return new Promise((resolve3, reject) => {
770
- server.once("error", reject);
771
- server.listen(port, "127.0.0.1", () => {
772
- server.off("error", reject);
2291
+ function listenLoopback(server, port = 0, options = {}) {
2292
+ return new Promise((resolve6, reject) => {
2293
+ const { signal } = options;
2294
+ if (signal?.aborted) {
2295
+ reject(signal.reason);
2296
+ return;
2297
+ }
2298
+ const cleanup = () => {
2299
+ signal?.removeEventListener("abort", onAbort);
2300
+ server.off("error", onError);
2301
+ server.off("listening", onListening);
2302
+ };
2303
+ const onError = (error) => {
2304
+ cleanup();
2305
+ reject(error);
2306
+ };
2307
+ const onAbort = () => {
2308
+ cleanup();
2309
+ server.close();
2310
+ reject(signal?.reason);
2311
+ };
2312
+ const onListening = () => {
2313
+ cleanup();
2314
+ if (signal?.aborted) {
2315
+ server.close();
2316
+ reject(signal.reason);
2317
+ return;
2318
+ }
773
2319
  const address = server.address();
774
- resolve3({ port: address.port, url: `http://127.0.0.1:${address.port}/` });
775
- });
2320
+ resolve6({ port: address.port, url: `http://127.0.0.1:${address.port}/` });
2321
+ };
2322
+ signal?.addEventListener("abort", onAbort, { once: true });
2323
+ server.once("error", onError);
2324
+ server.once("listening", onListening);
2325
+ server.listen({ port, host: "127.0.0.1", signal });
776
2326
  });
777
2327
  }
778
2328
 
2329
+ // src/source-ownership.ts
2330
+ import { ReviewPublishError as ReviewPublishError2 } from "@self-review/core";
2331
+ function ownedReviewState(session, state, outputPath, ErrorType = ReviewPublishError2) {
2332
+ const owned = normalizePublicationState(
2333
+ state,
2334
+ session.diffData,
2335
+ capturePublicationOwnership(session.diffData)
2336
+ );
2337
+ if (!owned)
2338
+ throw new ErrorType(
2339
+ "validation-failed",
2340
+ outputPath,
2341
+ "The submitted source does not match the loaded review."
2342
+ );
2343
+ return owned;
2344
+ }
2345
+
2346
+ // src/review-operations.ts
2347
+ function createValidatedPublicationOperations(session, output, engine = installedServeEngine, reportDiagnostic) {
2348
+ const { core: core2, applySuggestion } = engine;
2349
+ const report = reportDiagnostic && nonThrowingReporter(reportDiagnostic);
2350
+ return {
2351
+ requestValidation: createRequestValidation(engine),
2352
+ publicationError: core2.ReviewPublishError,
2353
+ authorizeReviewedPath: (path5) => core2.authorizeReviewedPath(session, path5),
2354
+ getDiffLoad: () => core2.getDiffLoad(session),
2355
+ getConfigLoad: () => core2.getConfigLoad(session),
2356
+ getResumeLoad: () => core2.getResumeLoad(session),
2357
+ getFileHunks: (path5) => core2.getFileHunks(session, path5),
2358
+ loadImage: (path5, options) => core2.loadImage(session, path5, report ? { ...options, reportDiagnostic: report } : options),
2359
+ readAttachment: (path5, options) => core2.readAttachment(
2360
+ session,
2361
+ path5,
2362
+ report ? { ...options, reportDiagnostic: report } : options
2363
+ ),
2364
+ expandContext: (request, options) => core2.expandContext(session, request, void 0, options),
2365
+ applySuggestionForSession: (request, options) => applySuggestion(session, request, options),
2366
+ publishReview: (state, options) => {
2367
+ const owned = ownedReviewState(session, state, output.path, core2.ReviewPublishError);
2368
+ if (report)
2369
+ report(
2370
+ "[review] Review state submitted:",
2371
+ JSON.stringify({
2372
+ timestamp: owned.timestamp,
2373
+ source: owned.source,
2374
+ fileCount: owned.files.length
2375
+ })
2376
+ );
2377
+ return core2.publishReview(owned, output.path, {
2378
+ ...core2.publishOptionsFor(output, session.attachmentOrigins),
2379
+ signal: options?.signal,
2380
+ reportDiagnostic: report
2381
+ });
2382
+ }
2383
+ };
2384
+ }
2385
+
779
2386
  // src/cli.ts
780
2387
  var HELP = `
781
2388
  self-review-serve - Serve the self-review interface over HTTP
@@ -834,16 +2441,60 @@ async function main() {
834
2441
  printVersion();
835
2442
  return;
836
2443
  }
837
- const { session, output } = await resolveSession(args);
838
- const capability = generateCapability();
839
- const server = createReviewServer({ session, output, capability });
840
- completeReviewOnSubmit({ server });
841
- const { url } = await listenLoopback(server);
842
- console.error(`[serve] Review ready at ${formatLaunchUrl(url, capability)}`);
843
- console.error(`[serve] Completing the review writes ${output.path} and stops this process.`);
844
- console.error(
845
- "[serve] The listener is loopback-only. The part of the URL after # is this session's key: open the URL exactly as printed, and do not share it."
846
- );
2444
+ const host = createStartupHost(process.cwd(), (message) => console.error(message));
2445
+ reportCoreCompatibility(host.reportDiagnostic);
2446
+ const lifetime = createServeLifecycle({
2447
+ signals: process,
2448
+ reportDiagnostic: host.reportDiagnostic
2449
+ });
2450
+ const startupTimer = setTimeout(() => {
2451
+ console.error("[serve] Startup deadline reached; stopping.");
2452
+ lifetime.stop(1);
2453
+ }, 45e3);
2454
+ try {
2455
+ await lifetime.track(
2456
+ (async () => {
2457
+ const { session, output } = await resolveSession(
2458
+ args,
2459
+ {
2460
+ signal: lifetime.signal,
2461
+ timeoutMs: 3e4
2462
+ },
2463
+ host
2464
+ );
2465
+ if (lifetime.signal.aborted) throw lifetime.signal.reason;
2466
+ const capability = generateCapability();
2467
+ const operations = createValidatedPublicationOperations(
2468
+ session,
2469
+ output,
2470
+ installedServeEngine,
2471
+ host.reportDiagnostic
2472
+ );
2473
+ const server = createValidatedReviewServer({
2474
+ capability,
2475
+ operations,
2476
+ publication: operations,
2477
+ reportDiagnostic: host.reportDiagnostic
2478
+ });
2479
+ lifetime.attach(server);
2480
+ const { url } = await listenLoopback(server, 0, { signal: lifetime.signal });
2481
+ if (lifetime.signal.aborted) throw lifetime.signal.reason;
2482
+ console.error(`[serve] Review ready at ${formatLaunchUrl(url, capability)}`);
2483
+ console.error(
2484
+ `[serve] Completing the review writes ${output.path} and stops this process.`
2485
+ );
2486
+ console.error(
2487
+ "[serve] The listener is loopback-only. The part of the URL after # is this session's key: open the URL exactly as printed, and do not share it."
2488
+ );
2489
+ })()
2490
+ );
2491
+ } catch (error) {
2492
+ if (!lifetime.signal.aborted)
2493
+ console.error(`[serve] ${error instanceof Error ? error.message : String(error)}`);
2494
+ lifetime.stop(1);
2495
+ } finally {
2496
+ clearTimeout(startupTimer);
2497
+ }
847
2498
  }
848
2499
  main().catch((error) => {
849
2500
  console.error(`[serve] ${error instanceof Error ? error.message : String(error)}`);