@self-review/core 2.0.4 → 2.1.3

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 (68) hide show
  1. package/README.md +441 -0
  2. package/dist/chunk-5SGPWHGH.cjs +106 -0
  3. package/dist/chunk-5SGPWHGH.cjs.map +1 -0
  4. package/dist/chunk-6OEFXBIZ.cjs +5212 -0
  5. package/dist/chunk-6OEFXBIZ.cjs.map +1 -0
  6. package/dist/chunk-6X3PJHP5.cjs +416 -0
  7. package/dist/chunk-6X3PJHP5.cjs.map +1 -0
  8. package/dist/chunk-CJQEOLI3.js +37 -0
  9. package/dist/chunk-CJQEOLI3.js.map +1 -0
  10. package/dist/chunk-IG2YF5LH.js +416 -0
  11. package/dist/chunk-IG2YF5LH.js.map +1 -0
  12. package/dist/chunk-IX226KG4.js +106 -0
  13. package/dist/chunk-IX226KG4.js.map +1 -0
  14. package/dist/chunk-LSLCQQBN.cjs +3684 -0
  15. package/dist/chunk-LSLCQQBN.cjs.map +1 -0
  16. package/dist/chunk-MOYO4RIX.js +3684 -0
  17. package/dist/chunk-MOYO4RIX.js.map +1 -0
  18. package/dist/chunk-TOUYY7I6.js +5212 -0
  19. package/dist/chunk-TOUYY7I6.js.map +1 -0
  20. package/dist/chunk-VOYTFLPH.cjs +37 -0
  21. package/dist/chunk-VOYTFLPH.cjs.map +1 -0
  22. package/dist/filesystem.cjs +56 -0
  23. package/dist/filesystem.cjs.map +1 -0
  24. package/dist/filesystem.d.cts +22 -0
  25. package/dist/filesystem.d.ts +22 -0
  26. package/dist/filesystem.js +56 -0
  27. package/dist/index.cjs +348 -6192
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +80 -1332
  30. package/dist/index.d.ts +80 -1332
  31. package/dist/index.js +234 -5172
  32. package/dist/index.js.map +1 -1
  33. package/dist/node-scan-fs-CaufzUZR.d.cts +5 -0
  34. package/dist/node-scan-fs-DcHI_BYB.d.ts +5 -0
  35. package/dist/operations-Bqhi9EBH.d.ts +765 -0
  36. package/dist/operations-UyiUD2Nx.d.cts +765 -0
  37. package/dist/operations.cjs +91 -0
  38. package/dist/operations.cjs.map +1 -0
  39. package/dist/operations.d.cts +6 -0
  40. package/dist/operations.d.ts +6 -0
  41. package/dist/operations.js +91 -0
  42. package/dist/resume-worker.cjs +152 -0
  43. package/dist/resume-worker.cjs.map +1 -0
  44. package/dist/resume-worker.d.cts +56 -0
  45. package/dist/resume-worker.d.ts +56 -0
  46. package/dist/resume-worker.js +152 -0
  47. package/dist/resume-worker.js.map +1 -0
  48. package/dist/review-request-validation-VJG7XZiE.d.cts +62 -0
  49. package/dist/review-request-validation-VJG7XZiE.d.ts +62 -0
  50. package/dist/review-xml-decoder-COgRtfkf.d.cts +33 -0
  51. package/dist/review-xml-decoder-COgRtfkf.d.ts +33 -0
  52. package/dist/source-identity-CQpAzugz.d.cts +959 -0
  53. package/dist/source-identity-CQpAzugz.d.ts +959 -0
  54. package/dist/validation.cjs +67 -0
  55. package/dist/validation.cjs.map +1 -0
  56. package/dist/validation.d.cts +30 -0
  57. package/dist/validation.d.ts +30 -0
  58. package/dist/validation.js +67 -0
  59. package/dist/validation.js.map +1 -0
  60. package/package.json +44 -3
  61. package/dist/chunk-4YO2MI6B.js +0 -269
  62. package/dist/chunk-4YO2MI6B.js.map +0 -1
  63. package/dist/chunk-QHS36X6T.js +0 -450
  64. package/dist/chunk-QHS36X6T.js.map +0 -1
  65. package/dist/diff-parser-B6S3KG5T.js +0 -9
  66. package/dist/git-N5HVNPKQ.js +0 -24
  67. /package/dist/{diff-parser-B6S3KG5T.js.map → filesystem.js.map} +0 -0
  68. /package/dist/{git-N5HVNPKQ.js.map → operations.js.map} +0 -0
