@self-review/core 1.0.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1234 @@
1
+ // src/diff-parser.ts
2
+ function parseDiff(rawDiff) {
3
+ if (!rawDiff.trim()) {
4
+ return [];
5
+ }
6
+ const lines = rawDiff.split("\n");
7
+ const files = [];
8
+ let currentFile = null;
9
+ let currentHunk = null;
10
+ let oldLineNumber = 0;
11
+ let newLineNumber = 0;
12
+ for (let i = 0; i < lines.length; i++) {
13
+ const line = lines[i];
14
+ if (line.startsWith("diff --git ")) {
15
+ if (currentHunk && currentHunk.header && currentFile) {
16
+ currentFile.hunks.push(currentHunk);
17
+ currentHunk = null;
18
+ }
19
+ if (currentFile && currentFile.oldPath !== void 0 && currentFile.newPath !== void 0) {
20
+ if (currentFile.isBinary || currentFile.hunks && currentFile.hunks.length > 0 || currentFile.changeType === "added") {
21
+ files.push(currentFile);
22
+ }
23
+ }
24
+ const gitPaths = parseGitDiffHeader(line);
25
+ currentFile = {
26
+ oldPath: gitPaths.oldPath,
27
+ newPath: gitPaths.newPath,
28
+ changeType: "modified",
29
+ isBinary: false,
30
+ hunks: []
31
+ };
32
+ currentHunk = null;
33
+ continue;
34
+ }
35
+ if (!currentFile) continue;
36
+ if (line.startsWith("new file mode")) {
37
+ currentFile.changeType = "added";
38
+ continue;
39
+ }
40
+ if (line.startsWith("deleted file mode")) {
41
+ currentFile.changeType = "deleted";
42
+ continue;
43
+ }
44
+ if (line.startsWith("rename from ")) {
45
+ currentFile.changeType = "renamed";
46
+ continue;
47
+ }
48
+ if (line.startsWith("--- ")) {
49
+ const path2 = line.substring(4);
50
+ currentFile.oldPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
51
+ continue;
52
+ }
53
+ if (line.startsWith("+++ ")) {
54
+ const path2 = line.substring(4);
55
+ currentFile.newPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
56
+ continue;
57
+ }
58
+ if (line.startsWith("Binary files ")) {
59
+ currentFile.isBinary = true;
60
+ continue;
61
+ }
62
+ if (line.startsWith("@@")) {
63
+ if (currentHunk && currentHunk.header) {
64
+ currentFile.hunks.push(currentHunk);
65
+ }
66
+ const match = line.match(
67
+ /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/
68
+ );
69
+ if (match) {
70
+ const oldStart = parseInt(match[1], 10);
71
+ const oldLines = match[2] ? parseInt(match[2], 10) : 1;
72
+ const newStart = parseInt(match[3], 10);
73
+ const newLines = match[4] ? parseInt(match[4], 10) : 1;
74
+ const _context = match[5];
75
+ currentHunk = {
76
+ header: line,
77
+ oldStart,
78
+ oldLines,
79
+ newStart,
80
+ newLines,
81
+ lines: []
82
+ };
83
+ oldLineNumber = oldStart;
84
+ newLineNumber = newStart;
85
+ }
86
+ continue;
87
+ }
88
+ if (currentHunk && currentHunk.lines) {
89
+ if (line.startsWith("+")) {
90
+ currentHunk.lines.push({
91
+ type: "addition",
92
+ oldLineNumber: null,
93
+ newLineNumber,
94
+ content: line.substring(1)
95
+ });
96
+ newLineNumber++;
97
+ } else if (line.startsWith("-")) {
98
+ currentHunk.lines.push({
99
+ type: "deletion",
100
+ oldLineNumber,
101
+ newLineNumber: null,
102
+ content: line.substring(1)
103
+ });
104
+ oldLineNumber++;
105
+ } else if (line.startsWith(" ")) {
106
+ currentHunk.lines.push({
107
+ type: "context",
108
+ oldLineNumber,
109
+ newLineNumber,
110
+ content: line.substring(1)
111
+ });
112
+ oldLineNumber++;
113
+ newLineNumber++;
114
+ } else if (line.startsWith("\\")) {
115
+ continue;
116
+ } else {
117
+ if (currentHunk.lines.length > 0) {
118
+ currentHunk.lines.push({
119
+ type: "context",
120
+ oldLineNumber,
121
+ newLineNumber,
122
+ content: line
123
+ });
124
+ oldLineNumber++;
125
+ newLineNumber++;
126
+ }
127
+ }
128
+ }
129
+ }
130
+ if (currentHunk && currentHunk.header && currentFile) {
131
+ currentFile.hunks.push(currentHunk);
132
+ }
133
+ if (currentFile && currentFile.oldPath !== void 0 && currentFile.newPath !== void 0) {
134
+ if (currentFile.isBinary || currentFile.hunks && currentFile.hunks.length > 0 || currentFile.changeType === "added") {
135
+ files.push(currentFile);
136
+ }
137
+ }
138
+ return files;
139
+ }
140
+ function stripPrefix(path2) {
141
+ if (path2.length > 2 && path2[1] === "/") {
142
+ return path2.substring(2);
143
+ }
144
+ return path2;
145
+ }
146
+ function parseGitDiffHeader(line) {
147
+ const withoutPrefix = line.substring("diff --git ".length);
148
+ let bIdx = -1;
149
+ for (const prefix of [" b/", " w/", " i/", " c/", " o/"]) {
150
+ bIdx = withoutPrefix.indexOf(prefix);
151
+ if (bIdx !== -1) break;
152
+ }
153
+ if (bIdx === -1) {
154
+ return { oldPath: "", newPath: "" };
155
+ }
156
+ const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));
157
+ const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));
158
+ return { oldPath, newPath };
159
+ }
160
+
161
+ // src/xml-serializer.ts
162
+ import * as path from "path";
163
+ import * as fs from "fs";
164
+ import { validateXML } from "xmllint-wasm";
165
+ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
166
+ <xs:schema
167
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
168
+ xmlns:sr="urn:self-review:v1"
169
+ targetNamespace="urn:self-review:v1"
170
+ elementFormDefault="qualified"
171
+ >
172
+
173
+ <xs:element name="review" type="sr:ReviewType">
174
+ <xs:annotation>
175
+ <xs:documentation>
176
+ Root element of a self-review output file. Contains one file element
177
+ per file in the git diff, including files with no comments.
178
+ </xs:documentation>
179
+ </xs:annotation>
180
+ </xs:element>
181
+
182
+ <xs:complexType name="ReviewType">
183
+ <xs:sequence>
184
+ <xs:element name="file" type="sr:FileType" minOccurs="0" maxOccurs="unbounded" />
185
+ </xs:sequence>
186
+ <xs:attribute name="timestamp" type="xs:dateTime" use="required">
187
+ <xs:annotation>
188
+ <xs:documentation>
189
+ ISO 8601 timestamp of when the review was completed (window closed).
190
+ </xs:documentation>
191
+ </xs:annotation>
192
+ </xs:attribute>
193
+ <xs:attribute name="git-diff-args" type="xs:string" use="optional">
194
+ <xs:annotation>
195
+ <xs:documentation>
196
+ The git diff arguments that were passed to self-review on the CLI.
197
+ Example: "--staged", "main..feature-branch", "HEAD~3".
198
+ Present only when reviewing a git diff.
199
+ </xs:documentation>
200
+ </xs:annotation>
201
+ </xs:attribute>
202
+ <xs:attribute name="repository" type="xs:string" use="optional">
203
+ <xs:annotation>
204
+ <xs:documentation>
205
+ Absolute path to the repository root where self-review was invoked.
206
+ Present only when reviewing a git diff.
207
+ </xs:documentation>
208
+ </xs:annotation>
209
+ </xs:attribute>
210
+ <xs:attribute name="source-path" type="xs:string" use="optional">
211
+ <xs:annotation>
212
+ <xs:documentation>
213
+ Absolute path to the directory being reviewed.
214
+ Present only when reviewing a directory (non-git mode).
215
+ </xs:documentation>
216
+ </xs:annotation>
217
+ </xs:attribute>
218
+ </xs:complexType>
219
+
220
+ <xs:complexType name="FileType">
221
+ <xs:annotation>
222
+ <xs:documentation>
223
+ Represents a single file in the diff. Files with no comments
224
+ appear as empty elements. The path is relative to the repository root.
225
+ </xs:documentation>
226
+ </xs:annotation>
227
+ <xs:sequence>
228
+ <xs:element name="comment" type="sr:CommentType" minOccurs="0" maxOccurs="unbounded" />
229
+ </xs:sequence>
230
+ <xs:attribute name="path" type="xs:string" use="required">
231
+ <xs:annotation>
232
+ <xs:documentation>
233
+ File path relative to the repository root. For renamed files,
234
+ this is the new path.
235
+ </xs:documentation>
236
+ </xs:annotation>
237
+ </xs:attribute>
238
+ <xs:attribute name="change-type" type="sr:ChangeTypeEnum" use="required">
239
+ <xs:annotation>
240
+ <xs:documentation>
241
+ The type of change: added, modified, deleted, or renamed.
242
+ </xs:documentation>
243
+ </xs:annotation>
244
+ </xs:attribute>
245
+ <xs:attribute name="viewed" type="xs:boolean" use="required">
246
+ <xs:annotation>
247
+ <xs:documentation>
248
+ Whether the reviewer marked this file as reviewed.
249
+ true = the reviewer looked at this file.
250
+ false = the reviewer did not mark this file as viewed.
251
+ This helps an AI agent distinguish "reviewed with no comments"
252
+ from "not yet reviewed."
253
+ </xs:documentation>
254
+ </xs:annotation>
255
+ </xs:attribute>
256
+ </xs:complexType>
257
+
258
+ <xs:complexType name="CommentType">
259
+ <xs:annotation>
260
+ <xs:documentation>
261
+ A review comment. Three forms:
262
+
263
+ 1. File-level comment: no line attributes present.
264
+ Applies to the file as a whole.
265
+
266
+ 2. Comment on new/added/context lines: new-line-start and
267
+ new-line-end are present. These reference line numbers in the
268
+ post-change version of the file.
269
+
270
+ 3. Comment on old/deleted lines: old-line-start and old-line-end
271
+ are present. These reference line numbers in the pre-change
272
+ version of the file.
273
+
274
+ For single-line comments, start and end are equal.
275
+ Exactly one pair (old or new) should be present for line-level
276
+ comments. Both pairs absent = file-level comment.
277
+ </xs:documentation>
278
+ </xs:annotation>
279
+ <xs:sequence>
280
+ <xs:element name="body" type="xs:string">
281
+ <xs:annotation>
282
+ <xs:documentation>
283
+ The comment text. May contain markdown formatting.
284
+ </xs:documentation>
285
+ </xs:annotation>
286
+ </xs:element>
287
+ <xs:element name="category" type="xs:string">
288
+ <xs:annotation>
289
+ <xs:documentation>
290
+ Required category tag for this comment (e.g., "bug", "style",
291
+ "nit", "question", "security"). Categories are defined in the
292
+ project-level .self-review.yaml configuration. Every comment
293
+ must have a category to help AI agents prioritize and triage
294
+ feedback.
295
+ </xs:documentation>
296
+ </xs:annotation>
297
+ </xs:element>
298
+ <xs:element name="suggestion" type="sr:SuggestionType" minOccurs="0">
299
+ <xs:annotation>
300
+ <xs:documentation>
301
+ Optional code replacement proposal. When present, the AI agent
302
+ should replace the original-code with the proposed-code at the
303
+ referenced line range.
304
+ </xs:documentation>
305
+ </xs:annotation>
306
+ </xs:element>
307
+ <xs:element name="attachment" type="sr:AttachmentType" minOccurs="0" maxOccurs="unbounded">
308
+ <xs:annotation>
309
+ <xs:documentation>
310
+ Optional image attachment. The path attribute references an image file
311
+ stored in the .self-review-assets/ directory alongside the XML output.
312
+ </xs:documentation>
313
+ </xs:annotation>
314
+ </xs:element>
315
+ </xs:sequence>
316
+ <xs:attribute name="old-line-start" type="xs:positiveInteger" use="optional">
317
+ <xs:annotation>
318
+ <xs:documentation>
319
+ Start line number in the pre-change (old) version of the file.
320
+ Use for comments on deleted lines.
321
+ </xs:documentation>
322
+ </xs:annotation>
323
+ </xs:attribute>
324
+ <xs:attribute name="old-line-end" type="xs:positiveInteger" use="optional">
325
+ <xs:annotation>
326
+ <xs:documentation>
327
+ End line number (inclusive) in the pre-change (old) version.
328
+ Must be >= old-line-start when both are present.
329
+ </xs:documentation>
330
+ </xs:annotation>
331
+ </xs:attribute>
332
+ <xs:attribute name="new-line-start" type="xs:positiveInteger" use="optional">
333
+ <xs:annotation>
334
+ <xs:documentation>
335
+ Start line number in the post-change (new) version of the file.
336
+ Use for comments on added or context (unchanged) lines.
337
+ </xs:documentation>
338
+ </xs:annotation>
339
+ </xs:attribute>
340
+ <xs:attribute name="new-line-end" type="xs:positiveInteger" use="optional">
341
+ <xs:annotation>
342
+ <xs:documentation>
343
+ End line number (inclusive) in the post-change (new) version.
344
+ Must be >= new-line-start when both are present.
345
+ </xs:documentation>
346
+ </xs:annotation>
347
+ </xs:attribute>
348
+ </xs:complexType>
349
+
350
+ <xs:complexType name="SuggestionType">
351
+ <xs:annotation>
352
+ <xs:documentation>
353
+ A code replacement proposal. The original-code is the literal text
354
+ currently at the referenced lines. The proposed-code is what the
355
+ reviewer suggests it should be replaced with. The AI agent can apply
356
+ this by performing a text substitution.
357
+ </xs:documentation>
358
+ </xs:annotation>
359
+ <xs:sequence>
360
+ <xs:element name="original-code" type="xs:string">
361
+ <xs:annotation>
362
+ <xs:documentation>
363
+ The existing code at the referenced line range, copied verbatim
364
+ from the diff. Used by the AI agent to locate the replacement
365
+ target via text matching.
366
+ </xs:documentation>
367
+ </xs:annotation>
368
+ </xs:element>
369
+ <xs:element name="proposed-code" type="xs:string">
370
+ <xs:annotation>
371
+ <xs:documentation>
372
+ The replacement code proposed by the reviewer. The AI agent
373
+ should substitute original-code with this text.
374
+ </xs:documentation>
375
+ </xs:annotation>
376
+ </xs:element>
377
+ </xs:sequence>
378
+ </xs:complexType>
379
+
380
+ <xs:complexType name="AttachmentType">
381
+ <xs:annotation>
382
+ <xs:documentation>
383
+ Reference to an image file attached to a review comment. The file is stored
384
+ alongside the XML output in the .self-review-assets/ directory.
385
+ </xs:documentation>
386
+ </xs:annotation>
387
+ <xs:attribute name="path" type="xs:string" use="required">
388
+ <xs:annotation>
389
+ <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>
390
+ </xs:annotation>
391
+ </xs:attribute>
392
+ <xs:attribute name="media-type" type="xs:string" use="required">
393
+ <xs:annotation>
394
+ <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>
395
+ </xs:annotation>
396
+ </xs:attribute>
397
+ </xs:complexType>
398
+
399
+ <xs:simpleType name="ChangeTypeEnum">
400
+ <xs:annotation>
401
+ <xs:documentation>
402
+ The type of change a file underwent in the diff.
403
+ </xs:documentation>
404
+ </xs:annotation>
405
+ <xs:restriction base="xs:string">
406
+ <xs:enumeration value="added">
407
+ <xs:annotation>
408
+ <xs:documentation>New file that did not exist before.</xs:documentation>
409
+ </xs:annotation>
410
+ </xs:enumeration>
411
+ <xs:enumeration value="modified">
412
+ <xs:annotation>
413
+ <xs:documentation>Existing file with content changes.</xs:documentation>
414
+ </xs:annotation>
415
+ </xs:enumeration>
416
+ <xs:enumeration value="deleted">
417
+ <xs:annotation>
418
+ <xs:documentation>File was removed.</xs:documentation>
419
+ </xs:annotation>
420
+ </xs:enumeration>
421
+ <xs:enumeration value="renamed">
422
+ <xs:annotation>
423
+ <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>
424
+ </xs:annotation>
425
+ </xs:enumeration>
426
+ </xs:restriction>
427
+ </xs:simpleType>
428
+
429
+ </xs:schema>`;
430
+ function extFromMediaType(mediaType) {
431
+ const map = {
432
+ "image/png": "png",
433
+ "image/jpeg": "jpg",
434
+ "image/webp": "webp",
435
+ "image/gif": "gif"
436
+ };
437
+ return map[mediaType] || "png";
438
+ }
439
+ function writeAttachments(state, outputFilePath) {
440
+ const assetDir = path.join(path.dirname(outputFilePath), ".self-review-assets");
441
+ let hasAttachments = false;
442
+ const updatedFiles = state.files.map((file) => ({
443
+ ...file,
444
+ comments: file.comments.map((comment) => {
445
+ if (!comment.attachments?.length) return comment;
446
+ const updatedAttachments = comment.attachments.map((att, index) => {
447
+ if (!att.data) return att;
448
+ hasAttachments = true;
449
+ const ext = extFromMediaType(att.mediaType);
450
+ const fileName = `${comment.id}-${index}.${ext}`;
451
+ const relativePath = `.self-review-assets/${fileName}`;
452
+ if (!fs.existsSync(assetDir)) {
453
+ fs.mkdirSync(assetDir, { recursive: true });
454
+ }
455
+ fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));
456
+ return { ...att, fileName: relativePath, data: void 0 };
457
+ });
458
+ return { ...comment, attachments: updatedAttachments };
459
+ })
460
+ }));
461
+ if (hasAttachments) {
462
+ console.error(`[main] Wrote attachment files to ${assetDir}`);
463
+ }
464
+ return { ...state, files: updatedFiles };
465
+ }
466
+ async function serializeReview(state, outputFilePath) {
467
+ const processedState = writeAttachments(state, outputFilePath);
468
+ const xml = buildXml(processedState);
469
+ try {
470
+ const validationResult = await validateXML({
471
+ xml: [{ fileName: "review.xml", contents: xml }],
472
+ schema: [{ fileName: "self-review-v1.xsd", contents: XSD_SCHEMA }]
473
+ });
474
+ if (!validationResult.valid) {
475
+ const errors = validationResult.errors || [];
476
+ console.error("XML validation failed:");
477
+ errors.forEach((err) => console.error(` ${err}`));
478
+ throw new Error("Generated XML does not conform to schema");
479
+ }
480
+ } catch (error) {
481
+ if (error instanceof Error && error.message === "Generated XML does not conform to schema") {
482
+ throw error;
483
+ }
484
+ if (error instanceof Error) {
485
+ console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);
486
+ } else {
487
+ console.error("[main] XML validation infrastructure failed - emitting XML without validation");
488
+ }
489
+ return xml;
490
+ }
491
+ return xml;
492
+ }
493
+ function buildSourceAttributes(state) {
494
+ const source = state.source;
495
+ if (source.type === "git") {
496
+ return ` git-diff-args="${escapeXml(source.gitDiffArgs)}" repository="${escapeXml(source.repository)}"`;
497
+ }
498
+ if (source.type === "directory" || source.type === "file") {
499
+ return ` source-path="${escapeXml(source.sourcePath)}"`;
500
+ }
501
+ return "";
502
+ }
503
+ function buildXml(state) {
504
+ const lines = [];
505
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
506
+ const sourceAttrs = buildSourceAttributes(state);
507
+ lines.push(
508
+ `<review xmlns="urn:self-review:v1" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}>`
509
+ );
510
+ for (const file of state.files) {
511
+ lines.push(...buildFileXml(file));
512
+ }
513
+ lines.push("</review>");
514
+ return lines.join("\n");
515
+ }
516
+ function buildFileXml(file) {
517
+ const lines = [];
518
+ if (file.comments.length === 0) {
519
+ lines.push(
520
+ ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}" />`
521
+ );
522
+ } else {
523
+ lines.push(
524
+ ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}">`
525
+ );
526
+ for (const comment of file.comments) {
527
+ lines.push(...buildCommentXml(comment));
528
+ }
529
+ lines.push(" </file>");
530
+ }
531
+ return lines;
532
+ }
533
+ function buildCommentXml(comment) {
534
+ const lines = [];
535
+ const attrs = [];
536
+ if (comment.lineRange) {
537
+ if (comment.lineRange.side === "old") {
538
+ attrs.push(`old-line-start="${comment.lineRange.start}"`);
539
+ attrs.push(`old-line-end="${comment.lineRange.end}"`);
540
+ } else {
541
+ attrs.push(`new-line-start="${comment.lineRange.start}"`);
542
+ attrs.push(`new-line-end="${comment.lineRange.end}"`);
543
+ }
544
+ }
545
+ const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
546
+ lines.push(` <comment${attrStr}>`);
547
+ lines.push(` <body>${escapeXml(comment.body)}</body>`);
548
+ lines.push(` <category>${escapeXml(comment.category)}</category>`);
549
+ if (comment.suggestion) {
550
+ lines.push(" <suggestion>");
551
+ lines.push(
552
+ ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`
553
+ );
554
+ lines.push(
555
+ ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`
556
+ );
557
+ lines.push(" </suggestion>");
558
+ }
559
+ if (comment.attachments?.length) {
560
+ for (const att of comment.attachments) {
561
+ lines.push(` <attachment path="${escapeXml(att.fileName)}" media-type="${escapeXml(att.mediaType)}" />`);
562
+ }
563
+ }
564
+ lines.push(" </comment>");
565
+ return lines;
566
+ }
567
+ function escapeXml(str) {
568
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
569
+ }
570
+
571
+ // src/xml-parser.ts
572
+ import { readFileSync } from "fs";
573
+ import { XMLParser } from "fast-xml-parser";
574
+ function parseReviewXml(xmlPath) {
575
+ try {
576
+ const xmlContent = readFileSync(xmlPath, "utf-8");
577
+ return parseReviewXmlString(xmlContent);
578
+ } catch (error) {
579
+ if (error instanceof Error) {
580
+ console.error(`Error reading XML file: ${error.message}`);
581
+ } else {
582
+ console.error("Error reading XML file: unknown error");
583
+ }
584
+ process.exit(1);
585
+ }
586
+ }
587
+ function parseReviewXmlString(xmlContent) {
588
+ const parser = new XMLParser({
589
+ ignoreAttributes: false,
590
+ attributeNamePrefix: "@_",
591
+ allowBooleanAttributes: true
592
+ });
593
+ try {
594
+ const result = parser.parse(xmlContent);
595
+ if (!result.review) {
596
+ throw new Error("Invalid XML: missing <review> root element");
597
+ }
598
+ const review = result.review;
599
+ const gitDiffArgs = review["@_git-diff-args"] || "";
600
+ const source = parseSource(review);
601
+ const comments = [];
602
+ const files = Array.isArray(review.file) ? review.file : review.file ? [review.file] : [];
603
+ for (const file of files) {
604
+ const filePath = file["@_path"];
605
+ if (!filePath) continue;
606
+ const fileComments = Array.isArray(file.comment) ? file.comment : file.comment ? [file.comment] : [];
607
+ for (const comment of fileComments) {
608
+ const reviewComment = {
609
+ id: generateId(),
610
+ filePath,
611
+ lineRange: parseLineRange(comment),
612
+ body: comment.body || "",
613
+ category: comment.category || "",
614
+ suggestion: parseSuggestion(comment)
615
+ };
616
+ const commentAttachments = Array.isArray(comment.attachment) ? comment.attachment : comment.attachment ? [comment.attachment] : [];
617
+ if (commentAttachments.length > 0) {
618
+ reviewComment.attachments = commentAttachments.map(
619
+ (att, i) => ({
620
+ id: `${reviewComment.id}-att-${i}`,
621
+ fileName: String(att["@_path"] || ""),
622
+ mediaType: String(att["@_media-type"] || "image/png")
623
+ })
624
+ );
625
+ }
626
+ comments.push(reviewComment);
627
+ }
628
+ }
629
+ return { comments, gitDiffArgs, source };
630
+ } catch (error) {
631
+ if (error instanceof Error) {
632
+ console.error(`Error parsing XML: ${error.message}`);
633
+ } else {
634
+ console.error("Error parsing XML: unknown error");
635
+ }
636
+ process.exit(1);
637
+ }
638
+ }
639
+ function parseSource(review) {
640
+ const sourcePath = review["@_source-path"];
641
+ if (sourcePath) {
642
+ return { type: "directory", sourcePath: String(sourcePath) };
643
+ }
644
+ const gitDiffArgs = review["@_git-diff-args"];
645
+ const repository = review["@_repository"];
646
+ if (gitDiffArgs !== void 0 || repository !== void 0) {
647
+ return {
648
+ type: "git",
649
+ gitDiffArgs: String(gitDiffArgs || ""),
650
+ repository: String(repository || "")
651
+ };
652
+ }
653
+ return { type: "welcome" };
654
+ }
655
+ function parseLineRange(comment) {
656
+ const hasOld = comment["@_old-line-start"] !== void 0 && comment["@_old-line-end"] !== void 0;
657
+ const hasNew = comment["@_new-line-start"] !== void 0 && comment["@_new-line-end"] !== void 0;
658
+ if (hasOld) {
659
+ return {
660
+ side: "old",
661
+ start: parseInt(String(comment["@_old-line-start"]), 10),
662
+ end: parseInt(String(comment["@_old-line-end"]), 10)
663
+ };
664
+ }
665
+ if (hasNew) {
666
+ return {
667
+ side: "new",
668
+ start: parseInt(String(comment["@_new-line-start"]), 10),
669
+ end: parseInt(String(comment["@_new-line-end"]), 10)
670
+ };
671
+ }
672
+ return null;
673
+ }
674
+ function parseSuggestion(comment) {
675
+ if (!comment.suggestion) {
676
+ return null;
677
+ }
678
+ const suggestion = comment.suggestion;
679
+ return {
680
+ originalCode: String(suggestion["original-code"] || ""),
681
+ proposedCode: String(suggestion["proposed-code"] || "")
682
+ };
683
+ }
684
+ function generateId() {
685
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
686
+ }
687
+
688
+ // src/git.ts
689
+ import { execSync, exec } from "child_process";
690
+ import { promisify } from "util";
691
+
692
+ // src/synthetic-diff.ts
693
+ import { readFileSync as readFileSync2 } from "fs";
694
+ function generateSyntheticDiffs(paths, rootDir) {
695
+ const diffs = [];
696
+ for (const filePath of paths) {
697
+ const fullPath = `${rootDir}/${filePath}`;
698
+ let content;
699
+ try {
700
+ content = readFileSync2(fullPath);
701
+ } catch {
702
+ continue;
703
+ }
704
+ const sample = content.subarray(0, 8192);
705
+ const isBinary = sample.includes(0);
706
+ if (isBinary) {
707
+ diffs.push(
708
+ `diff --git a/${filePath} b/${filePath}
709
+ new file mode 100644
710
+ Binary files /dev/null and b/${filePath} differ`
711
+ );
712
+ continue;
713
+ }
714
+ const text = content.toString("utf-8");
715
+ const lines = text.split("\n");
716
+ if (lines.length > 0 && lines[lines.length - 1] === "") {
717
+ lines.pop();
718
+ }
719
+ const lineCount = lines.length;
720
+ const addedLines = lines.map((line) => `+${line}`).join("\n");
721
+ let diff = `diff --git a/${filePath} b/${filePath}
722
+ new file mode 100644
723
+ --- /dev/null
724
+ +++ b/${filePath}
725
+ @@ -0,0 +1,${lineCount} @@
726
+ ` + addedLines;
727
+ if (text.length > 0 && !text.endsWith("\n")) {
728
+ diff += "\n\";
729
+ }
730
+ diffs.push(diff);
731
+ }
732
+ return diffs.join("\n");
733
+ }
734
+
735
+ // src/git.ts
736
+ var execAsync = promisify(exec);
737
+ function runGitDiff(args) {
738
+ try {
739
+ try {
740
+ execSync("git --version", { stdio: "ignore" });
741
+ } catch {
742
+ console.error("Error: git is not installed or not in PATH");
743
+ process.exit(1);
744
+ }
745
+ try {
746
+ execSync("git rev-parse --git-dir", { stdio: "ignore" });
747
+ } catch {
748
+ console.error(
749
+ "Error: not a git repository (or any parent up to mount point)"
750
+ );
751
+ process.exit(1);
752
+ }
753
+ const result = execSync(`git diff ${args.join(" ")}`, {
754
+ encoding: "utf-8",
755
+ maxBuffer: 50 * 1024 * 1024
756
+ // 50MB buffer for large diffs
757
+ });
758
+ return result;
759
+ } catch (error) {
760
+ if (error instanceof Error) {
761
+ console.error(`Error running git diff: ${error.message}`);
762
+ } else {
763
+ console.error("Error running git diff: unknown error");
764
+ }
765
+ process.exit(1);
766
+ }
767
+ }
768
+ function getRepoRoot() {
769
+ try {
770
+ const result = execSync("git rev-parse --show-toplevel", {
771
+ encoding: "utf-8"
772
+ });
773
+ return result.trim();
774
+ } catch (error) {
775
+ if (error instanceof Error) {
776
+ console.error(`Error getting repository root: ${error.message}`);
777
+ } else {
778
+ console.error("Error getting repository root: unknown error");
779
+ }
780
+ process.exit(1);
781
+ }
782
+ }
783
+ function validateGitAvailable() {
784
+ try {
785
+ execSync("git --version", { stdio: "ignore" });
786
+ } catch {
787
+ console.error("Error: git is not installed or not in PATH");
788
+ process.exit(1);
789
+ }
790
+ try {
791
+ execSync("git rev-parse --git-dir", { stdio: "ignore" });
792
+ } catch {
793
+ console.error(
794
+ "Error: not a git repository (or any parent up to mount point)"
795
+ );
796
+ process.exit(1);
797
+ }
798
+ }
799
+ async function getRepoRootAsync(cwd) {
800
+ try {
801
+ const { stdout } = await execAsync("git rev-parse --show-toplevel", {
802
+ timeout: 1e4,
803
+ // 10 second timeout
804
+ cwd
805
+ });
806
+ return stdout.trim();
807
+ } catch (error) {
808
+ if (error instanceof Error) {
809
+ console.error(`Error getting repository root: ${error.message}`);
810
+ } else {
811
+ console.error("Error getting repository root: unknown error");
812
+ }
813
+ throw error;
814
+ }
815
+ }
816
+ async function runGitDiffAsync(args, cwd) {
817
+ try {
818
+ const { stdout } = await execAsync(`git diff ${args.join(" ")}`, {
819
+ maxBuffer: 50 * 1024 * 1024,
820
+ // 50MB buffer
821
+ timeout: 3e4,
822
+ // 30 second timeout
823
+ cwd
824
+ });
825
+ return stdout;
826
+ } catch (error) {
827
+ if (error instanceof Error) {
828
+ console.error(`Error running git diff: ${error.message}`);
829
+ } else {
830
+ console.error("Error running git diff: unknown error");
831
+ }
832
+ throw error;
833
+ }
834
+ }
835
+ async function getUntrackedFilesAsync(cwd) {
836
+ try {
837
+ const { stdout } = await execAsync(
838
+ "git ls-files --others --exclude-standard",
839
+ {
840
+ maxBuffer: 10 * 1024 * 1024,
841
+ timeout: 1e4,
842
+ cwd
843
+ }
844
+ );
845
+ return stdout.trim().split("\n").filter((line) => line.length > 0);
846
+ } catch (error) {
847
+ if (error instanceof Error) {
848
+ console.error(
849
+ `Warning: Failed to list untracked files: ${error.message}`
850
+ );
851
+ } else {
852
+ console.error("Warning: Failed to list untracked files: unknown error");
853
+ }
854
+ return [];
855
+ }
856
+ }
857
+ function generateUntrackedDiffs(paths, repoRoot) {
858
+ return generateSyntheticDiffs(paths, repoRoot);
859
+ }
860
+
861
+ // src/directory-scanner.ts
862
+ import { readdir, stat } from "fs/promises";
863
+ import { join as join2, relative, basename, dirname as dirname2 } from "path";
864
+
865
+ // src/ignore-filter.ts
866
+ import ignore from "ignore";
867
+ function createIgnoreFilter(patterns) {
868
+ if (patterns.length === 0) return () => true;
869
+ const ig = ignore().add(patterns);
870
+ return (filePath) => !ig.ignores(filePath);
871
+ }
872
+
873
+ // src/directory-scanner.ts
874
+ async function scanDirectory(directoryPath, ignorePatterns = []) {
875
+ try {
876
+ const dirStat = await stat(directoryPath);
877
+ if (!dirStat.isDirectory()) {
878
+ console.error(
879
+ `Error: "${directoryPath}" is not a directory`
880
+ );
881
+ return [];
882
+ }
883
+ } catch (error) {
884
+ if (error instanceof Error) {
885
+ console.error(
886
+ `Error accessing directory "${directoryPath}": ${error.message}`
887
+ );
888
+ } else {
889
+ console.error(
890
+ `Error accessing directory "${directoryPath}": unknown error`
891
+ );
892
+ }
893
+ return [];
894
+ }
895
+ const filePaths = [];
896
+ try {
897
+ const entries = await readdir(directoryPath, {
898
+ recursive: true,
899
+ withFileTypes: true
900
+ });
901
+ for (const entry of entries) {
902
+ if (!entry.isFile()) {
903
+ continue;
904
+ }
905
+ const parentDir = entry.parentPath ?? entry.path;
906
+ const fullPath = join2(parentDir, entry.name);
907
+ const relativePath = relative(directoryPath, fullPath);
908
+ filePaths.push(relativePath);
909
+ }
910
+ } catch (error) {
911
+ if (error instanceof Error) {
912
+ console.error(
913
+ `Error reading directory "${directoryPath}": ${error.message}`
914
+ );
915
+ } else {
916
+ console.error(
917
+ `Error reading directory "${directoryPath}": unknown error`
918
+ );
919
+ }
920
+ return [];
921
+ }
922
+ filePaths.sort();
923
+ const shouldKeep = createIgnoreFilter(ignorePatterns);
924
+ const filteredPaths = filePaths.filter((p) => shouldKeep(p));
925
+ if (filteredPaths.length === 0) {
926
+ return [];
927
+ }
928
+ const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);
929
+ return parseDiff(diffText);
930
+ }
931
+ async function scanFile(filePath) {
932
+ try {
933
+ const fileStat = await stat(filePath);
934
+ if (!fileStat.isFile()) {
935
+ console.error(`Error: "${filePath}" is not a file`);
936
+ return [];
937
+ }
938
+ } catch (error) {
939
+ if (error instanceof Error) {
940
+ console.error(`Error accessing file "${filePath}": ${error.message}`);
941
+ } else {
942
+ console.error(`Error accessing file "${filePath}": unknown error`);
943
+ }
944
+ return [];
945
+ }
946
+ const fileName = basename(filePath);
947
+ const rootDir = dirname2(filePath);
948
+ const diffText = generateSyntheticDiffs([fileName], rootDir);
949
+ return parseDiff(diffText);
950
+ }
951
+
952
+ // src/config.ts
953
+ import { readFileSync as readFileSync3, existsSync as existsSync2 } from "fs";
954
+ import { join as join3 } from "path";
955
+ import { homedir } from "os";
956
+ import { parse as parseYaml } from "yaml";
957
+ var defaults = {
958
+ theme: "system",
959
+ diffView: "split",
960
+ fontSize: 14,
961
+ outputFormat: "xml",
962
+ outputFile: "./review.xml",
963
+ ignore: [
964
+ ".git",
965
+ "node_modules",
966
+ "vendor",
967
+ ".vendor",
968
+ "__pycache__",
969
+ ".venv",
970
+ "venv",
971
+ ".env",
972
+ "dist",
973
+ "build",
974
+ ".next",
975
+ ".nuxt",
976
+ ".svelte-kit",
977
+ "target",
978
+ "*.min.js",
979
+ "*.min.css",
980
+ "package-lock.json",
981
+ "yarn.lock",
982
+ "pnpm-lock.yaml",
983
+ "composer.lock",
984
+ "Gemfile.lock",
985
+ "Cargo.lock",
986
+ "poetry.lock",
987
+ "go.sum"
988
+ ],
989
+ categories: [
990
+ {
991
+ name: "question",
992
+ description: "Clarification needed \u2014 not necessarily a problem",
993
+ color: "#805ad5"
994
+ },
995
+ {
996
+ name: "bug",
997
+ description: "Likely defect or incorrect behavior",
998
+ color: "#e53e3e"
999
+ },
1000
+ {
1001
+ name: "security",
1002
+ description: "Security vulnerability or concern",
1003
+ color: "#dd6b20"
1004
+ },
1005
+ {
1006
+ name: "style",
1007
+ description: "Code style, naming, or formatting issue",
1008
+ color: "#3182ce"
1009
+ },
1010
+ {
1011
+ name: "task",
1012
+ description: "Action item or follow-up task",
1013
+ color: "#38a169"
1014
+ },
1015
+ {
1016
+ name: "nit",
1017
+ description: "Minor nitpick, low priority",
1018
+ color: "#718096"
1019
+ }
1020
+ ],
1021
+ defaultDiffArgs: "",
1022
+ showUntracked: true,
1023
+ wordWrap: true,
1024
+ maxFiles: 500,
1025
+ maxTotalLines: 1e5
1026
+ };
1027
+ function loadConfig() {
1028
+ let config = { ...defaults };
1029
+ const userConfigPath = join3(
1030
+ homedir(),
1031
+ ".config",
1032
+ "self-review",
1033
+ "config.yaml"
1034
+ );
1035
+ if (existsSync2(userConfigPath)) {
1036
+ try {
1037
+ const userConfig = loadYamlConfig(userConfigPath);
1038
+ config = mergeConfig(config, userConfig);
1039
+ } catch (error) {
1040
+ console.error(
1041
+ `Warning: Failed to load user config from ${userConfigPath}: ${error}`
1042
+ );
1043
+ }
1044
+ }
1045
+ const projectConfigPath = join3(process.cwd(), ".self-review.yaml");
1046
+ if (existsSync2(projectConfigPath)) {
1047
+ try {
1048
+ const projectConfig = loadYamlConfig(projectConfigPath);
1049
+ config = mergeConfig(config, projectConfig);
1050
+ } catch (error) {
1051
+ console.error(
1052
+ `Warning: Failed to load project config from ${projectConfigPath}: ${error}`
1053
+ );
1054
+ }
1055
+ }
1056
+ return config;
1057
+ }
1058
+ function loadYamlConfig(path2) {
1059
+ const content = readFileSync3(path2, "utf-8");
1060
+ const raw = parseYaml(content);
1061
+ if (!raw || typeof raw !== "object") {
1062
+ throw new Error("Invalid YAML format");
1063
+ }
1064
+ const config = {};
1065
+ if ("theme" in raw) {
1066
+ if (["light", "dark", "system"].includes(raw.theme)) {
1067
+ config.theme = raw.theme;
1068
+ } else {
1069
+ console.error(
1070
+ `Warning: Invalid theme value "${raw.theme}", using default`
1071
+ );
1072
+ }
1073
+ }
1074
+ if ("diff-view" in raw) {
1075
+ if (["split", "unified"].includes(raw["diff-view"])) {
1076
+ config.diffView = raw["diff-view"];
1077
+ } else {
1078
+ console.error(
1079
+ `Warning: Invalid diff-view value "${raw["diff-view"]}", using default`
1080
+ );
1081
+ }
1082
+ }
1083
+ if ("font-size" in raw && typeof raw["font-size"] === "number") {
1084
+ config.fontSize = raw["font-size"];
1085
+ }
1086
+ if ("output-format" in raw && typeof raw["output-format"] === "string") {
1087
+ config.outputFormat = raw["output-format"];
1088
+ }
1089
+ if ("ignore" in raw && Array.isArray(raw.ignore)) {
1090
+ config.ignore = raw.ignore.filter(
1091
+ (item) => typeof item === "string"
1092
+ );
1093
+ }
1094
+ if ("categories" in raw && Array.isArray(raw.categories)) {
1095
+ config.categories = raw.categories.filter(
1096
+ (cat) => cat !== null && typeof cat === "object" && typeof cat.name === "string" && typeof cat.description === "string" && typeof cat.color === "string"
1097
+ );
1098
+ }
1099
+ if ("default-diff-args" in raw && typeof raw["default-diff-args"] === "string") {
1100
+ config.defaultDiffArgs = raw["default-diff-args"];
1101
+ }
1102
+ if ("show-untracked" in raw && typeof raw["show-untracked"] === "boolean") {
1103
+ config.showUntracked = raw["show-untracked"];
1104
+ }
1105
+ if ("word-wrap" in raw && typeof raw["word-wrap"] === "boolean") {
1106
+ config.wordWrap = raw["word-wrap"];
1107
+ }
1108
+ if ("max-files" in raw && typeof raw["max-files"] === "number") {
1109
+ config.maxFiles = raw["max-files"] >= 0 ? raw["max-files"] : defaults.maxFiles;
1110
+ }
1111
+ if ("max-total-lines" in raw && typeof raw["max-total-lines"] === "number") {
1112
+ config.maxTotalLines = raw["max-total-lines"] >= 0 ? raw["max-total-lines"] : defaults.maxTotalLines;
1113
+ }
1114
+ if ("output-file" in raw && typeof raw["output-file"] === "string" && raw["output-file"].length > 0) {
1115
+ config.outputFile = raw["output-file"];
1116
+ }
1117
+ return config;
1118
+ }
1119
+ function mergeConfig(base, override) {
1120
+ return {
1121
+ ...base,
1122
+ ...override,
1123
+ // Arrays are replaced, not merged
1124
+ ignore: override.ignore !== void 0 ? override.ignore : base.ignore,
1125
+ categories: override.categories !== void 0 ? override.categories : base.categories
1126
+ };
1127
+ }
1128
+
1129
+ // src/payload-sizing.ts
1130
+ import { exec as exec2 } from "child_process";
1131
+ import { promisify as promisify2 } from "util";
1132
+ var execAsync2 = promisify2(exec2);
1133
+ function computePayloadStats(fileCount, totalLines, config) {
1134
+ const maxFiles = config.maxFiles;
1135
+ const maxTotalLines = config.maxTotalLines;
1136
+ const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;
1137
+ const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;
1138
+ return {
1139
+ fileCount,
1140
+ totalLines,
1141
+ exceedsFiles,
1142
+ exceedsLines,
1143
+ exceedsAny: exceedsFiles || exceedsLines
1144
+ };
1145
+ }
1146
+ function countTotalLines(files) {
1147
+ let total = 0;
1148
+ for (const file of files) {
1149
+ for (const hunk of file.hunks) {
1150
+ total += hunk.lines.length;
1151
+ }
1152
+ }
1153
+ return total;
1154
+ }
1155
+ async function getGitDiffStats(args, repoRoot) {
1156
+ try {
1157
+ const { stdout } = await execAsync2(`git diff --numstat ${args.join(" ")}`, {
1158
+ maxBuffer: 10 * 1024 * 1024,
1159
+ timeout: 15e3,
1160
+ cwd: repoRoot
1161
+ });
1162
+ let fileCount = 0;
1163
+ let totalLines = 0;
1164
+ for (const line of stdout.trim().split("\n")) {
1165
+ if (!line) continue;
1166
+ const parts = line.split(" ");
1167
+ if (parts.length < 3) continue;
1168
+ fileCount++;
1169
+ const added = parts[0] === "-" ? 0 : parseInt(parts[0], 10);
1170
+ const removed = parts[1] === "-" ? 0 : parseInt(parts[1], 10);
1171
+ totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);
1172
+ }
1173
+ return { fileCount, totalLines };
1174
+ } catch (error) {
1175
+ if (error instanceof Error) {
1176
+ console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);
1177
+ } else {
1178
+ console.error("[payload-sizing] Failed to get git diff stats: unknown error");
1179
+ }
1180
+ return { fileCount: 0, totalLines: 0 };
1181
+ }
1182
+ }
1183
+
1184
+ // src/fs-utils.ts
1185
+ import { accessSync, constants as fsConstants } from "fs";
1186
+ import { dirname as dirname3 } from "path";
1187
+ function checkWritability(filePath) {
1188
+ try {
1189
+ const dir = dirname3(filePath);
1190
+ accessSync(dir, fsConstants.W_OK);
1191
+ return true;
1192
+ } catch {
1193
+ return false;
1194
+ }
1195
+ }
1196
+
1197
+ // src/file-type-utils.ts
1198
+ var RASTER_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".ico", ".bmp"]);
1199
+ function getExtension(filePath) {
1200
+ const lastDot = filePath.lastIndexOf(".");
1201
+ if (lastDot === -1 || lastDot === filePath.length - 1) return "";
1202
+ return filePath.slice(lastDot).toLowerCase();
1203
+ }
1204
+ function isPreviewableImage(filePath) {
1205
+ return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));
1206
+ }
1207
+ function isPreviewableSvg(filePath) {
1208
+ return getExtension(filePath) === ".svg";
1209
+ }
1210
+ export {
1211
+ checkWritability,
1212
+ computePayloadStats,
1213
+ countTotalLines,
1214
+ createIgnoreFilter,
1215
+ generateSyntheticDiffs,
1216
+ generateUntrackedDiffs,
1217
+ getGitDiffStats,
1218
+ getRepoRoot,
1219
+ getRepoRootAsync,
1220
+ getUntrackedFilesAsync,
1221
+ isPreviewableImage,
1222
+ isPreviewableSvg,
1223
+ loadConfig,
1224
+ parseDiff,
1225
+ parseReviewXml,
1226
+ parseReviewXmlString,
1227
+ runGitDiff,
1228
+ runGitDiffAsync,
1229
+ scanDirectory,
1230
+ scanFile,
1231
+ serializeReview,
1232
+ validateGitAvailable
1233
+ };
1234
+ //# sourceMappingURL=index.js.map