docrev 0.9.5 → 0.9.7

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 (99) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dev_notes/bug_repro_comment_parser.md +71 -0
  3. package/dist/lib/anchor-match.d.ts +41 -0
  4. package/dist/lib/anchor-match.d.ts.map +1 -0
  5. package/dist/lib/anchor-match.js +192 -0
  6. package/dist/lib/anchor-match.js.map +1 -0
  7. package/dist/lib/annotations.d.ts.map +1 -1
  8. package/dist/lib/annotations.js +8 -5
  9. package/dist/lib/annotations.js.map +1 -1
  10. package/dist/lib/commands/file-ops.d.ts +11 -0
  11. package/dist/lib/commands/file-ops.d.ts.map +1 -0
  12. package/dist/lib/commands/file-ops.js +301 -0
  13. package/dist/lib/commands/file-ops.js.map +1 -0
  14. package/dist/lib/commands/index.d.ts +10 -1
  15. package/dist/lib/commands/index.d.ts.map +1 -1
  16. package/dist/lib/commands/index.js +19 -1
  17. package/dist/lib/commands/index.js.map +1 -1
  18. package/dist/lib/commands/merge-resolve.d.ts +12 -0
  19. package/dist/lib/commands/merge-resolve.d.ts.map +1 -0
  20. package/dist/lib/commands/merge-resolve.js +318 -0
  21. package/dist/lib/commands/merge-resolve.js.map +1 -0
  22. package/dist/lib/commands/preview.d.ts +11 -0
  23. package/dist/lib/commands/preview.d.ts.map +1 -0
  24. package/dist/lib/commands/preview.js +138 -0
  25. package/dist/lib/commands/preview.js.map +1 -0
  26. package/dist/lib/commands/project-info.d.ts +11 -0
  27. package/dist/lib/commands/project-info.d.ts.map +1 -0
  28. package/dist/lib/commands/project-info.js +187 -0
  29. package/dist/lib/commands/project-info.js.map +1 -0
  30. package/dist/lib/commands/quality.d.ts +11 -0
  31. package/dist/lib/commands/quality.d.ts.map +1 -0
  32. package/dist/lib/commands/quality.js +384 -0
  33. package/dist/lib/commands/quality.js.map +1 -0
  34. package/dist/lib/commands/section-boundaries.d.ts +22 -0
  35. package/dist/lib/commands/section-boundaries.d.ts.map +1 -0
  36. package/dist/lib/commands/section-boundaries.js +53 -0
  37. package/dist/lib/commands/section-boundaries.js.map +1 -0
  38. package/dist/lib/commands/sections.d.ts +3 -2
  39. package/dist/lib/commands/sections.d.ts.map +1 -1
  40. package/dist/lib/commands/sections.js +4 -736
  41. package/dist/lib/commands/sections.js.map +1 -1
  42. package/dist/lib/commands/sync.d.ts +11 -0
  43. package/dist/lib/commands/sync.d.ts.map +1 -0
  44. package/dist/lib/commands/sync.js +576 -0
  45. package/dist/lib/commands/sync.js.map +1 -0
  46. package/dist/lib/commands/text-ops.d.ts +11 -0
  47. package/dist/lib/commands/text-ops.d.ts.map +1 -0
  48. package/dist/lib/commands/text-ops.js +357 -0
  49. package/dist/lib/commands/text-ops.js.map +1 -0
  50. package/dist/lib/commands/utilities.d.ts +2 -4
  51. package/dist/lib/commands/utilities.d.ts.map +1 -1
  52. package/dist/lib/commands/utilities.js +3 -1572
  53. package/dist/lib/commands/utilities.js.map +1 -1
  54. package/dist/lib/commands/verify-anchors.d.ts +17 -0
  55. package/dist/lib/commands/verify-anchors.d.ts.map +1 -0
  56. package/dist/lib/commands/verify-anchors.js +215 -0
  57. package/dist/lib/commands/verify-anchors.js.map +1 -0
  58. package/dist/lib/commands/word-tools.d.ts +11 -0
  59. package/dist/lib/commands/word-tools.d.ts.map +1 -0
  60. package/dist/lib/commands/word-tools.js +272 -0
  61. package/dist/lib/commands/word-tools.js.map +1 -0
  62. package/dist/lib/diff-engine.d.ts +25 -0
  63. package/dist/lib/diff-engine.d.ts.map +1 -0
  64. package/dist/lib/diff-engine.js +354 -0
  65. package/dist/lib/diff-engine.js.map +1 -0
  66. package/dist/lib/import.d.ts +44 -118
  67. package/dist/lib/import.d.ts.map +1 -1
  68. package/dist/lib/import.js +25 -1173
  69. package/dist/lib/import.js.map +1 -1
  70. package/dist/lib/restore-references.d.ts +35 -0
  71. package/dist/lib/restore-references.d.ts.map +1 -0
  72. package/dist/lib/restore-references.js +188 -0
  73. package/dist/lib/restore-references.js.map +1 -0
  74. package/dist/lib/word-extraction.d.ts +100 -0
  75. package/dist/lib/word-extraction.d.ts.map +1 -0
  76. package/dist/lib/word-extraction.js +594 -0
  77. package/dist/lib/word-extraction.js.map +1 -0
  78. package/lib/anchor-match.ts +238 -0
  79. package/lib/annotations.ts +9 -5
  80. package/lib/commands/file-ops.ts +372 -0
  81. package/lib/commands/index.ts +27 -0
  82. package/lib/commands/merge-resolve.ts +378 -0
  83. package/lib/commands/preview.ts +178 -0
  84. package/lib/commands/project-info.ts +244 -0
  85. package/lib/commands/quality.ts +517 -0
  86. package/lib/commands/section-boundaries.ts +72 -0
  87. package/lib/commands/sections.ts +3 -870
  88. package/lib/commands/sync.ts +701 -0
  89. package/lib/commands/text-ops.ts +449 -0
  90. package/lib/commands/utilities.ts +62 -2043
  91. package/lib/commands/verify-anchors.ts +261 -0
  92. package/lib/commands/word-tools.ts +340 -0
  93. package/lib/diff-engine.ts +465 -0
  94. package/lib/import.ts +108 -1504
  95. package/lib/restore-references.ts +240 -0
  96. package/lib/word-extraction.ts +759 -0
  97. package/package.json +1 -1
  98. package/skill/REFERENCE.md +29 -2
  99. package/skill/SKILL.md +12 -2
@@ -1,29 +1,9 @@
1
1
  /**
2
- * Utility commands: help, completions, word-count, stats, search, backup, archive,
3
- * export, preview, watch, lint, grammar, annotate, apply, comment, clean, check,
4
- * open, spelling, upgrade, batch, install-cli-skill, uninstall-cli-skill
2
+ * Utility commands: help, completions, open, upgrade, install-cli-skill, uninstall-cli-skill
5
3
  *
6
- * Miscellaneous utility commands for project management.
4
+ * Core utility commands that don't fit into a specific domain.
7
5
  */
8
- import { chalk, fs, path, fmt, findFiles, loadBuildConfig, getComments, setCommentStatus, countAnnotations, stripAnnotations, parseAnnotations, getUserName, countWords, } from './context.js';
9
- /**
10
- * Recursively add directory contents to a zip archive, filtering by predicate
11
- */
12
- function addDirToZip(zip, dir, shouldInclude, zipPath = '') {
13
- const entries = fs.readdirSync(dir, { withFileTypes: true });
14
- for (const entry of entries) {
15
- const fullPath = path.join(dir, entry.name);
16
- const entryZipPath = path.join(zipPath, entry.name);
17
- if (!shouldInclude(entry.name))
18
- continue;
19
- if (entry.isDirectory()) {
20
- addDirToZip(zip, fullPath, shouldInclude, entryZipPath);
21
- }
22
- else {
23
- zip.addLocalFile(fullPath, zipPath || undefined);
24
- }
25
- }
26
- }
6
+ import { chalk, fs, path, fmt, } from './context.js';
27
7
  /**
28
8
  * Register utility commands with the program
29
9
  */
@@ -99,1210 +79,6 @@ export function register(program, pkg) {
99
79
  }
100
80
  });
101
81
  // ==========================================================================
