docrev 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +207 -197
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +433 -433
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/annotations.d.ts.map +1 -1
  11. package/dist/lib/annotations.js +28 -0
  12. package/dist/lib/annotations.js.map +1 -1
  13. package/dist/lib/build.d.ts +28 -0
  14. package/dist/lib/build.d.ts.map +1 -1
  15. package/dist/lib/build.js +81 -4
  16. package/dist/lib/build.js.map +1 -1
  17. package/dist/lib/commands/comments.d.ts.map +1 -1
  18. package/dist/lib/commands/comments.js +58 -28
  19. package/dist/lib/commands/comments.js.map +1 -1
  20. package/dist/lib/commands/context.d.ts +1 -0
  21. package/dist/lib/commands/context.d.ts.map +1 -1
  22. package/dist/lib/commands/context.js +1 -0
  23. package/dist/lib/commands/context.js.map +1 -1
  24. package/dist/lib/commands/core.d.ts.map +1 -1
  25. package/dist/lib/commands/core.js +25 -8
  26. package/dist/lib/commands/core.js.map +1 -1
  27. package/dist/lib/commands/response.js +1 -1
  28. package/dist/lib/commands/response.js.map +1 -1
  29. package/dist/lib/commands/utilities.js +164 -164
  30. package/dist/lib/commands/word-tools.js +8 -8
  31. package/dist/lib/grammar.js +3 -3
  32. package/dist/lib/import.d.ts +14 -0
  33. package/dist/lib/import.d.ts.map +1 -1
  34. package/dist/lib/import.js +23 -0
  35. package/dist/lib/import.js.map +1 -1
  36. package/dist/lib/input.d.ts +67 -0
  37. package/dist/lib/input.d.ts.map +1 -0
  38. package/dist/lib/input.js +164 -0
  39. package/dist/lib/input.js.map +1 -0
  40. package/dist/lib/macro-filter.lua +201 -201
  41. package/dist/lib/pdf-comments.js +44 -44
  42. package/dist/lib/plugins.js +57 -57
  43. package/dist/lib/pptx-color-filter.lua +37 -37
  44. package/dist/lib/pptx-themes.js +115 -115
  45. package/dist/lib/response.d.ts +1 -1
  46. package/dist/lib/response.d.ts.map +1 -1
  47. package/dist/lib/response.js +5 -2
  48. package/dist/lib/response.js.map +1 -1
  49. package/dist/lib/schema.d.ts.map +1 -1
  50. package/dist/lib/schema.js +8 -2
  51. package/dist/lib/schema.js.map +1 -1
  52. package/dist/lib/spelling.js +2 -2
  53. package/dist/lib/templates.js +387 -387
  54. package/dist/lib/themes.js +51 -51
  55. package/eslint.config.js +27 -27
  56. package/lib/anchor-match.ts +307 -307
  57. package/lib/annotations.ts +695 -664
  58. package/lib/build.ts +2047 -1956
  59. package/lib/citations.ts +160 -160
  60. package/lib/commands/build.ts +885 -885
  61. package/lib/commands/citations.ts +515 -515
  62. package/lib/commands/comments.ts +1077 -1050
  63. package/lib/commands/context.ts +185 -176
  64. package/lib/commands/core.ts +328 -309
  65. package/lib/commands/doi.ts +451 -451
  66. package/lib/commands/file-ops.ts +372 -372
  67. package/lib/commands/history.ts +320 -320
  68. package/lib/commands/index.ts +87 -87
  69. package/lib/commands/init.ts +259 -259
  70. package/lib/commands/merge-resolve.ts +378 -378
  71. package/lib/commands/preview.ts +178 -178
  72. package/lib/commands/project-info.ts +244 -244
  73. package/lib/commands/quality.ts +517 -517
  74. package/lib/commands/response.ts +454 -454
  75. package/lib/commands/section-boundaries.ts +82 -82
  76. package/lib/commands/sections.ts +451 -451
  77. package/lib/commands/sync.ts +689 -689
  78. package/lib/commands/text-ops.ts +449 -449
  79. package/lib/commands/utilities.ts +448 -448
  80. package/lib/commands/verify-anchors.ts +272 -272
  81. package/lib/commands/word-tools.ts +340 -340
  82. package/lib/comment-realign.ts +99 -99
  83. package/lib/config.ts +84 -84
  84. package/lib/crossref.ts +781 -781
  85. package/lib/csl.ts +191 -191
  86. package/lib/dependencies.ts +132 -132
  87. package/lib/diff-engine.ts +465 -465
  88. package/lib/doi-cache.ts +115 -115
  89. package/lib/doi.ts +879 -879
  90. package/lib/equations.ts +506 -506
  91. package/lib/errors.ts +350 -350
  92. package/lib/format.ts +541 -541
  93. package/lib/git.ts +326 -326
  94. package/lib/grammar.ts +303 -303
  95. package/lib/image-registry.ts +180 -180
  96. package/lib/import.ts +932 -906
  97. package/lib/input.ts +174 -0
  98. package/lib/journals.ts +543 -543
  99. package/lib/macro-filter.lua +201 -201
  100. package/lib/macros.ts +273 -273
  101. package/lib/merge.ts +633 -633
  102. package/lib/ooxml.ts +768 -768
  103. package/lib/orcid.ts +144 -144
  104. package/lib/pdf-comments.ts +263 -263
  105. package/lib/pdf-import.ts +524 -524
  106. package/lib/plugins.ts +362 -362
  107. package/lib/postprocess.ts +188 -188
  108. package/lib/pptx-color-filter.lua +37 -37
  109. package/lib/pptx-template.ts +469 -469
  110. package/lib/pptx-themes.ts +483 -483
  111. package/lib/protect-restore.ts +520 -520
  112. package/lib/rate-limiter.ts +127 -127
  113. package/lib/response.ts +200 -197
  114. package/lib/restore-references.ts +240 -240
  115. package/lib/review.ts +327 -327
  116. package/lib/schema.ts +494 -488
  117. package/lib/scientific-words.ts +73 -73
  118. package/lib/sections.ts +428 -428
  119. package/lib/slides.ts +756 -756
  120. package/lib/spelling.ts +334 -334
  121. package/lib/templates.ts +526 -526
  122. package/lib/themes.ts +742 -742
  123. package/lib/trackchanges.ts +166 -166
  124. package/lib/tui.ts +450 -450
  125. package/lib/types.ts +546 -546
  126. package/lib/undo.ts +250 -250
  127. package/lib/utils.ts +69 -69
  128. package/lib/variables.ts +179 -179
  129. package/lib/word-extraction.ts +525 -525
  130. package/lib/word.ts +526 -526
  131. package/lib/wordcomments.ts +789 -789
  132. package/package.json +1 -1
  133. package/scripts/postbuild.js +47 -47
  134. package/skill/REFERENCE.md +550 -550
  135. package/skill/SKILL.md +302 -302
  136. package/tsconfig.json +26 -26
  137. package/types/index.d.ts +531 -531
  138. package/issues.md +0 -180
  139. package/site/assets/extra.css +0 -208
  140. package/site/commands.html +0 -926
  141. package/site/configuration.html +0 -469
  142. package/site/index.html +0 -288
  143. package/site/troubleshooting.html +0 -461
  144. package/site/workflow.html +0 -518
