docrev 0.11.1 → 0.11.2

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 (116) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +202 -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/build.d.ts +28 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +81 -4
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/utilities.js +164 -164
  15. package/dist/lib/commands/word-tools.js +8 -8
  16. package/dist/lib/grammar.js +3 -3
  17. package/dist/lib/macro-filter.lua +201 -201
  18. package/dist/lib/pdf-comments.js +44 -44
  19. package/dist/lib/plugins.js +57 -57
  20. package/dist/lib/pptx-color-filter.lua +37 -37
  21. package/dist/lib/pptx-themes.js +115 -115
  22. package/dist/lib/schema.d.ts.map +1 -1
  23. package/dist/lib/schema.js +8 -2
  24. package/dist/lib/schema.js.map +1 -1
  25. package/dist/lib/spelling.js +2 -2
  26. package/dist/lib/templates.js +387 -387
  27. package/dist/lib/themes.js +51 -51
  28. package/eslint.config.js +27 -27
  29. package/lib/anchor-match.ts +307 -307
  30. package/lib/annotations.ts +664 -664
  31. package/lib/build.ts +2047 -1956
  32. package/lib/citations.ts +160 -160
  33. package/lib/commands/build.ts +885 -885
  34. package/lib/commands/citations.ts +515 -515
  35. package/lib/commands/comments.ts +1050 -1050
  36. package/lib/commands/context.ts +176 -176
  37. package/lib/commands/core.ts +309 -309
  38. package/lib/commands/doi.ts +451 -451
  39. package/lib/commands/file-ops.ts +372 -372
  40. package/lib/commands/history.ts +320 -320
  41. package/lib/commands/index.ts +87 -87
  42. package/lib/commands/init.ts +259 -259
  43. package/lib/commands/merge-resolve.ts +378 -378
  44. package/lib/commands/preview.ts +178 -178
  45. package/lib/commands/project-info.ts +244 -244
  46. package/lib/commands/quality.ts +517 -517
  47. package/lib/commands/response.ts +454 -454
  48. package/lib/commands/section-boundaries.ts +82 -82
  49. package/lib/commands/sections.ts +451 -451
  50. package/lib/commands/sync.ts +689 -689
  51. package/lib/commands/text-ops.ts +449 -449
  52. package/lib/commands/utilities.ts +448 -448
  53. package/lib/commands/verify-anchors.ts +272 -272
  54. package/lib/commands/word-tools.ts +340 -340
  55. package/lib/comment-realign.ts +99 -99
  56. package/lib/config.ts +84 -84
  57. package/lib/crossref.ts +781 -781
  58. package/lib/csl.ts +191 -191
  59. package/lib/dependencies.ts +132 -132
  60. package/lib/diff-engine.ts +465 -465
  61. package/lib/doi-cache.ts +115 -115
  62. package/lib/doi.ts +879 -879
  63. package/lib/equations.ts +506 -506
  64. package/lib/errors.ts +350 -350
  65. package/lib/format.ts +541 -541
  66. package/lib/git.ts +326 -326
  67. package/lib/grammar.ts +303 -303
  68. package/lib/image-registry.ts +180 -180
  69. package/lib/import.ts +906 -906
  70. package/lib/journals.ts +543 -543
  71. package/lib/macro-filter.lua +201 -201
  72. package/lib/macros.ts +273 -273
  73. package/lib/merge.ts +633 -633
  74. package/lib/ooxml.ts +768 -768
  75. package/lib/orcid.ts +144 -144
  76. package/lib/pdf-comments.ts +263 -263
  77. package/lib/pdf-import.ts +524 -524
  78. package/lib/plugins.ts +362 -362
  79. package/lib/postprocess.ts +188 -188
  80. package/lib/pptx-color-filter.lua +37 -37
  81. package/lib/pptx-template.ts +469 -469
  82. package/lib/pptx-themes.ts +483 -483
  83. package/lib/protect-restore.ts +520 -520
  84. package/lib/rate-limiter.ts +127 -127
  85. package/lib/response.ts +197 -197
  86. package/lib/restore-references.ts +240 -240
  87. package/lib/review.ts +327 -327
  88. package/lib/schema.ts +494 -488
  89. package/lib/scientific-words.ts +73 -73
  90. package/lib/sections.ts +428 -428
  91. package/lib/slides.ts +756 -756
  92. package/lib/spelling.ts +334 -334
  93. package/lib/templates.ts +526 -526
  94. package/lib/themes.ts +742 -742
  95. package/lib/trackchanges.ts +166 -166
  96. package/lib/tui.ts +450 -450
  97. package/lib/types.ts +546 -546
  98. package/lib/undo.ts +250 -250
  99. package/lib/utils.ts +69 -69
  100. package/lib/variables.ts +179 -179
  101. package/lib/word-extraction.ts +525 -525
  102. package/lib/word.ts +526 -526
  103. package/lib/wordcomments.ts +789 -789
  104. package/package.json +1 -1
  105. package/scripts/postbuild.js +47 -47
  106. package/skill/REFERENCE.md +550 -550
  107. package/skill/SKILL.md +302 -302
  108. package/tsconfig.json +26 -26
  109. package/types/index.d.ts +531 -531
  110. package/issues.md +0 -180
  111. package/site/assets/extra.css +0 -208
  112. package/site/commands.html +0 -926
  113. package/site/configuration.html +0 -469
  114. package/site/index.html +0 -288
  115. package/site/troubleshooting.html +0 -461
  116. package/site/workflow.html +0 -518