102
- // WORD-COUNT command - Per-section word counts
103
- // ==========================================================================
104
- program
105
- .command('word-count')
106
- .alias('wc')
107
- .description('Show word counts per section')
108
- .option('-l, --limit <number>', 'Warn if total exceeds limit', parseInt)
109
- .option('-j, --journal <name>', 'Use journal word limit')
110
- .action(async (options) => {
111
- let config = {};
112
- try {
113
- config = loadBuildConfig('.') || {};
114
- }
115
- catch {
116
- // Not in a rev project, that's ok
117
- }
118
- const sections = config.sections || [];
119
- if (sections.length === 0) {
120
- // Try to find .md files
121
- const mdFiles = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
122
- if (mdFiles.length === 0) {
123
- console.error(chalk.red('No section files found. Run from a rev project directory.'));
124
- process.exit(1);
125
- }
126
- sections.push(...mdFiles);
127
- }
128
- let total = 0;
129
- const rows = [];
130
- for (const section of sections) {
131
- if (!fs.existsSync(section))
132
- continue;
133
- const text = fs.readFileSync(section, 'utf-8');
134
- const words = countWords(text);
135
- total += words;
136
- rows.push([section, words.toLocaleString()]);
137
- }
138
- rows.push(['', '']);
139
- rows.push([chalk.bold('Total'), chalk.bold(total.toLocaleString())]);
140
- console.log(fmt.header('Word Count'));
141
- console.log(fmt.table(['Section', 'Words'], rows));
142
- // Check limit
143
- let limit = options.limit;
144
- if (options.journal) {
145
- const { getJournalProfile } = await import('../journals.js');
146
- const profile = getJournalProfile(options.journal);
147
- if (profile?.requirements?.wordLimit?.main) {
148
- limit = profile.requirements.wordLimit.main;
149
- console.log(chalk.dim(`\nUsing ${profile.name} word limit: ${limit.toLocaleString()}`));
150
- }
151
- }
152
- if (limit && total > limit) {
153
- console.log(chalk.red(`\n⚠ Over limit by ${(total - limit).toLocaleString()} words`));
154
- }
155
- else if (limit) {
156
- console.log(chalk.green(`\n✓ Within limit (${(limit - total).toLocaleString()} words remaining)`));
157
- }
158
- });
159
- // ==========================================================================
160
- // STATS command - Project dashboard
161
- // ==========================================================================
162
- program
163
- .command('stats')
164
- .description('Show project statistics dashboard')
165
- .action(async (_options) => {
166
- let config = {};
167
- try {
168
- config = loadBuildConfig('.') || {};
169
- }
170
- catch {
171
- // Not in a rev project, that's ok
172
- }
173
- let sections = config.sections || [];
174
- if (sections.length === 0) {
175
- sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
176
- }
177
- let totalWords = 0;
178
- let totalFigures = 0;
179
- let totalTables = 0;
180
- let totalComments = 0;
181
- let pendingComments = 0;
182
- const citations = new Set();
183
- for (const section of sections) {
184
- if (!fs.existsSync(section))
185
- continue;
186
- const text = fs.readFileSync(section, 'utf-8');
187
- totalWords += countWords(text);
188
- totalFigures += (text.match(/!\[.*?\]\(.*?\)/g) || []).length;
189
- totalTables += (text.match(/^\|[^|]+\|/gm) || []).length / 5; // Approximate
190
- const comments = getComments(text);
191
- totalComments += comments.length;
192
- pendingComments += comments.filter(c => !c.resolved).length;
193
- const cites = text.match(/@(\w+)(?![:\w])/g) || [];
194
- cites.forEach(c => citations.add(c.slice(1)));
195
- }
196
- console.log(fmt.header('Project Statistics'));
197
- console.log();
198
- const stats = [
199
- ['Sections', sections.length],
200
- ['Words', totalWords.toLocaleString()],
201
- ['Figures', Math.round(totalFigures)],
202
- ['Tables', Math.round(totalTables)],
203
- ['Citations', citations.size],
204
- ['Comments', `${totalComments} (${pendingComments} pending)`],
205
- ];
206
- for (const [label, value] of stats) {
207
- console.log(` ${chalk.dim(label.padEnd(12))} ${chalk.bold(value)}`);
208
- }
209
- // Bibliography stats
210
- const bibPath = config.bibliography || 'references.bib';
211
- if (fs.existsSync(bibPath)) {
212
- const bibContent = fs.readFileSync(bibPath, 'utf-8');
213
- const bibEntries = (bibContent.match(/@\w+\s*\{/g) || []).length;
214
- console.log(` ${chalk.dim('Bib entries'.padEnd(12))} ${chalk.bold(bibEntries)}`);
215
- }
216
- console.log();
217
- });
218
- // ==========================================================================
219
- // SEARCH command - Search across section files
220
- // ==========================================================================
221
- program
222
- .command('search')
223
- .description('Search across all section files')
224
- .argument('<query>', 'Search query (supports regex)')
225
- .option('-i, --ignore-case', 'Case-insensitive search')
226
- .option('-c, --context <lines>', 'Show context lines', parseInt, 1)
227
- .action((query, options) => {
228
- let config = {};
229
- try {
230
- config = loadBuildConfig('.') || {};
231
- }
232
- catch {
233
- // Not in a rev project, that's ok
234
- }
235
- let sections = config.sections || [];
236
- if (sections.length === 0) {
237
- sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f));
238
- }
239
- const flags = options.ignoreCase ? 'gi' : 'g';
240
- let pattern;
241
- try {
242
- pattern = new RegExp(query, flags);
243
- }
244
- catch {
245
- pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), flags);
246
- }
247
- let totalMatches = 0;
248
- for (const section of sections) {
249
- if (!fs.existsSync(section))
250
- continue;
251
- const text = fs.readFileSync(section, 'utf-8');
252
- const lines = text.split('\n');
253
- const matches = [];
254
- for (let i = 0; i < lines.length; i++) {
255
- if (pattern.test(lines[i])) {
256
- matches.push({ line: i + 1, text: lines[i] });
257
- pattern.lastIndex = 0;
258
- }
259
- }
260
- if (matches.length > 0) {
261
- console.log(chalk.cyan.bold(`\n${section}`));
262
- for (const match of matches) {
263
- const highlighted = match.text.replace(pattern, (m) => chalk.yellow.bold(m));
264
- console.log(` ${chalk.dim(match.line + ':')} ${highlighted}`);
265
- }
266
- totalMatches += matches.length;
267
- }
268
- }
269
- if (totalMatches === 0) {
270
- console.log(chalk.yellow(`No matches found for "${query}"`));
271
- }
272
- else {
273
- console.log(chalk.dim(`\n${totalMatches} match${totalMatches === 1 ? '' : 'es'} found`));
274
- }
275
- });
276
- // ==========================================================================
277
- // BACKUP command - Timestamped project backup
278
- // ==========================================================================
279
- program
280
- .command('backup')
281
- .description('Create timestamped project backup')
282
- .option('-n, --name <name>', 'Custom backup name')
283
- .option('-o, --output <dir>', 'Output directory', '.')
284
- .action(async (options) => {
285
- const { default: AdmZip } = await import('adm-zip');
286
- const zip = new AdmZip();
287
- const date = new Date().toISOString().slice(0, 10);
288
- const name = options.name || `backup-${date}`;
289
- const outputPath = path.join(options.output || '.', `${name}.zip`);
290
- // Files to exclude
291
- const excludePatterns = [
292
- 'node_modules', '.git', '.DS_Store', '*.zip',
293
- 'paper.md' // Generated file
294
- ];
295
- const shouldInclude = (file) => {
296
- for (const pattern of excludePatterns) {
297
- if (file.includes(pattern.replace('*', '')))
298
- return false;
299
- }
300
- return true;
301
- };
302
- addDirToZip(zip, '.', shouldInclude);
303
- zip.writeZip(outputPath);
304
- console.log(fmt.status('success', `Backup created: ${outputPath}`));
305
- });
306
- // ==========================================================================
307
- // ARCHIVE command - Archive reviewer docx files
308
- // ==========================================================================
309
- program
310
- .command('archive')
311
- .description('Move reviewer .docx files to archive folder')
312
- .argument('[files...]', 'Specific files to archive (default: all .docx)')
313
- .option('-d, --dir <folder>', 'Archive folder name', 'archive')
314
- .option('--by <name>', 'Reviewer name (auto-detected if single commenter)')
315
- .option('--no-rename', 'Keep original filenames')
316
- .option('--dry-run', 'Preview without moving files')
317
- .action(async (files, options) => {
318
- const { extractWordComments } = await import('../import.js');
319
- const { default: YAML } = await import('yaml');
320
- // Find docx files to archive
321
- let docxFiles = files && files.length > 0
322
- ? files.filter(f => f.endsWith('.docx') && fs.existsSync(f))
323
- : findFiles('.docx');
324
- // Exclude our own build outputs
325
- let projectSlug = null;
326
- const configPath = path.join(process.cwd(), 'rev.yaml');
327
- if (fs.existsSync(configPath)) {
328
- try {
329
- const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
330
- if (config.title) {
331
- projectSlug = config.title
332
- .toLowerCase()
333
- .replace(/[^a-z0-9]+/g, '-')
334
- .replace(/^-|-$/g, '')
335
- .slice(0, 50);
336
- }
337
- }
338
- catch (e) {
339
- // Ignore config errors
340
- }
341
- }
342
- // Filter out build outputs
343
- if (projectSlug && (!files || files.length === 0)) {
344
- const buildPatterns = [
345
- `${projectSlug}.docx`,
346
- `${projectSlug}_comments.docx`,
347
- `${projectSlug}-changes.docx`,
348
- 'paper.docx',
349
- 'paper_comments.docx',
350
- 'paper-changes.docx',
351
- ];
352
- const excluded = [];
353
- docxFiles = docxFiles.filter(f => {
354
- const base = path.basename(f).toLowerCase();
355
- const isBuilt = buildPatterns.includes(base);
356
- if (isBuilt)
357
- excluded.push(f);
358
- return !isBuilt;
359
- });
360
- if (excluded.length > 0) {
361
- console.log(chalk.dim(` Skipping build outputs: ${excluded.join(', ')}`));
362
- console.log();
363
- }
364
- }
365
- if (docxFiles.length === 0) {
366
- console.log(fmt.status('info', 'No .docx files to archive.'));
367
- return;
368
- }
369
- const projectTitle = projectSlug;
370
- // Create archive folder
371
- const archiveDir = path.resolve(options.dir || 'archive');
372
- if (!options.dryRun && !fs.existsSync(archiveDir)) {
373
- fs.mkdirSync(archiveDir, { recursive: true });
374
- }
375
- console.log(fmt.header('Archive'));
376
- console.log();
377
- const moved = [];
378
- for (const file of docxFiles) {
379
- const stat = fs.statSync(file);
380
- const mtime = stat.mtime;
381
- const timestamp = mtime.toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '_');
382
- // Determine reviewer name
383
- let reviewer = options.by || null;
384
- if (!reviewer && options.rename !== false) {
385
- try {
386
- const comments = await extractWordComments(file);
387
- const authors = [...new Set(comments.map(c => c.author).filter(a => a && a !== 'Unknown'))];
388
- if (authors.length === 1) {
389
- reviewer = authors[0].replace(/[^a-zA-Z0-9]/g, '-').replace(/^-|-$/g, '');
390
- }
391
- }
392
- catch (e) {
393
- // Ignore extraction errors
394
- }
395
- }
396
- // Generate new name
397
- let newName;
398
- if (options.rename === false) {
399
- newName = path.basename(file);
400
- }
401
- else {
402
- const base = path.basename(file, '.docx');
403
- if (/^\d{8}_\d{6}_/.test(base)) {
404
- newName = path.basename(file);
405
- }
406
- else {
407
- const namePart = projectTitle || base;
408
- if (reviewer) {
409
- newName = `${timestamp}_${reviewer}_${namePart}.docx`;
410
- }
411
- else {
412
- newName = `${timestamp}_${namePart}.docx`;
413
- }
414
- }
415
- }
416
- const destPath = path.join(archiveDir, newName);
417
- if (options.dryRun) {
418
- console.log(` ${chalk.dim(file)} → ${chalk.cyan(path.join(options.dir || 'archive', newName))}`);
419
- }
420
- else {
421
- // Handle name collision
422
- let finalPath = destPath;
423
- let counter = 1;
424
- while (fs.existsSync(finalPath)) {
425
- const ext = path.extname(newName);
426
- const base = path.basename(newName, ext);
427
- finalPath = path.join(archiveDir, `${base}_${counter}${ext}`);
428
- counter++;
429
- }
430
- fs.renameSync(file, finalPath);
431
- console.log(` ${chalk.dim(file)} → ${chalk.green(path.relative(process.cwd(), finalPath))}`);
432
- }
433
- moved.push(file);
434
- }
435
- console.log();
436
- if (options.dryRun) {
437
- console.log(fmt.status('info', `Would archive ${moved.length} file(s). Run without --dry-run to proceed.`));
438
- }
439
- else {
440
- console.log(fmt.status('success', `Archived ${moved.length} file(s) to ${options.dir || 'archive'}/`));
441
- }
442
- });
443
- // ==========================================================================
444
- // EXPORT command - Export project as distributable zip
445
- // ==========================================================================
446
- program
447
- .command('export')
448
- .description('Export project as distributable zip')
449
- .option('-o, --output <file>', 'Output filename')
450
- .option('--include-output', 'Include built PDF/DOCX files')
451
- .action(async (options) => {
452
- const { default: AdmZip } = await import('adm-zip');
453
- const { build } = await import('../build.js');
454
- let config = {};
455
- try {
456
- config = loadBuildConfig('.') || {};
457
- }
458
- catch {
459
- // Not in a rev project, that's ok
460
- }
461
- // Build first if including output
462
- if (options.includeOutput) {
463
- console.log(chalk.dim('Building documents...'));
464
- await build('.', ['pdf', 'docx']);
465
- }
466
- const zip = new AdmZip();
467
- const projectName = config.title?.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() || 'project';
468
- const outputPath = options.output || `${projectName}-export.zip`;
469
- const exclude = ['node_modules', '.git', '.DS_Store', '*.zip'];
470
- const shouldInclude = (name) => {
471
- if (!options.includeOutput && (name.endsWith('.pdf') || name.endsWith('.docx'))) {
472
- return false;
473
- }
474
- for (const pattern of exclude) {
475
- if (name === pattern || name.includes(pattern.replace('*', '')))
476
- return false;
477
- }
478
- return true;
479
- };
480
- addDirToZip(zip, '.', shouldInclude);
481
- zip.writeZip(outputPath);
482
- console.log(fmt.status('success', `Exported: ${outputPath}`));
483
- });
484
- // ==========================================================================
485
- // PREVIEW command - Build and open document
486
- // ==========================================================================
487
- program
488
- .command('preview')
489
- .description('Build and open document in default app')
490
- .argument('[format]', 'Format to preview: pdf, docx', 'pdf')
491
- .action(async (format, _options) => {
492
- const { exec } = await import('child_process');
493
- const { build } = await import('../build.js');
494
- let config = {};
495
- try {
496
- config = loadBuildConfig('.') || {};
497
- }
498
- catch (err) {
499
- console.error(chalk.red('Not in a rev project directory (no rev.yaml found)'));
500
- process.exit(1);
501
- }
502
- console.log(chalk.dim(`Building ${format}...`));
503
- const result = await build('.', [format]);
504
- const buildResult = result.results.find(r => r.format === format);
505
- if (!buildResult?.success) {
506
- const errorMsg = buildResult?.error || 'Unknown error';
507
- console.error(chalk.red(`Build failed: ${errorMsg}`));
508
- process.exit(1);
509
- }
510
- const outputFile = buildResult.outputPath;
511
- if (!outputFile || !fs.existsSync(outputFile)) {
512
- console.error(chalk.red(`Output file not found: ${outputFile}`));
513
- process.exit(1);
514
- }
515
- // Open with system default
516
- const openCmd = process.platform === 'darwin' ? 'open' :
517
- process.platform === 'win32' ? 'start' : 'xdg-open';
518
- exec(`${openCmd} "${outputFile}"`, (err) => {
519
- if (err) {
520
- console.error(chalk.red(`Could not open file: ${err.message}`));
521
- }
522
- else {
523
- console.log(fmt.status('success', `Opened ${outputFile}`));
524
- }
525
- });
526
- });
527
- // ==========================================================================
528
- // WATCH command - Auto-rebuild on changes
529
- // ==========================================================================
530
- program
531
- .command('watch')
532
- .description('Watch files and auto-rebuild on changes')
533
- .argument('[format]', 'Format to build: pdf, docx, all', 'pdf')
534
- .option('--no-open', 'Do not open after first build')
535
- .action(async (format, options) => {
536
- const { exec } = await import('child_process');
537
- const { build } = await import('../build.js');
538
- let config = {};
539
- try {
540
- config = loadBuildConfig('.') || {};
541
- }
542
- catch (err) {
543
- console.error(chalk.red('Not in a rev project directory (no rev.yaml found)'));
544
- process.exit(1);
545
- }
546
- let sections = config.sections || [];
547
- if (sections.length === 0) {
548
- sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
549
- }
550
- const filesToWatch = [
551
- ...sections,
552
- 'rev.yaml',
553
- config.bibliography || 'references.bib'
554
- ].filter(f => fs.existsSync(f));
555
- console.log(fmt.header('Watch Mode'));
556
- console.log(chalk.dim(`Watching: ${filesToWatch.join(', ')}`));
557
- console.log(chalk.dim('Press Ctrl+C to stop\n'));
558
- let building = false;
559
- let pendingBuild = false;
560
- const doBuild = async () => {
561
- if (building) {
562
- pendingBuild = true;
563
- return;
564
- }
565
- building = true;
566
- console.log(chalk.dim(`\n[${new Date().toLocaleTimeString()}] Rebuilding...`));
567
- try {
568
- const formats = format === 'all' ? ['pdf', 'docx'] : [format];
569
- const result = await build('.', formats);
570
- for (const r of result.results) {
571
- if (r.success) {
572
- console.log(chalk.green(` ✓ ${r.format}: ${r.outputPath}`));
573
- }
574
- else {
575
- console.log(chalk.red(` ✗ ${r.format}: ${r.error}`));
576
- }
577
- }
578
- }
579
- catch (err) {
580
- console.error(chalk.red(` Build error: ${err.message}`));
581
- }
582
- building = false;
583
- if (pendingBuild) {
584
- pendingBuild = false;
585
- doBuild();
586
- }
587
- };
588
- // Initial build
589
- await doBuild();
590
- // Open after first build
591
- if (options.open) {
592
- const outputFile = format === 'docx' ?
593
- (config.title?.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() || 'paper') + '.docx' :
594
- (config.title?.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() || 'paper') + '.pdf';
595
- if (fs.existsSync(outputFile)) {
596
- const openCmd = process.platform === 'darwin' ? 'open' :
597
- process.platform === 'win32' ? 'start' : 'xdg-open';
598
- exec(`${openCmd} "${outputFile}"`);
599
- }
600
- }
601
- // Watch files
602
- for (const file of filesToWatch) {
603
- fs.watch(file, { persistent: true }, (eventType) => {
604
- if (eventType === 'change') {
605
- doBuild();
606
- }
607
- });
608
- }
609
- });
610
- // ==========================================================================
611
- // LINT command - Check for common issues
612
- // ==========================================================================
613
- program
614
- .command('lint')
615
- .description('Check for common issues in the project')
616
- .option('--fix', 'Auto-fix issues where possible')
617
- .action(async (_options) => {
618
- let config = {};
619
- try {
620
- config = loadBuildConfig('.') || {};
621
- }
622
- catch {
623
- // Not in a rev project, that's ok
624
- }
625
- let sections = config.sections || [];
626
- if (sections.length === 0) {
627
- sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
628
- }
629
- const issues = [];
630
- const warnings = [];
631
- // Collect all content
632
- let allText = '';
633
- for (const section of sections) {
634
- if (fs.existsSync(section)) {
635
- allText += fs.readFileSync(section, 'utf-8') + '\n';
636
- }
637
- }
638
- // Check 1: Broken cross-references
639
- const figAnchors = new Set();
640
- const tblAnchors = new Set();
641
- const eqAnchors = new Set();
642
- const anchorPattern = /\{#(fig|tbl|eq):([^}]+)\}/g;
643
- let match;
644
- while ((match = anchorPattern.exec(allText)) !== null) {
645
- if (match[1] === 'fig')
646
- figAnchors.add(match[2]);
647
- else if (match[1] === 'tbl')
648
- tblAnchors.add(match[2]);
649
- else if (match[1] === 'eq')
650
- eqAnchors.add(match[2]);
651
- }
652
- const refPattern = /@(fig|tbl|eq):([a-zA-Z0-9_-]+)/g;
653
- while ((match = refPattern.exec(allText)) !== null) {
654
- const type = match[1];
655
- const label = match[2];
656
- const anchors = type === 'fig' ? figAnchors : type === 'tbl' ? tblAnchors : eqAnchors;
657
- if (!anchors.has(label)) {
658
- issues.push({
659
- type: 'error',
660
- message: `Broken reference: @${type}:${label}`,
661
- fix: null
662
- });
663
- }
664
- }
665
- // Check 2: Orphaned figures
666
- for (const label of figAnchors) {
667
- if (!allText.includes(`@fig:${label}`)) {
668
- warnings.push({
669
- type: 'warning',
670
- message: `Unreferenced figure: {#fig:${label}}`,
671
- });
672
- }
673
- }
674
- // Check 3: Missing citations
675
- const bibPath = config.bibliography || 'references.bib';
676
- if (fs.existsSync(bibPath)) {
677
- const bibContent = fs.readFileSync(bibPath, 'utf-8');
678
- const bibKeys = new Set();
679
- const bibPattern = /@\w+\s*\{\s*([^,]+)/g;
680
- while ((match = bibPattern.exec(bibContent)) !== null) {
681
- bibKeys.add(match[1].trim());
682
- }
683
- const citePattern = /@([a-zA-Z][a-zA-Z0-9_-]*)(?![:\w])/g;
684
- while ((match = citePattern.exec(allText)) !== null) {
685
- const key = match[1];
686
- if (!bibKeys.has(key) && !['fig', 'tbl', 'eq'].includes(key)) {
687
- issues.push({
688
- type: 'error',
689
- message: `Missing citation: @${key}`,
690
- });
691
- }
692
- }
693
- }
694
- // Check 4: Unresolved comments
695
- const comments = getComments(allText);
696
- const pending = comments.filter(c => !c.resolved);
697
- if (pending.length > 0) {
698
- warnings.push({
699
- type: 'warning',
700
- message: `${pending.length} unresolved comment${pending.length === 1 ? '' : 's'}`,
701
- });
702
- }
703
- // Check 5: Empty sections
704
- for (const section of sections) {
705
- if (fs.existsSync(section)) {
706
- const content = fs.readFileSync(section, 'utf-8').trim();
707
- if (content.length < 50) {
708
- warnings.push({
709
- type: 'warning',
710
- message: `Section appears empty: ${section}`,
711
- });
712
- }
713
- }
714
- }
715
- // Output results
716
- console.log(fmt.header('Lint Results'));
717
- console.log();
718
- if (issues.length === 0 && warnings.length === 0) {
719
- console.log(chalk.green('✓ No issues found'));
720
- return;
721
- }
722
- for (const issue of issues) {
723
- console.log(chalk.red(` ✗ ${issue.message}`));
724
- }
725
- for (const warning of warnings) {
726
- console.log(chalk.yellow(` ⚠ ${warning.message}`));
727
- }
728
- console.log();
729
- console.log(chalk.dim(`${issues.length} error${issues.length === 1 ? '' : 's'}, ${warnings.length} warning${warnings.length === 1 ? '' : 's'}`));
730
- if (issues.length > 0) {
731
- process.exit(1);
732
- }
733
- });
734
- // ==========================================================================
735
- // GRAMMAR command - Check grammar and style
736
- // ==========================================================================
737
- program
738
- .command('grammar')
739
- .description('Check grammar and style issues')
740
- .argument('[files...]', 'Markdown files to check')
741
- .option('--learn <word>', 'Add word to custom dictionary')
742
- .option('--forget <word>', 'Remove word from custom dictionary')
743
- .option('--list', 'List custom dictionary words')
744
- .option('--rules', 'List available grammar rules')
745
- .option('--no-scientific', 'Disable scientific writing rules')
746
- .option('-s, --severity <level>', 'Minimum severity: error, warning, info', 'info')
747
- .action(async (files, options) => {
748
- const { checkGrammar, getGrammarSummary, loadDictionary, addToDictionary, removeFromDictionary, listRules, } = await import('../grammar.js');
749
- // Handle dictionary management
750
- if (options.learn) {
751
- const added = addToDictionary(options.learn);
752
- if (added) {
753
- console.log(fmt.status('success', `Added "${options.learn}" to dictionary`));
754
- }
755
- else {
756
- console.log(chalk.dim(`"${options.learn}" already in dictionary`));
757
- }
758
- return;
759
- }
760
- if (options.forget) {
761
- const removed = removeFromDictionary(options.forget);
762
- if (removed) {
763
- console.log(fmt.status('success', `Removed "${options.forget}" from dictionary`));
764
- }
765
- else {
766
- console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
767
- }
768
- return;
769
- }
770
- if (options.list) {
771
- const words = loadDictionary();
772
- console.log(fmt.header('Custom Dictionary'));
773
- console.log();
774
- if (words.size === 0) {
775
- console.log(chalk.dim(' No custom words defined'));
776
- console.log(chalk.dim(' Use --learn <word> to add words'));
777
- }
778
- else {
779
- const sorted = [...words].sort();
780
- for (const word of sorted) {
781
- console.log(` ${word}`);
782
- }
783
- console.log();
784
- console.log(chalk.dim(`${words.size} word(s)`));
785
- }
786
- return;
787
- }
788
- if (options.rules) {
789
- const rules = listRules(options.scientific);
790
- console.log(fmt.header('Grammar Rules'));
791
- console.log();
792
- for (const rule of rules) {
793
- const icon = rule.severity === 'error' ? chalk.red('●') :
794
- rule.severity === 'warning' ? chalk.yellow('●') :
795
- chalk.blue('●');
796
- console.log(` ${icon} ${chalk.bold(rule.id)}`);
797
- console.log(chalk.dim(` ${rule.message}`));
798
- }
799
- return;
800
- }
801
- // Get files to check
802
- let mdFiles = files;
803
- if (!mdFiles || mdFiles.length === 0) {
804
- let config = {};
805
- try {
806
- config = loadBuildConfig('.') || {};
807
- }
808
- catch {
809
- // Not in a rev project
810
- }
811
- mdFiles = config.sections || [];
812
- if (mdFiles.length === 0) {
813
- mdFiles = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
814
- }
815
- }
816
- if (mdFiles.length === 0) {
817
- console.error(chalk.red('No markdown files found'));
818
- process.exit(1);
819
- }
820
- console.log(fmt.header('Grammar Check'));
821
- console.log();
822
- const severityLevels = { error: 3, warning: 2, info: 1 };
823
- const minSeverity = severityLevels[options.severity || 'info'] || 1;
824
- let allIssues = [];
825
- for (const file of mdFiles) {
826
- if (!fs.existsSync(file))
827
- continue;
828
- const text = fs.readFileSync(file, 'utf-8');
829
- const issues = checkGrammar(text, { scientific: options.scientific });
830
- // Filter by severity
831
- const filtered = issues.filter((i) => severityLevels[i.severity] >= minSeverity);
832
- if (filtered.length > 0) {
833
- console.log(chalk.cyan.bold(file));
834
- for (const issue of filtered) {
835
- const icon = issue.severity === 'error' ? chalk.red('●') :
836
- issue.severity === 'warning' ? chalk.yellow('●') :
837
- chalk.blue('●');
838
- console.log(` ${chalk.dim(`L${issue.line}:`)} ${icon} ${issue.message}`);
839
- console.log(chalk.dim(` "${issue.match}" in: ${issue.context.slice(0, 60)}...`));
840
- }
841
- console.log();
842
- allIssues.push(...filtered.map(i => ({ ...i, file })));
843
- }
844
- }
845
- const summary = getGrammarSummary(allIssues);
846
- if (summary.total === 0) {
847
- console.log(chalk.green('✓ No issues found'));
848
- }
849
- else {
850
- console.log(chalk.dim(`Found ${summary.total} issue(s): ${summary.errors} errors, ${summary.warnings} warnings, ${summary.info} info`));
851
- console.log();
852
- console.log(chalk.dim('Tip: Use --learn <word> to add words to dictionary'));
853
- }
854
- });
855
- // ==========================================================================
856
- // ANNOTATE command - Add comments to Word document
857
- // ==========================================================================
858
- program
859
- .command('annotate')
860
- .description('Add comment to Word document')
861
- .argument('<docx>', 'Word document')
862
- .option('-m, --message <text>', 'Comment text')
863
- .option('-s, --search <text>', 'Text to attach comment to')
864
- .option('-a, --author <name>', 'Comment author')
865
- .action(async (docxPath, options) => {
866
- if (!fs.existsSync(docxPath)) {
867
- console.error(chalk.red(`File not found: ${docxPath}`));
868
- process.exit(1);
869
- }
870
- if (!options.message) {
871
- console.error(chalk.red('Comment message required (-m)'));
872
- process.exit(1);
873
- }
874
- const { default: AdmZip } = await import('adm-zip');
875
- const zip = new AdmZip(docxPath);
876
- // Read document.xml
877
- const docEntry = zip.getEntry('word/document.xml');
878
- if (!docEntry) {
879
- console.error(chalk.red('Invalid Word document'));
880
- process.exit(1);
881
- }
882
- let docXml = zip.readAsText(docEntry);
883
- // Read or create comments.xml
884
- let commentsEntry = zip.getEntry('word/comments.xml');
885
- let commentsXml;
886
- let nextCommentId = 1;
887
- if (commentsEntry) {
888
- commentsXml = zip.readAsText(commentsEntry);
889
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
890
- for (const m of idMatches) {
891
- const id = parseInt(m.match(/\d+/)[0]);
892
- if (id >= nextCommentId)
893
- nextCommentId = id + 1;
894
- }
895
- }
896
- else {
897
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
898
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
899
- </w:comments>`;
900
- }
901
- const author = options.author || getUserName() || 'Claude';
902
- const date = new Date().toISOString();
903
- const commentId = nextCommentId;
904
- // Add comment to comments.xml
905
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
906
- <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
907
- </w:comment>`;
908
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
909
- // Find text and add comment markers
910
- if (options.search) {
911
- const searchText = options.search;
912
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
913
- if (textPattern.test(docXml)) {
914
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
915
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
916
- });
917
- }
918
- else {
919
- console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
920
- }
921
- }
922
- // Update zip
923
- zip.updateFile('word/document.xml', Buffer.from(docXml));
924
- if (commentsEntry) {
925
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
926
- }
927
- else {
928
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
929
- // Update [Content_Types].xml
930
- const ctEntry = zip.getEntry('[Content_Types].xml');
931
- if (ctEntry) {
932
- let ctXml = zip.readAsText(ctEntry);
933
- if (!ctXml.includes('comments.xml')) {
934
- ctXml = ctXml.replace('</Types>', '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
935
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
936
- }
937
- }
938
- // Update document.xml.rels
939
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
940
- if (relsEntry) {
941
- let relsXml = zip.readAsText(relsEntry);
942
- if (!relsXml.includes('comments.xml')) {
943
- const newRelId = `rId${Date.now()}`;
944
- relsXml = relsXml.replace('</Relationships>', `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
945
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
946
- }
947
- }
948
- }
949
- // Write back
950
- zip.writeZip(docxPath);
951
- console.log(fmt.status('success', `Added comment to ${docxPath}`));
952
- });
953
- // ==========================================================================
954
- // APPLY command - Apply MD annotations as Word track changes
955
- // ==========================================================================
956
- program
957
- .command('apply')
958
- .description('Apply markdown annotations to Word document as track changes')
959
- .argument('<md>', 'Markdown file with annotations')
960
- .argument('<docx>', 'Output Word document')
961
- .option('-a, --author <name>', 'Author name for track changes')
962
- .action(async (mdPath, docxPath, options) => {
963
- if (!fs.existsSync(mdPath)) {
964
- console.error(chalk.red(`File not found: ${mdPath}`));
965
- process.exit(1);
966
- }
967
- const mdContent = fs.readFileSync(mdPath, 'utf-8');
968
- const annotations = parseAnnotations(mdContent);
969
- if (annotations.length === 0) {
970
- console.log(chalk.yellow('No annotations found in markdown file'));
971
- }
972
- const author = options.author || getUserName() || 'Author';
973
- // Build document with track changes
974
- const { buildWithTrackChanges } = await import('../trackchanges.js');
975
- try {
976
- const result = await buildWithTrackChanges(mdPath, docxPath, { author });
977
- if (result.success) {
978
- console.log(fmt.status('success', result.message));
979
- console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
980
- }
981
- else {
982
- console.error(chalk.red(result.message));
983
- process.exit(1);
984
- }
985
- }
986
- catch (err) {
987
- console.error(chalk.red(`Error: ${err.message}`));
988
- process.exit(1);
989
- }
990
- });
991
- // ==========================================================================
992
- // COMMENT command - Interactive comment addition to DOCX
993
- // ==========================================================================
994
- program
995
- .command('comment')
996
- .description('Add comments to Word document interactively')
997
- .argument('<docx>', 'Word document')
998
- .option('-a, --author <name>', 'Comment author')
999
- .action(async (docxPath, options) => {
1000
- if (!fs.existsSync(docxPath)) {
1001
- console.error(chalk.red(`File not found: ${docxPath}`));
1002
- process.exit(1);
1003
- }
1004
- const { default: AdmZip } = await import('adm-zip');
1005
- const readline = await import('readline');
1006
- const rl = readline.createInterface({
1007
- input: process.stdin,
1008
- output: process.stdout,
1009
- });
1010
- const ask = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
1011
- const author = options.author || getUserName() || 'Reviewer';
1012
- console.log(fmt.header('Interactive Comment Mode'));
1013
- console.log(chalk.dim(` Document: ${docxPath}`));
1014
- console.log(chalk.dim(` Author: ${author}`));
1015
- console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
1016
- console.log(chalk.dim(' Enter empty comment to quit.\n'));
1017
- let commentsAdded = 0;
1018
- while (true) {
1019
- const message = await ask(chalk.cyan('Comment: '));
1020
- if (!message.trim()) {
1021
- break;
1022
- }
1023
- const searchText = await ask(chalk.cyan('Attach to text: '));
1024
- // Load document fresh each time
1025
- const zip = new AdmZip(docxPath);
1026
- const docEntry = zip.getEntry('word/document.xml');
1027
- if (!docEntry) {
1028
- console.error(chalk.red('Invalid Word document'));
1029
- rl.close();
1030
- process.exit(1);
1031
- }
1032
- let docXml = zip.readAsText(docEntry);
1033
- // Read or create comments.xml
1034
- let commentsEntry = zip.getEntry('word/comments.xml');
1035
- let commentsXml;
1036
- let nextCommentId = 1;
1037
- if (commentsEntry) {
1038
- commentsXml = zip.readAsText(commentsEntry);
1039
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
1040
- for (const m of idMatches) {
1041
- const id = parseInt(m.match(/\d+/)[0]);
1042
- if (id >= nextCommentId)
1043
- nextCommentId = id + 1;
1044
- }
1045
- }
1046
- else {
1047
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1048
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
1049
- </w:comments>`;
1050
- }
1051
- const date = new Date().toISOString();
1052
- const commentId = nextCommentId;
1053
- // Add comment to comments.xml
1054
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
1055
- <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
1056
- </w:comment>`;
1057
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
1058
- // Find text and add comment markers
1059
- if (searchText.trim()) {
1060
- const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1061
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
1062
- if (textPattern.test(docXml)) {
1063
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
1064
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
1065
- });
1066
- console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
1067
- }
1068
- else {
1069
- console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
1070
- }
1071
- }
1072
- else {
1073
- console.log(chalk.dim(` Comment added without anchor.`));
1074
- }
1075
- // Update zip
1076
- zip.updateFile('word/document.xml', Buffer.from(docXml));
1077
- if (commentsEntry) {
1078
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
1079
- }
1080
- else {
1081
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
1082
- // Update [Content_Types].xml
1083
- const ctEntry = zip.getEntry('[Content_Types].xml');
1084
- if (ctEntry) {
1085
- let ctXml = zip.readAsText(ctEntry);
1086
- if (!ctXml.includes('comments.xml')) {
1087
- ctXml = ctXml.replace('</Types>', '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
1088
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
1089
- }
1090
- }
1091
- // Update document.xml.rels
1092
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
1093
- if (relsEntry) {
1094
- let relsXml = zip.readAsText(relsEntry);
1095
- if (!relsXml.includes('comments.xml')) {
1096
- const newRelId = `rId${Date.now()}`;
1097
- relsXml = relsXml.replace('</Relationships>', `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
1098
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
1099
- }
1100
- }
1101
- }
1102
- zip.writeZip(docxPath);
1103
- commentsAdded++;
1104
- console.log();
1105
- }
1106
- rl.close();
1107
- console.log();
1108
- if (commentsAdded > 0) {
1109
- console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
1110
- }
1111
- else {
1112
- console.log(chalk.dim('No comments added.'));
1113
- }
1114
- });
1115
- // ==========================================================================
1116
- // CLEAN command - Remove generated files
1117
- // ==========================================================================
1118
- program
1119
- .command('clean')
1120
- .description('Remove generated files (paper.md, PDFs, DOCXs)')
1121
- .option('-n, --dry-run', 'Show what would be deleted without deleting')
1122
- .option('--all', 'Also remove backup and export zips')
1123
- .action((options) => {
1124
- let config = {};
1125
- try {
1126
- config = loadBuildConfig('.') || {};
1127
- }
1128
- catch {
1129
- // Not in a rev project, that's ok
1130
- }
1131
- const projectName = config.title?.toLowerCase().replace(/\s+/g, '-') || 'paper';
1132
- // Files to clean
1133
- const patterns = [
1134
- 'paper.md',
1135
- '*.pdf',
1136
- `${projectName}.docx`,
1137
- `${projectName}.pdf`,
1138
- `${projectName}.tex`,
1139
- '.paper-*.md', // Temp build files
1140
- ];
1141
- if (options.all) {
1142
- patterns.push('*.zip', 'backup-*.zip', '*-export.zip');
1143
- }
1144
- const toDelete = [];
1145
- for (const pattern of patterns) {
1146
- if (pattern.includes('*')) {
1147
- const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
1148
- const files = fs.readdirSync('.').filter(f => regex.test(f));
1149
- toDelete.push(...files);
1150
- }
1151
- else if (fs.existsSync(pattern)) {
1152
- toDelete.push(pattern);
1153
- }
1154
- }
1155
- if (toDelete.length === 0) {
1156
- console.log(chalk.dim('No generated files to clean.'));
1157
- return;
1158
- }
1159
- console.log(fmt.header('Clean'));
1160
- console.log();
1161
- for (const file of toDelete) {
1162
- if (options.dryRun) {
1163
- console.log(chalk.dim(` Would delete: ${file}`));
1164
- }
1165
- else {
1166
- fs.unlinkSync(file);
1167
- console.log(chalk.red(` Deleted: ${file}`));
1168
- }
1169
- }
1170
- console.log();
1171
- if (options.dryRun) {
1172
- console.log(chalk.dim(`Would delete ${toDelete.length} file(s). Run without --dry-run to delete.`));
1173
- }
1174
- else {
1175
- console.log(fmt.status('success', `Cleaned ${toDelete.length} file(s)`));
1176
- }
1177
- });
1178
- // ==========================================================================
1179
- // CHECK command - Pre-submission check
1180
- // ==========================================================================
1181
- program
1182
- .command('check')
1183
- .description('Run all checks before submission (lint + grammar + citations)')
1184
- .option('--fix', 'Auto-fix issues where possible')
1185
- .option('-s, --severity <level>', 'Minimum grammar severity', 'warning')
1186
- .action(async (options) => {
1187
- const { validateCitations } = await import('../citations.js');
1188
- const { checkGrammar, getGrammarSummary } = await import('../grammar.js');
1189
- console.log(fmt.header('Pre-Submission Check'));
1190
- console.log();
1191
- let hasErrors = false;
1192
- let totalIssues = 0;
1193
- // 1. Run lint
1194
- console.log(chalk.cyan.bold('1. Linting...'));
1195
- let config = {};
1196
- try {
1197
- config = loadBuildConfig('.') || {};
1198
- }
1199
- catch {
1200
- // Not in a rev project
1201
- }
1202
- let sections = config.sections || [];
1203
- if (sections.length === 0) {
1204
- sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
1205
- }
1206
- const lintIssues = [];
1207
- const lintWarnings = [];
1208
- for (const file of sections) {
1209
- if (!fs.existsSync(file))
1210
- continue;
1211
- const content = fs.readFileSync(file, 'utf-8');
1212
- // Check for broken cross-references
1213
- const refs = content.match(/@(fig|tbl|eq|sec):\w+/g) || [];
1214
- const anchors = content.match(/\{#(fig|tbl|eq|sec):[^}]+\}/g) || [];
1215
- const anchorLabels = anchors.map(a => a.match(/#([^}]+)/)[1]);
1216
- for (const ref of refs) {
1217
- const label = ref.slice(1);
1218
- if (!anchorLabels.includes(label)) {
1219
- lintIssues.push({ file, message: `Broken reference: ${ref}` });
1220
- }
1221
- }
1222
- // Check for unresolved comments
1223
- const unresolvedComments = (content.match(/\{>>[^<]*<<\}/g) || [])
1224
- .filter(c => !c.includes('[RESOLVED]'));
1225
- if (unresolvedComments.length > 0) {
1226
- lintWarnings.push({ file, message: `${unresolvedComments.length} unresolved comment(s)` });
1227
- }
1228
- }
1229
- if (lintIssues.length > 0) {
1230
- for (const issue of lintIssues) {
1231
- console.log(chalk.red(` ✗ ${issue.file}: ${issue.message}`));
1232
- }
1233
- hasErrors = true;
1234
- totalIssues += lintIssues.length;
1235
- }
1236
- for (const warning of lintWarnings) {
1237
- console.log(chalk.yellow(` ⚠ ${warning.file}: ${warning.message}`));
1238
- totalIssues++;
1239
- }
1240
- if (lintIssues.length === 0 && lintWarnings.length === 0) {
1241
- console.log(chalk.green(' ✓ No lint issues'));
1242
- }
1243
- console.log();
1244
- // 2. Run grammar check
1245
- console.log(chalk.cyan.bold('2. Grammar check...'));
1246
- const severityLevels = { error: 3, warning: 2, info: 1 };
1247
- const minSeverity = severityLevels[options.severity || 'warning'] || 2;
1248
- let grammarIssues = [];
1249
- for (const file of sections) {
1250
- if (!fs.existsSync(file))
1251
- continue;
1252
- const text = fs.readFileSync(file, 'utf-8');
1253
- const issues = checkGrammar(text, { scientific: true });
1254
- const filtered = issues.filter((i) => severityLevels[i.severity] >= minSeverity);
1255
- grammarIssues.push(...filtered.map(i => ({ ...i, file })));
1256
- }
1257
- const grammarSummary = getGrammarSummary(grammarIssues);
1258
- if (grammarSummary.errors > 0) {
1259
- hasErrors = true;
1260
- }
1261
- totalIssues += grammarSummary.total;
1262
- if (grammarSummary.total > 0) {
1263
- console.log(chalk.yellow(` ⚠ ${grammarSummary.total} grammar issue(s): ${grammarSummary.errors} errors, ${grammarSummary.warnings} warnings`));
1264
- }
1265
- else {
1266
- console.log(chalk.green(' ✓ No grammar issues'));
1267
- }
1268
- console.log();
1269
- // 3. Run citation check
1270
- console.log(chalk.cyan.bold('3. Citation check...'));
1271
- const bibFile = config.bibliography || 'references.bib';
1272
- if (fs.existsSync(bibFile)) {
1273
- const existingSections = sections.filter(f => fs.existsSync(f));
1274
- const result = validateCitations(existingSections, bibFile);
1275
- if (result.missing.length > 0) {
1276
- console.log(chalk.red(` ✗ ${result.missing.length} missing citation(s): ${result.missing.slice(0, 3).join(', ')}${result.missing.length > 3 ? '...' : ''}`));
1277
- hasErrors = true;
1278
- totalIssues += result.missing.length;
1279
- }
1280
- if (result.unused.length > 0) {
1281
- console.log(chalk.yellow(` ⚠ ${result.unused.length} unused citation(s)`));
1282
- totalIssues += result.unused.length;
1283
- }
1284
- if (result.missing.length === 0 && result.unused.length === 0) {
1285
- console.log(chalk.green(' ✓ All citations valid'));
1286
- }
1287
- }
1288
- else {
1289
- console.log(chalk.dim(' - No bibliography file found'));
1290
- }
1291
- console.log();
1292
- // Summary
1293
- console.log(chalk.bold('Summary'));
1294
- if (hasErrors) {
1295
- console.log(chalk.red(` ${totalIssues} issue(s) found. Please fix before submission.`));
1296
- process.exit(1);
1297
- }
1298
- else if (totalIssues > 0) {
1299
- console.log(chalk.yellow(` ${totalIssues} warning(s). Review before submission.`));
1300
- }
1301
- else {
1302
- console.log(chalk.green(' ✓ All checks passed! Ready for submission.'));
1303
- }
1304
- });
1305
- // ==========================================================================
1306
82
  // OPEN command - Open project folder or file
1307
83
  // ==========================================================================
1308
84
  program
@@ -1389,200 +165,6 @@ export function register(program, pkg) {
1389
165
  }
1390
166
  });
1391
167
  // ==========================================================================
1392
- // SPELLING command - Spellcheck with global dictionary
1393
- // ==========================================================================
1394
- program
1395
- .command('spelling')
1396
- .description('Check spelling in markdown files')
1397
- .argument('[files...]', 'Files to check (default: section files)')
1398
- .option('--learn <word>', 'Add word to global dictionary')
1399
- .option('--learn-project <word>', 'Add word to project dictionary')
1400
- .option('--forget <word>', 'Remove word from global dictionary')
1401
- .option('--forget-project <word>', 'Remove word from project dictionary')
1402
- .option('--list', 'List global dictionary words')
1403
- .option('--list-project', 'List project dictionary words')
1404
- .option('--list-all', 'List all custom words (global + project)')
1405
- .option('--british', 'Use British English dictionary')
1406
- .option('--add-names', 'Add detected names to global dictionary')
1407
- .action(async (files, options) => {
1408
- const spelling = await import('../spelling.js');
1409
- // Handle dictionary management
1410
- if (options.learn) {
1411
- const added = spelling.addWord(options.learn, true);
1412
- if (added) {
1413
- console.log(fmt.status('success', `Added "${options.learn}" to global dictionary`));
1414
- }
1415
- else {
1416
- console.log(chalk.yellow(`"${options.learn}" already in dictionary`));
1417
- }
1418
- return;
1419
- }
1420
- if (options.learnProject) {
1421
- const added = spelling.addWord(options.learnProject, false);
1422
- if (added) {
1423
- console.log(fmt.status('success', `Added "${options.learnProject}" to project dictionary`));
1424
- }
1425
- else {
1426
- console.log(chalk.yellow(`"${options.learnProject}" already in dictionary`));
1427
- }
1428
- return;
1429
- }
1430
- if (options.forget) {
1431
- const removed = spelling.removeWord(options.forget, true);
1432
- if (removed) {
1433
- console.log(fmt.status('success', `Removed "${options.forget}" from global dictionary`));
1434
- }
1435
- else {
1436
- console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
1437
- }
1438
- return;
1439
- }
1440
- if (options.forgetProject) {
1441
- const removed = spelling.removeWord(options.forgetProject, false);
1442
- if (removed) {
1443
- console.log(fmt.status('success', `Removed "${options.forgetProject}" from project dictionary`));
1444
- }
1445
- else {
1446
- console.log(chalk.yellow(`"${options.forgetProject}" not in dictionary`));
1447
- }
1448
- return;
1449
- }
1450
- if (options.list) {
1451
- const words = spelling.listWords(true);
1452
- console.log(fmt.header('Global Dictionary'));
1453
- if (words.length === 0) {
1454
- console.log(chalk.dim(' No custom words'));
1455
- console.log(chalk.dim(' Use --learn <word> to add words'));
1456
- }
1457
- else {
1458
- for (const word of words) {
1459
- console.log(` ${word}`);
1460
- }
1461
- console.log(chalk.dim(`\n${words.length} word(s)`));
1462
- }
1463
- return;
1464
- }
1465
- if (options.listProject) {
1466
- const words = spelling.listWords(false);
1467
- console.log(fmt.header('Project Dictionary'));
1468
- if (words.length === 0) {
1469
- console.log(chalk.dim(' No custom words'));
1470
- console.log(chalk.dim(' Use --learn-project <word> to add words'));
1471
- }
1472
- else {
1473
- for (const word of words) {
1474
- console.log(` ${word}`);
1475
- }
1476
- console.log(chalk.dim(`\n${words.length} word(s)`));
1477
- }
1478
- return;
1479
- }
1480
- if (options.listAll) {
1481
- const globalWords = spelling.listWords(true);
1482
- const projectWords = spelling.listWords(false);
1483
- console.log(fmt.header('Global Dictionary'));
1484
- if (globalWords.length === 0) {
1485
- console.log(chalk.dim(' No custom words'));
1486
- }
1487
- else {
1488
- for (const word of globalWords) {
1489
- console.log(` ${word}`);
1490
- }
1491
- }
1492
- console.log(fmt.header('Project Dictionary'));
1493
- if (projectWords.length === 0) {
1494
- console.log(chalk.dim(' No custom words'));
1495
- }
1496
- else {
1497
- for (const word of projectWords) {
1498
- console.log(` ${word}`);
1499
- }
1500
- }
1501
- console.log(chalk.dim(`\nTotal: ${globalWords.length + projectWords.length} word(s)`));
1502
- return;
1503
- }
1504
- // Check spelling in files
1505
- let filesToCheck = files || [];
1506
- if (filesToCheck.length === 0) {
1507
- if (fs.existsSync('rev.yaml')) {
1508
- try {
1509
- const config = loadBuildConfig('.');
1510
- filesToCheck = config?.sections || [];
1511
- }
1512
- catch {
1513
- // Ignore errors
1514
- }
1515
- if (filesToCheck.length === 0) {
1516
- filesToCheck = fs.readdirSync('.')
1517
- .filter(f => f.endsWith('.md') && !f.startsWith('.'));
1518
- }
1519
- }
1520
- else {
1521
- filesToCheck = fs.readdirSync('.')
1522
- .filter(f => f.endsWith('.md') && !f.startsWith('.'));
1523
- }
1524
- }
1525
- if (filesToCheck.length === 0) {
1526
- console.log(chalk.yellow('No markdown files found'));
1527
- return;
1528
- }
1529
- const lang = options.british ? 'en-gb' : 'en';
1530
- console.log(fmt.header(`Spelling Check (${options.british ? 'British' : 'US'} English)`));
1531
- let totalMisspelled = 0;
1532
- const allNames = new Set();
1533
- for (const file of filesToCheck) {
1534
- if (!fs.existsSync(file)) {
1535
- console.log(chalk.yellow(`File not found: ${file}`));
1536
- continue;
1537
- }
1538
- const result = await spelling.checkFile(file, { projectDir: '.', lang });
1539
- const { misspelled, possibleNames } = result;
1540
- // Collect names
1541
- for (const n of possibleNames) {
1542
- allNames.add(n.word);
1543
- }
1544
- if (misspelled.length > 0) {
1545
- console.log(chalk.cyan(`\n${file}:`));
1546
- for (const issue of misspelled) {
1547
- const suggestions = issue.suggestions.length > 0
1548
- ? chalk.dim(` → ${issue.suggestions.join(', ')}`)
1549
- : '';
1550
- console.log(` ${chalk.yellow(issue.word)} ${chalk.dim(`(line ${issue.line})`)}${suggestions}`);
1551
- }
1552
- totalMisspelled += misspelled.length;
1553
- }
1554
- }
1555
- // Show possible names separately
1556
- if (allNames.size > 0) {
1557
- const nameList = [...allNames].sort();
1558
- if (options.addNames) {
1559
- console.log(fmt.header('Adding Names to Dictionary'));
1560
- for (const name of nameList) {
1561
- spelling.addWord(name, true);
1562
- console.log(chalk.green(` ✓ ${name}`));
1563
- }
1564
- console.log(chalk.dim(`\nAdded ${nameList.length} name(s) to global dictionary`));
1565
- }
1566
- else {
1567
- console.log(fmt.header('Possible Names'));
1568
- console.log(chalk.dim(` ${nameList.join(', ')}`));
1569
- console.log(chalk.dim(`\n Run with --add-names to add all to dictionary`));
1570
- }
1571
- }
1572
- if (totalMisspelled === 0 && allNames.size === 0) {
1573
- console.log(fmt.status('success', 'No spelling errors found'));
1574
- }
1575
- else {
1576
- if (totalMisspelled > 0) {
1577
- console.log(chalk.yellow(`\n${totalMisspelled} spelling error(s)`));
1578
- }
1579
- if (allNames.size > 0) {
1580
- console.log(chalk.blue(`${allNames.size} possible name(s)`));
1581
- }
1582
- console.log(chalk.dim('Use --learn <word> to add words to dictionary'));
1583
- }
1584
- });
1585
- // ==========================================================================
1586
168
  // UPGRADE command - Self-update via npm
1587
169
  // ==========================================================================
1588
170
  program
@@ -1644,157 +226,6 @@ export function register(program, pkg) {
1644
226
  process.exit(1);
1645
227
  }
1646
228
  });
1647
- // ==========================================================================
1648
- // BATCH command - Run operations on multiple documents
1649
- // ==========================================================================
1650
- program
1651
- .command('batch')
1652
- .description('Run operations on multiple documents')
1653
- .argument('<command>', 'Command to run (status, strip, resolve)')
1654
- .argument('[pattern]', 'File pattern (default: *.md)')
1655
- .option('--parallel', 'Run operations in parallel')
1656
- .option('--dry-run', 'Preview files without running')
1657
- .option('-a, --all', 'Include all .md files (not just sections)')
1658
- .action(async (command, pattern, options) => {
1659
- const validCommands = ['status', 'strip', 'resolve', 'comments'];
1660
- if (!validCommands.includes(command)) {
1661
- console.error(fmt.status('error', `Unknown batch command: ${command}`));
1662
- console.error(chalk.dim(`Available: ${validCommands.join(', ')}`));
1663
- process.exit(1);
1664
- }
1665
- // Find files
1666
- let files = [];
1667
- if (pattern) {
1668
- if (pattern.includes('*')) {
1669
- files = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
1670
- }
1671
- else {
1672
- files = [pattern];
1673
- }
1674
- }
1675
- else {
1676
- files = fs.readdirSync('.').filter(f => f.endsWith('.md') &&
1677
- (options.all || !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)));
1678
- }
1679
- if (files.length === 0) {
1680
- console.error(fmt.status('error', 'No files found'));
1681
- process.exit(1);
1682
- }
1683
- console.log(fmt.header(`Batch ${command} on ${files.length} file(s)`));
1684
- console.log();
1685
- if (options.dryRun) {
1686
- console.log(chalk.dim('Dry run - files that would be processed:'));
1687
- for (const file of files) {
1688
- console.log(chalk.dim(` ${file}`));
1689
- }
1690
- return;
1691
- }
1692
- // Process files
1693
- const results = [];
1694
- const progressBar = fmt.progressBar(files.length, 'Processing');
1695
- progressBar.update(0);
1696
- for (let i = 0; i < files.length; i++) {
1697
- const file = files[i];
1698
- progressBar.update(i + 1);
1699
- if (!fs.existsSync(file)) {
1700
- results.push({ file, status: 'not found' });
1701
- continue;
1702
- }
1703
- try {
1704
- const text = fs.readFileSync(file, 'utf-8');
1705
- let result = { file, status: 'ok' };
1706
- switch (command) {
1707
- case 'status': {
1708
- const counts = countAnnotations(text);
1709
- const comments = getComments(text);
1710
- result.annotations = counts.total;
1711
- result.comments = comments.length;
1712
- result.pending = comments.filter(c => !c.resolved).length;
1713
- break;
1714
- }
1715
- case 'comments': {
1716
- const comments = getComments(text);
1717
- result.total = comments.length;
1718
- result.pending = comments.filter(c => !c.resolved).length;
1719
- result.resolved = comments.filter(c => c.resolved).length;
1720
- break;
1721
- }
1722
- case 'resolve': {
1723
- const comments = getComments(text);
1724
- const pending = comments.filter(c => !c.resolved);
1725
- if (pending.length > 0) {
1726
- let newText = text;
1727
- for (const c of pending) {
1728
- newText = setCommentStatus(newText, c, true);
1729
- }
1730
- fs.writeFileSync(file, newText, 'utf-8');
1731
- result.resolved = pending.length;
1732
- }
1733
- else {
1734
- result.resolved = 0;
1735
- }
1736
- break;
1737
- }
1738
- case 'strip': {
1739
- const clean = stripAnnotations(text, { keepComments: false });
1740
- const hasChanges = clean !== text;
1741
- if (hasChanges) {
1742
- fs.writeFileSync(file, clean, 'utf-8');
1743
- result.stripped = true;
1744
- }
1745
- else {
1746
- result.stripped = false;
1747
- }
1748
- break;
1749
- }
1750
- }
1751
- results.push(result);
1752
- }
1753
- catch (err) {
1754
- results.push({ file, status: 'error', error: err.message });
1755
- }
1756
- }
1757
- progressBar.done();
1758
- console.log();
1759
- // Show results
1760
- console.log(fmt.header('Results'));
1761
- console.log();
1762
- for (const r of results) {
1763
- const statusIcon = r.status === 'ok'
1764
- ? chalk.green('✓')
1765
- : r.status === 'error'
1766
- ? chalk.red('✗')
1767
- : chalk.yellow('?');
1768
- let details = '';
1769
- switch (command) {
1770
- case 'status':
1771
- details = chalk.dim(`${r.annotations || 0} annotations, ${r.pending || 0} pending comments`);
1772
- break;
1773
- case 'comments':
1774
- details = chalk.dim(`${r.total || 0} total, ${r.pending || 0} pending`);
1775
- break;
1776
- case 'resolve':
1777
- details = r.resolved && r.resolved > 0
1778
- ? chalk.green(`${r.resolved} resolved`)
1779
- : chalk.dim('no pending');
1780
- break;
1781
- case 'strip':
1782
- details = r.stripped
1783
- ? chalk.green('cleaned')
1784
- : chalk.dim('no changes');
1785
- break;
1786
- }
1787
- console.log(` ${statusIcon} ${r.file} ${details}`);
1788
- if (r.error) {
1789
- console.log(chalk.red(` ${r.error}`));
1790
- }
1791
- }
1792
- // Summary
1793
- console.log();
1794
- const successful = results.filter(r => r.status === 'ok').length;
1795
- const failed = results.filter(r => r.status === 'error').length;
1796
- console.log(chalk.dim(`${successful} succeeded, ${failed} failed`));
1797
- });
1798
229
  }
1799
230
  // Helper functions for help text
1800
231
  function showFullHelp(pkg) {