@@ -1,454 +1,454 @@
1
- /**
2
- * Response commands: response, validate, profiles, anonymize
3
- *
4
- * Commands for generating reviewer responses and validating manuscripts.
5
- */
6
-
7
- import type { Command } from 'commander';
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- collectComments,
14
- generateResponseLetter,
15
- groupByReviewer,
16
- getUserName,
17
- } from './context.js';
18
-
19
- interface ResponseOptions {
20
- output?: string;
21
- author?: string;
22
- context?: boolean;
23
- location?: boolean;
24
- }
25
-
26
- interface ValidateOptions {
27
- journal?: string;
28
- list?: boolean;
29
- }
30
-
31
- interface ProfilesOptions {
32
- list?: boolean;
33
- new?: string;
34
- project?: boolean;
35
- dirs?: boolean;
36
- fetchCsl?: string;
37
- listCsl?: boolean;
38
- }
39
-
40
- interface AnonymizeOptions {
41
- output?: string;
42
- authors?: string;
43
- dryRun?: boolean;
44
- }
45
-
46
- /**
47
- * Register response commands with the program
48
- */
49
- export function register(program: Command): void {
50
- // ==========================================================================
51
- // RESPONSE command - Generate response letter for reviewers
52
- // ==========================================================================
53
-
54
- program
55
- .command('response')
56
- .description('Generate response letter from reviewer comments')
57
- .argument('[files...]', 'Markdown files to process (default: all section files)')
58
- .option('-o, --output <file>', 'Output file (default: response-letter.md)')
59
- .option('-a, --author <name>', 'Author name for identifying replies')
60
- .option('--no-context', 'Omit context snippets')
61
- .option('--no-location', 'Omit file:line references')
62
- .action(async (files: string[] | undefined, options: ResponseOptions) => {
63
- let mdFiles = files;
64
- if (!mdFiles || mdFiles.length === 0) {
65
- const allFiles = fs.readdirSync('.').filter(f =>
66
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
67
- );
68
- mdFiles = allFiles;
69
- }
70
-
71
- if (mdFiles.length === 0) {
72
- console.error(fmt.status('error', 'No markdown files found'));
73
- process.exit(1);
74
- }
75
-
76
- const spin = fmt.spinner('Collecting comments...').start();
77
-
78
- const comments = collectComments(mdFiles);
79
- spin.stop();
80
-
81
- if (comments.length === 0) {
82
- console.log(fmt.status('info', 'No comments found in files'));
83
- return;
84
- }
85
-
86
- const letter = generateResponseLetter(comments, {
87
- authorName: options.author || getUserName() || 'Author',
88
- includeContext: options.context !== false,
89
- includeLocation: options.location !== false,
90
- });
91
-
92
- const outputPath = options.output || 'response-letter.md';
93
- fs.writeFileSync(outputPath, letter, 'utf-8');
94
-
95
- const grouped = groupByReviewer(comments);
96
- const reviewers = [...grouped.keys()].filter(r =>
97
- !r.toLowerCase().includes('claude') &&
98
- r.toLowerCase() !== (options.author || '').toLowerCase()
99
- );
100
-
101
- console.log(fmt.header('Response Letter Generated'));
102
- console.log();
103
-
104
- const rows = reviewers.map(r => [r, grouped.get(r)!.length.toString()]);
105
- console.log(fmt.table(['Reviewer', 'Comments'], rows));
106
- console.log();
107
- console.log(fmt.status('success', `Created ${outputPath}`));
108
- });
109
-
110
- // ==========================================================================
111
- // VALIDATE command - Check manuscript against journal requirements
112
- // ==========================================================================
113
-
114
- program
115
- .command('validate')
116
- .description('Validate manuscript against journal requirements')
117
- .argument('[files...]', 'Markdown files to validate (default: all section files)')
118
- .option('-j, --journal <name>', 'Journal profile (e.g., nature, plos-one, science)')
119
- .option('--list', 'List available journal profiles')
120
- .action(async (files: string[] | undefined, options: ValidateOptions) => {
121
- const { listJournals, validateProject, getJournalProfile } = await import('../journals.js');
122
-
123
- if (options.list) {
124
- console.log(fmt.header('Available Journal Profiles'));
125
- console.log();
126
- const journals = listJournals();
127
- const builtIn = journals.filter(j => !j.custom);
128
- const custom = journals.filter(j => j.custom);
129
-
130
- for (const j of builtIn) {
131
- const profile = getJournalProfile(j.id);
132
- const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
133
- console.log(` ${chalk.bold(j.id)} - ${j.name}${fmtTag}`);
134
- if (j.url) console.log(chalk.dim(` ${j.url}`));
135
- }
136
-
137
- if (custom.length > 0) {
138
- console.log();
139
- console.log(chalk.cyan(' Custom Profiles:'));
140
- for (const j of custom) {
141
- const profile = getJournalProfile(j.id);
142
- const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
143
- console.log(` ${chalk.bold(j.id)} - ${j.name} ${chalk.cyan('[custom]')}${fmtTag}`);
144
- if (j.url) console.log(chalk.dim(` ${j.url}`));
145
- }
146
- }
147
-
148
- console.log();
149
- console.log(chalk.dim('Usage: rev validate --journal <name>'));
150
- console.log(chalk.dim('Profiles with [formatting] can also be used with: rev build -j <name>'));
151
- console.log(chalk.dim('Manage custom profiles: rev profiles'));
152
- return;
153
- }
154
-
155
- if (!options.journal) {
156
- console.error(fmt.status('error', 'Please specify a journal with --journal <name>'));
157
- console.error(chalk.dim('Use --list to see available profiles'));
158
- process.exit(1);
159
- }
160
-
161
- const profile = getJournalProfile(options.journal);
162
- if (!profile) {
163
- console.error(fmt.status('error', `Unknown journal: ${options.journal}`));
164
- console.error(chalk.dim('Use --list to see available profiles'));
165
- process.exit(1);
166
- }
167
-
168
- let mdFiles = files;
169
- if (!mdFiles || mdFiles.length === 0) {
170
- mdFiles = fs.readdirSync('.').filter(f =>
171
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
172
- );
173
- }
174
-
175
- if (mdFiles.length === 0) {
176
- console.error(fmt.status('error', 'No markdown files found'));
177
- process.exit(1);
178
- }
179
-
180
- console.log(fmt.header(`Validating for ${profile.name}`));
181
- console.log(chalk.dim(` ${profile.url}`));
182
- console.log();
183
-
184
- const result = validateProject(mdFiles, options.journal);
185
-
186
- if (result.stats) {
187
- console.log(chalk.cyan('Manuscript Stats:'));
188
- console.log(fmt.table(['Metric', 'Value'], [
189
- ['Word count', result.stats.wordCount.toString()],
190
- ['Abstract', `${result.stats.abstractWords} words`],
191
- ['Title', `${result.stats.titleChars} chars`],
192
- ['Figures', result.stats.figures.toString()],
193
- ['Tables', result.stats.tables.toString()],
194
- ['References', result.stats.references.toString()],
195
- ]));
196
- console.log();
197
- }
198
-
199
- if (result.errors.length > 0) {
200
- console.log(chalk.red('Errors:'));
201
- for (const err of result.errors) {
202
- console.log(chalk.red(` ✗ ${err}`));
203
- }
204
- console.log();
205
- }
206
-
207
- if (result.warnings.length > 0) {
208
- console.log(chalk.yellow('Warnings:'));
209
- for (const warn of result.warnings) {
210
- console.log(chalk.yellow(` ⚠ ${warn}`));
211
- }
212
- console.log();
213
- }
214
-
215
- if (result.valid) {
216
- console.log(fmt.status('success', `Manuscript meets ${profile.name} requirements`));
217
- } else {
218
- console.log(fmt.status('error', `Manuscript has ${result.errors.length} error(s)`));
219
- process.exit(1);
220
- }
221
- });
222
-
223
- // ==========================================================================
224
- // PROFILES command - Manage custom journal profiles
225
- // ==========================================================================
226
-
227
- program
228
- .command('profiles')
229
- .description('Manage custom journal profiles')
230
- .option('--list', 'List all custom profiles')
231
- .option('--new <name>', 'Create a new profile template')
232
- .option('--project', 'Create profile in project directory (with --new)')
233
- .option('--dirs', 'Show profile directory locations')
234
- .option('--fetch-csl <name>', 'Download a CSL citation style to cache')
235
- .option('--list-csl', 'List cached CSL citation styles')
236
- .action(async (options: ProfilesOptions) => {
237
- const {
238
- listCustomProfiles,
239
- saveProfileTemplate,
240
- getPluginDirs,
241
- } = await import('../plugins.js');
242
- const { listJournals } = await import('../journals.js');
243
-
244
- if (options.listCsl) {
245
- const { listCachedCSL, getCSLCacheDir } = await import('../csl.js');
246
- const cached = listCachedCSL();
247
- console.log(fmt.header('Cached CSL Styles'));
248
- console.log(chalk.dim(` ${getCSLCacheDir()}`));
249
- console.log();
250
- if (cached.length === 0) {
251
- console.log(chalk.dim(' No cached styles. Download with: rev profiles --fetch-csl <name>'));
252
- } else {
253
- for (const c of cached) {
254
- console.log(` ${chalk.bold(c.name)}`);
255
- }
256
- console.log();
257
- console.log(chalk.dim(` ${cached.length} cached style(s)`));
258
- }
259
- return;
260
- }
261
-
262
- if (options.fetchCsl) {
263
- const { fetchCSL, resolveCSL, getCSLAliases } = await import('../csl.js');
264
-
265
- // Check if already cached
266
- const existing = resolveCSL(options.fetchCsl);
267
- if (existing) {
268
- console.log(fmt.status('info', `Already cached: ${existing}`));
269
- return;
270
- }
271
-
272
- const spin = fmt.spinner(`Downloading CSL style "${options.fetchCsl}"...`).start();
273
- const result = await fetchCSL(options.fetchCsl);
274
- spin.stop();
275
-
276
- if (result) {
277
- console.log(fmt.status('success', `Downloaded: ${result}`));
278
- } else {
279
- console.error(fmt.status('error', `Could not download CSL style "${options.fetchCsl}"`));
280
- const aliases = getCSLAliases();
281
- const names = Object.keys(aliases).sort().join(', ');
282
- console.error(chalk.dim(` Known short names: ${names}`));
283
- process.exit(1);
284
- }
285
- return;
286
- }
287
-
288
- if (options.dirs) {
289
- const dirs = getPluginDirs();
290
- console.log(fmt.header('Profile Directories'));
291
- console.log();
292
- console.log(` User: ${dirs.user}`);
293
- console.log(chalk.dim(` ${dirs.userExists ? 'exists' : 'not created'}`));
294
- console.log();
295
- console.log(` Project: ${dirs.project}`);
296
- console.log(chalk.dim(` ${dirs.projectExists ? 'exists' : 'not created'}`));
297
- console.log();
298
- console.log(chalk.dim('Use --new <name> to create a profile template'));
299
- return;
300
- }
301
-
302
- if (options.new) {
303
- try {
304
- const filePath = saveProfileTemplate(options.new, options.project);
305
- console.log(fmt.status('success', `Created profile template: ${filePath}`));
306
- console.log(chalk.dim('Edit the file to customize journal requirements'));
307
- } catch (err) {
308
- console.error(fmt.status('error', (err as Error).message));
309
- process.exit(1);
310
- }
311
- return;
312
- }
313
-
314
- console.log(fmt.header('Custom Journal Profiles'));
315
- console.log();
316
-
317
- const customProfiles = listCustomProfiles();
318
-
319
- if (customProfiles.length === 0) {
320
- console.log(chalk.dim(' No custom profiles found'));
321
- console.log();
322
- console.log(chalk.dim(' Create one with: rev profiles --new "Journal Name"'));
323
- console.log();
324
- const dirs = getPluginDirs();
325
- console.log(chalk.dim(` User profiles: ${dirs.user}`));
326
- console.log(chalk.dim(` Project profiles: ${dirs.project}`));
327
- } else {
328
- for (const p of customProfiles) {
329
- const source = p.source === 'project' ? chalk.cyan('[project]') : chalk.dim('[user]');
330
- console.log(` ${chalk.bold(p.id)} - ${p.name} ${source}`);
331
- console.log(chalk.dim(` ${p.path}`));
332
- }
333
- console.log();
334
- console.log(chalk.dim(` ${customProfiles.length} custom profile(s)`));
335
- }
336
-
337
- console.log();
338
-
339
- const allJournals = listJournals();
340
- const builtIn = allJournals.filter(j => !j.custom).length;
341
- console.log(chalk.dim(` ${builtIn} built-in profiles available (rev validate --list)`));
342
- });
343
-
344
- // ==========================================================================
345
- // ANONYMIZE command - Prepare document for blind review
346
- // ==========================================================================
347
-
348
- program
349
- .command('anonymize')
350
- .description('Prepare document for blind review')
351
- .argument('<input>', 'Input markdown file or directory')
352
- .option('-o, --output <file>', 'Output file (default: input-anonymous.md)')
353
- .option('--authors <names>', 'Author names to redact (comma-separated)')
354
- .option('--dry-run', 'Show what would be changed without writing')
355
- .action(async (input: string, options: AnonymizeOptions) => {
356
- const { default: YAML } = await import('yaml');
357
-
358
- const isDir = fs.existsSync(input) && fs.statSync(input).isDirectory();
359
- const files = isDir
360
- ? fs.readdirSync(input)
361
- .filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f))
362
- .map(f => path.join(input, f))
363
- : [input];
364
-
365
- if (files.length === 0) {
366
- console.error(fmt.status('error', 'No markdown files found'));
367
- process.exit(1);
368
- }
369
-
370
- let authorNames: string[] = [];
371
- if (options.authors) {
372
- authorNames = options.authors.split(',').map(n => n.trim());
373
- } else {
374
- const configPath = isDir ? path.join(input, 'rev.yaml') : 'rev.yaml';
375
- if (fs.existsSync(configPath)) {
376
- try {
377
- const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
378
- if (config.authors) {
379
- authorNames = config.authors.map((a: string | { name: string }) => typeof a === 'string' ? a : a.name).filter(Boolean);
380
- }
381
- } catch { /* ignore */ }
382
- }
383
- }
384
-
385
- console.log(fmt.header('Anonymizing Document'));
386
- console.log();
387
-
388
- let totalChanges = 0;
389
-
390
- for (const file of files) {
391
- if (!fs.existsSync(file)) {
392
- console.error(chalk.yellow(` Skipping: ${file} (not found)`));
393
- continue;
394
- }
395
-
396
- let text = fs.readFileSync(file, 'utf-8');
397
- let changes = 0;
398
-
399
- text = text.replace(/^---\n([\s\S]*?)\n---/, (match, fm) => {
400
- let modified = fm;
401
- modified = modified.replace(/^author:.*(?:\n(?: |\t).*)*$/m, '');
402
- modified = modified.replace(/^authors:.*(?:\n(?: |\t|-\s+).*)*$/m, '');
403
- modified = modified.replace(/^affiliation:.*$/m, '');
404
- modified = modified.replace(/^email:.*$/m, '');
405
- if (modified !== fm) changes++;
406
- return '---\n' + modified.replace(/\n{3,}/g, '\n\n').trim() + '\n---';
407
- });
408
-
409
- const ackPatterns = [
410
- /^#+\s*Acknowledgments?[\s\S]*?(?=^#|\Z)/gmi,
411
- /^#+\s*Funding[\s\S]*?(?=^#|\Z)/gmi,
412
- ];
413
- for (const pattern of ackPatterns) {
414
- const before = text;
415
- text = text.replace(pattern, '');
416
- if (text !== before) changes++;
417
- }
418
-
419
- for (const name of authorNames) {
420
- const namePattern = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi');
421
- const before = text;
422
- text = text.replace(namePattern, '[AUTHOR]');
423
- if (text !== before) changes++;
424
- }
425
-
426
- for (const name of authorNames) {
427
- const lastName = name.split(/\s+/).pop();
428
- if (lastName && lastName.length > 2) {
429
- const citePat = new RegExp(`@${lastName}(\\d{4})`, 'gi');
430
- const before = text;
431
- text = text.replace(citePat, '@AUTHOR$1');
432
- if (text !== before) changes++;
433
- }
434
- }
435
-
436
- totalChanges += changes;
437
-
438
- if (options.dryRun) {
439
- console.log(chalk.dim(` ${path.basename(file)}: ${changes} change(s)`));
440
- } else {
441
- const outPath = options.output || file.replace(/\.md$/, '-anonymous.md');
442
- fs.writeFileSync(outPath, text, 'utf-8');
443
- console.log(fmt.status('success', `${path.basename(file)} → ${path.basename(outPath)} (${changes} changes)`));
444
- }
445
- }
446
-
447
- console.log();
448
- if (options.dryRun) {
449
- console.log(chalk.dim(` Total: ${totalChanges} change(s) would be made`));
450
- } else {
451
- console.log(fmt.status('success', `Anonymized ${files.length} file(s)`));
452
- }
453
- });
454
- }
1
+ /**
2
+ * Response commands: response, validate, profiles, anonymize
3
+ *
4
+ * Commands for generating reviewer responses and validating manuscripts.
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ collectComments,
14
+ generateResponseLetter,
15
+ groupByReviewer,
16
+ getUserName,
17
+ } from './context.js';
18
+
19
+ interface ResponseOptions {
20
+ output?: string;
21
+ author?: string;
22
+ context?: boolean;
23
+ location?: boolean;
24
+ }
25
+
26
+ interface ValidateOptions {
27
+ journal?: string;
28
+ list?: boolean;
29
+ }
30
+
31
+ interface ProfilesOptions {
32
+ list?: boolean;
33
+ new?: string;
34
+ project?: boolean;
35
+ dirs?: boolean;
36
+ fetchCsl?: string;
37
+ listCsl?: boolean;
38
+ }
39
+
40
+ interface AnonymizeOptions {
41
+ output?: string;
42
+ authors?: string;
43
+ dryRun?: boolean;
44
+ }
45
+
46
+ /**
47
+ * Register response commands with the program
48
+ */
49
+ export function register(program: Command): void {
50
+ // ==========================================================================
51
+ // RESPONSE command - Generate response letter for reviewers
52
+ // ==========================================================================
53
+
54
+ program
55
+ .command('response')
56
+ .description('Generate response letter from reviewer comments')
57
+ .argument('[files...]', 'Markdown files to process (default: all section files)')
58
+ .option('-o, --output <file>', 'Output file (default: response-letter.md)')
59
+ .option('-a, --author <name>', 'Author name for identifying replies')
60
+ .option('--no-context', 'Omit context snippets')
61
+ .option('--no-location', 'Omit file:line references')
62
+ .action(async (files: string[] | undefined, options: ResponseOptions) => {
63
+ let mdFiles = files;
64
+ if (!mdFiles || mdFiles.length === 0) {
65
+ const allFiles = fs.readdirSync('.').filter(f =>
66
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
67
+ );
68
+ mdFiles = allFiles;
69
+ }
70
+
71
+ if (mdFiles.length === 0) {
72
+ console.error(fmt.status('error', 'No markdown files found'));
73
+ process.exit(1);
74
+ }
75
+
76
+ const spin = fmt.spinner('Collecting comments...').start();
77
+
78
+ const comments = await collectComments(mdFiles);
79
+ spin.stop();
80
+
81
+ if (comments.length === 0) {
82
+ console.log(fmt.status('info', 'No comments found in files'));
83
+ return;
84
+ }
85
+
86
+ const letter = generateResponseLetter(comments, {
87
+ authorName: options.author || getUserName() || 'Author',
88
+ includeContext: options.context !== false,
89
+ includeLocation: options.location !== false,
90
+ });
91
+
92
+ const outputPath = options.output || 'response-letter.md';
93
+ fs.writeFileSync(outputPath, letter, 'utf-8');
94
+
95
+ const grouped = groupByReviewer(comments);
96
+ const reviewers = [...grouped.keys()].filter(r =>
97
+ !r.toLowerCase().includes('claude') &&
98
+ r.toLowerCase() !== (options.author || '').toLowerCase()
99
+ );
100
+
101
+ console.log(fmt.header('Response Letter Generated'));
102
+ console.log();
103
+
104
+ const rows = reviewers.map(r => [r, grouped.get(r)!.length.toString()]);
105
+ console.log(fmt.table(['Reviewer', 'Comments'], rows));
106
+ console.log();
107
+ console.log(fmt.status('success', `Created ${outputPath}`));
108
+ });
109
+
110
+ // ==========================================================================
111
+ // VALIDATE command - Check manuscript against journal requirements
112
+ // ==========================================================================
113
+
114
+ program
115
+ .command('validate')
116
+ .description('Validate manuscript against journal requirements')
117
+ .argument('[files...]', 'Markdown files to validate (default: all section files)')
118
+ .option('-j, --journal <name>', 'Journal profile (e.g., nature, plos-one, science)')
119
+ .option('--list', 'List available journal profiles')
120
+ .action(async (files: string[] | undefined, options: ValidateOptions) => {
121
+ const { listJournals, validateProject, getJournalProfile } = await import('../journals.js');
122
+
123
+ if (options.list) {
124
+ console.log(fmt.header('Available Journal Profiles'));
125
+ console.log();
126
+ const journals = listJournals();
127
+ const builtIn = journals.filter(j => !j.custom);
128
+ const custom = journals.filter(j => j.custom);
129
+
130
+ for (const j of builtIn) {
131
+ const profile = getJournalProfile(j.id);
132
+ const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
133
+ console.log(` ${chalk.bold(j.id)} - ${j.name}${fmtTag}`);
134
+ if (j.url) console.log(chalk.dim(` ${j.url}`));
135
+ }
136
+
137
+ if (custom.length > 0) {
138
+ console.log();
139
+ console.log(chalk.cyan(' Custom Profiles:'));
140
+ for (const j of custom) {
141
+ const profile = getJournalProfile(j.id);
142
+ const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
143
+ console.log(` ${chalk.bold(j.id)} - ${j.name} ${chalk.cyan('[custom]')}${fmtTag}`);
144
+ if (j.url) console.log(chalk.dim(` ${j.url}`));
145
+ }
146
+ }
147
+
148
+ console.log();
149
+ console.log(chalk.dim('Usage: rev validate --journal <name>'));
150
+ console.log(chalk.dim('Profiles with [formatting] can also be used with: rev build -j <name>'));
151
+ console.log(chalk.dim('Manage custom profiles: rev profiles'));
152
+ return;
153
+ }
154
+
155
+ if (!options.journal) {
156
+ console.error(fmt.status('error', 'Please specify a journal with --journal <name>'));
157
+ console.error(chalk.dim('Use --list to see available profiles'));
158
+ process.exit(1);
159
+ }
160
+
161
+ const profile = getJournalProfile(options.journal);
162
+ if (!profile) {
163
+ console.error(fmt.status('error', `Unknown journal: ${options.journal}`));
164
+ console.error(chalk.dim('Use --list to see available profiles'));
165
+ process.exit(1);
166
+ }
167
+
168
+ let mdFiles = files;
169
+ if (!mdFiles || mdFiles.length === 0) {
170
+ mdFiles = fs.readdirSync('.').filter(f =>
171
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
172
+ );
173
+ }
174
+
175
+ if (mdFiles.length === 0) {
176
+ console.error(fmt.status('error', 'No markdown files found'));
177
+ process.exit(1);
178
+ }
179
+
180
+ console.log(fmt.header(`Validating for ${profile.name}`));
181
+ console.log(chalk.dim(` ${profile.url}`));
182
+ console.log();
183
+
184
+ const result = validateProject(mdFiles, options.journal);
185
+
186
+ if (result.stats) {
187
+ console.log(chalk.cyan('Manuscript Stats:'));
188
+ console.log(fmt.table(['Metric', 'Value'], [
189
+ ['Word count', result.stats.wordCount.toString()],
190
+ ['Abstract', `${result.stats.abstractWords} words`],
191
+ ['Title', `${result.stats.titleChars} chars`],
192
+ ['Figures', result.stats.figures.toString()],
193
+ ['Tables', result.stats.tables.toString()],
194
+ ['References', result.stats.references.toString()],
195
+ ]));
196
+ console.log();
197
+ }
198
+
199
+ if (result.errors.length > 0) {
200
+ console.log(chalk.red('Errors:'));
201
+ for (const err of result.errors) {
202
+ console.log(chalk.red(` ✗ ${err}`));
203
+ }
204
+ console.log();
205
+ }
206
+
207
+ if (result.warnings.length > 0) {
208
+ console.log(chalk.yellow('Warnings:'));
209
+ for (const warn of result.warnings) {
210
+ console.log(chalk.yellow(` ⚠ ${warn}`));
211
+ }
212
+ console.log();
213
+ }
214
+
215
+ if (result.valid) {
216
+ console.log(fmt.status('success', `Manuscript meets ${profile.name} requirements`));
217
+ } else {
218
+ console.log(fmt.status('error', `Manuscript has ${result.errors.length} error(s)`));
219
+ process.exit(1);
220
+ }
221
+ });
222
+
223
+ // ==========================================================================
224
+ // PROFILES command - Manage custom journal profiles
225
+ // ==========================================================================
226
+
227
+ program
228
+ .command('profiles')
229
+ .description('Manage custom journal profiles')
230
+ .option('--list', 'List all custom profiles')
231
+ .option('--new <name>', 'Create a new profile template')
232
+ .option('--project', 'Create profile in project directory (with --new)')
233
+ .option('--dirs', 'Show profile directory locations')
234
+ .option('--fetch-csl <name>', 'Download a CSL citation style to cache')
235
+ .option('--list-csl', 'List cached CSL citation styles')
236
+ .action(async (options: ProfilesOptions) => {
237
+ const {
238
+ listCustomProfiles,
239
+ saveProfileTemplate,
240
+ getPluginDirs,
241
+ } = await import('../plugins.js');
242
+ const { listJournals } = await import('../journals.js');
243
+
244
+ if (options.listCsl) {
245
+ const { listCachedCSL, getCSLCacheDir } = await import('../csl.js');
246
+ const cached = listCachedCSL();
247
+ console.log(fmt.header('Cached CSL Styles'));
248
+ console.log(chalk.dim(` ${getCSLCacheDir()}`));
249
+ console.log();
250
+ if (cached.length === 0) {
251
+ console.log(chalk.dim(' No cached styles. Download with: rev profiles --fetch-csl <name>'));
252
+ } else {
253
+ for (const c of cached) {
254
+ console.log(` ${chalk.bold(c.name)}`);
255
+ }
256
+ console.log();
257
+ console.log(chalk.dim(` ${cached.length} cached style(s)`));
258
+ }
259
+ return;
260
+ }
261
+
262
+ if (options.fetchCsl) {
263
+ const { fetchCSL, resolveCSL, getCSLAliases } = await import('../csl.js');
264
+
265
+ // Check if already cached
266
+ const existing = resolveCSL(options.fetchCsl);
267
+ if (existing) {
268
+ console.log(fmt.status('info', `Already cached: ${existing}`));
269
+ return;
270
+ }
271
+
272
+ const spin = fmt.spinner(`Downloading CSL style "${options.fetchCsl}"...`).start();
273
+ const result = await fetchCSL(options.fetchCsl);
274
+ spin.stop();
275
+
276
+ if (result) {
277
+ console.log(fmt.status('success', `Downloaded: ${result}`));
278
+ } else {
279
+ console.error(fmt.status('error', `Could not download CSL style "${options.fetchCsl}"`));
280
+ const aliases = getCSLAliases();
281
+ const names = Object.keys(aliases).sort().join(', ');
282
+ console.error(chalk.dim(` Known short names: ${names}`));
283
+ process.exit(1);
284
+ }
285
+ return;
286
+ }
287
+
288
+ if (options.dirs) {
289
+ const dirs = getPluginDirs();
290
+ console.log(fmt.header('Profile Directories'));
291
+ console.log();
292
+ console.log(` User: ${dirs.user}`);
293
+ console.log(chalk.dim(` ${dirs.userExists ? 'exists' : 'not created'}`));
294
+ console.log();
295
+ console.log(` Project: ${dirs.project}`);
296
+ console.log(chalk.dim(` ${dirs.projectExists ? 'exists' : 'not created'}`));
297
+ console.log();
298
+ console.log(chalk.dim('Use --new <name> to create a profile template'));
299
+ return;
300
+ }
301
+
302
+ if (options.new) {
303
+ try {
304
+ const filePath = saveProfileTemplate(options.new, options.project);
305
+ console.log(fmt.status('success', `Created profile template: ${filePath}`));
306
+ console.log(chalk.dim('Edit the file to customize journal requirements'));
307
+ } catch (err) {
308
+ console.error(fmt.status('error', (err as Error).message));
309
+ process.exit(1);
310
+ }
311
+ return;
312
+ }
313
+
314
+ console.log(fmt.header('Custom Journal Profiles'));
315
+ console.log();
316
+
317
+ const customProfiles = listCustomProfiles();
318
+
319
+ if (customProfiles.length === 0) {
320
+ console.log(chalk.dim(' No custom profiles found'));
321
+ console.log();
322
+ console.log(chalk.dim(' Create one with: rev profiles --new "Journal Name"'));
323
+ console.log();
324
+ const dirs = getPluginDirs();
325
+ console.log(chalk.dim(` User profiles: ${dirs.user}`));
326
+ console.log(chalk.dim(` Project profiles: ${dirs.project}`));
327
+ } else {
328
+ for (const p of customProfiles) {
329
+ const source = p.source === 'project' ? chalk.cyan('[project]') : chalk.dim('[user]');
330
+ console.log(` ${chalk.bold(p.id)} - ${p.name} ${source}`);
331
+ console.log(chalk.dim(` ${p.path}`));
332
+ }
333
+ console.log();
334
+ console.log(chalk.dim(` ${customProfiles.length} custom profile(s)`));
335
+ }
336
+
337
+ console.log();
338
+
339
+ const allJournals = listJournals();
340
+ const builtIn = allJournals.filter(j => !j.custom).length;
341
+ console.log(chalk.dim(` ${builtIn} built-in profiles available (rev validate --list)`));
342
+ });
343
+
344
+ // ==========================================================================
345
+ // ANONYMIZE command - Prepare document for blind review
346
+ // ==========================================================================
347
+
348
+ program
349
+ .command('anonymize')
350
+ .description('Prepare document for blind review')
351
+ .argument('<input>', 'Input markdown file or directory')
352
+ .option('-o, --output <file>', 'Output file (default: input-anonymous.md)')
353
+ .option('--authors <names>', 'Author names to redact (comma-separated)')
354
+ .option('--dry-run', 'Show what would be changed without writing')
355
+ .action(async (input: string, options: AnonymizeOptions) => {
356
+ const { default: YAML } = await import('yaml');
357
+
358
+ const isDir = fs.existsSync(input) && fs.statSync(input).isDirectory();
359
+ const files = isDir
360
+ ? fs.readdirSync(input)
361
+ .filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f))
362
+ .map(f => path.join(input, f))
363
+ : [input];
364
+
365
+ if (files.length === 0) {
366
+ console.error(fmt.status('error', 'No markdown files found'));
367
+ process.exit(1);
368
+ }
369
+
370
+ let authorNames: string[] = [];
371
+ if (options.authors) {
372
+ authorNames = options.authors.split(',').map(n => n.trim());
373
+ } else {
374
+ const configPath = isDir ? path.join(input, 'rev.yaml') : 'rev.yaml';
375
+ if (fs.existsSync(configPath)) {
376
+ try {
377
+ const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
378
+ if (config.authors) {
379
+ authorNames = config.authors.map((a: string | { name: string }) => typeof a === 'string' ? a : a.name).filter(Boolean);
380
+ }
381
+ } catch { /* ignore */ }
382
+ }
383
+ }
384
+
385
+ console.log(fmt.header('Anonymizing Document'));
386
+ console.log();
387
+
388
+ let totalChanges = 0;
389
+
390
+ for (const file of files) {
391
+ if (!fs.existsSync(file)) {
392
+ console.error(chalk.yellow(` Skipping: ${file} (not found)`));
393
+ continue;
394
+ }
395
+
396
+ let text = fs.readFileSync(file, 'utf-8');
397
+ let changes = 0;
398
+
399
+ text = text.replace(/^---\n([\s\S]*?)\n---/, (match, fm) => {
400
+ let modified = fm;
401
+ modified = modified.replace(/^author:.*(?:\n(?: |\t).*)*$/m, '');
402
+ modified = modified.replace(/^authors:.*(?:\n(?: |\t|-\s+).*)*$/m, '');
403
+ modified = modified.replace(/^affiliation:.*$/m, '');
404
+ modified = modified.replace(/^email:.*$/m, '');
405
+ if (modified !== fm) changes++;
406
+ return '---\n' + modified.replace(/\n{3,}/g, '\n\n').trim() + '\n---';
407
+ });
408
+
409
+ const ackPatterns = [
410
+ /^#+\s*Acknowledgments?[\s\S]*?(?=^#|\Z)/gmi,
411
+ /^#+\s*Funding[\s\S]*?(?=^#|\Z)/gmi,
412
+ ];
413
+ for (const pattern of ackPatterns) {
414
+ const before = text;
415
+ text = text.replace(pattern, '');
416
+ if (text !== before) changes++;
417
+ }
418
+
419
+ for (const name of authorNames) {
420
+ const namePattern = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi');
421
+ const before = text;
422
+ text = text.replace(namePattern, '[AUTHOR]');
423
+ if (text !== before) changes++;
424
+ }
425
+
426
+ for (const name of authorNames) {
427
+ const lastName = name.split(/\s+/).pop();
428
+ if (lastName && lastName.length > 2) {
429
+ const citePat = new RegExp(`@${lastName}(\\d{4})`, 'gi');
430
+ const before = text;
431
+ text = text.replace(citePat, '@AUTHOR$1');
432
+ if (text !== before) changes++;
433
+ }
434
+ }
435
+
436
+ totalChanges += changes;
437
+
438
+ if (options.dryRun) {
439
+ console.log(chalk.dim(` ${path.basename(file)}: ${changes} change(s)`));
440
+ } else {
441
+ const outPath = options.output || file.replace(/\.md$/, '-anonymous.md');
442
+ fs.writeFileSync(outPath, text, 'utf-8');
443
+ console.log(fmt.status('success', `${path.basename(file)} → ${path.basename(outPath)} (${changes} changes)`));
444
+ }
445
+ }
446
+
447
+ console.log();
448
+ if (options.dryRun) {
449
+ console.log(chalk.dim(` Total: ${totalChanges} change(s) would be made`));
450
+ } else {
451
+ console.log(fmt.status('success', `Anonymized ${files.length} file(s)`));
452
+ }
453
+ });
454
+ }