docrev 0.9.18 → 0.10.1

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 (134) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +173 -149
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -406
  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/build.d.ts +8 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +62 -6
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/context.d.ts +1 -1
  15. package/dist/lib/commands/context.d.ts.map +1 -1
  16. package/dist/lib/commands/context.js +1 -1
  17. package/dist/lib/commands/context.js.map +1 -1
  18. package/dist/lib/commands/sections.js +7 -7
  19. package/dist/lib/commands/sections.js.map +1 -1
  20. package/dist/lib/commands/sync.d.ts.map +1 -1
  21. package/dist/lib/commands/sync.js +15 -14
  22. package/dist/lib/commands/sync.js.map +1 -1
  23. package/dist/lib/commands/utilities.js +164 -164
  24. package/dist/lib/commands/verify-anchors.js +6 -6
  25. package/dist/lib/commands/verify-anchors.js.map +1 -1
  26. package/dist/lib/commands/word-tools.js +8 -8
  27. package/dist/lib/grammar.js +3 -3
  28. package/dist/lib/macro-filter.lua +201 -0
  29. package/dist/lib/macros.d.ts +102 -0
  30. package/dist/lib/macros.d.ts.map +1 -0
  31. package/dist/lib/macros.js +218 -0
  32. package/dist/lib/macros.js.map +1 -0
  33. package/dist/lib/pdf-comments.js +44 -44
  34. package/dist/lib/plugins.js +57 -57
  35. package/dist/lib/pptx-color-filter.lua +37 -0
  36. package/dist/lib/pptx-themes.js +115 -115
  37. package/dist/lib/schema.d.ts.map +1 -1
  38. package/dist/lib/schema.js +34 -0
  39. package/dist/lib/schema.js.map +1 -1
  40. package/dist/lib/sections.d.ts +35 -0
  41. package/dist/lib/sections.d.ts.map +1 -1
  42. package/dist/lib/sections.js +81 -0
  43. package/dist/lib/sections.js.map +1 -1
  44. package/dist/lib/spelling.js +2 -2
  45. package/dist/lib/templates.js +387 -387
  46. package/dist/lib/themes.js +51 -51
  47. package/eslint.config.js +27 -27
  48. package/lib/anchor-match.ts +276 -276
  49. package/lib/annotations.ts +644 -644
  50. package/lib/build.ts +1766 -1694
  51. package/lib/citations.ts +160 -160
  52. package/lib/commands/build.ts +855 -855
  53. package/lib/commands/citations.ts +515 -515
  54. package/lib/commands/comments.ts +1050 -1050
  55. package/lib/commands/context.ts +176 -174
  56. package/lib/commands/core.ts +309 -309
  57. package/lib/commands/doi.ts +435 -435
  58. package/lib/commands/file-ops.ts +372 -372
  59. package/lib/commands/history.ts +320 -320
  60. package/lib/commands/index.ts +87 -87
  61. package/lib/commands/init.ts +259 -259
  62. package/lib/commands/merge-resolve.ts +378 -378
  63. package/lib/commands/preview.ts +178 -178
  64. package/lib/commands/project-info.ts +244 -244
  65. package/lib/commands/quality.ts +517 -517
  66. package/lib/commands/response.ts +454 -454
  67. package/lib/commands/section-boundaries.ts +82 -82
  68. package/lib/commands/sections.ts +451 -451
  69. package/lib/commands/sync.ts +709 -706
  70. package/lib/commands/text-ops.ts +449 -449
  71. package/lib/commands/utilities.ts +448 -448
  72. package/lib/commands/verify-anchors.ts +272 -272
  73. package/lib/commands/word-tools.ts +340 -340
  74. package/lib/comment-realign.ts +517 -517
  75. package/lib/config.ts +84 -84
  76. package/lib/crossref.ts +781 -781
  77. package/lib/csl.ts +191 -191
  78. package/lib/dependencies.ts +98 -98
  79. package/lib/diff-engine.ts +465 -465
  80. package/lib/doi-cache.ts +115 -115
  81. package/lib/doi.ts +897 -897
  82. package/lib/equations.ts +506 -506
  83. package/lib/errors.ts +346 -346
  84. package/lib/format.ts +541 -541
  85. package/lib/git.ts +326 -326
  86. package/lib/grammar.ts +303 -303
  87. package/lib/image-registry.ts +180 -180
  88. package/lib/import.ts +911 -911
  89. package/lib/journals.ts +543 -543
  90. package/lib/macro-filter.lua +201 -0
  91. package/lib/macros.ts +273 -0
  92. package/lib/merge.ts +633 -633
  93. package/lib/orcid.ts +144 -144
  94. package/lib/pdf-comments.ts +263 -263
  95. package/lib/pdf-import.ts +524 -524
  96. package/lib/plugins.ts +362 -362
  97. package/lib/postprocess.ts +188 -188
  98. package/lib/pptx-color-filter.lua +37 -37
  99. package/lib/pptx-template.ts +469 -469
  100. package/lib/pptx-themes.ts +483 -483
  101. package/lib/protect-restore.ts +520 -520
  102. package/lib/rate-limiter.ts +94 -94
  103. package/lib/response.ts +197 -197
  104. package/lib/restore-references.ts +240 -240
  105. package/lib/review.ts +327 -327
  106. package/lib/schema.ts +488 -454
  107. package/lib/scientific-words.ts +73 -73
  108. package/lib/sections.ts +425 -335
  109. package/lib/slides.ts +756 -756
  110. package/lib/spelling.ts +334 -334
  111. package/lib/templates.ts +526 -526
  112. package/lib/themes.ts +742 -742
  113. package/lib/trackchanges.ts +247 -247
  114. package/lib/tui.ts +450 -450
  115. package/lib/types.ts +550 -550
  116. package/lib/undo.ts +250 -250
  117. package/lib/utils.ts +69 -69
  118. package/lib/variables.ts +179 -179
  119. package/lib/word-extraction.ts +806 -806
  120. package/lib/word.ts +643 -643
  121. package/lib/wordcomments.ts +840 -840
  122. package/package.json +137 -137
  123. package/scripts/postbuild.js +47 -28
  124. package/skill/REFERENCE.md +539 -539
  125. package/skill/SKILL.md +295 -295
  126. package/tsconfig.json +26 -26
  127. package/types/index.d.ts +525 -525
  128. package/issues.md +0 -180
  129. package/site/assets/extra.css +0 -208
  130. package/site/commands.html +0 -926
  131. package/site/configuration.html +0 -469
  132. package/site/index.html +0 -288
  133. package/site/troubleshooting.html +0 -461
  134. package/site/workflow.html +0 -518