@@ -1,525 +1,525 @@
1
- /**
2
- * Word document data extraction - raw extraction from .docx files
3
- */
4
-
5
- import * as fs from 'fs';
6
- import * as path from 'path';
7
- import { exec } from 'child_process';
8
- import { promisify } from 'util';
9
- import { buildDocTextModel, buildCommentAnchorModel, extractComments, openDocx, readPartText } from './ooxml.js';
10
-
11
- const execAsync = promisify(exec);
12
-
13
- // ============================================
14
- // Type Definitions
15
- // ============================================
16
-
17
- export interface WordComment {
18
- id: string;
19
- author: string;
20
- date: string;
21
- text: string;
22
- /**
23
- * Parent comment id when this is a reply in a Word comment thread.
24
- * Resolved from `commentsExtended.xml`'s `w15:paraIdParent` field.
25
- * `undefined` for top-level comments.
26
- */
27
- parentId?: string;
28
- }
29
-
30
- export interface TextNode {
31
- xmlStart: number;
32
- xmlEnd: number;
33
- textStart: number;
34
- textEnd: number;
35
- text: string;
36
- }
37
-
38
- export interface CommentAnchorData {
39
- anchor: string;
40
- before: string;
41
- after: string;
42
- docPosition: number;
43
- docLength: number;
44
- isEmpty: boolean;
45
- }
46
-
47
- export interface CommentAnchorsResult {
48
- anchors: Map<string, CommentAnchorData>;
49
- fullDocText: string;
50
- }
51
-
52
- export interface DocxHeading {
53
- /** Heading style name from `<w:pStyle>`, e.g. "Heading1" */
54
- style: string;
55
- /** Heading depth: 1, 2, 3, ... (parsed from style name; 0 if unknown) */
56
- level: number;
57
- /** Concatenated text content of the heading paragraph */
58
- text: string;
59
- /** Position in fullDocText (same coordinate system as CommentAnchorData.docPosition) */
60
- docPosition: number;
61
- }
62
-
63
- export interface WordTable {
64
- markdown: string;
65
- rowCount: number;
66
- colCount: number;
67
- }
68
-
69
- export interface ParsedRow {
70
- cells: string[];
71
- colSpans: number[];
72
- }
73
-
74
- export interface ExtractFromWordOptions {
75
- mediaDir?: string;
76
- skipMediaExtraction?: boolean;
77
- }
78
-
79
- export interface ExtractMessage {
80
- type: 'info' | 'warning';
81
- message: string;
82
- }
83
-
84
- export interface ExtractFromWordResult {
85
- text: string;
86
- comments: WordComment[];
87
- anchors: Map<string, CommentAnchorData>;
88
- messages: ExtractMessage[];
89
- extractedMedia: string[];
90
- tables: WordTable[];
91
- hasTrackChanges: boolean;
92
- trackChangeStats: { insertions: number; deletions: number };
93
- }
94
-
95
- // ============================================
96
- // Functions
97
- // ============================================
98
-
99
- /**
100
- * Extract comments directly from Word docx comments.xml
101
- */
102
- export async function extractWordComments(docxPath: string): Promise<WordComment[]> {
103
- if (!fs.existsSync(docxPath)) {
104
- throw new Error(`File not found: ${docxPath}`);
105
- }
106
-
107
- const zip = openDocx(docxPath);
108
- // Word truncates the stored date to its day for display; keep that contract.
109
- return extractComments(zip).map((c) => ({
110
- id: c.id,
111
- author: c.author,
112
- date: c.date.slice(0, 10),
113
- text: c.text,
114
- parentId: c.parentId,
115
- }));
116
- }
117
-
118
- /**
119
- * Extract comment anchor texts from document.xml with surrounding context
120
- * Returns map of comment ID -> {anchor, before, after, docPosition, isEmpty} for better matching
121
- * Also returns fullDocText for section boundary matching
122
- */
123
- export async function extractCommentAnchors(docxPath: string): Promise<CommentAnchorsResult> {
124
- const anchors = new Map<string, CommentAnchorData>();
125
-
126
- const zip = openDocx(docxPath);
127
- const { fullDocText, comments } = buildCommentAnchorModel(zip);
128
- if (!fullDocText && comments.length === 0) {
129
- return { anchors, fullDocText: '' };
130
- }
131
-
132
- // Context surrounding the anchor, taken from the same plain-text coordinate
133
- // system as docPosition so the placement engine can compare like with like.
134
- function getContextBefore(position: number, maxLength: number = 150): string {
135
- const beforeText = fullDocText.slice(Math.max(0, position - maxLength), position);
136
- const sentenceStart = beforeText.search(/[.!?]\s+[A-Z][^.!?]*$/);
137
- return sentenceStart >= 0
138
- ? beforeText.slice(sentenceStart + 2).trim()
139
- : beforeText.slice(-80).trim();
140
- }
141
-
142
- function getContextAfter(position: number, maxLength: number = 150): string {
143
- const afterText = fullDocText.slice(position, position + maxLength);
144
- const sentenceEnd = afterText.search(/[.!?]\s/);
145
- return sentenceEnd >= 0
146
- ? afterText.slice(0, sentenceEnd + 1).trim()
147
- : afterText.slice(0, 80).trim();
148
- }
149
-
150
- for (const range of comments) {
151
- anchors.set(range.id, {
152
- anchor: range.anchor,
153
- before: getContextBefore(range.start),
154
- after: getContextAfter(range.end),
155
- docPosition: range.start,
156
- docLength: fullDocText.length,
157
- isEmpty: range.isEmpty,
158
- });
159
- }
160
-
161
- return { anchors, fullDocText };
162
- }
163
-
164
- /**
165
- * Extract heading paragraphs from a docx, with their text positions in the
166
- * same coordinate system as `extractCommentAnchors`'s `fullDocText` and
167
- * `CommentAnchorData.docPosition`.
168
- *
169
- * Headings are paragraphs whose `<w:pStyle>` is a Heading style. Reading
170
- * styles directly is more reliable than keyword-matching the concatenated
171
- * body text — there, paragraph boundaries are gone, so the literal string
172
- * "Methods" can appear inside prose ("results across countries") and the
173
- * structured-abstract label "Methods:" loses its colon when text runs are
174
- * concatenated.
175
- */
176
- export async function extractHeadings(docxPath: string): Promise<DocxHeading[]> {
177
- if (!fs.existsSync(docxPath)) {
178
- throw new Error(`File not found: ${docxPath}`);
179
- }
180
-
181
- const zip = openDocx(docxPath);
182
- const docXml = readPartText(zip, 'word/document.xml');
183
- if (docXml === null) return [];
184
-
185
- return buildDocTextModel(docXml).headings.map((h) => ({
186
- style: h.style,
187
- level: h.level,
188
- text: h.text,
189
- docPosition: h.position,
190
- }));
191
- }
192
-
193
- /**
194
- * Decode XML entities in text
195
- */
196
- function decodeXmlEntities(text: string): string {
197
- return text
198
- .replace(/&amp;/g, '&')
199
- .replace(/&lt;/g, '<')
200
- .replace(/&gt;/g, '>')
201
- .replace(/&quot;/g, '"')
202
- .replace(/&apos;/g, "'")
203
- .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10)))
204
- .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
205
- }
206
-
207
- /**
208
- * Extract text content from a Word XML cell
209
- */
210
- function extractCellText(cellXml: string): string {
211
- const parts: string[] = [];
212
-
213
- // Check for OMML math - replace with [math] placeholder
214
- if (cellXml.includes('<m:oMath')) {
215
- // Try to extract the text representation of math
216
- const mathTextMatches = cellXml.match(/<m:t>([^<]*)<\/m:t>/g) || [];
217
- if (mathTextMatches.length > 0) {
218
- const mathText = mathTextMatches.map((t) => t.replace(/<[^>]+>/g, '')).join('');
219
- parts.push(mathText);
220
- } else {
221
- parts.push('[math]');
222
- }
223
- }
224
-
225
- // Extract regular text from w:t elements
226
- const textMatches = cellXml.match(/<w:t[^>]*>([^<]*)<\/w:t>/g) || [];
227
- for (const match of textMatches) {
228
- const text = match.replace(/<[^>]+>/g, '');
229
- if (text) {
230
- parts.push(text);
231
- }
232
- }
233
-
234
- let result = parts.join('').trim();
235
- result = decodeXmlEntities(result);
236
-
237
- // Escape pipe characters in cell content (would break table)
238
- result = result.replace(/\|/g, '\\|');
239
-
240
- return result;
241
- }
242
-
243
- /**
244
- * Parse a table row, handling merged cells (gridSpan)
245
- */
246
- function parseTableRow(rowXml: string, expectedCols: number): ParsedRow {
247
- // Match cells - handle both <w:tc> and <w:tc ...>
248
- const cellMatches = rowXml.match(/<w:tc(?:\s[^>]*)?>[\s\S]*?<\/w:tc>/g) || [];
249
- const cells: string[] = [];
250
- const colSpans: number[] = [];
251
-
252
- for (const cellXml of cellMatches) {
253
- // Check for horizontal merge (gridSpan)
254
- const gridSpanMatch = cellXml.match(/<w:gridSpan\s+w:val="(\d+)"/);
255
- const span = gridSpanMatch ? parseInt(gridSpanMatch[1], 10) : 1;
256
-
257
- // Check for vertical merge continuation (vMerge without restart)
258
- // If vMerge is present without w:val="restart", it's a continuation - use empty
259
- const vMergeMatch = cellXml.match(/<w:vMerge(?:\s+w:val="([^"]+)")?/);
260
- const isVMergeContinuation = vMergeMatch && vMergeMatch[1] !== 'restart';
261
-
262
- const cellText = isVMergeContinuation ? '' : extractCellText(cellXml);
263
-
264
- // Add the cell content
265
- cells.push(cellText);
266
- colSpans.push(span);
267
-
268
- // For gridSpan > 1, add empty cells to maintain column alignment
269
- for (let i = 1; i < span; i++) {
270
- cells.push('');
271
- colSpans.push(0); // 0 indicates this is a spanned cell
272
- }
273
- }
274
-
275
- return { cells, colSpans };
276
- }
277
-
278
- /**
279
- * Determine table grid column count from table XML
280
- */
281
- function getTableGridCols(tableXml: string): number {
282
- // Try to get from tblGrid
283
- const gridColMatches = tableXml.match(/<w:gridCol/g) || [];
284
- if (gridColMatches.length > 0) {
285
- return gridColMatches.length;
286
- }
287
-
288
- // Fallback: count max cells in any row
289
- const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
290
- let maxCols = 0;
291
- for (const rowXml of rowMatches) {
292
- const { cells } = parseTableRow(rowXml, 0);
293
- maxCols = Math.max(maxCols, cells.length);
294
- }
295
- return maxCols;
296
- }
297
-
298
- /**
299
- * Extract tables directly from Word document XML and convert to markdown pipe tables
300
- */
301
- export async function extractWordTables(docxPath: string): Promise<WordTable[]> {
302
- const AdmZip = (await import('adm-zip')).default;
303
- const tables: WordTable[] = [];
304
-
305
- try {
306
- const zip = new AdmZip(docxPath);
307
- const docEntry = zip.getEntry('word/document.xml');
308
-
309
- if (!docEntry) {
310
- return tables;
311
- }
312
-
313
- const xml = docEntry.getData().toString('utf8');
314
-
315
- // Find all table elements
316
- const tableMatches = xml.match(/<w:tbl>[\s\S]*?<\/w:tbl>/g) || [];
317
-
318
- for (const tableXml of tableMatches) {
319
- // Determine expected column count from grid
320
- const expectedCols = getTableGridCols(tableXml);
321
-
322
- // Extract rows
323
- const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
324
- const rows: string[][] = [];
325
-
326
- for (const rowXml of rowMatches) {
327
- const { cells } = parseTableRow(rowXml, expectedCols);
328
- if (cells.length > 0) {
329
- rows.push(cells);
330
- }
331
- }
332
-
333
- if (rows.length > 0) {
334
- // Convert to markdown pipe table
335
- const markdown = convertRowsToMarkdownTable(rows);
336
- tables.push({ markdown, rowCount: rows.length, colCount: expectedCols || rows[0]?.length || 0 });
337
- }
338
- }
339
- } catch (err: any) {
340
- console.error('Error extracting tables from Word:', err.message);
341
- }
342
-
343
- return tables;
344
- }
345
-
346
- /**
347
- * Convert array of rows (each row is array of cell strings) to markdown pipe table
348
- */
349
- function convertRowsToMarkdownTable(rows: string[][]): string {
350
- if (rows.length === 0) return '';
351
-
352
- // Normalize column count (use max across all rows)
353
- const colCount = Math.max(...rows.map((r) => r.length));
354
-
355
- // Pad rows to have consistent column count
356
- const normalizedRows = rows.map((row) => {
357
- while (row.length < colCount) {
358
- row.push('');
359
- }
360
- return row;
361
- });
362
-
363
- // Build markdown table
364
- const lines: string[] = [];
365
-
366
- // Header row
367
- const header = normalizedRows[0];
368
- lines.push('| ' + header.join(' | ') + ' |');
369
-
370
- // Separator row
371
- lines.push('|' + header.map(() => '---').join('|') + '|');
372
-
373
- // Data rows
374
- for (let i = 1; i < normalizedRows.length; i++) {
375
- lines.push('| ' + normalizedRows[i].join(' | ') + ' |');
376
- }
377
-
378
- return lines.join('\n');
379
- }
380
-
381
- /**
382
- * Extract text from Word document using pandoc with track changes preserved
383
- */
384
- export async function extractFromWord(
385
- docxPath: string,
386
- options: ExtractFromWordOptions = {}
387
- ): Promise<ExtractFromWordResult> {
388
- let text: string;
389
- let messages: ExtractMessage[] = [];
390
- let extractedMedia: string[] = [];
391
- let hasTrackChanges = false;
392
- let trackChangeStats = { insertions: 0, deletions: 0 };
393
-
394
- // Determine media extraction directory
395
- const docxDir = path.dirname(docxPath);
396
- const mediaDir = options.mediaDir || path.join(docxDir, 'media');
397
-
398
- // Skip media extraction if figures already exist (e.g., when re-importing with existing source)
399
- const skipMediaExtraction = options.skipMediaExtraction || false;
400
-
401
- // Extract tables directly from Word XML (reliable, no heuristics)
402
- const wordTables = await extractWordTables(docxPath);
403
-
404
- // Try pandoc first with --track-changes=all to preserve reviewer edits
405
- try {
406
- // Build pandoc command
407
- let pandocCmd = `pandoc "${docxPath}" -t markdown --wrap=none --track-changes=all`;
408
- if (!skipMediaExtraction) {
409
- pandocCmd += ` --extract-media="${mediaDir}"`;
410
- }
411
-
412
- const { stdout } = await execAsync(pandocCmd, { maxBuffer: 50 * 1024 * 1024 });
413
- text = stdout;
414
-
415
- // Convert pandoc's track change format to CriticMarkup
416
- const origLength = text.length;
417
-
418
- // Use a more robust pattern that handles nested content
419
- text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.insertion[^}]*\}/g, (match, content) => {
420
- if (content.trim()) {
421
- trackChangeStats.insertions++;
422
- return `{++${content}++}`;
423
- }
424
- return ''; // Empty insertions are removed
425
- });
426
-
427
- text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.deletion[^}]*\}/g, (match, content) => {
428
- if (content.trim()) {
429
- trackChangeStats.deletions++;
430
- return `{--${content}--}`;
431
- }
432
- return ''; // Empty deletions are removed
433
- });
434
-
435
- // Handle any remaining pandoc track change patterns
436
- let prevText;
437
- do {
438
- prevText = text;
439
- text = text.replace(/\[([^\]]*)\]\{\.insertion[^}]*\}/g, (match, content) => {
440
- if (content.trim()) {
441
- trackChangeStats.insertions++;
442
- return `{++${content}++}`;
443
- }
444
- return '';
445
- });
446
- text = text.replace(/\[([^\]]*)\]\{\.deletion[^}]*\}/g, (match, content) => {
447
- if (content.trim()) {
448
- trackChangeStats.deletions++;
449
- return `{--${content}--}`;
450
- }
451
- return '';
452
- });
453
- } while (text !== prevText);
454
-
455
- // Handle pandoc comment patterns - remove comment text from body
456
- text = text.replace(/\[[^\]]*\]\{\.comment-start[^}]*\}/g, '');
457
- text = text.replace(/\[\]\{\.comment-end[^}]*\}/g, '');
458
-
459
- // Also handle {.mark} spans
460
- text = text.replace(/\[([^\]]*)\]\{\.mark\}/g, '$1');
461
-
462
- hasTrackChanges = trackChangeStats.insertions > 0 || trackChangeStats.deletions > 0;
463
-
464
- if (hasTrackChanges) {
465
- messages.push({
466
- type: 'info',
467
- message: `Found ${trackChangeStats.insertions} insertion(s) and ${trackChangeStats.deletions} deletion(s) from track changes`
468
- });
469
- }
470
-
471
- // Find extracted media files
472
- const mediaSubdir = path.join(mediaDir, 'media');
473
- if (fs.existsSync(mediaSubdir)) {
474
- extractedMedia = fs.readdirSync(mediaSubdir)
475
- .filter(f => /\.(png|jpg|jpeg|gif|svg|emf|wmf|tiff?)$/i.test(f))
476
- .map(f => path.join(mediaSubdir, f));
477
-
478
- if (extractedMedia.length > 0) {
479
- messages.push({
480
- type: 'info',
481
- message: `Extracted ${extractedMedia.length} image(s) to ${mediaSubdir}`
482
- });
483
- }
484
- }
485
- } catch (pandocErr: any) {
486
- // Pandoc not available — use XML-based extraction with track change support
487
- const { extractPlainTextWithTrackChanges } = await import('./word.js');
488
- const { getInstallInstructions } = await import('./dependencies.js');
489
- const installCmd = getInstallInstructions('pandoc');
490
-
491
- const xmlResult = await extractPlainTextWithTrackChanges(docxPath);
492
- text = xmlResult.text;
493
- hasTrackChanges = xmlResult.hasTrackChanges;
494
- trackChangeStats = xmlResult.stats;
495
-
496
- if (hasTrackChanges) {
497
- messages.push({
498
- type: 'warning',
499
- message: `Pandoc not installed. Using built-in XML extractor (${trackChangeStats.insertions} insertions, ${trackChangeStats.deletions} deletions preserved). Formatting may differ. Install pandoc for best results: ${installCmd}`
500
- });
501
- } else {
502
- messages.push({
503
- type: 'warning',
504
- message: `Pandoc not installed. Using built-in XML extractor (no track changes found). Install pandoc for better formatting: ${installCmd}`
505
- });
506
- }
507
- }
508
-
509
- // Extract comments directly from docx XML
510
- const comments = await extractWordComments(docxPath);
511
-
512
- // Extract comment anchor texts
513
- const { anchors } = await extractCommentAnchors(docxPath);
514
-
515
- return {
516
- text,
517
- comments,
518
- anchors,
519
- messages,
520
- extractedMedia,
521
- tables: wordTables,
522
- hasTrackChanges,
523
- trackChangeStats,
524
- };
525
- }
1
+ /**
2
+ * Word document data extraction - raw extraction from .docx files
3
+ */
4
+
5
+ import * as fs from 'fs';
6
+ import * as path from 'path';
7
+ import { exec } from 'child_process';
8
+ import { promisify } from 'util';
9
+ import { buildDocTextModel, buildCommentAnchorModel, extractComments, openDocx, readPartText } from './ooxml.js';
10
+
11
+ const execAsync = promisify(exec);
12
+
13
+ // ============================================
14
+ // Type Definitions
15
+ // ============================================
16
+
17
+ export interface WordComment {
18
+ id: string;
19
+ author: string;
20
+ date: string;
21
+ text: string;
22
+ /**
23
+ * Parent comment id when this is a reply in a Word comment thread.
24
+ * Resolved from `commentsExtended.xml`'s `w15:paraIdParent` field.
25
+ * `undefined` for top-level comments.
26
+ */
27
+ parentId?: string;
28
+ }
29
+
30
+ export interface TextNode {
31
+ xmlStart: number;
32
+ xmlEnd: number;
33
+ textStart: number;
34
+ textEnd: number;
35
+ text: string;
36
+ }
37
+
38
+ export interface CommentAnchorData {
39
+ anchor: string;
40
+ before: string;
41
+ after: string;
42
+ docPosition: number;
43
+ docLength: number;
44
+ isEmpty: boolean;
45
+ }
46
+
47
+ export interface CommentAnchorsResult {
48
+ anchors: Map<string, CommentAnchorData>;
49
+ fullDocText: string;
50
+ }
51
+
52
+ export interface DocxHeading {
53
+ /** Heading style name from `<w:pStyle>`, e.g. "Heading1" */
54
+ style: string;
55
+ /** Heading depth: 1, 2, 3, ... (parsed from style name; 0 if unknown) */
56
+ level: number;
57
+ /** Concatenated text content of the heading paragraph */
58
+ text: string;
59
+ /** Position in fullDocText (same coordinate system as CommentAnchorData.docPosition) */
60
+ docPosition: number;
61
+ }
62
+
63
+ export interface WordTable {
64
+ markdown: string;
65
+ rowCount: number;
66
+ colCount: number;
67
+ }
68
+
69
+ export interface ParsedRow {
70
+ cells: string[];
71
+ colSpans: number[];
72
+ }
73
+
74
+ export interface ExtractFromWordOptions {
75
+ mediaDir?: string;
76
+ skipMediaExtraction?: boolean;
77
+ }
78
+
79
+ export interface ExtractMessage {
80
+ type: 'info' | 'warning';
81
+ message: string;
82
+ }
83
+
84
+ export interface ExtractFromWordResult {
85
+ text: string;
86
+ comments: WordComment[];
87
+ anchors: Map<string, CommentAnchorData>;
88
+ messages: ExtractMessage[];
89
+ extractedMedia: string[];
90
+ tables: WordTable[];
91
+ hasTrackChanges: boolean;
92
+ trackChangeStats: { insertions: number; deletions: number };
93
+ }
94
+
95
+ // ============================================
96
+ // Functions
97
+ // ============================================
98
+
99
+ /**
100
+ * Extract comments directly from Word docx comments.xml
101
+ */
102
+ export async function extractWordComments(docxPath: string): Promise<WordComment[]> {
103
+ if (!fs.existsSync(docxPath)) {
104
+ throw new Error(`File not found: ${docxPath}`);
105
+ }
106
+
107
+ const zip = openDocx(docxPath);
108
+ // Word truncates the stored date to its day for display; keep that contract.
109
+ return extractComments(zip).map((c) => ({
110
+ id: c.id,
111
+ author: c.author,
112
+ date: c.date.slice(0, 10),
113
+ text: c.text,
114
+ parentId: c.parentId,
115
+ }));
116
+ }
117
+
118
+ /**
119
+ * Extract comment anchor texts from document.xml with surrounding context
120
+ * Returns map of comment ID -> {anchor, before, after, docPosition, isEmpty} for better matching
121
+ * Also returns fullDocText for section boundary matching
122
+ */
123
+ export async function extractCommentAnchors(docxPath: string): Promise<CommentAnchorsResult> {
124
+ const anchors = new Map<string, CommentAnchorData>();
125
+
126
+ const zip = openDocx(docxPath);
127
+ const { fullDocText, comments } = buildCommentAnchorModel(zip);
128
+ if (!fullDocText && comments.length === 0) {
129
+ return { anchors, fullDocText: '' };
130
+ }
131
+
132
+ // Context surrounding the anchor, taken from the same plain-text coordinate
133
+ // system as docPosition so the placement engine can compare like with like.
134
+ function getContextBefore(position: number, maxLength: number = 150): string {
135
+ const beforeText = fullDocText.slice(Math.max(0, position - maxLength), position);
136
+ const sentenceStart = beforeText.search(/[.!?]\s+[A-Z][^.!?]*$/);
137
+ return sentenceStart >= 0
138
+ ? beforeText.slice(sentenceStart + 2).trim()
139
+ : beforeText.slice(-80).trim();
140
+ }
141
+
142
+ function getContextAfter(position: number, maxLength: number = 150): string {
143
+ const afterText = fullDocText.slice(position, position + maxLength);
144
+ const sentenceEnd = afterText.search(/[.!?]\s/);
145
+ return sentenceEnd >= 0
146
+ ? afterText.slice(0, sentenceEnd + 1).trim()
147
+ : afterText.slice(0, 80).trim();
148
+ }
149
+
150
+ for (const range of comments) {
151
+ anchors.set(range.id, {
152
+ anchor: range.anchor,
153
+ before: getContextBefore(range.start),
154
+ after: getContextAfter(range.end),
155
+ docPosition: range.start,
156
+ docLength: fullDocText.length,
157
+ isEmpty: range.isEmpty,
158
+ });
159
+ }
160
+
161
+ return { anchors, fullDocText };
162
+ }
163
+
164
+ /**
165
+ * Extract heading paragraphs from a docx, with their text positions in the
166
+ * same coordinate system as `extractCommentAnchors`'s `fullDocText` and
167
+ * `CommentAnchorData.docPosition`.
168
+ *
169
+ * Headings are paragraphs whose `<w:pStyle>` is a Heading style. Reading
170
+ * styles directly is more reliable than keyword-matching the concatenated
171
+ * body text — there, paragraph boundaries are gone, so the literal string
172
+ * "Methods" can appear inside prose ("results across countries") and the
173
+ * structured-abstract label "Methods:" loses its colon when text runs are
174
+ * concatenated.
175
+ */
176
+ export async function extractHeadings(docxPath: string): Promise<DocxHeading[]> {
177
+ if (!fs.existsSync(docxPath)) {
178
+ throw new Error(`File not found: ${docxPath}`);
179
+ }
180
+
181
+ const zip = openDocx(docxPath);
182
+ const docXml = readPartText(zip, 'word/document.xml');
183
+ if (docXml === null) return [];
184
+
185
+ return buildDocTextModel(docXml).headings.map((h) => ({
186
+ style: h.style,
187
+ level: h.level,
188
+ text: h.text,
189
+ docPosition: h.position,
190
+ }));
191
+ }
192
+
193
+ /**
194
+ * Decode XML entities in text
195
+ */
196
+ function decodeXmlEntities(text: string): string {
197
+ return text
198
+ .replace(/&amp;/g, '&')
199
+ .replace(/&lt;/g, '<')
200
+ .replace(/&gt;/g, '>')
201
+ .replace(/&quot;/g, '"')
202
+ .replace(/&apos;/g, "'")
203
+ .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10)))
204
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
205
+ }
206
+
207
+ /**
208
+ * Extract text content from a Word XML cell
209
+ */
210
+ function extractCellText(cellXml: string): string {
211
+ const parts: string[] = [];
212
+
213
+ // Check for OMML math - replace with [math] placeholder
214
+ if (cellXml.includes('<m:oMath')) {
215
+ // Try to extract the text representation of math
216
+ const mathTextMatches = cellXml.match(/<m:t>([^<]*)<\/m:t>/g) || [];
217
+ if (mathTextMatches.length > 0) {
218
+ const mathText = mathTextMatches.map((t) => t.replace(/<[^>]+>/g, '')).join('');
219
+ parts.push(mathText);
220
+ } else {
221
+ parts.push('[math]');
222
+ }
223
+ }
224
+
225
+ // Extract regular text from w:t elements
226
+ const textMatches = cellXml.match(/<w:t[^>]*>([^<]*)<\/w:t>/g) || [];
227
+ for (const match of textMatches) {
228
+ const text = match.replace(/<[^>]+>/g, '');
229
+ if (text) {
230
+ parts.push(text);
231
+ }
232
+ }
233
+
234
+ let result = parts.join('').trim();
235
+ result = decodeXmlEntities(result);
236
+
237
+ // Escape pipe characters in cell content (would break table)
238
+ result = result.replace(/\|/g, '\\|');
239
+
240
+ return result;
241
+ }
242
+
243
+ /**
244
+ * Parse a table row, handling merged cells (gridSpan)
245
+ */
246
+ function parseTableRow(rowXml: string, expectedCols: number): ParsedRow {
247
+ // Match cells - handle both <w:tc> and <w:tc ...>
248
+ const cellMatches = rowXml.match(/<w:tc(?:\s[^>]*)?>[\s\S]*?<\/w:tc>/g) || [];
249
+ const cells: string[] = [];
250
+ const colSpans: number[] = [];
251
+
252
+ for (const cellXml of cellMatches) {
253
+ // Check for horizontal merge (gridSpan)
254
+ const gridSpanMatch = cellXml.match(/<w:gridSpan\s+w:val="(\d+)"/);
255
+ const span = gridSpanMatch ? parseInt(gridSpanMatch[1], 10) : 1;
256
+
257
+ // Check for vertical merge continuation (vMerge without restart)
258
+ // If vMerge is present without w:val="restart", it's a continuation - use empty
259
+ const vMergeMatch = cellXml.match(/<w:vMerge(?:\s+w:val="([^"]+)")?/);
260
+ const isVMergeContinuation = vMergeMatch && vMergeMatch[1] !== 'restart';
261
+
262
+ const cellText = isVMergeContinuation ? '' : extractCellText(cellXml);
263
+
264
+ // Add the cell content
265
+ cells.push(cellText);
266
+ colSpans.push(span);
267
+
268
+ // For gridSpan > 1, add empty cells to maintain column alignment
269
+ for (let i = 1; i < span; i++) {
270
+ cells.push('');
271
+ colSpans.push(0); // 0 indicates this is a spanned cell
272
+ }
273
+ }
274
+
275
+ return { cells, colSpans };
276
+ }
277
+
278
+ /**
279
+ * Determine table grid column count from table XML
280
+ */
281
+ function getTableGridCols(tableXml: string): number {
282
+ // Try to get from tblGrid
283
+ const gridColMatches = tableXml.match(/<w:gridCol/g) || [];
284
+ if (gridColMatches.length > 0) {
285
+ return gridColMatches.length;
286
+ }
287
+
288
+ // Fallback: count max cells in any row
289
+ const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
290
+ let maxCols = 0;
291
+ for (const rowXml of rowMatches) {
292
+ const { cells } = parseTableRow(rowXml, 0);
293
+ maxCols = Math.max(maxCols, cells.length);
294
+ }
295
+ return maxCols;
296
+ }
297
+
298
+ /**
299
+ * Extract tables directly from Word document XML and convert to markdown pipe tables
300
+ */
301
+ export async function extractWordTables(docxPath: string): Promise<WordTable[]> {
302
+ const AdmZip = (await import('adm-zip')).default;
303
+ const tables: WordTable[] = [];
304
+
305
+ try {
306
+ const zip = new AdmZip(docxPath);
307
+ const docEntry = zip.getEntry('word/document.xml');
308
+
309
+ if (!docEntry) {
310
+ return tables;
311
+ }
312
+
313
+ const xml = docEntry.getData().toString('utf8');
314
+
315
+ // Find all table elements
316
+ const tableMatches = xml.match(/<w:tbl>[\s\S]*?<\/w:tbl>/g) || [];
317
+
318
+ for (const tableXml of tableMatches) {
319
+ // Determine expected column count from grid
320
+ const expectedCols = getTableGridCols(tableXml);
321
+
322
+ // Extract rows
323
+ const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
324
+ const rows: string[][] = [];
325
+
326
+ for (const rowXml of rowMatches) {
327
+ const { cells } = parseTableRow(rowXml, expectedCols);
328
+ if (cells.length > 0) {
329
+ rows.push(cells);
330
+ }
331
+ }
332
+
333
+ if (rows.length > 0) {
334
+ // Convert to markdown pipe table
335
+ const markdown = convertRowsToMarkdownTable(rows);
336
+ tables.push({ markdown, rowCount: rows.length, colCount: expectedCols || rows[0]?.length || 0 });
337
+ }
338
+ }
339
+ } catch (err: any) {
340
+ console.error('Error extracting tables from Word:', err.message);
341
+ }
342
+
343
+ return tables;
344
+ }
345
+
346
+ /**
347
+ * Convert array of rows (each row is array of cell strings) to markdown pipe table
348
+ */
349
+ function convertRowsToMarkdownTable(rows: string[][]): string {
350
+ if (rows.length === 0) return '';
351
+
352
+ // Normalize column count (use max across all rows)
353
+ const colCount = Math.max(...rows.map((r) => r.length));
354
+
355
+ // Pad rows to have consistent column count
356
+ const normalizedRows = rows.map((row) => {
357
+ while (row.length < colCount) {
358
+ row.push('');
359
+ }
360
+ return row;
361
+ });
362
+
363
+ // Build markdown table
364
+ const lines: string[] = [];
365
+
366
+ // Header row
367
+ const header = normalizedRows[0];
368
+ lines.push('| ' + header.join(' | ') + ' |');
369
+
370
+ // Separator row
371
+ lines.push('|' + header.map(() => '---').join('|') + '|');
372
+
373
+ // Data rows
374
+ for (let i = 1; i < normalizedRows.length; i++) {
375
+ lines.push('| ' + normalizedRows[i].join(' | ') + ' |');
376
+ }
377
+
378
+ return lines.join('\n');
379
+ }
380
+
381
+ /**
382
+ * Extract text from Word document using pandoc with track changes preserved
383
+ */
384
+ export async function extractFromWord(
385
+ docxPath: string,
386
+ options: ExtractFromWordOptions = {}
387
+ ): Promise<ExtractFromWordResult> {
388
+ let text: string;
389
+ let messages: ExtractMessage[] = [];
390
+ let extractedMedia: string[] = [];
391
+ let hasTrackChanges = false;
392
+ let trackChangeStats = { insertions: 0, deletions: 0 };
393
+
394
+ // Determine media extraction directory
395
+ const docxDir = path.dirname(docxPath);
396
+ const mediaDir = options.mediaDir || path.join(docxDir, 'media');
397
+
398
+ // Skip media extraction if figures already exist (e.g., when re-importing with existing source)
399
+ const skipMediaExtraction = options.skipMediaExtraction || false;
400
+
401
+ // Extract tables directly from Word XML (reliable, no heuristics)
402
+ const wordTables = await extractWordTables(docxPath);
403
+
404
+ // Try pandoc first with --track-changes=all to preserve reviewer edits
405
+ try {
406
+ // Build pandoc command
407
+ let pandocCmd = `pandoc "${docxPath}" -t markdown --wrap=none --track-changes=all`;
408
+ if (!skipMediaExtraction) {
409
+ pandocCmd += ` --extract-media="${mediaDir}"`;
410
+ }
411
+
412
+ const { stdout } = await execAsync(pandocCmd, { maxBuffer: 50 * 1024 * 1024 });
413
+ text = stdout;
414
+
415
+ // Convert pandoc's track change format to CriticMarkup
416
+ const origLength = text.length;
417
+
418
+ // Use a more robust pattern that handles nested content
419
+ text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.insertion[^}]*\}/g, (match, content) => {
420
+ if (content.trim()) {
421
+ trackChangeStats.insertions++;
422
+ return `{++${content}++}`;
423
+ }
424
+ return ''; // Empty insertions are removed
425
+ });
426
+
427
+ text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.deletion[^}]*\}/g, (match, content) => {
428
+ if (content.trim()) {
429
+ trackChangeStats.deletions++;
430
+ return `{--${content}--}`;
431
+ }
432
+ return ''; // Empty deletions are removed
433
+ });
434
+
435
+ // Handle any remaining pandoc track change patterns
436
+ let prevText;
437
+ do {
438
+ prevText = text;
439
+ text = text.replace(/\[([^\]]*)\]\{\.insertion[^}]*\}/g, (match, content) => {
440
+ if (content.trim()) {
441
+ trackChangeStats.insertions++;
442
+ return `{++${content}++}`;
443
+ }
444
+ return '';
445
+ });
446
+ text = text.replace(/\[([^\]]*)\]\{\.deletion[^}]*\}/g, (match, content) => {
447
+ if (content.trim()) {
448
+ trackChangeStats.deletions++;
449
+ return `{--${content}--}`;
450
+ }
451
+ return '';
452
+ });
453
+ } while (text !== prevText);
454
+
455
+ // Handle pandoc comment patterns - remove comment text from body
456
+ text = text.replace(/\[[^\]]*\]\{\.comment-start[^}]*\}/g, '');
457
+ text = text.replace(/\[\]\{\.comment-end[^}]*\}/g, '');
458
+
459
+ // Also handle {.mark} spans
460
+ text = text.replace(/\[([^\]]*)\]\{\.mark\}/g, '$1');
461
+
462
+ hasTrackChanges = trackChangeStats.insertions > 0 || trackChangeStats.deletions > 0;
463
+
464
+ if (hasTrackChanges) {
465
+ messages.push({
466
+ type: 'info',
467
+ message: `Found ${trackChangeStats.insertions} insertion(s) and ${trackChangeStats.deletions} deletion(s) from track changes`
468
+ });
469
+ }
470
+
471
+ // Find extracted media files
472
+ const mediaSubdir = path.join(mediaDir, 'media');
473
+ if (fs.existsSync(mediaSubdir)) {
474
+ extractedMedia = fs.readdirSync(mediaSubdir)
475
+ .filter(f => /\.(png|jpg|jpeg|gif|svg|emf|wmf|tiff?)$/i.test(f))
476
+ .map(f => path.join(mediaSubdir, f));
477
+
478
+ if (extractedMedia.length > 0) {
479
+ messages.push({
480
+ type: 'info',
481
+ message: `Extracted ${extractedMedia.length} image(s) to ${mediaSubdir}`
482
+ });
483
+ }
484
+ }
485
+ } catch (pandocErr: any) {
486
+ // Pandoc not available — use XML-based extraction with track change support
487
+ const { extractPlainTextWithTrackChanges } = await import('./word.js');
488
+ const { getInstallInstructions } = await import('./dependencies.js');
489
+ const installCmd = getInstallInstructions('pandoc');
490
+
491
+ const xmlResult = await extractPlainTextWithTrackChanges(docxPath);
492
+ text = xmlResult.text;
493
+ hasTrackChanges = xmlResult.hasTrackChanges;
494
+ trackChangeStats = xmlResult.stats;
495
+
496
+ if (hasTrackChanges) {
497
+ messages.push({
498
+ type: 'warning',
499
+ message: `Pandoc not installed. Using built-in XML extractor (${trackChangeStats.insertions} insertions, ${trackChangeStats.deletions} deletions preserved). Formatting may differ. Install pandoc for best results: ${installCmd}`
500
+ });
501
+ } else {
502
+ messages.push({
503
+ type: 'warning',
504
+ message: `Pandoc not installed. Using built-in XML extractor (no track changes found). Install pandoc for better formatting: ${installCmd}`
505
+ });
506
+ }
507
+ }
508
+
509
+ // Extract comments directly from docx XML
510
+ const comments = await extractWordComments(docxPath);
511
+
512
+ // Extract comment anchor texts
513
+ const { anchors } = await extractCommentAnchors(docxPath);
514
+
515
+ return {
516
+ text,
517
+ comments,
518
+ anchors,
519
+ messages,
520
+ extractedMedia,
521
+ tables: wordTables,
522
+ hasTrackChanges,
523
+ trackChangeStats,
524
+ };
525
+ }