@@ -0,0 +1,416 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/input-budgets.ts
2
+ var KIB = 1024;
3
+ var MIB = 1024 * KIB;
4
+ var MAX_SOURCE_ENTRIES = 5e4;
5
+ var BINARY_SNIFF_BYTES = 8 * KIB;
6
+ var MAX_SOURCE_FILE_BYTES = 5 * MIB;
7
+ var MAX_SOURCE_TOTAL_BYTES = 64 * MIB;
8
+ var MAX_GIT_DIFF_OUTPUT_BYTES = 50 * MIB;
9
+ var MAX_GUIDE_BYTES = 1 * MIB;
10
+ var MAX_RESUME_XML_BYTES = 16 * MIB;
11
+ var MAX_REVIEW_ATTACHMENTS = 1e3;
12
+ var MAX_RESUME_ATTACHMENTS = MAX_REVIEW_ATTACHMENTS;
13
+ var MAX_PUBLICATION_ASSET_BYTES = 64 * MIB;
14
+ var MAX_IMAGE_BYTES = 10 * MIB;
15
+ var MAX_SOURCE_FILE_LINES = 1e5;
16
+ var MAX_SOURCE_TOTAL_LINES = 25e4;
17
+ var MAX_DIFF_FILES = 1e4;
18
+ var MAX_DIFF_HUNKS = 5e4;
19
+ var MAX_DIFF_DIAGNOSTICS = 1e3;
20
+ var MAX_DIFF_DIAGNOSTIC_CHARS = 8 * KIB;
21
+ var DEFAULT_SOURCE_BUDGETS = Object.freeze({
22
+ maxEntries: MAX_SOURCE_ENTRIES,
23
+ maxFileBytes: MAX_SOURCE_FILE_BYTES,
24
+ maxTotalBytes: MAX_SOURCE_TOTAL_BYTES,
25
+ maxGitDiffOutputBytes: MAX_GIT_DIFF_OUTPUT_BYTES,
26
+ maxFileLines: MAX_SOURCE_FILE_LINES,
27
+ maxTotalLines: MAX_SOURCE_TOTAL_LINES,
28
+ maxDiffFiles: MAX_DIFF_FILES,
29
+ maxDiffHunks: MAX_DIFF_HUNKS,
30
+ maxDiagnostics: MAX_DIFF_DIAGNOSTICS
31
+ });
32
+ function resolveSourceBudgets(overrides = {}) {
33
+ const budgets = { ...DEFAULT_SOURCE_BUDGETS };
34
+ for (const name of Object.keys(budgets)) {
35
+ const value = overrides[name];
36
+ if (value !== void 0) budgets[name] = value;
37
+ }
38
+ for (const [name, value] of Object.entries(budgets)) {
39
+ if (!Number.isSafeInteger(value) || value < 0) {
40
+ throw new RangeError(`${name} must be a nonnegative safe integer`);
41
+ }
42
+ }
43
+ return budgets;
44
+ }
45
+ function formatBytes(bytes) {
46
+ if (bytes >= MIB) return `${trimFixed(bytes / MIB)} MiB`;
47
+ if (bytes >= KIB) return `${trimFixed(bytes / KIB)} KiB`;
48
+ return `${bytes} bytes`;
49
+ }
50
+ function trimFixed(value) {
51
+ return value.toFixed(1).replace(/\.0$/, "");
52
+ }
53
+ var RepresentationLimitError = class extends Error {
54
+ constructor(aggregate, detail) {
55
+ super(`Not loaded: ${detail} representation budget exceeded.`);
56
+ this.aggregate = aggregate;
57
+ this.name = "RepresentationLimitError";
58
+ }
59
+ };
60
+ function createRepresentationBudget(budgets) {
61
+ let files = 0;
62
+ let hunks = 0;
63
+ let lines = 0;
64
+ let fileLines = 0;
65
+ return {
66
+ beginFile() {
67
+ if (files >= budgets.maxDiffFiles)
68
+ throw new RepresentationLimitError(true, `${budgets.maxDiffFiles}-file`);
69
+ files++;
70
+ fileLines = 0;
71
+ },
72
+ addHunk() {
73
+ if (hunks >= budgets.maxDiffHunks)
74
+ throw new RepresentationLimitError(true, `${budgets.maxDiffHunks}-hunk total`);
75
+ hunks++;
76
+ },
77
+ addLines(count) {
78
+ if (count > budgets.maxFileLines - fileLines)
79
+ throw new RepresentationLimitError(false, `${budgets.maxFileLines}-line per-file`);
80
+ if (count > budgets.maxTotalLines - lines)
81
+ throw new RepresentationLimitError(true, `${budgets.maxTotalLines}-line total`);
82
+ fileLines += count;
83
+ lines += count;
84
+ }
85
+ };
86
+ }
87
+
88
+ // src/anchor-validation.ts
89
+ function validateLineAnchor(fields, maxLine) {
90
+ const old = sideFields("old", fields.oldLineStart, fields.oldLineEnd);
91
+ const next = sideFields("new", fields.newLineStart, fields.newLineEnd);
92
+ if (!old.present && !next.present) return null;
93
+ if (old.present && next.present) {
94
+ return { ok: false, reason: "carries both old and new line ranges" };
95
+ }
96
+ const side = old.present ? old : next;
97
+ if (side.start === void 0 || side.end === void 0) {
98
+ return { ok: false, reason: `${side.name}-line range is incomplete (start and end required)` };
99
+ }
100
+ const start = toPositiveSafeInteger(side.start);
101
+ if (start === null) {
102
+ return {
103
+ ok: false,
104
+ reason: `${side.name}-line-start is not a positive integer (${describe(side.start)})`
105
+ };
106
+ }
107
+ const end = toPositiveSafeInteger(side.end);
108
+ if (end === null) {
109
+ return {
110
+ ok: false,
111
+ reason: `${side.name}-line-end is not a positive integer (${describe(side.end)})`
112
+ };
113
+ }
114
+ return checkRange({ side: side.name, start, end }, maxLine);
115
+ }
116
+ function validateLineRange(range, maxLine) {
117
+ const start = toPositiveSafeInteger(range.start);
118
+ if (start === null) {
119
+ return {
120
+ ok: false,
121
+ reason: `${range.side}-line-start is not a positive integer (${describe(range.start)})`
122
+ };
123
+ }
124
+ const end = toPositiveSafeInteger(range.end);
125
+ if (end === null) {
126
+ return {
127
+ ok: false,
128
+ reason: `${range.side}-line-end is not a positive integer (${describe(range.end)})`
129
+ };
130
+ }
131
+ return checkRange({ side: range.side, start, end }, maxLine);
132
+ }
133
+ function checkRange(anchor, maxLine) {
134
+ if (anchor.start > anchor.end) {
135
+ return {
136
+ ok: false,
137
+ reason: `${anchor.side}-line range is reversed (${anchor.start} > ${anchor.end})`
138
+ };
139
+ }
140
+ if (maxLine !== void 0 && anchor.end > maxLine) {
141
+ return {
142
+ ok: false,
143
+ reason: `${anchor.side}-line range ends beyond line ${maxLine} (${anchor.end})`
144
+ };
145
+ }
146
+ return { ok: true, anchor };
147
+ }
148
+ function sideFields(name, start, end) {
149
+ const s = isAbsent(start) ? void 0 : start;
150
+ const e = isAbsent(end) ? void 0 : end;
151
+ return { name, present: s !== void 0 || e !== void 0, start: s, end: e };
152
+ }
153
+ function isAbsent(value) {
154
+ return value === void 0 || value === null;
155
+ }
156
+ function toPositiveSafeInteger(value) {
157
+ let n;
158
+ if (typeof value === "number") {
159
+ n = value;
160
+ } else if (typeof value === "string" && /^\d+$/.test(value)) {
161
+ n = Number(value);
162
+ } else {
163
+ return null;
164
+ }
165
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
166
+ }
167
+ function describe(value) {
168
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
169
+ }
170
+
171
+ // src/xml-errors.ts
172
+ var ReviewXmlError = class extends Error {
173
+ constructor(code, message, options) {
174
+ super(message);
175
+ this.name = "ReviewXmlError";
176
+ this.code = code;
177
+ this.details = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _ => _.details]), () => ( []));
178
+ if (_optionalChain([options, 'optionalAccess', _2 => _2.cause]) !== void 0) this.cause = options.cause;
179
+ }
180
+ };
181
+ var XmlIllegalCharacterError = class extends ReviewXmlError {
182
+ constructor(codePoint, location) {
183
+ super("xml-illegal-character", describeIllegalCharacter(codePoint, location));
184
+ this.name = "XmlIllegalCharacterError";
185
+ this.codePoint = codePoint;
186
+ this.field = location.field;
187
+ this.filePath = location.filePath;
188
+ this.commentId = location.commentId;
189
+ this.replyId = location.replyId;
190
+ }
191
+ };
192
+ function describeIllegalCharacter(codePoint, location) {
193
+ const hex = codePoint.toString(16).toUpperCase().padStart(4, "0");
194
+ const where = [
195
+ location.filePath !== void 0 ? `file "${location.filePath}"` : null,
196
+ location.commentId !== void 0 ? `comment ${location.commentId}` : null,
197
+ location.replyId !== void 0 ? `reply ${location.replyId}` : null
198
+ ].filter((part) => part !== null).join(", ");
199
+ return `Cannot write review XML: ${location.field}${where ? ` of ${where}` : ""} contains U+${hex}, which XML 1.0 cannot represent. Remove the character and save again.`;
200
+ }
201
+
202
+ // src/review-state-validation.ts
203
+ function validateReviewState(value) {
204
+ validateState(value, true);
205
+ return normalizeNullableFields(value);
206
+ }
207
+ function validateReviewForSerialization(state) {
208
+ validateState(state, false);
209
+ return normalizeNullableFields(state);
210
+ }
211
+ function validateState(value, requireCommentIds) {
212
+ const state = record(value, "review");
213
+ const budget = { attachments: 0, bytes: 0 };
214
+ string(state.timestamp, "review.timestamp");
215
+ const source = record(state.source, "review.source");
216
+ switch (source.type) {
217
+ case "git":
218
+ string(source.gitDiffArgs, "review.source.gitDiffArgs");
219
+ string(source.repository, "review.source.repository");
220
+ break;
221
+ case "directory":
222
+ case "file":
223
+ string(source.sourcePath, "review.source.sourcePath");
224
+ break;
225
+ case "welcome":
226
+ case "loading":
227
+ break;
228
+ default:
229
+ invalid("review.source.type", "must be git, directory, file, welcome or loading");
230
+ }
231
+ for (const key of ["remoteUrl", "remoteBaseSha", "remoteHeadSha"])
232
+ optionalString(state, key, "review");
233
+ optionalEnum(state, "remoteForge", ["github", "gitlab"], "review");
234
+ array(state.files, "review.files").forEach((value2, index) => {
235
+ const at = `review.files[${index}]`;
236
+ const file = record(value2, at);
237
+ string(file.path, `${at}.path`);
238
+ enumValue(
239
+ file.changeType,
240
+ ["added", "modified", "deleted", "renamed", "copied"],
241
+ `${at}.changeType`
242
+ );
243
+ boolean(file.viewed, `${at}.viewed`);
244
+ array(file.comments, `${at}.comments`).forEach(
245
+ (comment, index2) => validateComment(
246
+ comment,
247
+ `${at}.comments[${index2}]`,
248
+ file.path,
249
+ requireCommentIds,
250
+ budget
251
+ )
252
+ );
253
+ });
254
+ }
255
+ function validateComment(value, at, ownerPath, requireId, budget) {
256
+ const comment = record(value, at);
257
+ if (requireId || comment.id !== void 0) string(comment.id, `${at}.id`);
258
+ for (const key of ["filePath", "body", "category"]) string(comment[key], `${at}.${key}`);
259
+ if (comment.filePath !== ownerPath)
260
+ invalid(`${at}.filePath`, "must match its containing file path");
261
+ for (const key of ["author", "remoteId"]) optionalString(comment, key, at);
262
+ optionalEnum(comment, "severity", ["critical", "major", "minor", "info"], at);
263
+ optionalEnum(comment, "confidence", ["high", "medium", "low"], at);
264
+ if (comment.orphaned !== void 0) boolean(comment.orphaned, `${at}.orphaned`);
265
+ if (comment.lineRange !== null && comment.lineRange !== void 0) {
266
+ const range = record(comment.lineRange, `${at}.lineRange`);
267
+ enumValue(range.side, ["old", "new"], `${at}.lineRange.side`);
268
+ if (typeof range.start !== "number" || typeof range.end !== "number")
269
+ invalid(`${at}.lineRange`, "bounds must be numbers");
270
+ const checked = validateLineRange({
271
+ side: range.side,
272
+ start: range.start,
273
+ end: range.end
274
+ });
275
+ if (!checked.ok) invalid(`${at}.lineRange`, checked.reason);
276
+ }
277
+ if (comment.suggestion !== null && comment.suggestion !== void 0) {
278
+ const suggestion = record(comment.suggestion, `${at}.suggestion`);
279
+ string(suggestion.originalCode, `${at}.suggestion.originalCode`);
280
+ string(suggestion.proposedCode, `${at}.suggestion.proposedCode`);
281
+ if (comment.lineRange === null || comment.lineRange === void 0)
282
+ invalid(`${at}.suggestion`, "requires a line anchor");
283
+ }
284
+ validateAttachments(comment.attachments, `${at}.attachments`, budget);
285
+ if (comment.replies !== void 0) {
286
+ array(comment.replies, `${at}.replies`).forEach((value2, index) => {
287
+ const replyAt = `${at}.replies[${index}]`;
288
+ const reply = record(value2, replyAt);
289
+ string(reply.id, `${replyAt}.id`);
290
+ string(reply.body, `${replyAt}.body`);
291
+ for (const key of ["author", "remoteId"]) optionalString(reply, key, replyAt);
292
+ validateAttachments(reply.attachments, `${replyAt}.attachments`, budget);
293
+ });
294
+ }
295
+ }
296
+ function validateAttachments(value, at, budget) {
297
+ if (value === void 0) return;
298
+ const attachments = array(value, at);
299
+ budget.attachments += attachments.length;
300
+ if (budget.attachments > MAX_REVIEW_ATTACHMENTS)
301
+ invalid(at, `exceeds the ${MAX_REVIEW_ATTACHMENTS} attachment limit for a review document`);
302
+ attachments.forEach((value2, index) => {
303
+ const attachmentAt = `${at}[${index}]`;
304
+ const attachment = record(value2, attachmentAt);
305
+ for (const key of ["id", "fileName", "mediaType"])
306
+ string(attachment[key], `${attachmentAt}.${key}`);
307
+ if (attachment.data !== void 0 && !isReadableArrayBuffer(attachment.data))
308
+ invalid(`${attachmentAt}.data`, "must be a readable ArrayBuffer");
309
+ if (attachment.data !== void 0) {
310
+ const bytes = new Uint8Array(attachment.data).byteLength;
311
+ if (bytes > MAX_IMAGE_BYTES)
312
+ invalid(
313
+ `${attachmentAt}.data`,
314
+ `exceeds the ${formatBytes(MAX_IMAGE_BYTES)} attachment limit`
315
+ );
316
+ budget.bytes += bytes;
317
+ if (budget.bytes > MAX_PUBLICATION_ASSET_BYTES)
318
+ invalid(
319
+ at,
320
+ `exceeds the ${formatBytes(MAX_PUBLICATION_ASSET_BYTES)} publication asset limit`
321
+ );
322
+ }
323
+ });
324
+ }
325
+ function record(value, at) {
326
+ if (value === null || typeof value !== "object" || Array.isArray(value))
327
+ invalid(at, "must be an object");
328
+ return value;
329
+ }
330
+ function array(value, at) {
331
+ if (!Array.isArray(value)) invalid(at, "must be an array");
332
+ for (let index = 0; index < value.length; index++) {
333
+ if (!(index in value)) invalid(`${at}[${index}]`, "must be present");
334
+ }
335
+ return value;
336
+ }
337
+ function string(value, at) {
338
+ if (typeof value !== "string") invalid(at, "must be a string");
339
+ }
340
+ function boolean(value, at) {
341
+ if (typeof value !== "boolean") invalid(at, "must be a boolean");
342
+ }
343
+ function optionalString(node, key, at) {
344
+ if (node[key] !== void 0) string(node[key], `${at}.${key}`);
345
+ }
346
+ function enumValue(value, allowed, at) {
347
+ if (typeof value !== "string" || !allowed.includes(value))
348
+ invalid(at, `must be one of ${allowed.join(", ")}`);
349
+ }
350
+ function optionalEnum(node, key, allowed, at) {
351
+ if (node[key] !== void 0) enumValue(node[key], allowed, `${at}.${key}`);
352
+ }
353
+ function invalid(at, reason) {
354
+ const message = `Invalid review state: ${at} ${reason}`;
355
+ throw new ReviewXmlError("invalid-state", message, { details: [message] });
356
+ }
357
+ function normalizeNullableFields(state) {
358
+ const files = state.files.map((file) => {
359
+ const comments = file.comments.map(
360
+ (comment) => comment.lineRange === void 0 || comment.suggestion === void 0 ? {
361
+ ...comment,
362
+ lineRange: _nullishCoalesce(comment.lineRange, () => ( null)),
363
+ suggestion: _nullishCoalesce(comment.suggestion, () => ( null))
364
+ } : comment
365
+ );
366
+ return comments.some((comment, index) => comment !== file.comments[index]) ? { ...file, comments } : file;
367
+ });
368
+ return files.some((file, index) => file !== state.files[index]) ? { ...state, files } : state;
369
+ }
370
+ function isReadableArrayBuffer(value) {
371
+ try {
372
+ const getLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
373
+ getLength.call(value);
374
+ return new Uint8Array(value).buffer === value;
375
+ } catch (e2) {
376
+ return false;
377
+ }
378
+ }
379
+
380
+ // src/unicode-text.ts
381
+ function isWellFormedUnicode(value) {
382
+ return !/[\uD800-\uDFFF]/u.test(value);
383
+ }
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
409
+
410
+
411
+
412
+
413
+
414
+
415
+ exports.MAX_SOURCE_ENTRIES = MAX_SOURCE_ENTRIES; exports.BINARY_SNIFF_BYTES = BINARY_SNIFF_BYTES; exports.MAX_SOURCE_FILE_BYTES = MAX_SOURCE_FILE_BYTES; exports.MAX_SOURCE_TOTAL_BYTES = MAX_SOURCE_TOTAL_BYTES; exports.MAX_GIT_DIFF_OUTPUT_BYTES = MAX_GIT_DIFF_OUTPUT_BYTES; exports.MAX_GUIDE_BYTES = MAX_GUIDE_BYTES; exports.MAX_RESUME_XML_BYTES = MAX_RESUME_XML_BYTES; exports.MAX_REVIEW_ATTACHMENTS = MAX_REVIEW_ATTACHMENTS; exports.MAX_RESUME_ATTACHMENTS = MAX_RESUME_ATTACHMENTS; exports.MAX_PUBLICATION_ASSET_BYTES = MAX_PUBLICATION_ASSET_BYTES; exports.MAX_IMAGE_BYTES = MAX_IMAGE_BYTES; exports.MAX_SOURCE_FILE_LINES = MAX_SOURCE_FILE_LINES; exports.MAX_SOURCE_TOTAL_LINES = MAX_SOURCE_TOTAL_LINES; exports.MAX_DIFF_FILES = MAX_DIFF_FILES; exports.MAX_DIFF_HUNKS = MAX_DIFF_HUNKS; exports.MAX_DIFF_DIAGNOSTICS = MAX_DIFF_DIAGNOSTICS; exports.MAX_DIFF_DIAGNOSTIC_CHARS = MAX_DIFF_DIAGNOSTIC_CHARS; exports.DEFAULT_SOURCE_BUDGETS = DEFAULT_SOURCE_BUDGETS; exports.resolveSourceBudgets = resolveSourceBudgets; exports.formatBytes = formatBytes; exports.RepresentationLimitError = RepresentationLimitError; exports.createRepresentationBudget = createRepresentationBudget; exports.validateLineAnchor = validateLineAnchor; exports.validateLineRange = validateLineRange; exports.ReviewXmlError = ReviewXmlError; exports.XmlIllegalCharacterError = XmlIllegalCharacterError; exports.validateReviewState = validateReviewState; exports.validateReviewForSerialization = validateReviewForSerialization; exports.isWellFormedUnicode = isWellFormedUnicode;
416
+ //# sourceMappingURL=chunk-6X3PJHP5.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/self-review/self-review/packages/core/dist/chunk-6X3PJHP5.cjs","../src/input-budgets.ts","../src/anchor-validation.ts","../src/xml-errors.ts","../src/review-state-validation.ts","../src/unicode-text.ts"],"names":["value","index"],"mappings":"AAAA;ACIA,IAAM,IAAA,EAAM,IAAA;AACZ,IAAM,IAAA,EAAM,KAAA,EAAO,GAAA;AAMZ,IAAM,mBAAA,EAAqB,GAAA;AAG3B,IAAM,mBAAA,EAAqB,EAAA,EAAI,GAAA;AAM/B,IAAM,sBAAA,EAAwB,EAAA,EAAI,GAAA;AAGlC,IAAM,uBAAA,EAAyB,GAAA,EAAK,GAAA;AAGpC,IAAM,0BAAA,EAA4B,GAAA,EAAK,GAAA;AAGvC,IAAM,gB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K1XZ;AACN,EAAA;AACV;AL4X4B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/self-review/self-review/packages/core/dist/chunk-6X3PJHP5.cjs","sourcesContent":[null,"// Safety budgets, checked before the expensive step. Unlike the transport thresholds\n// (`max-files`, `max-total-lines`), these are deliberately not configurable.\n// Exceeding one surfaces as a diagnostic, a guide warning or `input-too-large`.\n\nconst KIB = 1024;\nconst MIB = 1024 * KIB;\n\n/**\n * Entries one directory walk (or untracked-file listing) may examine; ignored directories are\n * pruned first.\n */\nexport const MAX_SOURCE_ENTRIES = 50_000;\n\n/** Prefix sampled for a NUL byte to decide a file is binary. */\nexport const BINARY_SNIFF_BYTES = 8 * KIB;\n\n/**\n * Largest text file read into a synthetic diff; a larger one is listed without content and named in\n * a diagnostic.\n */\nexport const MAX_SOURCE_FILE_BYTES = 5 * MIB;\n\n/** Total bytes one synthetic-diff build may read, binary sniffs included. */\nexport const MAX_SOURCE_TOTAL_BYTES = 64 * MIB;\n\n/** Most bytes of `git diff` output captured from one invocation (the child process `maxBuffer`). */\nexport const MAX_GIT_DIFF_OUTPUT_BYTES = 50 * MIB;\n\n/** Largest guide sidecar the loader will read. */\nexport const MAX_GUIDE_BYTES = 1 * MIB;\n\n/**\n * Largest review document `--resume-from` will read (text and attachment references, never bytes).\n */\nexport const MAX_RESUME_XML_BYTES = 16 * MIB;\n\n/** Most attachment occurrences in a review document, including replies and repeated references. */\nexport const MAX_REVIEW_ATTACHMENTS = 1_000;\n\n/** Backwards-compatible name for the same reader/writer document contract. */\nexport const MAX_RESUME_ATTACHMENTS = MAX_REVIEW_ATTACHMENTS;\n\n/** Total newly staged asset bytes per publication. Existing references require no copy or read. */\nexport const MAX_PUBLICATION_ASSET_BYTES = 64 * MIB;\n\n/** Largest image read for a rendered preview or a comment attachment. */\nexport const MAX_IMAGE_BYTES = 10 * MIB;\n\n/**\n * The source-loading budgets as one value; overrides are for tests and embedders, never user\n * config.\n */\nexport interface SourceBudgets {\n maxEntries: number;\n maxFileBytes: number;\n maxTotalBytes: number;\n maxGitDiffOutputBytes: number;\n /** Representation limits are independent of bytes and transport/lazy thresholds. */\n maxFileLines?: number;\n maxTotalLines?: number;\n maxDiffFiles?: number;\n maxDiffHunks?: number;\n maxDiagnostics?: number;\n}\n\n/** Bounds retained objects even for empty lines, empty hunks and metadata-only files. */\nexport const MAX_SOURCE_FILE_LINES = 100_000;\nexport const MAX_SOURCE_TOTAL_LINES = 250_000;\nexport const MAX_DIFF_FILES = 10_000;\nexport const MAX_DIFF_HUNKS = 50_000;\nexport const MAX_DIFF_DIAGNOSTICS = 1_000;\n/** Avoid repeating an enormous malicious header in each diagnostic. */\nexport const MAX_DIFF_DIAGNOSTIC_CHARS = 8 * KIB;\n\nexport type ResolvedSourceBudgets = Required<SourceBudgets>;\n\nexport const DEFAULT_SOURCE_BUDGETS: Readonly<ResolvedSourceBudgets> = Object.freeze({\n maxEntries: MAX_SOURCE_ENTRIES,\n maxFileBytes: MAX_SOURCE_FILE_BYTES,\n maxTotalBytes: MAX_SOURCE_TOTAL_BYTES,\n maxGitDiffOutputBytes: MAX_GIT_DIFF_OUTPUT_BYTES,\n maxFileLines: MAX_SOURCE_FILE_LINES,\n maxTotalLines: MAX_SOURCE_TOTAL_LINES,\n maxDiffFiles: MAX_DIFF_FILES,\n maxDiffHunks: MAX_DIFF_HUNKS,\n maxDiagnostics: MAX_DIFF_DIAGNOSTICS,\n});\n\nexport function resolveSourceBudgets(\n overrides: Partial<SourceBudgets> = {}\n): ResolvedSourceBudgets {\n const budgets = { ...DEFAULT_SOURCE_BUDGETS };\n for (const name of Object.keys(budgets) as (keyof SourceBudgets)[]) {\n const value = overrides[name];\n if (value !== undefined) budgets[name] = value;\n }\n for (const [name, value] of Object.entries(budgets)) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a nonnegative safe integer`);\n }\n }\n return budgets;\n}\n\n/** `5 MiB`, `7.3 MiB`, `812 KiB`, `100 bytes`. */\nexport function formatBytes(bytes: number): string {\n if (bytes >= MIB) return `${trimFixed(bytes / MIB)} MiB`;\n if (bytes >= KIB) return `${trimFixed(bytes / KIB)} KiB`;\n return `${bytes} bytes`;\n}\n\nfunction trimFixed(value: number): string {\n return value.toFixed(1).replace(/\\.0$/, '');\n}\n\n/** Internal refusal shared by patch parsing and direct projection. */\nexport class RepresentationLimitError extends Error {\n constructor(\n readonly aggregate: boolean,\n detail: string\n ) {\n super(`Not loaded: ${detail} representation budget exceeded.`);\n this.name = 'RepresentationLimitError';\n }\n}\n\n/** Charge before allocating. Discarded objects still count toward this operation's work. */\nexport function createRepresentationBudget(budgets: ResolvedSourceBudgets) {\n let files = 0;\n let hunks = 0;\n let lines = 0;\n let fileLines = 0;\n return {\n beginFile() {\n if (files >= budgets.maxDiffFiles)\n throw new RepresentationLimitError(true, `${budgets.maxDiffFiles}-file`);\n files++;\n fileLines = 0;\n },\n addHunk() {\n if (hunks >= budgets.maxDiffHunks)\n throw new RepresentationLimitError(true, `${budgets.maxDiffHunks}-hunk total`);\n hunks++;\n },\n addLines(count: number) {\n if (count > budgets.maxFileLines - fileLines)\n throw new RepresentationLimitError(false, `${budgets.maxFileLines}-line per-file`);\n if (count > budgets.maxTotalLines - lines)\n throw new RepresentationLimitError(true, `${budgets.maxTotalLines}-line total`);\n fileLines += count;\n lines += count;\n },\n };\n}\n","// Line-anchor validation shared by the resume importer and Apply, both untrusted input.\n\nimport type { LineRange } from './types';\n\nexport type AnchorSide = 'old' | 'new';\n\nexport interface LineAnchor {\n side: AnchorSide;\n start: number;\n end: number;\n}\n\nexport type AnchorCheck = { ok: true; anchor: LineAnchor } | { ok: false; reason: string };\n\n/** The four raw line fields; `unknown` because XML gives strings and JSON gives anything. */\nexport interface AnchorFields {\n oldLineStart?: unknown;\n oldLineEnd?: unknown;\n newLineStart?: unknown;\n newLineEnd?: unknown;\n}\n\n/**\n * Returns `null` when no field is present (a file-level comment), else the first\n * rule broken: positive safe integers (digit strings accepted), exactly one\n * complete side, start <= end, end <= `maxLine`. `reason` is embedded in diagnostics.\n */\nexport function validateLineAnchor(fields: AnchorFields, maxLine?: number): AnchorCheck | null {\n const old = sideFields('old', fields.oldLineStart, fields.oldLineEnd);\n const next = sideFields('new', fields.newLineStart, fields.newLineEnd);\n\n if (!old.present && !next.present) return null;\n if (old.present && next.present) {\n return { ok: false, reason: 'carries both old and new line ranges' };\n }\n\n const side = old.present ? old : next;\n if (side.start === undefined || side.end === undefined) {\n return { ok: false, reason: `${side.name}-line range is incomplete (start and end required)` };\n }\n\n const start = toPositiveSafeInteger(side.start);\n if (start === null) {\n return {\n ok: false,\n reason: `${side.name}-line-start is not a positive integer (${describe(side.start)})`,\n };\n }\n const end = toPositiveSafeInteger(side.end);\n if (end === null) {\n return {\n ok: false,\n reason: `${side.name}-line-end is not a positive integer (${describe(side.end)})`,\n };\n }\n\n return checkRange({ side: side.name, start, end }, maxLine);\n}\n\n/**\n * Same rules as {@link validateLineAnchor} for a typed range; `NaN`, `0`, `1.5` and `Infinity` are\n * still numbers.\n */\nexport function validateLineRange(range: LineRange, maxLine?: number): AnchorCheck {\n const start = toPositiveSafeInteger(range.start);\n if (start === null) {\n return {\n ok: false,\n reason: `${range.side}-line-start is not a positive integer (${describe(range.start)})`,\n };\n }\n const end = toPositiveSafeInteger(range.end);\n if (end === null) {\n return {\n ok: false,\n reason: `${range.side}-line-end is not a positive integer (${describe(range.end)})`,\n };\n }\n return checkRange({ side: range.side, start, end }, maxLine);\n}\n\nfunction checkRange(anchor: LineAnchor, maxLine: number | undefined): AnchorCheck {\n if (anchor.start > anchor.end) {\n return {\n ok: false,\n reason: `${anchor.side}-line range is reversed (${anchor.start} > ${anchor.end})`,\n };\n }\n if (maxLine !== undefined && anchor.end > maxLine) {\n return {\n ok: false,\n reason: `${anchor.side}-line range ends beyond line ${maxLine} (${anchor.end})`,\n };\n }\n return { ok: true, anchor };\n}\n\ninterface SideFields {\n name: AnchorSide;\n present: boolean;\n start: unknown;\n end: unknown;\n}\n\nfunction sideFields(name: AnchorSide, start: unknown, end: unknown): SideFields {\n const s = isAbsent(start) ? undefined : start;\n const e = isAbsent(end) ? undefined : end;\n return { name, present: s !== undefined || e !== undefined, start: s, end: e };\n}\n\nfunction isAbsent(value: unknown): boolean {\n return value === undefined || value === null;\n}\n\n/**\n * A positive safe integer from a number or decimal digit string; anything else (`1e3`, `NaN`,\n * booleans) is `null`.\n */\nfunction toPositiveSafeInteger(value: unknown): number | null {\n let n: number;\n if (typeof value === 'number') {\n n = value;\n } else if (typeof value === 'string' && /^\\d+$/.test(value)) {\n n = Number(value);\n } else {\n return null;\n }\n return Number.isSafeInteger(n) && n > 0 ? n : null;\n}\n\nfunction describe(value: unknown): string {\n return typeof value === 'string' ? JSON.stringify(value) : String(value);\n}\n","// Typed failures of review XML reading and writing. Library code throws, hosts print\n// `.message` and choose their exit; nothing here calls `process.exit`.\n\nexport type ReviewXmlErrorCode =\n | 'read-failed'\n /** Over a safety budget (input-budgets.ts): byte size or attachment count. */\n | 'input-too-large'\n | 'parse-failed'\n /** Well-formed, but with no `<review>` root element. */\n | 'missing-root'\n /** The generated document does not validate against the v3 XSD. */\n | 'schema-invalid'\n /** The in-memory review DTO is malformed or has an unusable anchor. */\n | 'invalid-state'\n | 'xml-illegal-character';\n\nexport class ReviewXmlError extends Error {\n readonly code: ReviewXmlErrorCode;\n readonly cause?: unknown;\n /** One rendered line per problem (e.g. a schema violation with its line number). */\n readonly details: readonly string[];\n\n constructor(\n code: ReviewXmlErrorCode,\n message: string,\n options?: { cause?: unknown; details?: readonly string[] }\n ) {\n // Assigned, not passed to `super`: the app's tsconfig lib lacks `ErrorOptions`.\n super(message);\n this.name = 'ReviewXmlError';\n this.code = code;\n this.details = options?.details ?? [];\n if (options?.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport interface XmlIllegalCharacterLocation {\n /** e.g. `body`, `original-code`, `path`, `author`. */\n field: string;\n filePath?: string;\n commentId?: string;\n replyId?: string;\n}\n\n/**\n * Thrown before anything is written: no escaped form exists, and dropping the character would\n * change the reviewer's text or a suggestion's code.\n */\nexport class XmlIllegalCharacterError extends ReviewXmlError {\n readonly codePoint: number;\n readonly field: string;\n readonly filePath?: string;\n readonly commentId?: string;\n readonly replyId?: string;\n\n constructor(codePoint: number, location: XmlIllegalCharacterLocation) {\n super('xml-illegal-character', describeIllegalCharacter(codePoint, location));\n this.name = 'XmlIllegalCharacterError';\n this.codePoint = codePoint;\n this.field = location.field;\n this.filePath = location.filePath;\n this.commentId = location.commentId;\n this.replyId = location.replyId;\n }\n}\n\nfunction describeIllegalCharacter(\n codePoint: number,\n location: XmlIllegalCharacterLocation\n): string {\n const hex = codePoint.toString(16).toUpperCase().padStart(4, '0');\n const where = [\n location.filePath !== undefined ? `file \"${location.filePath}\"` : null,\n location.commentId !== undefined ? `comment ${location.commentId}` : null,\n location.replyId !== undefined ? `reply ${location.replyId}` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(', ');\n return (\n `Cannot write review XML: ${location.field}${where ? ` of ${where}` : ''} contains ` +\n `U+${hex}, which XML 1.0 cannot represent. Remove the character and save again.`\n );\n}\n","// Runtime boundary for review DTOs, shared by transports and XML publication.\n// Validated DTOs retain supported optional metadata, extension fields and binary assets.\n\nimport type { ReviewState } from './types';\nimport { validateLineRange } from './anchor-validation';\nimport { ReviewXmlError } from './xml-errors';\nimport {\n MAX_IMAGE_BYTES,\n MAX_REVIEW_ATTACHMENTS,\n MAX_PUBLICATION_ASSET_BYTES,\n formatBytes,\n} from './input-budgets';\n\n/**\n * Validate the complete in-memory DTO without I/O. Unknown extension fields are retained.\n * Historical submissions may omit nullable anchors/suggestions; the returned DTO defaults them to null.\n * Already complete DTOs are returned unchanged.\n * Hosts can catch ReviewXmlError (`invalid-state`) before accepting a submission. Serialization and\n * publication use the same boundary, including when the XSD validator is unavailable.\n */\nexport function validateReviewState(value: unknown): ReviewState {\n validateState(value, true);\n return normalizeNullableFields(value as ReviewState);\n}\n\n/** Existing serializers accept a missing transient comment id and use an empty asset prefix. */\nexport function validateReviewForSerialization(state: ReviewState): ReviewState {\n validateState(state, false);\n return normalizeNullableFields(state);\n}\n\nfunction validateState(value: unknown, requireCommentIds: boolean): void {\n const state = record(value, 'review');\n const budget = { attachments: 0, bytes: 0 };\n string(state.timestamp, 'review.timestamp');\n const source = record(state.source, 'review.source');\n switch (source.type) {\n case 'git':\n string(source.gitDiffArgs, 'review.source.gitDiffArgs');\n string(source.repository, 'review.source.repository');\n break;\n case 'directory':\n case 'file':\n string(source.sourcePath, 'review.source.sourcePath');\n break;\n case 'welcome':\n case 'loading':\n break;\n default:\n invalid('review.source.type', 'must be git, directory, file, welcome or loading');\n }\n for (const key of ['remoteUrl', 'remoteBaseSha', 'remoteHeadSha'])\n optionalString(state, key, 'review');\n optionalEnum(state, 'remoteForge', ['github', 'gitlab'], 'review');\n array(state.files, 'review.files').forEach((value, index) => {\n const at = `review.files[${index}]`;\n const file = record(value, at);\n string(file.path, `${at}.path`);\n enumValue(\n file.changeType,\n ['added', 'modified', 'deleted', 'renamed', 'copied'],\n `${at}.changeType`\n );\n boolean(file.viewed, `${at}.viewed`);\n array(file.comments, `${at}.comments`).forEach((comment, index) =>\n validateComment(\n comment,\n `${at}.comments[${index}]`,\n file.path as string,\n requireCommentIds,\n budget\n )\n );\n });\n}\n\nfunction validateComment(\n value: unknown,\n at: string,\n ownerPath: string,\n requireId: boolean,\n budget: AttachmentBudget\n): void {\n const comment = record(value, at);\n if (requireId || comment.id !== undefined) string(comment.id, `${at}.id`);\n for (const key of ['filePath', 'body', 'category']) string(comment[key], `${at}.${key}`);\n if (comment.filePath !== ownerPath)\n invalid(`${at}.filePath`, 'must match its containing file path');\n for (const key of ['author', 'remoteId']) optionalString(comment, key, at);\n optionalEnum(comment, 'severity', ['critical', 'major', 'minor', 'info'], at);\n optionalEnum(comment, 'confidence', ['high', 'medium', 'low'], at);\n if (comment.orphaned !== undefined) boolean(comment.orphaned, `${at}.orphaned`);\n if (comment.lineRange !== null && comment.lineRange !== undefined) {\n const range = record(comment.lineRange, `${at}.lineRange`);\n enumValue(range.side, ['old', 'new'], `${at}.lineRange.side`);\n if (typeof range.start !== 'number' || typeof range.end !== 'number')\n invalid(`${at}.lineRange`, 'bounds must be numbers');\n const checked = validateLineRange({\n side: range.side as 'old' | 'new',\n start: range.start as number,\n end: range.end as number,\n });\n if (!checked.ok) invalid(`${at}.lineRange`, checked.reason);\n }\n if (comment.suggestion !== null && comment.suggestion !== undefined) {\n const suggestion = record(comment.suggestion, `${at}.suggestion`);\n string(suggestion.originalCode, `${at}.suggestion.originalCode`);\n string(suggestion.proposedCode, `${at}.suggestion.proposedCode`);\n if (comment.lineRange === null || comment.lineRange === undefined)\n invalid(`${at}.suggestion`, 'requires a line anchor');\n }\n validateAttachments(comment.attachments, `${at}.attachments`, budget);\n if (comment.replies !== undefined) {\n array(comment.replies, `${at}.replies`).forEach((value, index) => {\n const replyAt = `${at}.replies[${index}]`;\n const reply = record(value, replyAt);\n string(reply.id, `${replyAt}.id`);\n string(reply.body, `${replyAt}.body`);\n for (const key of ['author', 'remoteId']) optionalString(reply, key, replyAt);\n validateAttachments(reply.attachments, `${replyAt}.attachments`, budget);\n });\n }\n}\n\ninterface AttachmentBudget {\n attachments: number;\n bytes: number;\n}\n\nfunction validateAttachments(value: unknown, at: string, budget: AttachmentBudget): void {\n if (value === undefined) return;\n const attachments = array(value, at);\n budget.attachments += attachments.length;\n if (budget.attachments > MAX_REVIEW_ATTACHMENTS)\n invalid(at, `exceeds the ${MAX_REVIEW_ATTACHMENTS} attachment limit for a review document`);\n attachments.forEach((value, index) => {\n const attachmentAt = `${at}[${index}]`;\n const attachment = record(value, attachmentAt);\n for (const key of ['id', 'fileName', 'mediaType'])\n string(attachment[key], `${attachmentAt}.${key}`);\n if (attachment.data !== undefined && !isReadableArrayBuffer(attachment.data))\n invalid(`${attachmentAt}.data`, 'must be a readable ArrayBuffer');\n if (attachment.data !== undefined) {\n const bytes = new Uint8Array(attachment.data as ArrayBuffer).byteLength;\n if (bytes > MAX_IMAGE_BYTES)\n invalid(\n `${attachmentAt}.data`,\n `exceeds the ${formatBytes(MAX_IMAGE_BYTES)} attachment limit`\n );\n budget.bytes += bytes;\n if (budget.bytes > MAX_PUBLICATION_ASSET_BYTES)\n invalid(\n at,\n `exceeds the ${formatBytes(MAX_PUBLICATION_ASSET_BYTES)} publication asset limit`\n );\n }\n });\n}\n\nfunction record(value: unknown, at: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n invalid(at, 'must be an object');\n return value as Record<string, unknown>;\n}\n\nfunction array(value: unknown, at: string): unknown[] {\n if (!Array.isArray(value)) invalid(at, 'must be an array');\n for (let index = 0; index < value.length; index++) {\n if (!(index in value)) invalid(`${at}[${index}]`, 'must be present');\n }\n return value;\n}\n\nfunction string(value: unknown, at: string): void {\n if (typeof value !== 'string') invalid(at, 'must be a string');\n}\n\nfunction boolean(value: unknown, at: string): void {\n if (typeof value !== 'boolean') invalid(at, 'must be a boolean');\n}\n\nfunction optionalString(node: Record<string, unknown>, key: string, at: string): void {\n if (node[key] !== undefined) string(node[key], `${at}.${key}`);\n}\n\nfunction enumValue(value: unknown, allowed: readonly string[], at: string): void {\n if (typeof value !== 'string' || !allowed.includes(value))\n invalid(at, `must be one of ${allowed.join(', ')}`);\n}\n\nfunction optionalEnum(\n node: Record<string, unknown>,\n key: string,\n allowed: readonly string[],\n at: string\n): void {\n if (node[key] !== undefined) enumValue(node[key], allowed, `${at}.${key}`);\n}\n\nfunction invalid(at: string, reason: string): never {\n const message = `Invalid review state: ${at} ${reason}`;\n throw new ReviewXmlError('invalid-state', message, { details: [message] });\n}\n\n/** Only copy branches with historical omissions; buffers and extension fields keep their identity. */\nfunction normalizeNullableFields(state: ReviewState): ReviewState {\n const files = state.files.map(file => {\n const comments = file.comments.map(comment =>\n comment.lineRange === undefined || comment.suggestion === undefined\n ? {\n ...comment,\n lineRange: comment.lineRange ?? null,\n suggestion: comment.suggestion ?? null,\n }\n : comment\n );\n return comments.some((comment, index) => comment !== file.comments[index])\n ? { ...file, comments }\n : file;\n });\n return files.some((file, index) => file !== state.files[index]) ? { ...state, files } : state;\n}\n\n/** Intrinsic slot checks accept buffers across realms and refuse detached buffers before staging. */\nfunction isReadableArrayBuffer(value: unknown): value is ArrayBuffer {\n try {\n const getLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')!.get!;\n getLength.call(value);\n return new Uint8Array(value as ArrayBuffer).buffer === value;\n } catch {\n return false;\n }\n}\n","/** Lone UTF-16 surrogates cannot round-trip through UTF-8 without replacement. */\nexport function isWellFormedUnicode(value: string): boolean {\n return !/[\\uD800-\\uDFFF]/u.test(value);\n}\n"]}
@@ -0,0 +1,37 @@
1
+ import {
2
+ isWellFormedUnicode
3
+ } from "./chunk-IG2YF5LH.js";
4
+
5
+ // src/review-request-validation.ts
6
+ var MAX_CONTEXT_LINES = 99999;
7
+ function record(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ function decodeSuggestionApplyRequest(value) {
11
+ if (!record(value)) return { ok: false, error: "body must be a JSON object" };
12
+ if (typeof value.filePath !== "string") return { ok: false, error: "filePath must be a string" };
13
+ const range = value.lineRange;
14
+ if (range !== null) {
15
+ if (!record(range)) return { ok: false, error: "lineRange must be an object or null" };
16
+ if (range.side !== "old" && range.side !== "new")
17
+ return { ok: false, error: "lineRange.side must be 'old' or 'new'" };
18
+ for (const key of ["start", "end"]) {
19
+ if (typeof range[key] !== "number")
20
+ return { ok: false, error: `lineRange.${key} must be a number` };
21
+ }
22
+ }
23
+ if (!record(value.suggestion)) return { ok: false, error: "suggestion must be an object" };
24
+ for (const key of ["originalCode", "proposedCode"]) {
25
+ if (typeof value.suggestion[key] !== "string")
26
+ return { ok: false, error: `suggestion.${key} must be a string` };
27
+ }
28
+ if (!isWellFormedUnicode(value.suggestion.proposedCode))
29
+ return { ok: false, error: "suggestion.proposedCode must be well-formed Unicode text" };
30
+ return { ok: true, value };
31
+ }
32
+
33
+ export {
34
+ MAX_CONTEXT_LINES,
35
+ decodeSuggestionApplyRequest
36
+ };
37
+ //# sourceMappingURL=chunk-CJQEOLI3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/review-request-validation.ts"],"sourcesContent":["// Transport-neutral request structure. Anchor usability belongs to the engine,\n// which returns typed refusals before reading or changing reviewed source.\nimport type { SuggestionApplyRequest } from './types';\nimport { isWellFormedUnicode } from './unicode-text';\n\nexport const MAX_CONTEXT_LINES = 99_999;\nexport type RequestDecodeResult<T> = { ok: true; value: T } | { ok: false; error: string };\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Preserves extension fields; each transport decides its own unknown-key policy. */\nexport function decodeSuggestionApplyRequest(\n value: unknown\n): RequestDecodeResult<SuggestionApplyRequest> {\n if (!record(value)) return { ok: false, error: 'body must be a JSON object' };\n if (typeof value.filePath !== 'string') return { ok: false, error: 'filePath must be a string' };\n const range = value.lineRange;\n if (range !== null) {\n if (!record(range)) return { ok: false, error: 'lineRange must be an object or null' };\n if (range.side !== 'old' && range.side !== 'new')\n return { ok: false, error: \"lineRange.side must be 'old' or 'new'\" };\n for (const key of ['start', 'end'] as const) {\n if (typeof range[key] !== 'number')\n return { ok: false, error: `lineRange.${key} must be a number` };\n }\n }\n if (!record(value.suggestion)) return { ok: false, error: 'suggestion must be an object' };\n for (const key of ['originalCode', 'proposedCode'] as const) {\n if (typeof value.suggestion[key] !== 'string')\n return { ok: false, error: `suggestion.${key} must be a string` };\n }\n if (!isWellFormedUnicode(value.suggestion.proposedCode as string))\n return { ok: false, error: 'suggestion.proposedCode must be well-formed Unicode text' };\n return { ok: true, value: value as unknown as SuggestionApplyRequest };\n}\n"],"mappings":";;;;;AAKO,IAAM,oBAAoB;AAGjC,SAAS,OAAO,OAAkD;AAChE,SAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAGO,SAAS,6BACd,OAC6C;AAC7C,MAAI,CAAC,OAAO,KAAK,EAAG,QAAO,EAAE,IAAI,OAAO,OAAO,6BAA6B;AAC5E,MAAI,OAAO,MAAM,aAAa,SAAU,QAAO,EAAE,IAAI,OAAO,OAAO,4BAA4B;AAC/F,QAAM,QAAQ,MAAM;AACpB,MAAI,UAAU,MAAM;AAClB,QAAI,CAAC,OAAO,KAAK,EAAG,QAAO,EAAE,IAAI,OAAO,OAAO,sCAAsC;AACrF,QAAI,MAAM,SAAS,SAAS,MAAM,SAAS;AACzC,aAAO,EAAE,IAAI,OAAO,OAAO,wCAAwC;AACrE,eAAW,OAAO,CAAC,SAAS,KAAK,GAAY;AAC3C,UAAI,OAAO,MAAM,GAAG,MAAM;AACxB,eAAO,EAAE,IAAI,OAAO,OAAO,aAAa,GAAG,oBAAoB;AAAA,IACnE;AAAA,EACF;AACA,MAAI,CAAC,OAAO,MAAM,UAAU,EAAG,QAAO,EAAE,IAAI,OAAO,OAAO,+BAA+B;AACzF,aAAW,OAAO,CAAC,gBAAgB,cAAc,GAAY;AAC3D,QAAI,OAAO,MAAM,WAAW,GAAG,MAAM;AACnC,aAAO,EAAE,IAAI,OAAO,OAAO,cAAc,GAAG,oBAAoB;AAAA,EACpE;AACA,MAAI,CAAC,oBAAoB,MAAM,WAAW,YAAsB;AAC9D,WAAO,EAAE,IAAI,OAAO,OAAO,2DAA2D;AACxF,SAAO,EAAE,IAAI,MAAM,MAAkD;AACvE;","names":[]}