docrev 0.9.11 → 0.9.14

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 (138) hide show
  1. package/.claude/settings.local.json +9 -9
  2. package/.gitattributes +1 -1
  3. package/CHANGELOG.md +149 -149
  4. package/PLAN-tables-and-postprocess.md +850 -850
  5. package/README.md +391 -391
  6. package/bin/rev.js +11 -11
  7. package/bin/rev.ts +145 -145
  8. package/completions/rev.bash +127 -127
  9. package/completions/rev.ps1 +210 -210
  10. package/completions/rev.zsh +207 -207
  11. package/dev_notes/stress2/build_adversarial.ts +186 -186
  12. package/dev_notes/stress2/drift_matcher.ts +62 -62
  13. package/dev_notes/stress2/probe_anchors.ts +35 -35
  14. package/dev_notes/stress2/project/discussion.before.md +3 -3
  15. package/dev_notes/stress2/project/discussion.md +3 -3
  16. package/dev_notes/stress2/project/methods.before.md +20 -20
  17. package/dev_notes/stress2/project/methods.md +20 -20
  18. package/dev_notes/stress2/project/rev.yaml +5 -5
  19. package/dev_notes/stress2/project/sections.yaml +4 -4
  20. package/dev_notes/stress2/sections.yaml +5 -5
  21. package/dev_notes/stress2/trace_placement.ts +50 -50
  22. package/dev_notes/stresstest_boundaries.ts +27 -27
  23. package/dev_notes/stresstest_drift_apply.ts +43 -43
  24. package/dev_notes/stresstest_drift_compare.ts +43 -43
  25. package/dev_notes/stresstest_drift_v2.ts +54 -54
  26. package/dev_notes/stresstest_inspect.ts +54 -54
  27. package/dev_notes/stresstest_pstyle.ts +55 -55
  28. package/dev_notes/stresstest_section_debug.ts +23 -23
  29. package/dev_notes/stresstest_split.ts +70 -70
  30. package/dev_notes/stresstest_trace.ts +19 -19
  31. package/dev_notes/stresstest_verify_no_overwrite.ts +40 -40
  32. package/dist/lib/build.d.ts +50 -1
  33. package/dist/lib/build.d.ts.map +1 -1
  34. package/dist/lib/build.js +80 -30
  35. package/dist/lib/build.js.map +1 -1
  36. package/dist/lib/commands/build.d.ts.map +1 -1
  37. package/dist/lib/commands/build.js +38 -5
  38. package/dist/lib/commands/build.js.map +1 -1
  39. package/dist/lib/commands/utilities.js +164 -164
  40. package/dist/lib/commands/word-tools.js +8 -8
  41. package/dist/lib/grammar.js +3 -3
  42. package/dist/lib/import.d.ts.map +1 -1
  43. package/dist/lib/import.js +146 -24
  44. package/dist/lib/import.js.map +1 -1
  45. package/dist/lib/pdf-comments.js +44 -44
  46. package/dist/lib/plugins.js +57 -57
  47. package/dist/lib/pptx-themes.js +115 -115
  48. package/dist/lib/spelling.js +2 -2
  49. package/dist/lib/templates.js +387 -387
  50. package/dist/lib/themes.js +51 -51
  51. package/dist/lib/types.d.ts +20 -0
  52. package/dist/lib/types.d.ts.map +1 -1
  53. package/dist/lib/word-extraction.d.ts +6 -0
  54. package/dist/lib/word-extraction.d.ts.map +1 -1
  55. package/dist/lib/word-extraction.js +46 -3
  56. package/dist/lib/word-extraction.js.map +1 -1
  57. package/dist/lib/wordcomments.d.ts.map +1 -1
  58. package/dist/lib/wordcomments.js +23 -5
  59. package/dist/lib/wordcomments.js.map +1 -1
  60. package/eslint.config.js +27 -27
  61. package/lib/anchor-match.ts +276 -276
  62. package/lib/annotations.ts +644 -644
  63. package/lib/build.ts +1300 -1227
  64. package/lib/citations.ts +160 -160
  65. package/lib/commands/build.ts +833 -801
  66. package/lib/commands/citations.ts +515 -515
  67. package/lib/commands/comments.ts +1050 -1050
  68. package/lib/commands/context.ts +174 -174
  69. package/lib/commands/core.ts +309 -309
  70. package/lib/commands/doi.ts +435 -435
  71. package/lib/commands/file-ops.ts +372 -372
  72. package/lib/commands/history.ts +320 -320
  73. package/lib/commands/index.ts +87 -87
  74. package/lib/commands/init.ts +259 -259
  75. package/lib/commands/merge-resolve.ts +378 -378
  76. package/lib/commands/preview.ts +178 -178
  77. package/lib/commands/project-info.ts +244 -244
  78. package/lib/commands/quality.ts +517 -517
  79. package/lib/commands/response.ts +454 -454
  80. package/lib/commands/section-boundaries.ts +82 -82
  81. package/lib/commands/sections.ts +451 -451
  82. package/lib/commands/sync.ts +706 -706
  83. package/lib/commands/text-ops.ts +449 -449
  84. package/lib/commands/utilities.ts +448 -448
  85. package/lib/commands/verify-anchors.ts +272 -272
  86. package/lib/commands/word-tools.ts +340 -340
  87. package/lib/comment-realign.ts +517 -517
  88. package/lib/config.ts +84 -84
  89. package/lib/crossref.ts +781 -781
  90. package/lib/csl.ts +191 -191
  91. package/lib/dependencies.ts +98 -98
  92. package/lib/diff-engine.ts +465 -465
  93. package/lib/doi-cache.ts +115 -115
  94. package/lib/doi.ts +897 -897
  95. package/lib/equations.ts +506 -506
  96. package/lib/errors.ts +346 -346
  97. package/lib/format.ts +541 -541
  98. package/lib/git.ts +326 -326
  99. package/lib/grammar.ts +303 -303
  100. package/lib/image-registry.ts +180 -180
  101. package/lib/import.ts +911 -792
  102. package/lib/journals.ts +543 -543
  103. package/lib/merge.ts +633 -633
  104. package/lib/orcid.ts +144 -144
  105. package/lib/pdf-comments.ts +263 -263
  106. package/lib/pdf-import.ts +524 -524
  107. package/lib/plugins.ts +362 -362
  108. package/lib/postprocess.ts +188 -188
  109. package/lib/pptx-color-filter.lua +37 -37
  110. package/lib/pptx-template.ts +469 -469
  111. package/lib/pptx-themes.ts +483 -483
  112. package/lib/protect-restore.ts +520 -520
  113. package/lib/rate-limiter.ts +94 -94
  114. package/lib/response.ts +197 -197
  115. package/lib/restore-references.ts +240 -240
  116. package/lib/review.ts +327 -327
  117. package/lib/schema.ts +417 -417
  118. package/lib/scientific-words.ts +73 -73
  119. package/lib/sections.ts +335 -335
  120. package/lib/slides.ts +756 -756
  121. package/lib/spelling.ts +334 -334
  122. package/lib/templates.ts +526 -526
  123. package/lib/themes.ts +742 -742
  124. package/lib/trackchanges.ts +247 -247
  125. package/lib/tui.ts +450 -450
  126. package/lib/types.ts +550 -530
  127. package/lib/undo.ts +250 -250
  128. package/lib/utils.ts +69 -69
  129. package/lib/variables.ts +179 -179
  130. package/lib/word-extraction.ts +806 -759
  131. package/lib/word.ts +643 -643
  132. package/lib/wordcomments.ts +817 -798
  133. package/package.json +137 -137
  134. package/scripts/postbuild.js +28 -28
  135. package/skill/REFERENCE.md +431 -431
  136. package/skill/SKILL.md +258 -258
  137. package/tsconfig.json +26 -26
  138. package/types/index.d.ts +525 -525
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
+ }