docrev 0.9.4 → 0.9.6

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 (141) hide show
  1. package/dist/lib/commands/comments.d.ts.map +1 -1
  2. package/dist/lib/commands/comments.js +19 -27
  3. package/dist/lib/commands/comments.js.map +1 -1
  4. package/dist/lib/commands/context.d.ts +1 -0
  5. package/dist/lib/commands/context.d.ts.map +1 -1
  6. package/dist/lib/commands/context.js +1 -2
  7. package/dist/lib/commands/context.js.map +1 -1
  8. package/dist/lib/commands/file-ops.d.ts +11 -0
  9. package/dist/lib/commands/file-ops.d.ts.map +1 -0
  10. package/dist/lib/commands/file-ops.js +301 -0
  11. package/dist/lib/commands/file-ops.js.map +1 -0
  12. package/dist/lib/commands/index.d.ts +9 -1
  13. package/dist/lib/commands/index.d.ts.map +1 -1
  14. package/dist/lib/commands/index.js +17 -1
  15. package/dist/lib/commands/index.js.map +1 -1
  16. package/dist/lib/commands/merge-resolve.d.ts +12 -0
  17. package/dist/lib/commands/merge-resolve.d.ts.map +1 -0
  18. package/dist/lib/commands/merge-resolve.js +318 -0
  19. package/dist/lib/commands/merge-resolve.js.map +1 -0
  20. package/dist/lib/commands/preview.d.ts +11 -0
  21. package/dist/lib/commands/preview.d.ts.map +1 -0
  22. package/dist/lib/commands/preview.js +138 -0
  23. package/dist/lib/commands/preview.js.map +1 -0
  24. package/dist/lib/commands/project-info.d.ts +11 -0
  25. package/dist/lib/commands/project-info.d.ts.map +1 -0
  26. package/dist/lib/commands/project-info.js +187 -0
  27. package/dist/lib/commands/project-info.js.map +1 -0
  28. package/dist/lib/commands/quality.d.ts +11 -0
  29. package/dist/lib/commands/quality.d.ts.map +1 -0
  30. package/dist/lib/commands/quality.js +384 -0
  31. package/dist/lib/commands/quality.js.map +1 -0
  32. package/dist/lib/commands/sections.d.ts +3 -2
  33. package/dist/lib/commands/sections.d.ts.map +1 -1
  34. package/dist/lib/commands/sections.js +4 -723
  35. package/dist/lib/commands/sections.js.map +1 -1
  36. package/dist/lib/commands/sync.d.ts +11 -0
  37. package/dist/lib/commands/sync.d.ts.map +1 -0
  38. package/dist/lib/commands/sync.js +441 -0
  39. package/dist/lib/commands/sync.js.map +1 -0
  40. package/dist/lib/commands/text-ops.d.ts +11 -0
  41. package/dist/lib/commands/text-ops.d.ts.map +1 -0
  42. package/dist/lib/commands/text-ops.js +357 -0
  43. package/dist/lib/commands/text-ops.js.map +1 -0
  44. package/dist/lib/commands/utilities.d.ts +2 -4
  45. package/dist/lib/commands/utilities.d.ts.map +1 -1
  46. package/dist/lib/commands/utilities.js +3 -1605
  47. package/dist/lib/commands/utilities.js.map +1 -1
  48. package/dist/lib/commands/word-tools.d.ts +11 -0
  49. package/dist/lib/commands/word-tools.d.ts.map +1 -0
  50. package/dist/lib/commands/word-tools.js +272 -0
  51. package/dist/lib/commands/word-tools.js.map +1 -0
  52. package/dist/lib/comment-realign.d.ts.map +1 -1
  53. package/dist/lib/comment-realign.js +0 -7
  54. package/dist/lib/comment-realign.js.map +1 -1
  55. package/dist/lib/dependencies.d.ts.map +1 -1
  56. package/dist/lib/dependencies.js +11 -23
  57. package/dist/lib/dependencies.js.map +1 -1
  58. package/dist/lib/diff-engine.d.ts +25 -0
  59. package/dist/lib/diff-engine.d.ts.map +1 -0
  60. package/dist/lib/diff-engine.js +354 -0
  61. package/dist/lib/diff-engine.js.map +1 -0
  62. package/dist/lib/git.d.ts.map +1 -1
  63. package/dist/lib/git.js +18 -28
  64. package/dist/lib/git.js.map +1 -1
  65. package/dist/lib/import.d.ts +37 -117
  66. package/dist/lib/import.d.ts.map +1 -1
  67. package/dist/lib/import.js +10 -1039
  68. package/dist/lib/import.js.map +1 -1
  69. package/dist/lib/merge.d.ts.map +1 -1
  70. package/dist/lib/merge.js +29 -117
  71. package/dist/lib/merge.js.map +1 -1
  72. package/dist/lib/pdf-comments.d.ts.map +1 -1
  73. package/dist/lib/pdf-comments.js +1 -13
  74. package/dist/lib/pdf-comments.js.map +1 -1
  75. package/dist/lib/pptx-themes.d.ts.map +1 -1
  76. package/dist/lib/pptx-themes.js +0 -403
  77. package/dist/lib/pptx-themes.js.map +1 -1
  78. package/dist/lib/protect-restore.d.ts.map +1 -1
  79. package/dist/lib/protect-restore.js +34 -36
  80. package/dist/lib/protect-restore.js.map +1 -1
  81. package/dist/lib/restore-references.d.ts +35 -0
  82. package/dist/lib/restore-references.d.ts.map +1 -0
  83. package/dist/lib/restore-references.js +188 -0
  84. package/dist/lib/restore-references.js.map +1 -0
  85. package/dist/lib/slides.d.ts.map +1 -1
  86. package/dist/lib/slides.js +0 -35
  87. package/dist/lib/slides.js.map +1 -1
  88. package/dist/lib/trackchanges.d.ts.map +1 -1
  89. package/dist/lib/trackchanges.js +1 -11
  90. package/dist/lib/trackchanges.js.map +1 -1
  91. package/dist/lib/tui.d.ts +36 -45
  92. package/dist/lib/tui.d.ts.map +1 -1
  93. package/dist/lib/tui.js +92 -108
  94. package/dist/lib/tui.js.map +1 -1
  95. package/dist/lib/undo.d.ts +3 -4
  96. package/dist/lib/undo.d.ts.map +1 -1
  97. package/dist/lib/undo.js +0 -7
  98. package/dist/lib/undo.js.map +1 -1
  99. package/dist/lib/utils.d.ts +12 -0
  100. package/dist/lib/utils.d.ts.map +1 -1
  101. package/dist/lib/utils.js +26 -0
  102. package/dist/lib/utils.js.map +1 -1
  103. package/dist/lib/word-extraction.d.ts +77 -0
  104. package/dist/lib/word-extraction.d.ts.map +1 -0
  105. package/dist/lib/word-extraction.js +515 -0
  106. package/dist/lib/word-extraction.js.map +1 -0
  107. package/dist/lib/wordcomments.d.ts.map +1 -1
  108. package/dist/lib/wordcomments.js +1 -8
  109. package/dist/lib/wordcomments.js.map +1 -1
  110. package/dist/package.json +137 -0
  111. package/lib/commands/comments.ts +20 -25
  112. package/lib/commands/context.ts +1 -2
  113. package/lib/commands/file-ops.ts +372 -0
  114. package/lib/commands/index.ts +24 -0
  115. package/lib/commands/merge-resolve.ts +378 -0
  116. package/lib/commands/preview.ts +178 -0
  117. package/lib/commands/project-info.ts +244 -0
  118. package/lib/commands/quality.ts +517 -0
  119. package/lib/commands/sections.ts +3 -857
  120. package/lib/commands/sync.ts +536 -0
  121. package/lib/commands/text-ops.ts +449 -0
  122. package/lib/commands/utilities.ts +62 -2066
  123. package/lib/commands/word-tools.ts +340 -0
  124. package/lib/comment-realign.ts +0 -8
  125. package/lib/dependencies.ts +12 -20
  126. package/lib/diff-engine.ts +465 -0
  127. package/lib/git.ts +24 -31
  128. package/lib/import.ts +78 -1348
  129. package/lib/merge.ts +42 -132
  130. package/lib/pdf-comments.ts +2 -14
  131. package/lib/pptx-themes.ts +0 -413
  132. package/lib/protect-restore.ts +48 -44
  133. package/lib/restore-references.ts +240 -0
  134. package/lib/slides.ts +0 -37
  135. package/lib/trackchanges.ts +1 -12
  136. package/lib/{tui.js → tui.ts} +139 -126
  137. package/lib/undo.ts +3 -12
  138. package/lib/utils.ts +28 -0
  139. package/lib/word-extraction.ts +666 -0
  140. package/lib/wordcomments.ts +1 -9
  141. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Section commands: import, extract, split, sync, merge
