docrev 0.9.5 → 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 (76) hide show
  1. package/dist/lib/commands/file-ops.d.ts +11 -0
  2. package/dist/lib/commands/file-ops.d.ts.map +1 -0
  3. package/dist/lib/commands/file-ops.js +301 -0
  4. package/dist/lib/commands/file-ops.js.map +1 -0
  5. package/dist/lib/commands/index.d.ts +9 -1
  6. package/dist/lib/commands/index.d.ts.map +1 -1
  7. package/dist/lib/commands/index.js +17 -1
  8. package/dist/lib/commands/index.js.map +1 -1
  9. package/dist/lib/commands/merge-resolve.d.ts +12 -0
  10. package/dist/lib/commands/merge-resolve.d.ts.map +1 -0
  11. package/dist/lib/commands/merge-resolve.js +318 -0
  12. package/dist/lib/commands/merge-resolve.js.map +1 -0
  13. package/dist/lib/commands/preview.d.ts +11 -0
  14. package/dist/lib/commands/preview.d.ts.map +1 -0
  15. package/dist/lib/commands/preview.js +138 -0
  16. package/dist/lib/commands/preview.js.map +1 -0
  17. package/dist/lib/commands/project-info.d.ts +11 -0
  18. package/dist/lib/commands/project-info.d.ts.map +1 -0
  19. package/dist/lib/commands/project-info.js +187 -0
  20. package/dist/lib/commands/project-info.js.map +1 -0
  21. package/dist/lib/commands/quality.d.ts +11 -0
  22. package/dist/lib/commands/quality.d.ts.map +1 -0
  23. package/dist/lib/commands/quality.js +384 -0
  24. package/dist/lib/commands/quality.js.map +1 -0
  25. package/dist/lib/commands/sections.d.ts +3 -2
  26. package/dist/lib/commands/sections.d.ts.map +1 -1
  27. package/dist/lib/commands/sections.js +4 -736
  28. package/dist/lib/commands/sections.js.map +1 -1
  29. package/dist/lib/commands/sync.d.ts +11 -0
  30. package/dist/lib/commands/sync.d.ts.map +1 -0
  31. package/dist/lib/commands/sync.js +441 -0
  32. package/dist/lib/commands/sync.js.map +1 -0
  33. package/dist/lib/commands/text-ops.d.ts +11 -0
  34. package/dist/lib/commands/text-ops.d.ts.map +1 -0
  35. package/dist/lib/commands/text-ops.js +357 -0
  36. package/dist/lib/commands/text-ops.js.map +1 -0
  37. package/dist/lib/commands/utilities.d.ts +2 -4
  38. package/dist/lib/commands/utilities.d.ts.map +1 -1
  39. package/dist/lib/commands/utilities.js +3 -1572
  40. package/dist/lib/commands/utilities.js.map +1 -1
  41. package/dist/lib/commands/word-tools.d.ts +11 -0
  42. package/dist/lib/commands/word-tools.d.ts.map +1 -0
  43. package/dist/lib/commands/word-tools.js +272 -0
  44. package/dist/lib/commands/word-tools.js.map +1 -0
  45. package/dist/lib/diff-engine.d.ts +25 -0
  46. package/dist/lib/diff-engine.d.ts.map +1 -0
  47. package/dist/lib/diff-engine.js +354 -0
  48. package/dist/lib/diff-engine.js.map +1 -0
  49. package/dist/lib/import.d.ts +37 -117
  50. package/dist/lib/import.d.ts.map +1 -1
  51. package/dist/lib/import.js +10 -1030
  52. package/dist/lib/import.js.map +1 -1
  53. package/dist/lib/restore-references.d.ts +35 -0
  54. package/dist/lib/restore-references.d.ts.map +1 -0
  55. package/dist/lib/restore-references.js +188 -0
  56. package/dist/lib/restore-references.js.map +1 -0
  57. package/dist/lib/word-extraction.d.ts +77 -0
  58. package/dist/lib/word-extraction.d.ts.map +1 -0
  59. package/dist/lib/word-extraction.js +515 -0
  60. package/dist/lib/word-extraction.js.map +1 -0
  61. package/lib/commands/file-ops.ts +372 -0
  62. package/lib/commands/index.ts +24 -0
  63. package/lib/commands/merge-resolve.ts +378 -0
  64. package/lib/commands/preview.ts +178 -0
  65. package/lib/commands/project-info.ts +244 -0
  66. package/lib/commands/quality.ts +517 -0
  67. package/lib/commands/sections.ts +3 -870
  68. package/lib/commands/sync.ts +536 -0
  69. package/lib/commands/text-ops.ts +449 -0
  70. package/lib/commands/utilities.ts +62 -2043
  71. package/lib/commands/word-tools.ts +340 -0
  72. package/lib/diff-engine.ts +465 -0
  73. package/lib/import.ts +78 -1338
  74. package/lib/restore-references.ts +240 -0
  75. package/lib/word-extraction.ts +666 -0
  76. package/package.json +1 -1