package/lib/format.ts CHANGED
@@ -1,541 +1,541 @@
1
- /**
2
- * Formatting utilities for CLI output
3
- * Tables, boxes, spinners, progress bars
4
- */
5
-
6
- import chalk from 'chalk';
7
-
8
- // Type definitions for function parameters
9
- interface TableOptions {
10
- align?: Array<'left' | 'right' | 'center'>;
11
- headerStyle?: (text: string) => string;
12
- borderStyle?: (text: string) => string;
13
- cellStyle?: ((value: string, colIndex: number, rowIndex: number) => string) | null;
14
- }
15
-
16
- interface SimpleTableOptions {
17
- headerStyle?: (text: string) => string;
18
- indent?: string;
19
- }
20
-
21
- interface BoxOptions {
22
- title?: string | null;
23
- padding?: number;
24
- borderStyle?: (text: string) => string;
25
- titleStyle?: (text: string) => string;
26
- }
27
-
28
- interface StatsOptions {
29
- title?: string | null;
30
- }
31
-
32
- interface ProgressOptions {
33
- width?: number;
34
- label?: string;
35
- }
36
-
37
- interface InlineDiffPreviewOptions {
38
- maxLines?: number;
39
- contextChars?: number;
40
- }
41
-
42
- interface HeaderOptions {
43
- style?: (text: string) => string;
44
- width?: number;
45
- }
46
-
47
- interface Spinner {
48
- text: string;
49
- start: () => Spinner;
50
- stop: (finalMessage?: string | null) => Spinner;
51
- success: (msg?: string) => Spinner;
52
- error: (msg?: string) => Spinner;
53
- }
54
-
55
- interface ProgressBar {
56
- update: (n: number) => ProgressBar;
57
- increment: () => ProgressBar;
58
- done: (message?: string) => ProgressBar;
59
- }
60
-
61
- /**
62
- * Format a table with borders and alignment
63
- * @param headers - Column headers
64
- * @param rows - Row data
65
- * @param options - Formatting options
66
- * @returns Formatted table string
67
- */
68
- export function table(headers: string[], rows: string[][], options: TableOptions = {}): string {
69
- const {
70
- align = headers.map(() => 'left'), // 'left', 'right', 'center'
71
- headerStyle = chalk.bold.cyan,
72
- borderStyle = chalk.dim,
73
- cellStyle = null, // function(value, colIndex, rowIndex) => styled string
74
- } = options;
75
-
76
- // Calculate column widths
77
- const widths = headers.map((h, i) => {
78
- const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
79
- return Math.max(stripAnsi(h), ...cellWidths);
80
- });
81
-
82
- // Border characters
83
- const border = {
84
- topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘',
85
- horizontal: '─', vertical: '│',
86
- leftT: '├', rightT: '┤', topT: '┬', bottomT: '┴', cross: '┼',
87
- };
88
-
89
- // Build lines
90
- const lines: string[] = [];
91
-
92
- // Top border
93
- const topBorder = border.topLeft +
94
- widths.map(w => border.horizontal.repeat(w + 2)).join(border.topT) +
95
- border.topRight;
96
- lines.push(borderStyle(topBorder));
97
-
98
- // Header row
99
- const headerRow = border.vertical +
100
- headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left') + ' ').join(border.vertical) +
101
- border.vertical;
102
- lines.push(borderStyle(border.vertical) +
103
- headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left', stripAnsi(h)) + ' ').join(borderStyle(border.vertical)) +
104
- borderStyle(border.vertical));
105
-
106
- // Header separator
107
- const headerSep = border.leftT +
108
- widths.map(w => border.horizontal.repeat(w + 2)).join(border.cross) +
109
- border.rightT;
110
- lines.push(borderStyle(headerSep));
111
-
112
- // Data rows
113
- for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
114
- const row = rows[rowIdx];
115
- if (!row) continue;
116
- const cells = row.map((cell, colIdx) => {
117
- let value = String(cell || '');
118
- if (cellStyle) {
119
- value = cellStyle(value, colIdx, rowIdx);
120
- }
121
- const plainLen = stripAnsi(String(cell || ''));
122
- return ' ' + pad(value, widths[colIdx] || 0, align[colIdx] || 'left', plainLen) + ' ';
123
- });
124
- lines.push(borderStyle(border.vertical) + cells.join(borderStyle(border.vertical)) + borderStyle(border.vertical));
125
- }
126
-
127
- // Bottom border
128
- const bottomBorder = border.bottomLeft +
129
- widths.map(w => border.horizontal.repeat(w + 2)).join(border.bottomT) +
130
- border.bottomRight;
131
- lines.push(borderStyle(bottomBorder));
132
-
133
- return lines.join('\n');
134
- }
135
-
136
- /**
137
- * Simple table without borders (compact)
138
- */
139
- export function simpleTable(headers: string[], rows: string[][], options: SimpleTableOptions = {}): string {
140
- const { headerStyle = chalk.dim, indent = ' ' } = options;
141
-
142
- const widths = headers.map((h, i) => {
143
- const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
144
- return Math.max(stripAnsi(h), ...cellWidths);
145
- });
146
-
147
- const lines: string[] = [];
148
- lines.push(indent + headers.map((h, i) => headerStyle(pad(h, widths[i] || 0, 'left'))).join(' '));
149
- lines.push(indent + widths.map(w => chalk.dim('─'.repeat(w))).join(' '));
150
-
151
- for (const row of rows) {
152
- lines.push(indent + row.map((cell, i) => pad(String(cell || ''), widths[i] || 0, 'left')).join(' '));
153
- }
154
-
155
- return lines.join('\n');
156
- }
157
-
158
- /**
159
- * Format a box around content
160
- */
161
- export function box(content: string, options: BoxOptions = {}): string {
162
- const {
163
- title = null,
164
- padding = 1,
165
- borderStyle = chalk.dim,
166
- titleStyle = chalk.bold.cyan,
167
- } = options;
168
-
169
- const lines = content.split('\n');
170
- const maxWidth = Math.max(...lines.map(l => stripAnsi(l)), title ? stripAnsi(title) + 4 : 0);
171
-
172
- const border = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' };
173
- const result: string[] = [];
174
-
175
- // Top border with optional title
176
- if (title) {
177
- const titlePart = ` ${titleStyle(title)} `;
178
- const remaining = maxWidth + 2 - stripAnsi(titlePart);
179
- result.push(borderStyle(border.tl + border.h) + titlePart + borderStyle(border.h.repeat(remaining) + border.tr));
180
- } else {
181
- result.push(borderStyle(border.tl + border.h.repeat(maxWidth + 2) + border.tr));
182
- }
183
-
184
- // Padding top
185
- for (let i = 0; i < padding; i++) {
186
- result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
187
- }
188
-
189
- // Content
190
- for (const line of lines) {
191
- const plainLen = stripAnsi(line);
192
- const padded = line + ' '.repeat(maxWidth - plainLen);
193
- result.push(borderStyle(border.v) + ' ' + padded + ' ' + borderStyle(border.v));
194
- }
195
-
196
- // Padding bottom
197
- for (let i = 0; i < padding; i++) {
198
- result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
199
- }
200
-
201
- // Bottom border
202
- result.push(borderStyle(border.bl + border.h.repeat(maxWidth + 2) + border.br));
203
-
204
- return result.join('\n');
205
- }
206
-
207
- /**
208
- * Summary stats in a nice format
209
- */
210
- export function stats(data: Record<string, string | number>, options: StatsOptions = {}): string {
211
- const { title = null } = options;
212
-
213
- const lines: string[] = [];
214
- if (title) {
215
- lines.push(chalk.bold.cyan(title));
216
- lines.push('');
217
- }
218
-
219
- const keys = Object.keys(data);
220
- const maxKeyLen = keys.length > 0 ? Math.max(...keys.map(k => k.length)) : 0;
221
-
222
- for (const [key, value] of Object.entries(data)) {
223
- const label = chalk.dim(key.padEnd(maxKeyLen) + ':');
224
- lines.push(` ${label} ${value}`);
225
- }
226
-
227
- return lines.join('\n');
228
- }
229
-
230
- /**
231
- * Progress indicator
232
- */
233
- export function progress(current: number, total: number, options: ProgressOptions = {}): string {
234
- const { width = 30, label = '' } = options;
235
- const pct = Math.round((current / total) * 100);
236
- const filled = Math.round((current / total) * width);
237
- const empty = width - filled;
238
-
239
- const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
240
- return `${label}${bar} ${pct}% (${current}/${total})`;
241
- }
242
-
243
- // Global setting for emoji usage
244
- let useEmoji = false;
245
-
246
- export function setEmoji(enabled: boolean): void {
247
- useEmoji = enabled;
248
- }
249
-
250
- /**
251
- * Status line with icon
252
- */
253
- export function status(type: string, message: string): string {
254
- const textIcons: Record<string, string> = {
255
- success: chalk.green('✓'),
256
- error: chalk.red('✗'),
257
- warning: chalk.yellow('!'),
258
- info: chalk.blue('i'),
259
- comment: chalk.blue('#'),
260
- file: chalk.cyan('·'),
261
- folder: chalk.cyan('>'),
262
- build: chalk.magenta('*'),
263
- import: chalk.cyan('<'),
264
- export: chalk.cyan('>'),
265
- };
266
-
267
- const emojiIcons: Record<string, string> = {
268
- success: chalk.green('✓'),
269
- error: chalk.red('✗'),
270
- warning: chalk.yellow('⚠'),
271
- info: chalk.blue('ℹ'),
272
- comment: chalk.blue('💬'),
273
- file: chalk.cyan('📄'),
274
- folder: chalk.cyan('📁'),
275
- build: chalk.magenta('🔨'),
276
- import: chalk.cyan('📥'),
277
- export: chalk.cyan('📤'),
278
- };
279
-
280
- const icons = useEmoji ? emojiIcons : textIcons;
281
- const icon = icons[type] || chalk.dim('•');
282
- return `${icon} ${message}`;
283
- }
284
-
285
- /**
286
- * Pulsing star spinner frames (Claude-style)
287
- * Cycles through star brightness using unicode stars
288
- */
289
- const starFrames = ['✦', '✧', '✦', '✧', '⋆', '✧', '✦', '✧'];
290
- const starColors = [
291
- chalk.yellow,
292
- chalk.yellow.dim,
293
- chalk.white,
294
- chalk.yellow.dim,
295
- chalk.dim,
296
- chalk.yellow.dim,
297
- chalk.white,
298
- chalk.yellow.dim,
299
- ];
300
-
301
- /**
302
- * Create a pulsing star spinner for async operations
303
- */
304
- export function spinner(message: string): Spinner {
305
- let frameIndex = 0;
306
- let interval: NodeJS.Timeout | null = null;
307
-
308
- const spin: Spinner = {
309
- text: message,
310
- start() {
311
- process.stdout.write('\x1B[?25l'); // Hide cursor
312
- interval = setInterval(() => {
313
- const colorFn = starColors[frameIndex];
314
- const frameChr = starFrames[frameIndex];
315
- if (colorFn && frameChr) {
316
- const frame = colorFn(frameChr);
317
- process.stdout.write(`\r${frame} ${spin.text}`);
318
- }
319
- frameIndex = (frameIndex + 1) % starFrames.length;
320
- }, 120);
321
- return spin;
322
- },
323
- stop(finalMessage: string | null = null) {
324
- if (interval) {
325
- clearInterval(interval);
326
- interval = null;
327
- }
328
- process.stdout.write('\r\x1B[K'); // Clear line
329
- process.stdout.write('\x1B[?25h'); // Show cursor
330
- if (finalMessage) {
331
- console.log(finalMessage);
332
- }
333
- return spin;
334
- },
335
- success(msg?: string) {
336
- return spin.stop(status('success', msg || message));
337
- },
338
- error(msg?: string) {
339
- return spin.stop(status('error', msg || message));
340
- },
341
- };
342
-
343
- return spin;
344
- }
345
-
346
- /**
347
- * Create a progress bar for batch operations
348
- * @param total - Total number of items
349
- * @param label - Label for the progress bar
350
- * @returns Progress bar controller with update(), increment(), and done()
351
- */
352
- export function progressBar(total: number, label: string = 'Progress'): ProgressBar {
353
- let current = 0;
354
- const barWidth = 30;
355
-
356
- const bar: ProgressBar = {
357
- update(n: number) {
358
- current = Math.min(n, total);
359
- const percent = Math.floor((current / total) * 100);
360
- const filled = Math.floor((current / total) * barWidth);
361
- const empty = barWidth - filled;
362
- const filledBar = chalk.cyan('█'.repeat(filled));
363
- const emptyBar = chalk.dim('░'.repeat(empty));
364
- process.stdout.write(`\r${label} [${filledBar}${emptyBar}] ${percent}% (${current}/${total})`);
365
- return bar;
366
- },
367
- increment() {
368
- return bar.update(current + 1);
369
- },
370
- done(message?: string) {
371
- process.stdout.write('\r\x1B[K'); // Clear line
372
- if (message) {
373
- console.log(status('success', message));
374
- }
375
- return bar;
376
- },
377
- };
378
-
379
- return bar;
380
- }
381
-
382
- /**
383
- * Diff display with inline highlighting
384
- */
385
- export function diff(insertions: number, deletions: number, substitutions: number): string {
386
- const lines: string[] = [];
387
-
388
- if (insertions > 0) {
389
- lines.push(chalk.green(` + ${insertions} insertion${insertions !== 1 ? 's' : ''}`));
390
- }
391
- if (deletions > 0) {
392
- lines.push(chalk.red(` - ${deletions} deletion${deletions !== 1 ? 's' : ''}`));
393
- }
394
- if (substitutions > 0) {
395
- lines.push(chalk.yellow(` ~ ${substitutions} substitution${substitutions !== 1 ? 's' : ''}`));
396
- }
397
-
398
- return lines.join('\n');
399
- }
400
-
401
- /**
402
- * Show inline diff preview for CriticMarkup changes
403
- * @param text - Text with CriticMarkup annotations
404
- * @param options - Display options
405
- * @returns Formatted preview string
406
- */
407
- export function inlineDiffPreview(text: string, options: InlineDiffPreviewOptions = {}): string {
408
- const { maxLines = 10, contextChars = 40 } = options;
409
- const lines: string[] = [];
410
-
411
- // Find all changes
412
- const changes: Array<{
413
- type: 'insert' | 'delete' | 'substitute';
414
- content?: string;
415
- oldContent?: string;
416
- newContent?: string;
417
- index: number;
418
- fullMatch: string;
419
- }> = [];
420
-
421
- // Insertions: {++text++}
422
- const insertPattern = /\{\+\+([^+]*)\+\+\}/g;
423
- let match: RegExpExecArray | null;
424
- while ((match = insertPattern.exec(text)) !== null) {
425
- changes.push({
426
- type: 'insert',
427
- content: match[1],
428
- index: match.index,
429
- fullMatch: match[0],
430
- });
431
- }
432
-
433
- // Deletions: {--text--}
434
- const deletePattern = /\{--([^-]*)--\}/g;
435
- while ((match = deletePattern.exec(text)) !== null) {
436
- changes.push({
437
- type: 'delete',
438
- content: match[1],
439
- index: match.index,
440
- fullMatch: match[0],
441
- });
442
- }
443
-
444
- // Substitutions: {~~old~>new~~}
445
- const subPattern = /\{~~([^~]*)~>([^~]*)~~\}/g;
446
- while ((match = subPattern.exec(text)) !== null) {
447
- changes.push({
448
- type: 'substitute',
449
- oldContent: match[1],
450
- newContent: match[2],
451
- index: match.index,
452
- fullMatch: match[0],
453
- });
454
- }
455
-
456
- // Sort by position
457
- changes.sort((a, b) => a.index - b.index);
458
-
459
- // Show preview for each change (up to maxLines)
460
- const shown = changes.slice(0, maxLines);
461
-
462
- for (const change of shown) {
463
- // Get context
464
- const before = text.slice(Math.max(0, change.index - contextChars), change.index)
465
- .replace(/\n/g, ' ').trim();
466
- const afterIdx = change.index + change.fullMatch.length;
467
- const after = text.slice(afterIdx, afterIdx + contextChars)
468
- .replace(/\n/g, ' ').trim();
469
-
470
- let preview = '';
471
- if (change.type === 'insert') {
472
- preview = chalk.dim(before) + chalk.green.bold('+' + change.content) + chalk.dim(after);
473
- lines.push(chalk.green(' + ') + truncate(preview, 80));
474
- } else if (change.type === 'delete') {
475
- preview = chalk.dim(before) + chalk.red.bold('-' + change.content) + chalk.dim(after);
476
- lines.push(chalk.red(' - ') + truncate(preview, 80));
477
- } else if (change.type === 'substitute') {
478
- preview = chalk.dim(before) +
479
- chalk.red.strikethrough(change.oldContent || '') +
480
- chalk.green.bold(change.newContent || '') +
481
- chalk.dim(after);
482
- lines.push(chalk.yellow(' ~ ') + truncate(preview, 80));
483
- }
484
- }
485
-
486
- if (changes.length > maxLines) {
487
- lines.push(chalk.dim(` ... and ${changes.length - maxLines} more changes`));
488
- }
489
-
490
- return lines.join('\n');
491
- }
492
-
493
- /**
494
- * Truncate string to max length
495
- */
496
- function truncate(str: string, maxLen: number): string {
497
- const plain = stripAnsiStr(str);
498
- if (plain.length <= maxLen) return str;
499
- // This is approximate since we have ANSI codes
500
- return str.slice(0, maxLen + (str.length - plain.length)) + chalk.dim('...');
501
- }
502
-
503
- /**
504
- * Section header
505
- */
506
- export function header(text: string, options: HeaderOptions = {}): string {
507
- const { style = chalk.bold.cyan, width = 60 } = options;
508
- const padding = Math.max(0, width - text.length - 4);
509
- return style(`── ${text} ${'─'.repeat(padding)}`);
510
- }
511
-
512
- /**
513
- * Strip ANSI codes for length calculation
514
- */
515
- function stripAnsi(str: string): number {
516
- return str.replace(/\x1b\[[0-9;]*m/g, '').length;
517
- }
518
-
519
- /**
520
- * Strip ANSI codes and return string
521
- */
522
- function stripAnsiStr(str: string): string {
523
- return str.replace(/\x1b\[[0-9;]*m/g, '');
524
- }
525
-
526
- /**
527
- * Pad string with alignment
528
- */
529
- function pad(str: string, width: number, align: 'left' | 'right' | 'center', strLen: number | null = null): string {
530
- const len = strLen !== null ? strLen : stripAnsi(str);
531
- const padding = Math.max(0, width - len);
532
-
533
- if (align === 'right') {
534
- return ' '.repeat(padding) + str;
535
- } else if (align === 'center') {
536
- const left = Math.floor(padding / 2);
537
- const right = padding - left;
538
- return ' '.repeat(left) + str + ' '.repeat(right);
539
- }
540
- return str + ' '.repeat(padding);
541
- }
1
+ /**
2
+ * Formatting utilities for CLI output
3
+ * Tables, boxes, spinners, progress bars
4
+ */
5
+
6
+ import chalk from 'chalk';
7
+
8
+ // Type definitions for function parameters
9
+ interface TableOptions {
10
+ align?: Array<'left' | 'right' | 'center'>;
11
+ headerStyle?: (text: string) => string;
12
+ borderStyle?: (text: string) => string;
13
+ cellStyle?: ((value: string, colIndex: number, rowIndex: number) => string) | null;
14
+ }
15
+
16
+ interface SimpleTableOptions {
17
+ headerStyle?: (text: string) => string;
18
+ indent?: string;
19
+ }
20
+
21
+ interface BoxOptions {
22
+ title?: string | null;
23
+ padding?: number;
24
+ borderStyle?: (text: string) => string;
25
+ titleStyle?: (text: string) => string;
26
+ }
27
+
28
+ interface StatsOptions {
29
+ title?: string | null;
30
+ }
31
+
32
+ interface ProgressOptions {
33
+ width?: number;
34
+ label?: string;
35
+ }
36
+
37
+ interface InlineDiffPreviewOptions {
38
+ maxLines?: number;
39
+ contextChars?: number;
40
+ }
41
+
42
+ interface HeaderOptions {
43
+ style?: (text: string) => string;
44
+ width?: number;
45
+ }
46
+
47
+ interface Spinner {
48
+ text: string;
49
+ start: () => Spinner;
50
+ stop: (finalMessage?: string | null) => Spinner;
51
+ success: (msg?: string) => Spinner;
52
+ error: (msg?: string) => Spinner;
53
+ }
54
+
55
+ interface ProgressBar {
56
+ update: (n: number) => ProgressBar;
57
+ increment: () => ProgressBar;
58
+ done: (message?: string) => ProgressBar;
59
+ }
60
+
61
+ /**
62
+ * Format a table with borders and alignment
63
+ * @param headers - Column headers
64
+ * @param rows - Row data
65
+ * @param options - Formatting options
66
+ * @returns Formatted table string
67
+ */
68
+ export function table(headers: string[], rows: string[][], options: TableOptions = {}): string {
69
+ const {
70
+ align = headers.map(() => 'left'), // 'left', 'right', 'center'
71
+ headerStyle = chalk.bold.cyan,
72
+ borderStyle = chalk.dim,
73
+ cellStyle = null, // function(value, colIndex, rowIndex) => styled string
74
+ } = options;
75
+
76
+ // Calculate column widths
77
+ const widths = headers.map((h, i) => {
78
+ const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
79
+ return Math.max(stripAnsi(h), ...cellWidths);
80
+ });
81
+
82
+ // Border characters
83
+ const border = {
84
+ topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘',
85
+ horizontal: '─', vertical: '│',
86
+ leftT: '├', rightT: '┤', topT: '┬', bottomT: '┴', cross: '┼',
87
+ };
88
+
89
+ // Build lines
90
+ const lines: string[] = [];
91
+
92
+ // Top border
93
+ const topBorder = border.topLeft +
94
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.topT) +
95
+ border.topRight;
96
+ lines.push(borderStyle(topBorder));
97
+
98
+ // Header row
99
+ const headerRow = border.vertical +
100
+ headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left') + ' ').join(border.vertical) +
101
+ border.vertical;
102
+ lines.push(borderStyle(border.vertical) +
103
+ headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left', stripAnsi(h)) + ' ').join(borderStyle(border.vertical)) +
104
+ borderStyle(border.vertical));
105
+
106
+ // Header separator
107
+ const headerSep = border.leftT +
108
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.cross) +
109
+ border.rightT;
110
+ lines.push(borderStyle(headerSep));
111
+
112
+ // Data rows
113
+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
114
+ const row = rows[rowIdx];
115
+ if (!row) continue;
116
+ const cells = row.map((cell, colIdx) => {
117
+ let value = String(cell || '');
118
+ if (cellStyle) {
119
+ value = cellStyle(value, colIdx, rowIdx);
120
+ }
121
+ const plainLen = stripAnsi(String(cell || ''));
122
+ return ' ' + pad(value, widths[colIdx] || 0, align[colIdx] || 'left', plainLen) + ' ';
123
+ });
124
+ lines.push(borderStyle(border.vertical) + cells.join(borderStyle(border.vertical)) + borderStyle(border.vertical));
125
+ }
126
+
127
+ // Bottom border
128
+ const bottomBorder = border.bottomLeft +
129
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.bottomT) +
130
+ border.bottomRight;
131
+ lines.push(borderStyle(bottomBorder));
132
+
133
+ return lines.join('\n');
134
+ }
135
+
136
+ /**
137
+ * Simple table without borders (compact)
138
+ */
139
+ export function simpleTable(headers: string[], rows: string[][], options: SimpleTableOptions = {}): string {
140
+ const { headerStyle = chalk.dim, indent = ' ' } = options;
141
+
142
+ const widths = headers.map((h, i) => {
143
+ const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
144
+ return Math.max(stripAnsi(h), ...cellWidths);
145
+ });
146
+
147
+ const lines: string[] = [];
148
+ lines.push(indent + headers.map((h, i) => headerStyle(pad(h, widths[i] || 0, 'left'))).join(' '));
149
+ lines.push(indent + widths.map(w => chalk.dim('─'.repeat(w))).join(' '));
150
+
151
+ for (const row of rows) {
152
+ lines.push(indent + row.map((cell, i) => pad(String(cell || ''), widths[i] || 0, 'left')).join(' '));
153
+ }
154
+
155
+ return lines.join('\n');
156
+ }
157
+
158
+ /**
159
+ * Format a box around content
160
+ */
161
+ export function box(content: string, options: BoxOptions = {}): string {
162
+ const {
163
+ title = null,
164
+ padding = 1,
165
+ borderStyle = chalk.dim,
166
+ titleStyle = chalk.bold.cyan,
167
+ } = options;
168
+
169
+ const lines = content.split('\n');
170
+ const maxWidth = Math.max(...lines.map(l => stripAnsi(l)), title ? stripAnsi(title) + 4 : 0);
171
+
172
+ const border = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' };
173
+ const result: string[] = [];
174
+
175
+ // Top border with optional title
176
+ if (title) {
177
+ const titlePart = ` ${titleStyle(title)} `;
178
+ const remaining = maxWidth + 2 - stripAnsi(titlePart);
179
+ result.push(borderStyle(border.tl + border.h) + titlePart + borderStyle(border.h.repeat(remaining) + border.tr));
180
+ } else {
181
+ result.push(borderStyle(border.tl + border.h.repeat(maxWidth + 2) + border.tr));
182
+ }
183
+
184
+ // Padding top
185
+ for (let i = 0; i < padding; i++) {
186
+ result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
187
+ }
188
+
189
+ // Content
190
+ for (const line of lines) {
191
+ const plainLen = stripAnsi(line);
192
+ const padded = line + ' '.repeat(maxWidth - plainLen);
193
+ result.push(borderStyle(border.v) + ' ' + padded + ' ' + borderStyle(border.v));
194
+ }
195
+
196
+ // Padding bottom
197
+ for (let i = 0; i < padding; i++) {
198
+ result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
199
+ }
200
+
201
+ // Bottom border
202
+ result.push(borderStyle(border.bl + border.h.repeat(maxWidth + 2) + border.br));
203
+
204
+ return result.join('\n');
205
+ }
206
+
207
+ /**
208
+ * Summary stats in a nice format
209
+ */
210
+ export function stats(data: Record<string, string | number>, options: StatsOptions = {}): string {
211
+ const { title = null } = options;
212
+
213
+ const lines: string[] = [];
214
+ if (title) {
215
+ lines.push(chalk.bold.cyan(title));
216
+ lines.push('');
217
+ }
218
+
219
+ const keys = Object.keys(data);
220
+ const maxKeyLen = keys.length > 0 ? Math.max(...keys.map(k => k.length)) : 0;
221
+
222
+ for (const [key, value] of Object.entries(data)) {
223
+ const label = chalk.dim(key.padEnd(maxKeyLen) + ':');
224
+ lines.push(` ${label} ${value}`);
225
+ }
226
+
227
+ return lines.join('\n');
228
+ }
229
+
230
+ /**
231
+ * Progress indicator
232
+ */
233
+ export function progress(current: number, total: number, options: ProgressOptions = {}): string {
234
+ const { width = 30, label = '' } = options;
235
+ const pct = Math.round((current / total) * 100);
236
+ const filled = Math.round((current / total) * width);
237
+ const empty = width - filled;
238
+
239
+ const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
240
+ return `${label}${bar} ${pct}% (${current}/${total})`;
241
+ }
242
+
243
+ // Global setting for emoji usage
244
+ let useEmoji = false;
245
+
246
+ export function setEmoji(enabled: boolean): void {
247
+ useEmoji = enabled;
248
+ }
249
+
250
+ /**
251
+ * Status line with icon
252
+ */
253
+ export function status(type: string, message: string): string {
254
+ const textIcons: Record<string, string> = {
255
+ success: chalk.green('✓'),
256
+ error: chalk.red('✗'),
257
+ warning: chalk.yellow('!'),
258
+ info: chalk.blue('i'),
259
+ comment: chalk.blue('#'),
260
+ file: chalk.cyan('·'),
261
+ folder: chalk.cyan('>'),
262
+ build: chalk.magenta('*'),
263
+ import: chalk.cyan('<'),
264
+ export: chalk.cyan('>'),
265
+ };
266
+
267
+ const emojiIcons: Record<string, string> = {
268
+ success: chalk.green('✓'),
269
+ error: chalk.red('✗'),
270
+ warning: chalk.yellow('⚠'),
271
+ info: chalk.blue('ℹ'),
272
+ comment: chalk.blue('💬'),
273
+ file: chalk.cyan('📄'),
274
+ folder: chalk.cyan('📁'),
275
+ build: chalk.magenta('🔨'),
276
+ import: chalk.cyan('📥'),
277
+ export: chalk.cyan('📤'),
278
+ };
279
+
280
+ const icons = useEmoji ? emojiIcons : textIcons;
281
+ const icon = icons[type] || chalk.dim('•');
282
+ return `${icon} ${message}`;
283
+ }
284
+
285
+ /**
286
+ * Pulsing star spinner frames (Claude-style)
287
+ * Cycles through star brightness using unicode stars
288
+ */
289
+ const starFrames = ['✦', '✧', '✦', '✧', '⋆', '✧', '✦', '✧'];
290
+ const starColors = [
291
+ chalk.yellow,
292
+ chalk.yellow.dim,
293
+ chalk.white,
294
+ chalk.yellow.dim,
295
+ chalk.dim,
296
+ chalk.yellow.dim,
297
+ chalk.white,
298
+ chalk.yellow.dim,
299
+ ];
300
+
301
+ /**
302
+ * Create a pulsing star spinner for async operations
303
+ */
304
+ export function spinner(message: string): Spinner {
305
+ let frameIndex = 0;
306
+ let interval: NodeJS.Timeout | null = null;
307
+
308
+ const spin: Spinner = {
309
+ text: message,
310
+ start() {
311
+ process.stdout.write('\x1B[?25l'); // Hide cursor
312
+ interval = setInterval(() => {
313
+ const colorFn = starColors[frameIndex];
314
+ const frameChr = starFrames[frameIndex];
315
+ if (colorFn && frameChr) {
316
+ const frame = colorFn(frameChr);
317
+ process.stdout.write(`\r${frame} ${spin.text}`);
318
+ }
319
+ frameIndex = (frameIndex + 1) % starFrames.length;
320
+ }, 120);
321
+ return spin;
322
+ },
323
+ stop(finalMessage: string | null = null) {
324
+ if (interval) {
325
+ clearInterval(interval);
326
+ interval = null;
327
+ }
328
+ process.stdout.write('\r\x1B[K'); // Clear line
329
+ process.stdout.write('\x1B[?25h'); // Show cursor
330
+ if (finalMessage) {
331
+ console.log(finalMessage);
332
+ }
333
+ return spin;
334
+ },
335
+ success(msg?: string) {
336
+ return spin.stop(status('success', msg || message));
337
+ },
338
+ error(msg?: string) {
339
+ return spin.stop(status('error', msg || message));
340
+ },
341
+ };
342
+
343
+ return spin;
344
+ }
345
+
346
+ /**
347
+ * Create a progress bar for batch operations
348
+ * @param total - Total number of items
349
+ * @param label - Label for the progress bar
350
+ * @returns Progress bar controller with update(), increment(), and done()
351
+ */
352
+ export function progressBar(total: number, label: string = 'Progress'): ProgressBar {
353
+ let current = 0;
354
+ const barWidth = 30;
355
+
356
+ const bar: ProgressBar = {
357
+ update(n: number) {
358
+ current = Math.min(n, total);
359
+ const percent = Math.floor((current / total) * 100);
360
+ const filled = Math.floor((current / total) * barWidth);
361
+ const empty = barWidth - filled;
362
+ const filledBar = chalk.cyan('█'.repeat(filled));
363
+ const emptyBar = chalk.dim('░'.repeat(empty));
364
+ process.stdout.write(`\r${label} [${filledBar}${emptyBar}] ${percent}% (${current}/${total})`);
365
+ return bar;
366
+ },
367
+ increment() {
368
+ return bar.update(current + 1);
369
+ },
370
+ done(message?: string) {
371
+ process.stdout.write('\r\x1B[K'); // Clear line
372
+ if (message) {
373
+ console.log(status('success', message));
374
+ }
375
+ return bar;
376
+ },
377
+ };
378
+
379
+ return bar;
380
+ }
381
+
382
+ /**
383
+ * Diff display with inline highlighting
384
+ */
385
+ export function diff(insertions: number, deletions: number, substitutions: number): string {
386
+ const lines: string[] = [];
387
+
388
+ if (insertions > 0) {
389
+ lines.push(chalk.green(` + ${insertions} insertion${insertions !== 1 ? 's' : ''}`));
390
+ }
391
+ if (deletions > 0) {
392
+ lines.push(chalk.red(` - ${deletions} deletion${deletions !== 1 ? 's' : ''}`));
393
+ }
394
+ if (substitutions > 0) {
395
+ lines.push(chalk.yellow(` ~ ${substitutions} substitution${substitutions !== 1 ? 's' : ''}`));
396
+ }
397
+
398
+ return lines.join('\n');
399
+ }
400
+
401
+ /**
402
+ * Show inline diff preview for CriticMarkup changes
403
+ * @param text - Text with CriticMarkup annotations
404
+ * @param options - Display options
405
+ * @returns Formatted preview string
406
+ */
407
+ export function inlineDiffPreview(text: string, options: InlineDiffPreviewOptions = {}): string {
408
+ const { maxLines = 10, contextChars = 40 } = options;
409
+ const lines: string[] = [];
410
+
411
+ // Find all changes
412
+ const changes: Array<{
413
+ type: 'insert' | 'delete' | 'substitute';
414
+ content?: string;
415
+ oldContent?: string;
416
+ newContent?: string;
417
+ index: number;
418
+ fullMatch: string;
419
+ }> = [];
420
+
421
+ // Insertions: {++text++}
422
+ const insertPattern = /\{\+\+([^+]*)\+\+\}/g;
423
+ let match: RegExpExecArray | null;
424
+ while ((match = insertPattern.exec(text)) !== null) {
425
+ changes.push({
426
+ type: 'insert',
427
+ content: match[1],
428
+ index: match.index,
429
+ fullMatch: match[0],
430
+ });
431
+ }
432
+
433
+ // Deletions: {--text--}
434
+ const deletePattern = /\{--([^-]*)--\}/g;
435
+ while ((match = deletePattern.exec(text)) !== null) {
436
+ changes.push({
437
+ type: 'delete',
438
+ content: match[1],
439
+ index: match.index,
440
+ fullMatch: match[0],
441
+ });
442
+ }
443
+
444
+ // Substitutions: {~~old~>new~~}
445
+ const subPattern = /\{~~([^~]*)~>([^~]*)~~\}/g;
446
+ while ((match = subPattern.exec(text)) !== null) {
447
+ changes.push({
448
+ type: 'substitute',
449
+ oldContent: match[1],
450
+ newContent: match[2],
451
+ index: match.index,
452
+ fullMatch: match[0],
453
+ });
454
+ }
455
+
456
+ // Sort by position
457
+ changes.sort((a, b) => a.index - b.index);
458
+
459
+ // Show preview for each change (up to maxLines)
460
+ const shown = changes.slice(0, maxLines);
461
+
462
+ for (const change of shown) {
463
+ // Get context
464
+ const before = text.slice(Math.max(0, change.index - contextChars), change.index)
465
+ .replace(/\n/g, ' ').trim();
466
+ const afterIdx = change.index + change.fullMatch.length;
467
+ const after = text.slice(afterIdx, afterIdx + contextChars)
468
+ .replace(/\n/g, ' ').trim();
469
+
470
+ let preview = '';
471
+ if (change.type === 'insert') {
472
+ preview = chalk.dim(before) + chalk.green.bold('+' + change.content) + chalk.dim(after);
473
+ lines.push(chalk.green(' + ') + truncate(preview, 80));
474
+ } else if (change.type === 'delete') {
475
+ preview = chalk.dim(before) + chalk.red.bold('-' + change.content) + chalk.dim(after);
476
+ lines.push(chalk.red(' - ') + truncate(preview, 80));
477
+ } else if (change.type === 'substitute') {
478
+ preview = chalk.dim(before) +
479
+ chalk.red.strikethrough(change.oldContent || '') +
480
+ chalk.green.bold(change.newContent || '') +
481
+ chalk.dim(after);
482
+ lines.push(chalk.yellow(' ~ ') + truncate(preview, 80));
483
+ }
484
+ }
485
+
486
+ if (changes.length > maxLines) {
487
+ lines.push(chalk.dim(` ... and ${changes.length - maxLines} more changes`));
488
+ }
489
+
490
+ return lines.join('\n');
491
+ }
492
+
493
+ /**
494
+ * Truncate string to max length
495
+ */
496
+ function truncate(str: string, maxLen: number): string {
497
+ const plain = stripAnsiStr(str);
498
+ if (plain.length <= maxLen) return str;
499
+ // This is approximate since we have ANSI codes
500
+ return str.slice(0, maxLen + (str.length - plain.length)) + chalk.dim('...');
501
+ }
502
+
503
+ /**
504
+ * Section header
505
+ */
506
+ export function header(text: string, options: HeaderOptions = {}): string {
507
+ const { style = chalk.bold.cyan, width = 60 } = options;
508
+ const padding = Math.max(0, width - text.length - 4);
509
+ return style(`── ${text} ${'─'.repeat(padding)}`);
510
+ }
511
+
512
+ /**
513
+ * Strip ANSI codes for length calculation
514
+ */
515
+ function stripAnsi(str: string): number {
516
+ return str.replace(/\x1b\[[0-9;]*m/g, '').length;
517
+ }
518
+
519
+ /**
520
+ * Strip ANSI codes and return string
521
+ */
522
+ function stripAnsiStr(str: string): string {
523
+ return str.replace(/\x1b\[[0-9;]*m/g, '');
524
+ }
525
+
526
+ /**
527
+ * Pad string with alignment
528
+ */
529
+ function pad(str: string, width: number, align: 'left' | 'right' | 'center', strLen: number | null = null): string {
530
+ const len = strLen !== null ? strLen : stripAnsi(str);
531
+ const padding = Math.max(0, width - len);
532
+
533
+ if (align === 'right') {
534
+ return ' '.repeat(padding) + str;
535
+ } else if (align === 'center') {
536
+ const left = Math.floor(padding / 2);
537
+ const right = padding - left;
538
+ return ' '.repeat(left) + str + ' '.repeat(right);
539
+ }
540
+ return str + ' '.repeat(padding);
541
+ }