2
+ * Section commands: import, extract, split
3
3
  *
4
- * Commands for importing Word documents, splitting/syncing section files.
4
+ * Commands for importing Word documents and splitting section files.
5
+ * Sync and merge commands are in sync.ts and merge-resolve.ts respectively.
5
6
  */
6
- import { chalk, fs, path, fmt, findFiles, countAnnotations, loadConfig, extractSectionsFromText, splitAnnotatedPaper, buildRegistry, convertHardcodedRefs, inlineDiffPreview, } from './context.js';
7
- import * as readline from 'readline';
7
+ import { chalk, fs, path, countAnnotations, loadConfig, splitAnnotatedPaper, } from './context.js';
8
8
  /**
9
9
  * Detect sections from Word document text
10
10
  * Looks for common academic paper section headers
@@ -367,724 +367,5 @@ export function register(program) {
367
367
  console.log(chalk.cyan('\nNext: rev review <section.md> for each section'));
368
368
  }
369
369
  });
370
- // ==========================================================================
371
- // SYNC command - Import with section awareness
372
- // ==========================================================================
373
- program
374
- .command('sync')
375
- .alias('sections')
376
- .description('Sync feedback from Word/PDF back to section files')
377
- .argument('[file]', 'Word (.docx) or PDF file from reviewer (default: most recent)')
378
- .argument('[sections...]', 'Specific sections to sync (default: all)')
379
- .option('-c, --config <file>', 'Sections config file', 'sections.yaml')
380
- .option('-d, --dir <directory>', 'Directory with section files', '.')
381
- .option('--no-crossref', 'Skip converting hardcoded figure/table refs')
382
- .option('--no-diff', 'Skip showing diff preview')
383
- .option('--force', 'Overwrite files without conflict warning')
384
- .option('--dry-run', 'Preview without writing files')
385
- .action(async (docx, sections, options) => {
386
- // Auto-detect most recent docx or pdf if not provided
387
- if (!docx) {
388
- const docxFiles = findFiles('.docx');
389
- const pdfFiles = findFiles('.pdf');
390
- const allFiles = [...docxFiles, ...pdfFiles];
391
- if (allFiles.length === 0) {
392
- console.error(fmt.status('error', 'No .docx or .pdf files found in current directory.'));
393
- process.exit(1);
394
- }
395
- const sorted = allFiles
396
- .map(f => ({ name: f, mtime: fs.statSync(f).mtime }))
397
- .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
398
- docx = sorted[0].name;
399
- console.log(fmt.status('info', `Using most recent: ${docx}`));
400
- console.log();
401
- }
402
- if (!fs.existsSync(docx)) {
403
- console.error(fmt.status('error', `File not found: ${docx}`));
404
- process.exit(1);
405
- }
406
- // Handle PDF files
407
- if (docx.toLowerCase().endsWith('.pdf')) {
408
- const { extractPdfComments, formatPdfComments, getPdfCommentStats } = await import('../pdf-import.js');
409
- const spin = fmt.spinner(`Extracting comments from ${path.basename(docx)}...`).start();
410
- try {
411
- const comments = await extractPdfComments(docx);
412
- spin.stop();
413
- if (comments.length === 0) {
414
- console.log(fmt.status('info', 'No comments found in PDF.'));
415
- return;
416
- }
417
- const stats = getPdfCommentStats(comments);
418
- console.log(fmt.header(`PDF Comments from ${path.basename(docx)}`));
419
- console.log();
420
- console.log(formatPdfComments(comments));
421
- console.log();
422
- const authorList = Object.entries(stats.byAuthor)
423
- .map(([author, count]) => `${author} (${count})`)
424
- .join(', ');
425
- console.log(chalk.dim(`Total: ${stats.total} comments from ${authorList}`));
426
- console.log();
427
- const configPath = path.resolve(options.dir, options.config);
428
- if (fs.existsSync(configPath) && !options.dryRun) {
429
- const config = loadConfig(configPath);
430
- const mainSection = config.sections?.[0];
431
- if (mainSection && typeof mainSection === 'string') {
432
- const mainPath = path.join(options.dir, mainSection);
433
- if (fs.existsSync(mainPath)) {
434
- console.log(chalk.dim(`Use 'rev pdf-comments ${docx} --append ${mainSection}' to add comments to markdown.`));
435
- }
436
- }
437
- }
438
- }
439
- catch (err) {
440
- spin.stop();
441
- const error = err;
442
- console.error(fmt.status('error', `Failed to extract PDF comments: ${error.message}`));
443
- if (process.env.DEBUG)
444
- console.error(error.stack);
445
- process.exit(1);
446
- }
447
- return;
448
- }
449
- const configPath = path.resolve(options.dir, options.config);
450
- if (!fs.existsSync(configPath)) {
451
- console.error(fmt.status('error', `Config not found: ${configPath}`));
452
- console.error(chalk.dim(' Run "rev init" first to generate sections.yaml'));
453
- process.exit(1);
454
- }
455
- // Check pandoc availability upfront and warn
456
- const { hasPandoc, getInstallInstructions } = await import('../dependencies.js');
457
- if (!hasPandoc()) {
458
- console.log(fmt.status('warning', `Pandoc not installed. Track changes will be extracted from XML (formatting may differ).`));
459
- console.log(chalk.dim(` Install for best results: ${getInstallInstructions('pandoc')}`));
460
- console.log();
461
- }
462
- const spin = fmt.spinner(`Importing ${path.basename(docx)}...`).start();
463
- try {
464
- const config = loadConfig(configPath);
465
- const { importFromWord, extractWordComments, extractCommentAnchors, insertCommentsIntoMarkdown, extractFromWord } = await import('../import.js');
466
- let registry = null;
467
- let totalRefConversions = 0;
468
- if (options.crossref !== false) {
469
- registry = buildRegistry(options.dir);
470
- }
471
- const comments = await extractWordComments(docx);
472
- const { anchors, fullDocText: xmlDocText } = await extractCommentAnchors(docx);
473
- // Extract Word text (uses pandoc if available, falls back to XML extraction)
474
- const wordExtraction = await extractFromWord(docx, { mediaDir: options.dir });
475
- let wordText = wordExtraction.text;
476
- const wordTables = wordExtraction.tables || [];
477
- // Log extraction messages (warnings about pandoc, track change stats, etc.)
478
- for (const msg of wordExtraction.messages || []) {
479
- if (msg.type === 'warning') {
480
- spin.stop();
481
- console.log(fmt.status('warning', msg.message));
482
- spin.start();
483
- }
484
- }
485
- // Restore crossref on FULL text BEFORE splitting into sections
486
- // This ensures duplicate labels from track changes are handled correctly
487
- // (the same figure may appear multiple times in old/new versions)
488
- const { restoreCrossrefFromWord, restoreImagesFromRegistry } = await import('../import.js');
489
- const crossrefResult = restoreCrossrefFromWord(wordText, options.dir);
490
- wordText = crossrefResult.text;
491
- if (crossrefResult.restored > 0) {
492
- console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
493
- }
494
- // Also restore images from registry using shared restoredLabels
495
- const imageRestoreResult = restoreImagesFromRegistry(wordText, options.dir, crossrefResult.restoredLabels);
496
- wordText = imageRestoreResult.text;
497
- if (imageRestoreResult.restored > 0) {
498
- console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
499
- }
500
- let wordSections = extractSectionsFromText(wordText, config.sections);
501
- if (wordSections.length === 0) {
502
- spin.stop();
503
- console.error(fmt.status('warning', 'No sections detected in Word document.'));
504
- console.error(chalk.dim(' Check that headings match sections.yaml'));
505
- process.exit(1);
506
- }
507
- if (sections && sections.length > 0) {
508
- const onlyList = sections.map(s => s.trim().toLowerCase());
509
- wordSections = wordSections.filter(section => {
510
- const fileName = section.file.replace(/\.md$/i, '').toLowerCase();
511
- const header = section.header.toLowerCase();
512
- return onlyList.some(name => fileName === name || fileName.includes(name) || header.includes(name));
513
- });
514
- if (wordSections.length === 0) {
515
- spin.stop();
516
- console.error(fmt.status('error', `No sections matched: ${sections.join(', ')}`));
517
- console.error(chalk.dim(` Available: ${extractSectionsFromText(wordText, config.sections).map(s => s.file.replace(/\.md$/i, '')).join(', ')}`));
518
- process.exit(1);
519
- }
520
- }
521
- spin.stop();
522
- console.log(fmt.header(`Import from ${path.basename(docx)}`));
523
- console.log();
524
- // Conflict detection
525
- if (!options.force && !options.dryRun) {
526
- const conflicts = [];
527
- for (const section of wordSections) {
528
- const sectionPath = path.join(options.dir, section.file);
529
- if (fs.existsSync(sectionPath)) {
530
- const existing = fs.readFileSync(sectionPath, 'utf-8');
531
- const existingCounts = countAnnotations(existing);
532
- if (existingCounts.total > 0) {
533
- conflicts.push({
534
- file: section.file,
535
- annotations: existingCounts.total,
536
- });
537
- }
538
- }
539
- }
540
- if (conflicts.length > 0) {
541
- console.log(fmt.status('warning', 'Files with existing annotations will be overwritten:'));
542
- for (const c of conflicts) {
543
- console.log(chalk.yellow(` - ${c.file} (${c.annotations} annotations)`));
544
- }
545
- console.log();
546
- const rl = readline.createInterface({
547
- input: process.stdin,
548
- output: process.stdout,
549
- });
550
- const answer = await new Promise((resolve) => rl.question(chalk.cyan('Continue and overwrite? [y/N] '), resolve));
551
- rl.close();
552
- if (answer.toLowerCase() !== 'y') {
553
- console.log(chalk.dim('Aborted. Use --force to skip this check.'));
554
- process.exit(0);
555
- }
556
- console.log();
557
- }
558
- }
559
- const sectionResults = [];
560
- let totalChanges = 0;
561
- // Calculate section boundaries in the XML document text for comment filtering
562
- // Comment positions (docPosition) are relative to xmlDocText, NOT wordText
563
- // So we must find section headers in xmlDocText to get matching boundaries
564
- const sectionBoundaries = [];
565
- const xmlLower = xmlDocText.toLowerCase();
566
- // Standard section header keywords to search for in XML
567
- // Map from file name pattern to search terms
568
- const sectionKeywords = {
569
- 'abstract': ['abstract', 'summary'],
570
- 'introduction': ['introduction', 'background'],
571
- 'methods': ['methods', 'materials and methods', 'methodology'],
572
- 'results': ['results'],
573
- 'discussion': ['discussion'],
574
- 'conclusion': ['conclusion', 'conclusions'],
575
- };
576
- // Helper: find section header (skip labels like "Methods:" in structured abstracts)
577
- // Real section headers are NOT followed by ":" immediately
578
- function findSectionHeader(text, keyword, startFrom = 0) {
579
- const lower = text.toLowerCase();
580
- let idx = startFrom;
581
- while ((idx = lower.indexOf(keyword, idx)) !== -1) {
582
- // Check what follows the keyword
583
- const afterKeyword = text.slice(idx + keyword.length, idx + keyword.length + 5);
584
- // Skip if followed by ":" (this is a label, not a section header)
585
- // Real headers are followed by text content, a newline, or a subheading
586
- if (!afterKeyword.startsWith(':') && !afterKeyword.startsWith(' :')) {
587
- return idx;
588
- }
589
- idx++;
590
- }
591
- return -1;
592
- }
593
- for (const section of wordSections) {
594
- const fileBase = section.file.replace(/\.md$/i, '').toLowerCase();
595
- // Get keywords for this section
596
- const keywords = sectionKeywords[fileBase] || [fileBase];
597
- // Find the first valid keyword that exists in XML (not a label)
598
- let headerIdx = -1;
599
- for (const kw of keywords) {
600
- const idx = findSectionHeader(xmlDocText, kw, 0);
601
- if (idx >= 0 && (headerIdx < 0 || idx < headerIdx)) {
602
- headerIdx = idx;
603
- }
604
- }
605
- if (headerIdx >= 0) {
606
- // Find the next section's start to determine end boundary
607
- let nextHeaderIdx = xmlDocText.length;
608
- const sectionIdx = wordSections.indexOf(section);
609
- if (sectionIdx < wordSections.length - 1) {
610
- const nextFileBase = wordSections[sectionIdx + 1].file.replace(/\.md$/i, '').toLowerCase();
611
- const nextKeywords = sectionKeywords[nextFileBase] || [nextFileBase];
612
- for (const nkw of nextKeywords) {
613
- const foundNext = findSectionHeader(xmlDocText, nkw, headerIdx + 10);
614
- if (foundNext >= 0 && foundNext < nextHeaderIdx) {
615
- nextHeaderIdx = foundNext;
616
- }
617
- }
618
- }
619
- sectionBoundaries.push({
620
- file: section.file,
621
- start: headerIdx,
622
- end: nextHeaderIdx
623
- });
624
- }
625
- }
626
- // Document length is the XML text length (same coordinate system as docPosition)
627
- const docLength = xmlDocText.length;
628
- for (const section of wordSections) {
629
- const sectionPath = path.join(options.dir, section.file);
630
- if (!fs.existsSync(sectionPath)) {
631
- sectionResults.push({
632
- file: section.file,
633
- header: section.header,
634
- status: 'skipped',
635
- stats: undefined,
636
- });
637
- continue;
638
- }
639
- const result = await importFromWord(docx, sectionPath, {
640
- sectionContent: section.content,
641
- author: 'Reviewer',
642
- wordTables: wordTables,
643
- });
644
- let { annotated, stats } = result;
645
- let refConversions = [];
646
- if (registry && options.crossref !== false) {
647
- const crossrefResult = convertHardcodedRefs(annotated, registry);
648
- annotated = crossrefResult.converted;
649
- refConversions = crossrefResult.conversions;
650
- totalRefConversions += refConversions.length;
651
- }
652
- let commentsInserted = 0;
653
- if (comments.length > 0 && anchors.size > 0) {
654
- // Filter comments to only those that belong to this section
655
- // Use exact position matching: docPosition is in xmlDocText coordinates,
656
- // and sectionBoundaries are also in xmlDocText coordinates (same source!)
657
- const boundary = sectionBoundaries.find(b => b.file === section.file);
658
- const isFirstSection = wordSections.indexOf(section) === 0;
659
- const firstBoundaryStart = sectionBoundaries.length > 0 ? Math.min(...sectionBoundaries.map(b => b.start)) : 0;
660
- const sectionComments = comments.filter((c) => {
661
- const anchorData = anchors.get(c.id);
662
- if (!anchorData)
663
- return false;
664
- // Use exact position - no scaling needed since both are in xmlDocText coordinates
665
- if (anchorData.docPosition !== undefined && boundary) {
666
- // Include comments within section boundaries
667
- if (anchorData.docPosition >= boundary.start && anchorData.docPosition < boundary.end) {
668
- return true;
669
- }
670
- // Also include "outside" comments (before first section) in the first section file
671
- if (isFirstSection && anchorData.docPosition < firstBoundaryStart) {
672
- return true;
673
- }
674
- }
675
- return false;
676
- });
677
- if (process.env.DEBUG) {
678
- console.log(`[DEBUG] ${section.file}: ${sectionComments.length} comments to place (boundary: ${boundary?.start}-${boundary?.end})`);
679
- }
680
- if (sectionComments.length > 0) {
681
- // Use a more robust pattern that handles < in comment text
682
- const commentPattern = /\{>>.*?<<\}/gs;
683
- const beforeCount = (annotated.match(commentPattern) || []).length;
684
- annotated = insertCommentsIntoMarkdown(annotated, sectionComments, anchors, {
685
- quiet: !process.env.DEBUG,
686
- sectionBoundary: boundary // Pass section boundary for position-based insertion
687
- });
688
- const afterCount = (annotated.match(commentPattern) || []).length;
689
- commentsInserted = afterCount - beforeCount;
690
- if (process.env.DEBUG) {
691
- console.log(`[DEBUG] ${section.file}: inserted ${commentsInserted} of ${sectionComments.length} comments`);
692
- }
693
- if (commentsInserted > 0) {
694
- stats.comments = (stats.comments || 0) + commentsInserted;
695
- }
696
- }
697
- }
698
- totalChanges += stats.total;
699
- sectionResults.push({
700
- file: section.file,
701
- header: section.header,
702
- status: 'ok',
703
- stats,
704
- refs: refConversions.length,
705
- });
706
- if (!options.dryRun) {
707
- fs.writeFileSync(sectionPath, annotated, 'utf-8');
708
- }
709
- }
710
- const tableRows = sectionResults.map((r) => {
711
- if (r.status === 'skipped') {
712
- return [
713
- chalk.dim(r.file),
714
- chalk.dim(r.header.slice(0, 25)),
715
- chalk.yellow('skipped'),
716
- '',
717
- '',
718
- '',
719
- '',
720
- ];
721
- }
722
- const s = r.stats;
723
- return [
724
- chalk.bold(r.file),
725
- r.header.length > 25 ? r.header.slice(0, 22) + '...' : r.header,
726
- s.insertions > 0 ? chalk.green(`+${s.insertions}`) : chalk.dim('-'),
727
- s.deletions > 0 ? chalk.red(`-${s.deletions}`) : chalk.dim('-'),
728
- s.substitutions > 0 ? chalk.yellow(`~${s.substitutions}`) : chalk.dim('-'),
729
- s.comments > 0 ? chalk.blue(`#${s.comments}`) : chalk.dim('-'),
730
- r.refs > 0 ? chalk.magenta(`@${r.refs}`) : chalk.dim('-'),
731
- ];
732
- });
733
- console.log(fmt.table(['File', 'Section', 'Ins', 'Del', 'Sub', 'Cmt', 'Ref'], tableRows, { align: ['left', 'left', 'right', 'right', 'right', 'right', 'right'] }));
734
- console.log();
735
- if (options.diff !== false && totalChanges > 0) {
736
- console.log(fmt.header('Changes Preview'));
737
- console.log();
738
- for (const result of sectionResults) {
739
- if (result.status === 'ok' && result.stats && result.stats.total > 0) {
740
- const sectionPath = path.join(options.dir, result.file);
741
- if (fs.existsSync(sectionPath)) {
742
- const content = fs.readFileSync(sectionPath, 'utf-8');
743
- const preview = inlineDiffPreview(content, { maxLines: 3 });
744
- if (preview) {
745
- console.log(chalk.bold(result.file) + ':');
746
- console.log(preview);
747
- console.log();
748
- }
749
- }
750
- }
751
- }
752
- }
753
- if (options.dryRun) {
754
- console.log(fmt.box(chalk.yellow('Dry run - no files written'), { padding: 0 }));
755
- }
756
- else if (totalChanges > 0 || totalRefConversions > 0 || comments.length > 0) {
757
- const summaryLines = [];
758
- summaryLines.push(`${chalk.bold(wordSections.length)} sections processed`);
759
- if (totalChanges > 0)
760
- summaryLines.push(`${chalk.bold(totalChanges)} annotations imported`);
761
- if (comments.length > 0)
762
- summaryLines.push(`${chalk.bold(comments.length)} comments placed`);
763
- if (totalRefConversions > 0)
764
- summaryLines.push(`${chalk.bold(totalRefConversions)} refs converted to @-syntax`);
765
- console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
766
- console.log();
767
- console.log(chalk.dim('Next steps:'));
768
- console.log(chalk.dim(' 1. rev review <section.md> - Accept/reject changes'));
769
- console.log(chalk.dim(' 2. rev comments <section.md> - View/address comments'));
770
- console.log(chalk.dim(' 3. rev build docx - Rebuild Word doc'));
771
- }
772
- else {
773
- console.log(fmt.status('success', 'No changes detected.'));
774
- }
775
- }
776
- catch (err) {
777
- spin.stop();
778
- const error = err;
779
- console.error(fmt.status('error', error.message));
780
- if (process.env.DEBUG)
781
- console.error(error.stack);
782
- process.exit(1);
783
- }
784
- });
785
- // ==========================================================================
786
- // MERGE command - Combine feedback from multiple reviewers (three-way merge)
787
- // ==========================================================================
788
- program
789
- .command('merge')
790
- .description('Merge feedback from multiple Word documents using three-way merge')
791
- .argument('<docx...>', 'Word documents from reviewers')
792
- .option('-b, --base <file>', 'Base document (original sent to reviewers). Auto-detected if not specified.')
793
- .option('-o, --output <file>', 'Output file (default: writes to section files)')
794
- .option('--names <names>', 'Reviewer names (comma-separated, in order of docx files)')
795
- .option('--strategy <strategy>', 'Conflict resolution: first, latest, or interactive (default)', 'interactive')
796
- .option('--diff-level <level>', 'Diff granularity: sentence or word (default: sentence)', 'sentence')
797
- .option('--dry-run', 'Show conflicts without writing')
798
- .option('--sections', 'Split merged output back to section files')
799
- .action(async (docxFiles, options) => {
800
- const { mergeThreeWay, formatConflict, resolveConflict, getBaseDocument, checkBaseMatch, saveConflicts, } = await import('../merge.js');
801
- // Validate reviewer files exist
802
- for (const docx of docxFiles) {
803
- if (!fs.existsSync(docx)) {
804
- console.error(fmt.status('error', `Reviewer file not found: ${docx}`));
805
- process.exit(1);
806
- }
807
- }
808
- // Determine base document
809
- let basePath = options.base;
810
- let baseSource = 'specified';
811
- if (!basePath) {
812
- // Try to use .rev/base.docx
813
- const projectDir = process.cwd();
814
- basePath = getBaseDocument(projectDir) ?? undefined;
815
- if (basePath) {
816
- baseSource = 'auto (.rev/base.docx)';
817
- }
818
- else {
819
- console.log(chalk.yellow('\n No base document found in .rev/base.docx'));
820
- console.log(chalk.dim(' Tip: Run "rev build docx" to automatically save the base document.\n'));
821
- console.error(fmt.status('error', 'Base document required. Use --base <file.docx>'));
822
- process.exit(1);
823
- }
824
- }
825
- if (!fs.existsSync(basePath)) {
826
- console.error(fmt.status('error', `Base document not found: ${basePath}`));
827
- process.exit(1);
828
- }
829
- // Check similarity between base and reviewer docs
830
- const { matches, similarity } = await checkBaseMatch(basePath, docxFiles[0]);
831
- if (!matches) {
832
- console.log(chalk.yellow(`\n Warning: Base document may not match reviewer file (${Math.round(similarity * 100)}% similar)`));
833
- console.log(chalk.dim(' If this is wrong, use --base to specify the correct original document.\n'));
834
- }
835
- // Parse reviewer names
836
- const names = options.names
837
- ? options.names.split(',').map(n => n.trim())
838
- : docxFiles.map((f, i) => {
839
- // Try to extract name from filename (e.g., paper_reviewer_A.docx)
840
- const basename = path.basename(f, '.docx');
841
- const match = basename.match(/_([A-Za-z]+)$/);
842
- return match ? match[1] : `Reviewer ${i + 1}`;
843
- });
844
- // Pad names if needed
845
- while (names.length < docxFiles.length) {
846
- names.push(`Reviewer ${names.length + 1}`);
847
- }
848
- const reviewerDocs = docxFiles.map((p, i) => ({
849
- path: p,
850
- name: names[i],
851
- }));
852
- console.log(fmt.header('Three-Way Merge'));
853
- console.log();
854
- console.log(chalk.dim(` Base: ${path.basename(basePath)} (${baseSource})`));
855
- console.log(chalk.dim(` Reviewers: ${names.join(', ')}`));
856
- console.log(chalk.dim(` Diff level: ${options.diffLevel}`));
857
- console.log();
858
- const spin = fmt.spinner('Analyzing changes...').start();
859
- try {
860
- const { merged, conflicts, stats, baseText } = await mergeThreeWay(basePath, reviewerDocs, {
861
- diffLevel: options.diffLevel,
862
- });
863
- spin.stop();
864
- // Display stats
865
- console.log(fmt.table(['Metric', 'Count'], [
866
- ['Total changes', stats.totalChanges.toString()],
867
- ['Non-conflicting', stats.nonConflicting.toString()],
868
- ['Conflicts', stats.conflicts.toString()],
869
- ['Comments', stats.comments.toString()],
870
- ]));
871
- console.log();
872
- let finalMerged = merged;
873
- // Handle conflicts
874
- if (conflicts.length > 0) {
875
- console.log(chalk.yellow(`Found ${conflicts.length} conflict(s):\n`));
876
- if (options.strategy === 'first') {
877
- // Auto-resolve: take first reviewer's change
878
- for (const conflict of conflicts) {
879
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[0].reviewer}'s change`));
880
- resolveConflict(conflict, 0);
881
- }
882
- }
883
- else if (options.strategy === 'latest') {
884
- // Auto-resolve: take last reviewer's change
885
- for (const conflict of conflicts) {
886
- const lastIdx = conflict.changes.length - 1;
887
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[lastIdx].reviewer}'s change`));
888
- resolveConflict(conflict, lastIdx);
889
- }
890
- }
891
- else if (!options.dryRun) {
892
- // Interactive resolution
893
- for (let i = 0; i < conflicts.length; i++) {
894
- const conflict = conflicts[i];
895
- console.log(chalk.bold(`\nConflict ${i + 1}/${conflicts.length} (${conflict.id}):`));
896
- console.log(formatConflict(conflict, baseText));
897
- console.log();
898
- const rl = readline.createInterface({
899
- input: process.stdin,
900
- output: process.stdout,
901
- });
902
- const answer = await new Promise((resolve) => rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip): `), resolve));
903
- rl.close();
904
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
905
- const choice = parseInt(answer) - 1;
906
- if (choice >= 0 && choice < conflict.changes.length) {
907
- resolveConflict(conflict, choice);
908
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
909
- }
910
- }
911
- else {
912
- console.log(chalk.dim(' Skipped (will need manual resolution)'));
913
- }
914
- }
915
- }
916
- // Save unresolved conflicts for later
917
- const unresolved = conflicts.filter(c => c.resolved === null);
918
- if (unresolved.length > 0) {
919
- saveConflicts(process.cwd(), conflicts, basePath);
920
- console.log(chalk.yellow(`\n ${unresolved.length} unresolved conflict(s) saved to .rev/conflicts.json`));
921
- console.log(chalk.dim(' Run "rev conflicts" to view, "rev merge-resolve" to resolve'));
922
- }
923
- }
924
- // Write output
925
- if (!options.dryRun) {
926
- if (options.output) {
927
- // Write to single file
928
- fs.writeFileSync(options.output, finalMerged, 'utf-8');
929
- console.log(fmt.status('success', `Merged output written to ${options.output}`));
930
- }
931
- else if (options.sections) {
932
- // Split to section files (TODO: implement section splitting)
933
- console.log(chalk.yellow(' Section splitting not yet implemented'));
934
- console.log(chalk.dim(' Use -o to specify output file'));
935
- }
936
- else {
937
- // Default: write to merged.md
938
- const outPath = 'merged.md';
939
- fs.writeFileSync(outPath, finalMerged, 'utf-8');
940
- console.log(fmt.status('success', `Merged output written to ${outPath}`));
941
- }
942
- console.log();
943
- console.log(chalk.dim('Next steps:'));
944
- console.log(chalk.dim(' 1. rev review merged.md - Accept/reject changes'));
945
- console.log(chalk.dim(' 2. rev comments merged.md - Address comments'));
946
- if (conflicts.some(c => c.resolved === null)) {
947
- console.log(chalk.dim(' 3. rev merge-resolve - Resolve remaining conflicts'));
948
- }
949
- }
950
- else {
951
- console.log(fmt.status('info', 'Dry run - no output written'));
952
- }
953
- }
954
- catch (err) {
955
- spin.stop();
956
- const error = err;
957
- console.error(fmt.status('error', error.message));
958
- if (process.env.DEBUG)
959
- console.error(error.stack);
960
- process.exit(1);
961
- }
962
- });
963
- // ==========================================================================
964
- // CONFLICTS command - List unresolved conflicts
965
- // ==========================================================================
966
- program
967
- .command('conflicts')
968
- .description('List unresolved merge conflicts')
969
- .action(async () => {
970
- const { loadConflicts, formatConflict } = await import('../merge.js');
971
- const projectDir = process.cwd();
972
- const data = loadConflicts(projectDir);
973
- if (!data) {
974
- console.log(fmt.status('info', 'No conflicts file found'));
975
- return;
976
- }
977
- const unresolved = data.conflicts.filter((c) => c.resolved === null);
978
- if (unresolved.length === 0) {
979
- console.log(fmt.status('success', 'All conflicts resolved!'));
980
- return;
981
- }
982
- console.log(fmt.header(`Unresolved Conflicts (${unresolved.length})`));
983
- console.log();
984
- console.log(chalk.dim(` Base: ${data.base}`));
985
- console.log(chalk.dim(` Merged: ${data.merged}`));
986
- console.log();
987
- for (const conflict of unresolved) {
988
- console.log(chalk.bold(`Conflict ${conflict.id}:`));
989
- // Show abbreviated info
990
- console.log(chalk.dim(` Original: "${conflict.original.slice(0, 50)}${conflict.original.length > 50 ? '...' : ''}"`));
991
- console.log(chalk.dim(` Options: ${conflict.changes.map((c) => c.reviewer).join(', ')}`));
992
- console.log();
993
- }
994
- console.log(chalk.dim('Run "rev merge-resolve" to resolve conflicts interactively'));
995
- });
996
- // ==========================================================================
997
- // MERGE-RESOLVE command - Interactively resolve merge conflicts
998
- // ==========================================================================
999
- program
1000
- .command('merge-resolve')
1001
- .alias('mresolve')
1002
- .description('Resolve merge conflicts interactively')
1003
- .option('--theirs', 'Accept all changes from last reviewer')
1004
- .option('--ours', 'Accept all changes from first reviewer')
1005
- .action(async (options) => {
1006
- const { loadConflicts, saveConflicts, clearConflicts, resolveConflict, formatConflict } = await import('../merge.js');
1007
- const projectDir = process.cwd();
1008
- const data = loadConflicts(projectDir);
1009
- if (!data) {
1010
- console.log(fmt.status('info', 'No conflicts to resolve'));
1011
- return;
1012
- }
1013
- const unresolved = data.conflicts.filter((c) => c.resolved === null);
1014
- if (unresolved.length === 0) {
1015
- console.log(fmt.status('success', 'All conflicts already resolved!'));
1016
- clearConflicts(projectDir);
1017
- return;
1018
- }
1019
- console.log(fmt.header(`Resolving ${unresolved.length} Conflict(s)`));
1020
- console.log();
1021
- if (options.theirs) {
1022
- // Accept all from last reviewer
1023
- for (const conflict of unresolved) {
1024
- const lastIdx = conflict.changes.length - 1;
1025
- resolveConflict(conflict, lastIdx);
1026
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[lastIdx].reviewer}'s change`));
1027
- }
1028
- saveConflicts(projectDir, data.conflicts, data.base);
1029
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--theirs)`));
1030
- }
1031
- else if (options.ours) {
1032
- // Accept all from first reviewer
1033
- for (const conflict of unresolved) {
1034
- resolveConflict(conflict, 0);
1035
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[0].reviewer}'s change`));
1036
- }
1037
- saveConflicts(projectDir, data.conflicts, data.base);
1038
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--ours)`));
1039
- }
1040
- else {
1041
- // Interactive resolution
1042
- // Read base text for context display
1043
- let baseText = '';
1044
- try {
1045
- const { extractFromWord } = await import('../import.js');
1046
- const { text } = await extractFromWord(data.base);
1047
- baseText = text;
1048
- }
1049
- catch {
1050
- // Can't read base, show without context
1051
- }
1052
- for (let i = 0; i < unresolved.length; i++) {
1053
- const conflict = unresolved[i];
1054
- console.log(chalk.bold(`\nConflict ${i + 1}/${unresolved.length} (${conflict.id}):`));
1055
- console.log(formatConflict(conflict, baseText));
1056
- console.log();
1057
- const rl = readline.createInterface({
1058
- input: process.stdin,
1059
- output: process.stdout,
1060
- });
1061
- const answer = await new Promise((resolve) => rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip, q=quit): `), resolve));
1062
- rl.close();
1063
- if (answer.toLowerCase() === 'q') {
1064
- console.log(chalk.dim('\n Saving progress...'));
1065
- break;
1066
- }
1067
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
1068
- const choice = parseInt(answer) - 1;
1069
- if (choice >= 0 && choice < conflict.changes.length) {
1070
- resolveConflict(conflict, choice);
1071
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
1072
- }
1073
- }
1074
- else {
1075
- console.log(chalk.dim(' Skipped'));
1076
- }
1077
- }
1078
- saveConflicts(projectDir, data.conflicts, data.base);
1079
- const remaining = data.conflicts.filter((c) => c.resolved === null).length;
1080
- if (remaining === 0) {
1081
- console.log(fmt.status('success', '\nAll conflicts resolved!'));
1082
- clearConflicts(projectDir);
1083
- }
1084
- else {
1085
- console.log(chalk.yellow(`\n ${remaining} conflict(s) remaining`));
1086
- }
1087
- }
1088
- });
1089
370
  }
1090
371
  //# sourceMappingURL=sections.js.map