@@ -0,0 +1,517 @@
1
+ /**
2
+ * Quality commands: lint, grammar, check
3
+ *
4
+ * Commands for checking project quality before submission.
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ loadBuildConfig,
14
+ getComments,
15
+ } from './context.js';
16
+
17
+ // Use the actual BuildConfig from build.ts which allows string|Author[]
18
+ type BuildConfig = ReturnType<typeof loadBuildConfig>;
19
+
20
+ // Options interfaces
21
+ interface LintOptions {
22
+ fix?: boolean;
23
+ }
24
+
25
+ interface GrammarOptions {
26
+ learn?: string;
27
+ forget?: string;
28
+ list?: boolean;
29
+ rules?: boolean;
30
+ scientific?: boolean;
31
+ severity?: string;
32
+ }
33
+
34
+ interface CheckOptions {
35
+ fix?: boolean;
36
+ severity?: string;
37
+ }
38
+
39
+ // Grammar issue interface (from grammar.ts)
40
+ interface GrammarIssue {
41
+ rule: string;
42
+ severity: 'error' | 'warning' | 'info';
43
+ message: string;
44
+ line: number;
45
+ column: number;
46
+ match: string;
47
+ context: string;
48
+ file?: string;
49
+ }
50
+
51
+ // Grammar summary interface (from grammar.ts)
52
+ interface GrammarSummary {
53
+ total: number;
54
+ errors: number;
55
+ warnings: number;
56
+ info: number;
57
+ byRule?: Record<string, number>;
58
+ }
59
+
60
+ // Lint issue interface
61
+ interface LintIssue {
62
+ type: 'error' | 'warning';
63
+ message: string;
64
+ fix?: string | null;
65
+ file?: string;
66
+ }
67
+
68
+ // Build result interface - matches build.ts export
69
+ interface BuildResult {
70
+ format: string;
71
+ success: boolean;
72
+ outputPath?: string;
73
+ error?: string;
74
+ }
75
+
76
+ // Full build result interface - matches build.ts FullBuildResult
77
+ interface FullBuildResult {
78
+ results: BuildResult[];
79
+ paperPath: string;
80
+ warnings: string[];
81
+ forwardRefsResolved: number;
82
+ refsAutoInjected?: boolean;
83
+ }
84
+
85
+ /**
86
+ * Register quality commands with the program
87
+ */
88
+ export function register(program: Command): void {
89
+ // ==========================================================================
90
+ // LINT command - Check for common issues
91
+ // ==========================================================================
92
+
93
+ program
94
+ .command('lint')
95
+ .description('Check for common issues in the project')
96
+ .option('--fix', 'Auto-fix issues where possible')
97
+ .action(async (_options: LintOptions) => {
98
+ let config: Partial<BuildConfig> = {};
99
+ try {
100
+ config = loadBuildConfig('.') || {};
101
+ } catch {
102
+ // Not in a rev project, that's ok
103
+ }
104
+ let sections = config.sections || [];
105
+
106
+ if (sections.length === 0) {
107
+ sections = fs.readdirSync('.').filter(f =>
108
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
109
+ );
110
+ }
111
+
112
+ const issues: LintIssue[] = [];
113
+ const warnings: LintIssue[] = [];
114
+
115
+ // Collect all content
116
+ let allText = '';
117
+ for (const section of sections) {
118
+ if (fs.existsSync(section)) {
119
+ allText += fs.readFileSync(section, 'utf-8') + '\n';
120
+ }
121
+ }
122
+
123
+ // Check 1: Broken cross-references
124
+ const figAnchors = new Set<string>();
125
+ const tblAnchors = new Set<string>();
126
+ const eqAnchors = new Set<string>();
127
+
128
+ const anchorPattern = /\{#(fig|tbl|eq):([^}]+)\}/g;
129
+ let match: RegExpExecArray | null;
130
+ while ((match = anchorPattern.exec(allText)) !== null) {
131
+ if (match[1] === 'fig') figAnchors.add(match[2]);
132
+ else if (match[1] === 'tbl') tblAnchors.add(match[2]);
133
+ else if (match[1] === 'eq') eqAnchors.add(match[2]);
134
+ }
135
+
136
+ const refPattern = /@(fig|tbl|eq):([a-zA-Z0-9_-]+)/g;
137
+ while ((match = refPattern.exec(allText)) !== null) {
138
+ const type = match[1];
139
+ const label = match[2];
140
+ const anchors = type === 'fig' ? figAnchors : type === 'tbl' ? tblAnchors : eqAnchors;
141
+
142
+ if (!anchors.has(label)) {
143
+ issues.push({
144
+ type: 'error',
145
+ message: `Broken reference: @${type}:${label}`,
146
+ fix: null
147
+ });
148
+ }
149
+ }
150
+
151
+ // Check 2: Orphaned figures
152
+ for (const label of figAnchors) {
153
+ if (!allText.includes(`@fig:${label}`)) {
154
+ warnings.push({
155
+ type: 'warning',
156
+ message: `Unreferenced figure: {#fig:${label}}`,
157
+ });
158
+ }
159
+ }
160
+
161
+ // Check 3: Missing citations
162
+ const bibPath = config.bibliography || 'references.bib';
163
+ if (fs.existsSync(bibPath)) {
164
+ const bibContent = fs.readFileSync(bibPath, 'utf-8');
165
+ const bibKeys = new Set<string>();
166
+ const bibPattern = /@\w+\s*\{\s*([^,]+)/g;
167
+ while ((match = bibPattern.exec(bibContent)) !== null) {
168
+ bibKeys.add(match[1].trim());
169
+ }
170
+
171
+ const citePattern = /@([a-zA-Z][a-zA-Z0-9_-]*)(?![:\w])/g;
172
+ while ((match = citePattern.exec(allText)) !== null) {
173
+ const key = match[1];
174
+ if (!bibKeys.has(key) && !['fig', 'tbl', 'eq'].includes(key)) {
175
+ issues.push({
176
+ type: 'error',
177
+ message: `Missing citation: @${key}`,
178
+ });
179
+ }
180
+ }
181
+ }
182
+
183
+ // Check 4: Unresolved comments
184
+ const comments = getComments(allText);
185
+ const pending = comments.filter(c => !c.resolved);
186
+ if (pending.length > 0) {
187
+ warnings.push({
188
+ type: 'warning',
189
+ message: `${pending.length} unresolved comment${pending.length === 1 ? '' : 's'}`,
190
+ });
191
+ }
192
+
193
+ // Check 5: Empty sections
194
+ for (const section of sections) {
195
+ if (fs.existsSync(section)) {
196
+ const content = fs.readFileSync(section, 'utf-8').trim();
197
+ if (content.length < 50) {
198
+ warnings.push({
199
+ type: 'warning',
200
+ message: `Section appears empty: ${section}`,
201
+ });
202
+ }
203
+ }
204
+ }
205
+
206
+ // Output results
207
+ console.log(fmt.header('Lint Results'));
208
+ console.log();
209
+
210
+ if (issues.length === 0 && warnings.length === 0) {
211
+ console.log(chalk.green('✓ No issues found'));
212
+ return;
213
+ }
214
+
215
+ for (const issue of issues) {
216
+ console.log(chalk.red(` ✗ ${issue.message}`));
217
+ }
218
+
219
+ for (const warning of warnings) {
220
+ console.log(chalk.yellow(` ⚠ ${warning.message}`));
221
+ }
222
+
223
+ console.log();
224
+ console.log(chalk.dim(`${issues.length} error${issues.length === 1 ? '' : 's'}, ${warnings.length} warning${warnings.length === 1 ? '' : 's'}`));
225
+
226
+ if (issues.length > 0) {
227
+ process.exit(1);
228
+ }
229
+ });
230
+
231
+ // ==========================================================================
232
+ // GRAMMAR command - Check grammar and style
233
+ // ==========================================================================
234
+
235
+ program
236
+ .command('grammar')
237
+ .description('Check grammar and style issues')
238
+ .argument('[files...]', 'Markdown files to check')
239
+ .option('--learn <word>', 'Add word to custom dictionary')
240
+ .option('--forget <word>', 'Remove word from custom dictionary')
241
+ .option('--list', 'List custom dictionary words')
242
+ .option('--rules', 'List available grammar rules')
243
+ .option('--no-scientific', 'Disable scientific writing rules')
244
+ .option('-s, --severity <level>', 'Minimum severity: error, warning, info', 'info')
245
+ .action(async (files: string[] | undefined, options: GrammarOptions) => {
246
+ const {
247
+ checkGrammar,
248
+ getGrammarSummary,
249
+ loadDictionary,
250
+ addToDictionary,
251
+ removeFromDictionary,
252
+ listRules,
253
+ } = await import('../grammar.js');
254
+
255
+ // Handle dictionary management
256
+ if (options.learn) {
257
+ const added = addToDictionary(options.learn);
258
+ if (added) {
259
+ console.log(fmt.status('success', `Added "${options.learn}" to dictionary`));
260
+ } else {
261
+ console.log(chalk.dim(`"${options.learn}" already in dictionary`));
262
+ }
263
+ return;
264
+ }
265
+
266
+ if (options.forget) {
267
+ const removed = removeFromDictionary(options.forget);
268
+ if (removed) {
269
+ console.log(fmt.status('success', `Removed "${options.forget}" from dictionary`));
270
+ } else {
271
+ console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
272
+ }
273
+ return;
274
+ }
275
+
276
+ if (options.list) {
277
+ const words = loadDictionary();
278
+ console.log(fmt.header('Custom Dictionary'));
279
+ console.log();
280
+ if (words.size === 0) {
281
+ console.log(chalk.dim(' No custom words defined'));
282
+ console.log(chalk.dim(' Use --learn <word> to add words'));
283
+ } else {
284
+ const sorted = [...words].sort();
285
+ for (const word of sorted) {
286
+ console.log(` ${word}`);
287
+ }
288
+ console.log();
289
+ console.log(chalk.dim(`${words.size} word(s)`));
290
+ }
291
+ return;
292
+ }
293
+
294
+ if (options.rules) {
295
+ const rules = listRules(options.scientific);
296
+ console.log(fmt.header('Grammar Rules'));
297
+ console.log();
298
+ for (const rule of rules) {
299
+ const icon = rule.severity === 'error' ? chalk.red('●') :
300
+ rule.severity === 'warning' ? chalk.yellow('●') :
301
+ chalk.blue('●');
302
+ console.log(` ${icon} ${chalk.bold(rule.id)}`);
303
+ console.log(chalk.dim(` ${rule.message}`));
304
+ }
305
+ return;
306
+ }
307
+
308
+ // Get files to check
309
+ let mdFiles = files;
310
+ if (!mdFiles || mdFiles.length === 0) {
311
+ let config: Partial<BuildConfig> = {};
312
+ try {
313
+ config = loadBuildConfig('.') || {};
314
+ } catch {
315
+ // Not in a rev project
316
+ }
317
+ mdFiles = config.sections || [];
318
+
319
+ if (mdFiles.length === 0) {
320
+ mdFiles = fs.readdirSync('.').filter(f =>
321
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
322
+ );
323
+ }
324
+ }
325
+
326
+ if (mdFiles.length === 0) {
327
+ console.error(chalk.red('No markdown files found'));
328
+ process.exit(1);
329
+ }
330
+
331
+ console.log(fmt.header('Grammar Check'));
332
+ console.log();
333
+
334
+ const severityLevels: Record<string, number> = { error: 3, warning: 2, info: 1 };
335
+ const minSeverity = severityLevels[options.severity || 'info'] || 1;
336
+
337
+ let allIssues: GrammarIssue[] = [];
338
+
339
+ for (const file of mdFiles) {
340
+ if (!fs.existsSync(file)) continue;
341
+
342
+ const text = fs.readFileSync(file, 'utf-8');
343
+ const issues = checkGrammar(text, { scientific: options.scientific });
344
+
345
+ // Filter by severity
346
+ const filtered = issues.filter((i: GrammarIssue) => severityLevels[i.severity] >= minSeverity);
347
+
348
+ if (filtered.length > 0) {
349
+ console.log(chalk.cyan.bold(file));
350
+
351
+ for (const issue of filtered) {
352
+ const icon = issue.severity === 'error' ? chalk.red('●') :
353
+ issue.severity === 'warning' ? chalk.yellow('●') :
354
+ chalk.blue('●');
355
+
356
+ console.log(` ${chalk.dim(`L${issue.line}:`)} ${icon} ${issue.message}`);
357
+ console.log(chalk.dim(` "${issue.match}" in: ${issue.context.slice(0, 60)}...`));
358
+ }
359
+ console.log();
360
+ allIssues.push(...filtered.map(i => ({ ...i, file })));
361
+ }
362
+ }
363
+
364
+ const summary = getGrammarSummary(allIssues);
365
+
366
+ if (summary.total === 0) {
367
+ console.log(chalk.green('✓ No issues found'));
368
+ } else {
369
+ console.log(chalk.dim(`Found ${summary.total} issue(s): ${summary.errors} errors, ${summary.warnings} warnings, ${summary.info} info`));
370
+ console.log();
371
+ console.log(chalk.dim('Tip: Use --learn <word> to add words to dictionary'));
372
+ }
373
+ });
374
+
375
+ // ==========================================================================
376
+ // CHECK command - Pre-submission check
377
+ // ==========================================================================
378
+
379
+ program
380
+ .command('check')
381
+ .description('Run all checks before submission (lint + grammar + citations)')
382
+ .option('--fix', 'Auto-fix issues where possible')
383
+ .option('-s, --severity <level>', 'Minimum grammar severity', 'warning')
384
+ .action(async (options: CheckOptions) => {
385
+ const { validateCitations } = await import('../citations.js');
386
+ const { checkGrammar, getGrammarSummary } = await import('../grammar.js');
387
+
388
+ console.log(fmt.header('Pre-Submission Check'));
389
+ console.log();
390
+
391
+ let hasErrors = false;
392
+ let totalIssues = 0;
393
+
394
+ // 1. Run lint
395
+ console.log(chalk.cyan.bold('1. Linting...'));
396
+ let config: Partial<BuildConfig> = {};
397
+ try {
398
+ config = loadBuildConfig('.') || {};
399
+ } catch {
400
+ // Not in a rev project
401
+ }
402
+
403
+ let sections = config.sections || [];
404
+ if (sections.length === 0) {
405
+ sections = fs.readdirSync('.').filter(f =>
406
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
407
+ );
408
+ }
409
+
410
+ const lintIssues: { file: string; message: string }[] = [];
411
+ const lintWarnings: { file: string; message: string }[] = [];
412
+
413
+ for (const file of sections) {
414
+ if (!fs.existsSync(file)) continue;
415
+ const content = fs.readFileSync(file, 'utf-8');
416
+
417
+ // Check for broken cross-references
418
+ const refs = content.match(/@(fig|tbl|eq|sec):\w+/g) || [];
419
+ const anchors = content.match(/\{#(fig|tbl|eq|sec):[^}]+\}/g) || [];
420
+ const anchorLabels = anchors.map(a => a.match(/#([^}]+)/)![1]);
421
+
422
+ for (const ref of refs) {
423
+ const label = ref.slice(1);
424
+ if (!anchorLabels.includes(label)) {
425
+ lintIssues.push({ file, message: `Broken reference: ${ref}` });
426
+ }
427
+ }
428
+
429
+ // Check for unresolved comments
430
+ const unresolvedComments = (content.match(/\{>>[^<]*<<\}/g) || [])
431
+ .filter(c => !c.includes('[RESOLVED]'));
432
+ if (unresolvedComments.length > 0) {
433
+ lintWarnings.push({ file, message: `${unresolvedComments.length} unresolved comment(s)` });
434
+ }
435
+ }
436
+
437
+ if (lintIssues.length > 0) {
438
+ for (const issue of lintIssues) {
439
+ console.log(chalk.red(` ✗ ${issue.file}: ${issue.message}`));
440
+ }
441
+ hasErrors = true;
442
+ totalIssues += lintIssues.length;
443
+ }
444
+ for (const warning of lintWarnings) {
445
+ console.log(chalk.yellow(` ⚠ ${warning.file}: ${warning.message}`));
446
+ totalIssues++;
447
+ }
448
+ if (lintIssues.length === 0 && lintWarnings.length === 0) {
449
+ console.log(chalk.green(' ✓ No lint issues'));
450
+ }
451
+ console.log();
452
+
453
+ // 2. Run grammar check
454
+ console.log(chalk.cyan.bold('2. Grammar check...'));
455
+
456
+ const severityLevels: Record<string, number> = { error: 3, warning: 2, info: 1 };
457
+ const minSeverity = severityLevels[options.severity || 'warning'] || 2;
458
+ let grammarIssues: GrammarIssue[] = [];
459
+
460
+ for (const file of sections) {
461
+ if (!fs.existsSync(file)) continue;
462
+ const text = fs.readFileSync(file, 'utf-8');
463
+ const issues = checkGrammar(text, { scientific: true });
464
+ const filtered = issues.filter((i: GrammarIssue) => severityLevels[i.severity] >= minSeverity);
465
+ grammarIssues.push(...filtered.map(i => ({ ...i, file })));
466
+ }
467
+
468
+ const grammarSummary = getGrammarSummary(grammarIssues);
469
+ if (grammarSummary.errors > 0) {
470
+ hasErrors = true;
471
+ }
472
+ totalIssues += grammarSummary.total;
473
+
474
+ if (grammarSummary.total > 0) {
475
+ console.log(chalk.yellow(` ⚠ ${grammarSummary.total} grammar issue(s): ${grammarSummary.errors} errors, ${grammarSummary.warnings} warnings`));
476
+ } else {
477
+ console.log(chalk.green(' ✓ No grammar issues'));
478
+ }
479
+ console.log();
480
+
481
+ // 3. Run citation check
482
+ console.log(chalk.cyan.bold('3. Citation check...'));
483
+ const bibFile = config.bibliography || 'references.bib';
484
+ if (fs.existsSync(bibFile)) {
485
+ const existingSections = sections.filter(f => fs.existsSync(f));
486
+
487
+ const result = validateCitations(existingSections, bibFile);
488
+
489
+ if (result.missing.length > 0) {
490
+ console.log(chalk.red(` ✗ ${result.missing.length} missing citation(s): ${result.missing.slice(0, 3).join(', ')}${result.missing.length > 3 ? '...' : ''}`));
491
+ hasErrors = true;
492
+ totalIssues += result.missing.length;
493
+ }
494
+ if (result.unused.length > 0) {
495
+ console.log(chalk.yellow(` ⚠ ${result.unused.length} unused citation(s)`));
496
+ totalIssues += result.unused.length;
497
+ }
498
+ if (result.missing.length === 0 && result.unused.length === 0) {
499
+ console.log(chalk.green(' ✓ All citations valid'));
500
+ }
501
+ } else {
502
+ console.log(chalk.dim(' - No bibliography file found'));
503
+ }
504
+ console.log();
505
+
506
+ // Summary
507
+ console.log(chalk.bold('Summary'));
508
+ if (hasErrors) {
509
+ console.log(chalk.red(` ${totalIssues} issue(s) found. Please fix before submission.`));
510
+ process.exit(1);
511
+ } else if (totalIssues > 0) {
512
+ console.log(chalk.yellow(` ${totalIssues} warning(s). Review before submission.`));
513
+ } else {
514
+ console.log(chalk.green(' ✓ All checks passed! Ready for submission.'));
515
+ }
516
+ });
517
+ }