docrev 0.11.3 → 0.12.0

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 (193) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/dist/bin/rev.js +29 -21
  4. package/dist/bin/rev.js.map +1 -1
  5. package/dist/lib/build.d.ts +43 -0
  6. package/dist/lib/build.d.ts.map +1 -1
  7. package/dist/lib/build.js +175 -5
  8. package/dist/lib/build.js.map +1 -1
  9. package/dist/lib/commands/build.d.ts.map +1 -1
  10. package/dist/lib/commands/build.js +39 -125
  11. package/dist/lib/commands/build.js.map +1 -1
  12. package/dist/lib/commands/comments.js +3 -3
  13. package/dist/lib/commands/comments.js.map +1 -1
  14. package/dist/lib/commands/context.d.ts +12 -1
  15. package/dist/lib/commands/context.d.ts.map +1 -1
  16. package/dist/lib/commands/context.js +34 -1
  17. package/dist/lib/commands/context.js.map +1 -1
  18. package/dist/lib/commands/merge-resolve.js +1 -1
  19. package/dist/lib/commands/merge-resolve.js.map +1 -1
  20. package/dist/lib/commands/quality.js +2 -2
  21. package/dist/lib/commands/quality.js.map +1 -1
  22. package/dist/lib/commands/sections.js +1 -1
  23. package/dist/lib/commands/sections.js.map +1 -1
  24. package/dist/lib/commands/text-ops.js +1 -1
  25. package/dist/lib/commands/text-ops.js.map +1 -1
  26. package/dist/lib/commands/utilities.d.ts.map +1 -1
  27. package/dist/lib/commands/utilities.js +5 -2
  28. package/dist/lib/commands/utilities.js.map +1 -1
  29. package/dist/lib/commands/word-tools.js +2 -2
  30. package/dist/lib/commands/word-tools.js.map +1 -1
  31. package/dist/lib/crossref.d.ts.map +1 -1
  32. package/dist/lib/crossref.js +12 -41
  33. package/dist/lib/crossref.js.map +1 -1
  34. package/dist/lib/csl.d.ts.map +1 -1
  35. package/dist/lib/csl.js +14 -22
  36. package/dist/lib/csl.js.map +1 -1
  37. package/dist/lib/diff-engine.js +1 -1
  38. package/dist/lib/diff-engine.js.map +1 -1
  39. package/dist/lib/equations.d.ts.map +1 -1
  40. package/dist/lib/equations.js +12 -3
  41. package/dist/lib/equations.js.map +1 -1
  42. package/dist/lib/errors.d.ts.map +1 -1
  43. package/dist/lib/errors.js +1 -30
  44. package/dist/lib/errors.js.map +1 -1
  45. package/dist/lib/image-registry.d.ts.map +1 -1
  46. package/dist/lib/image-registry.js +4 -0
  47. package/dist/lib/image-registry.js.map +1 -1
  48. package/dist/lib/import.d.ts +1 -1
  49. package/dist/lib/import.d.ts.map +1 -1
  50. package/dist/lib/import.js +1 -1
  51. package/dist/lib/import.js.map +1 -1
  52. package/dist/lib/input.d.ts +0 -11
  53. package/dist/lib/input.d.ts.map +1 -1
  54. package/dist/lib/input.js +0 -35
  55. package/dist/lib/input.js.map +1 -1
  56. package/dist/lib/merge.d.ts.map +1 -1
  57. package/dist/lib/merge.js +9 -1
  58. package/dist/lib/merge.js.map +1 -1
  59. package/dist/lib/ooxml.d.ts +22 -0
  60. package/dist/lib/ooxml.d.ts.map +1 -1
  61. package/dist/lib/ooxml.js +130 -0
  62. package/dist/lib/ooxml.js.map +1 -1
  63. package/dist/lib/orcid.d.ts.map +1 -1
  64. package/dist/lib/orcid.js +16 -7
  65. package/dist/lib/orcid.js.map +1 -1
  66. package/dist/lib/plugins.d.ts.map +1 -1
  67. package/dist/lib/plugins.js +8 -4
  68. package/dist/lib/plugins.js.map +1 -1
  69. package/dist/lib/protect-restore.d.ts.map +1 -1
  70. package/dist/lib/protect-restore.js +7 -5
  71. package/dist/lib/protect-restore.js.map +1 -1
  72. package/dist/lib/restore-references.d.ts.map +1 -1
  73. package/dist/lib/restore-references.js +25 -3
  74. package/dist/lib/restore-references.js.map +1 -1
  75. package/dist/lib/schema.d.ts.map +1 -1
  76. package/dist/lib/schema.js +1 -19
  77. package/dist/lib/schema.js.map +1 -1
  78. package/dist/lib/slides.js +1 -1
  79. package/dist/lib/slides.js.map +1 -1
  80. package/dist/lib/spelling.js +1 -1
  81. package/dist/lib/spelling.js.map +1 -1
  82. package/dist/lib/tui.js +0 -1
  83. package/dist/lib/tui.js.map +1 -1
  84. package/dist/lib/utils.d.ts +14 -0
  85. package/dist/lib/utils.d.ts.map +1 -1
  86. package/dist/lib/utils.js +41 -0
  87. package/dist/lib/utils.js.map +1 -1
  88. package/dist/lib/word-extraction.d.ts +5 -5
  89. package/dist/lib/word-extraction.d.ts.map +1 -1
  90. package/dist/lib/word-extraction.js +25 -106
  91. package/dist/lib/word-extraction.js.map +1 -1
  92. package/dist/lib/word.d.ts +14 -38
  93. package/dist/lib/word.d.ts.map +1 -1
  94. package/dist/lib/word.js +24 -179
  95. package/dist/lib/word.js.map +1 -1
  96. package/dist/lib/wordcomments.d.ts.map +1 -1
  97. package/dist/lib/wordcomments.js +9 -7
  98. package/dist/lib/wordcomments.js.map +1 -1
  99. package/package.json +17 -6
  100. package/.gitattributes +0 -1
  101. package/PLAN-tables-and-postprocess.md +0 -850
  102. package/bin/rev.ts +0 -145
  103. package/docs-src/build.py +0 -113
  104. package/docs-src/extra.css +0 -208
  105. package/docs-src/md-to-html.lua +0 -6
  106. package/docs-src/template.html +0 -116
  107. package/eslint.config.js +0 -27
  108. package/lib/anchor-match.ts +0 -307
  109. package/lib/annotations.ts +0 -695
  110. package/lib/build.ts +0 -2047
  111. package/lib/citations.ts +0 -160
  112. package/lib/commands/build.ts +0 -885
  113. package/lib/commands/citations.ts +0 -515
  114. package/lib/commands/comments.ts +0 -1077
  115. package/lib/commands/context.ts +0 -185
  116. package/lib/commands/core.ts +0 -328
  117. package/lib/commands/doi.ts +0 -451
  118. package/lib/commands/file-ops.ts +0 -372
  119. package/lib/commands/history.ts +0 -320
  120. package/lib/commands/index.ts +0 -87
  121. package/lib/commands/init.ts +0 -259
  122. package/lib/commands/merge-resolve.ts +0 -378
  123. package/lib/commands/preview.ts +0 -178
  124. package/lib/commands/project-info.ts +0 -244
  125. package/lib/commands/quality.ts +0 -517
  126. package/lib/commands/response.ts +0 -454
  127. package/lib/commands/section-boundaries.ts +0 -82
  128. package/lib/commands/sections.ts +0 -451
  129. package/lib/commands/sync.ts +0 -689
  130. package/lib/commands/text-ops.ts +0 -449
  131. package/lib/commands/utilities.ts +0 -448
  132. package/lib/commands/verify-anchors.ts +0 -272
  133. package/lib/commands/word-tools.ts +0 -340
  134. package/lib/comment-realign.ts +0 -99
  135. package/lib/config.ts +0 -84
  136. package/lib/crossref.ts +0 -781
  137. package/lib/csl.ts +0 -191
  138. package/lib/dependencies.ts +0 -132
  139. package/lib/diff-engine.ts +0 -465
  140. package/lib/doi-cache.ts +0 -115
  141. package/lib/doi.ts +0 -879
  142. package/lib/equations.ts +0 -506
  143. package/lib/errors.ts +0 -350
  144. package/lib/format.ts +0 -541
  145. package/lib/git.ts +0 -326
  146. package/lib/grammar.ts +0 -303
  147. package/lib/image-registry.ts +0 -180
  148. package/lib/import.ts +0 -932
  149. package/lib/input.ts +0 -174
  150. package/lib/journals.ts +0 -543
  151. package/lib/macro-filter.lua +0 -201
  152. package/lib/macros.ts +0 -273
  153. package/lib/merge.ts +0 -633
  154. package/lib/ooxml.ts +0 -768
  155. package/lib/orcid.ts +0 -144
  156. package/lib/pdf-comments.ts +0 -263
  157. package/lib/pdf-import.ts +0 -524
  158. package/lib/plugins.ts +0 -362
  159. package/lib/postprocess.ts +0 -188
  160. package/lib/pptx-color-filter.lua +0 -37
  161. package/lib/pptx-template.ts +0 -469
  162. package/lib/pptx-themes/academic.pptx +0 -0
  163. package/lib/pptx-themes/corporate.pptx +0 -0
  164. package/lib/pptx-themes/dark.pptx +0 -0
  165. package/lib/pptx-themes/default.pptx +0 -0
  166. package/lib/pptx-themes/minimal.pptx +0 -0
  167. package/lib/pptx-themes/plant.pptx +0 -0
  168. package/lib/pptx-themes.ts +0 -483
  169. package/lib/protect-restore.ts +0 -520
  170. package/lib/rate-limiter.ts +0 -127
  171. package/lib/response.ts +0 -200
  172. package/lib/restore-references.ts +0 -240
  173. package/lib/review.ts +0 -327
  174. package/lib/schema.ts +0 -494
  175. package/lib/scientific-words.ts +0 -73
  176. package/lib/sections.ts +0 -428
  177. package/lib/slides.ts +0 -756
  178. package/lib/spelling.ts +0 -334
  179. package/lib/templates.ts +0 -526
  180. package/lib/themes.ts +0 -742
  181. package/lib/trackchanges.ts +0 -166
  182. package/lib/tui.ts +0 -450
  183. package/lib/types.ts +0 -546
  184. package/lib/undo.ts +0 -250
  185. package/lib/utils.ts +0 -69
  186. package/lib/variables.ts +0 -179
  187. package/lib/word-extraction.ts +0 -525
  188. package/lib/word.ts +0 -526
  189. package/lib/wordcomments.ts +0 -789
  190. package/mkdocs.yml +0 -64
  191. package/scripts/postbuild.js +0 -47
  192. package/tsconfig.json +0 -26
  193. package/types/index.d.ts +0 -531
package/lib/pdf-import.ts DELETED
@@ -1,524 +0,0 @@
1
- /**
2
- * PDF comment extraction for docrev
3
- *
4
- * Extracts annotations (comments, highlights, sticky notes) from PDF files
5
- * and converts them to CriticMarkup format for insertion into markdown.
6
- * Also extracts the actual text content under highlights using pdfjs-dist.
7
- */
8
-
9
- import * as fs from 'fs';
10
- import { PDFDocument } from 'pdf-lib';
11
-
12
- /**
13
- * Annotation types we care about
14
- */
15
- const COMMENT_TYPES = [
16
- 'Text', // Sticky notes
17
- 'FreeText', // Text boxes
18
- 'Highlight', // Highlighted text with comment
19
- 'Underline', // Underlined text with comment
20
- 'StrikeOut', // Strikethrough (deletion suggestion)
21
- 'Squiggly', // Squiggly underline
22
- 'Popup', // Popup comments (attached to other annotations)
23
- ];
24
-
25
- /**
26
- * Raw PDF annotation extracted from pdf-lib
27
- */
28
- export interface PdfAnnotation {
29
- type: string;
30
- page: number;
31
- contents: string;
32
- author: string;
33
- date: string;
34
- rect: number[];
35
- quadPoints: number[];
36
- }
37
-
38
- /**
39
- * PDF comment converted to CriticMarkup format
40
- */
41
- export interface PdfComment {
42
- author: string;
43
- text: string;
44
- page: number;
45
- type: string;
46
- date?: string;
47
- }
48
-
49
- /**
50
- * PDF annotation with extracted highlighted text
51
- */
52
- export interface PdfAnnotationWithText extends PdfAnnotation {
53
- highlightedText: string;
54
- }
55
-
56
- /**
57
- * Options for PDF extraction
58
- */
59
- export interface ExtractOptions {
60
- timeout?: number;
61
- }
62
-
63
- /**
64
- * Options for markdown insertion
65
- */
66
- export interface InsertOptions {
67
- sectionPerPage?: boolean;
68
- }
69
-
70
- /**
71
- * Statistics about PDF comments
72
- */
73
- export interface PdfCommentStats {
74
- total: number;
75
- byType: Record<string, number>;
76
- byAuthor: Record<string, number>;
77
- byPage: Record<number, number>;
78
- }
79
-
80
- /**
81
- * Text item from pdfjs-dist
82
- */
83
- interface PdfTextItem {
84
- str: string;
85
- x: number;
86
- y: number;
87
- width: number;
88
- height: number;
89
- }
90
-
91
- /**
92
- * Extract raw annotations from a PDF file
93
- * @param pdfPath - Path to PDF file
94
- * @param options - { timeout: number (ms) }
95
- * @returns Array of PDF annotations
96
- */
97
- export async function extractPdfAnnotations(
98
- pdfPath: string,
99
- options: ExtractOptions = {}
100
- ): Promise<PdfAnnotation[]> {
101
- const { timeout = 30000 } = options;
102
-
103
- // Validate file exists
104
- if (!fs.existsSync(pdfPath)) {
105
- throw new Error(`File not found: ${pdfPath}`);
106
- }
107
-
108
- let pdfBytes: Buffer;
109
- try {
110
- pdfBytes = fs.readFileSync(pdfPath);
111
- } catch (err) {
112
- const error = err as Error;
113
- throw new Error(`Cannot read PDF file: ${error.message}`);
114
- }
115
-
116
- // Create a promise that rejects after timeout
117
- const timeoutPromise = new Promise<never>((_, reject) => {
118
- setTimeout(() => reject(new Error(`PDF extraction timed out after ${timeout / 1000}s`)), timeout);
119
- });
120
-
121
- let pdfDoc: PDFDocument;
122
- try {
123
- pdfDoc = await Promise.race([
124
- PDFDocument.load(pdfBytes, { ignoreEncryption: true }),
125
- timeoutPromise,
126
- ]);
127
- } catch (err) {
128
- const error = err as Error;
129
- if (error.message.includes('timed out')) {
130
- throw error;
131
- }
132
- throw new Error(`Invalid or corrupted PDF file: ${error.message}`);
133
- }
134
-
135
- const annotations: PdfAnnotation[] = [];
136
- const pages = pdfDoc.getPages();
137
-
138
- for (let pageNum = 0; pageNum < pages.length; pageNum++) {
139
- const page = pages[pageNum];
140
- const annots = page.node.Annots();
141
-
142
- if (!annots) continue;
143
-
144
- const annotRefs = annots.asArray();
145
-
146
- for (const annotRef of annotRefs) {
147
- try {
148
- const annot = (annotRef as any).dict || annotRef;
149
- if (!annot) continue;
150
-
151
- // Get annotation type
152
- const subtypeName = annot.get(pdfDoc.context.obj('Subtype'));
153
- const subtype = subtypeName?.toString?.()?.replace('/', '') || '';
154
-
155
- if (!COMMENT_TYPES.includes(subtype)) continue;
156
-
157
- // Extract contents (the comment text)
158
- const contentsObj = annot.get(pdfDoc.context.obj('Contents'));
159
- const contents = contentsObj?.toString?.() || contentsObj?.decodeText?.() || '';
160
-
161
- // Extract author (T field in PDF spec)
162
- const authorObj = annot.get(pdfDoc.context.obj('T'));
163
- const author = authorObj?.toString?.() || authorObj?.decodeText?.() || 'Unknown';
164
-
165
- // Extract modification date
166
- const dateObj = annot.get(pdfDoc.context.obj('M'));
167
- const dateStr = dateObj?.toString?.() || '';
168
- const date = parsePdfDate(dateStr);
169
-
170
- // Extract rectangle (position on page)
171
- const rectObj = annot.get(pdfDoc.context.obj('Rect'));
172
- const rect = rectObj?.asArray?.()?.map((n: any) => n?.asNumber?.() || 0) || [0, 0, 0, 0];
173
-
174
- // Extract QuadPoints for highlights (the actual text bounds)
175
- const quadObj = annot.get(pdfDoc.context.obj('QuadPoints'));
176
- const quadPoints = quadObj?.asArray?.()?.map((n: any) => n?.asNumber?.() || 0) || [];
177
-
178
- // Skip empty annotations
179
- if (!contents.trim() && subtype !== 'StrikeOut') continue;
180
-
181
- annotations.push({
182
- type: subtype,
183
- page: pageNum + 1,
184
- contents: cleanPdfString(contents),
185
- author: cleanPdfString(author),
186
- date,
187
- rect,
188
- quadPoints,
189
- });
190
- } catch (err) {
191
- // Skip malformed annotations
192
- continue;
193
- }
194
- }
195
- }
196
-
197
- // Sort by page, then by vertical position (top to bottom)
198
- annotations.sort((a, b) => {
199
- if (a.page !== b.page) return a.page - b.page;
200
- // Higher Y = higher on page in PDF coords
201
- return (b.rect[1] || 0) - (a.rect[1] || 0);
202
- });
203
-
204
- return annotations;
205
- }
206
-
207
- /**
208
- * Parse PDF date string (D:YYYYMMDDHHmmSS format)
209
- * @param dateStr - PDF date string
210
- * @returns ISO date string
211
- */
212
- function parsePdfDate(dateStr: string): string {
213
- if (!dateStr) return '';
214
-
215
- // Remove D: prefix and timezone info
216
- const clean = dateStr.replace(/^D:/, '').replace(/[Z+-].*$/, '');
217
-
218
- if (clean.length >= 8) {
219
- const year = clean.slice(0, 4);
220
- const month = clean.slice(4, 6);
221
- const day = clean.slice(6, 8);
222
- return `${year}-${month}-${day}`;
223
- }
224
-
225
- return '';
226
- }
227
-
228
- /**
229
- * Clean PDF string (remove parentheses, decode escape sequences)
230
- * @param str - Raw PDF string
231
- * @returns Cleaned string
232
- */
233
- function cleanPdfString(str: string): string {
234
- if (!str) return '';
235
-
236
- return str
237
- .replace(/^\(/, '') // Remove leading paren
238
- .replace(/\)$/, '') // Remove trailing paren
239
- .replace(/\\n/g, '\n') // Newlines
240
- .replace(/\\r/g, '') // Carriage returns
241
- .replace(/\\t/g, ' ') // Tabs
242
- .replace(/\\\(/g, '(') // Escaped parens
243
- .replace(/\\\)/g, ')')
244
- .replace(/\\\\/g, '\\') // Escaped backslash
245
- .trim();
246
- }
247
-
248
- /**
249
- * Convert PDF annotations to CriticMarkup comments
250
- * @param annotations - From extractPdfAnnotations
251
- * @returns Array of PDF comments
252
- */
253
- export function annotationsToComments(annotations: PdfAnnotation[]): PdfComment[] {
254
- return annotations
255
- .filter(a => a.contents.trim())
256
- .map(a => ({
257
- author: a.author || 'Reviewer',
258
- text: a.contents,
259
- page: a.page,
260
- type: a.type,
261
- date: a.date,
262
- }));
263
- }
264
-
265
- /**
266
- * Extract comments from PDF and format for display
267
- * @param pdfPath - Path to PDF file
268
- * @returns Array of PDF comments
269
- */
270
- export async function extractPdfComments(pdfPath: string): Promise<PdfComment[]> {
271
- const annotations = await extractPdfAnnotations(pdfPath);
272
- return annotationsToComments(annotations);
273
- }
274
-
275
- /**
276
- * Insert PDF comments into markdown based on page/position heuristics
277
- * Since PDFs don't have direct text anchors like Word, we use page numbers
278
- * and append comments to the end of corresponding sections
279
- *
280
- * @param markdown - The markdown content
281
- * @param comments - Comments from extractPdfComments
282
- * @param options - { sectionPerPage: boolean }
283
- * @returns Markdown with comments inserted
284
- */
285
- export function insertPdfCommentsIntoMarkdown(
286
- markdown: string,
287
- comments: PdfComment[],
288
- options: InsertOptions = {}
289
- ): string {
290
- if (comments.length === 0) return markdown;
291
-
292
- // Group comments by page
293
- const commentsByPage = new Map<number, PdfComment[]>();
294
- for (const c of comments) {
295
- if (!commentsByPage.has(c.page)) {
296
- commentsByPage.set(c.page, []);
297
- }
298
- commentsByPage.get(c.page)!.push(c);
299
- }
300
-
301
- // Strategy: Append all comments at the end with page references
302
- // This is the safest approach since we can't reliably map PDF positions to markdown
303
- const lines = markdown.split('\n');
304
- const commentBlock: string[] = [];
305
-
306
- commentBlock.push('');
307
- commentBlock.push('<!-- PDF Comments -->');
308
-
309
- for (const [page, pageComments] of Array.from(commentsByPage.entries())) {
310
- for (const c of pageComments) {
311
- const authorPrefix = c.author ? `${c.author}: ` : '';
312
- const pageRef = `[p.${page}]`;
313
- commentBlock.push(`{>>${authorPrefix}${pageRef} ${c.text}<<}`);
314
- }
315
- }
316
-
317
- return lines.join('\n') + commentBlock.join('\n');
318
- }
319
-
320
- /**
321
- * Format PDF comments for CLI display
322
- * @param comments - Array of PDF comments
323
- * @returns Formatted string
324
- */
325
- export function formatPdfComments(comments: PdfComment[]): string {
326
- if (comments.length === 0) {
327
- return 'No comments found in PDF.';
328
- }
329
-
330
- const lines: string[] = [];
331
- let currentPage = 0;
332
-
333
- for (const c of comments) {
334
- if (c.page !== currentPage) {
335
- if (currentPage > 0) lines.push('');
336
- lines.push(`Page ${c.page}:`);
337
- currentPage = c.page;
338
- }
339
-
340
- const typeIcon = getTypeIcon(c.type);
341
- const author = c.author || 'Unknown';
342
- lines.push(` ${typeIcon} [${author}] ${c.text}`);
343
- }
344
-
345
- return lines.join('\n');
346
- }
347
-
348
- /**
349
- * Get icon for annotation type
350
- * @param type - Annotation type
351
- * @returns Icon string
352
- */
353
- function getTypeIcon(type: string): string {
354
- switch (type) {
355
- case 'Text': return '📝'; // Sticky note
356
- case 'FreeText': return '💬'; // Text box
357
- case 'Highlight': return '🖍️'; // Highlight
358
- case 'Underline': return '📍'; // Underline
359
- case 'StrikeOut': return '❌'; // Strikethrough
360
- case 'Squiggly': return '〰️'; // Squiggly
361
- default: return '💬';
362
- }
363
- }
364
-
365
- /**
366
- * Get statistics about PDF comments
367
- * @param comments - Array of PDF comments
368
- * @returns Statistics object
369
- */
370
- export function getPdfCommentStats(comments: PdfComment[]): PdfCommentStats {
371
- const stats: PdfCommentStats = {
372
- total: comments.length,
373
- byType: {},
374
- byAuthor: {},
375
- byPage: {},
376
- };
377
-
378
- for (const c of comments) {
379
- stats.byType[c.type] = (stats.byType[c.type] || 0) + 1;
380
- stats.byAuthor[c.author] = (stats.byAuthor[c.author] || 0) + 1;
381
- stats.byPage[c.page] = (stats.byPage[c.page] || 0) + 1;
382
- }
383
-
384
- return stats;
385
- }
386
-
387
- /**
388
- * Extract text content from a PDF page
389
- * @param page - pdfjs page object
390
- * @returns Array of text items with positions
391
- */
392
- async function getPageTextItems(page: any): Promise<PdfTextItem[]> {
393
- const textContent = await page.getTextContent();
394
- return textContent.items.map((item: any) => ({
395
- str: item.str,
396
- x: item.transform[4],
397
- y: item.transform[5],
398
- width: item.width,
399
- height: item.height,
400
- }));
401
- }
402
-
403
- /**
404
- * Check if a point is inside a quadrilateral defined by QuadPoints
405
- * QuadPoints format: [x1,y1, x2,y2, x3,y3, x4,y4] for each quad
406
- * @param x - X coordinate
407
- * @param y - Y coordinate
408
- * @param quad - 8 numbers defining corners
409
- * @returns True if point is inside quad
410
- */
411
- function isPointInQuad(x: number, y: number, quad: number[]): boolean {
412
- if (quad.length < 8) return false;
413
-
414
- // Get bounding box from quad points
415
- const xs = [quad[0], quad[2], quad[4], quad[6]];
416
- const ys = [quad[1], quad[3], quad[5], quad[7]];
417
- const minX = Math.min(...xs);
418
- const maxX = Math.max(...xs);
419
- const minY = Math.min(...ys);
420
- const maxY = Math.max(...ys);
421
-
422
- return x >= minX && x <= maxX && y >= minY && y <= maxY;
423
- }
424
-
425
- /**
426
- * Extract highlighted text from a PDF using QuadPoints
427
- * @param pdfPath - Path to PDF file
428
- * @param annotations - Annotations with quadPoints from extractPdfAnnotations
429
- * @returns Annotations with highlighted text extracted
430
- */
431
- export async function extractHighlightedText(
432
- pdfPath: string,
433
- annotations: PdfAnnotation[]
434
- ): Promise<PdfAnnotationWithText[]> {
435
- const pdfBytes = fs.readFileSync(pdfPath);
436
- const data = new Uint8Array(pdfBytes);
437
-
438
- // Load pdfjs-dist dynamically (requires DOMMatrix, not available in Node 18)
439
- const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
440
- const loadingTask = getDocument({ data, useSystemFonts: true });
441
- const pdfDoc = await loadingTask.promise;
442
-
443
- const results: PdfAnnotationWithText[] = [];
444
-
445
- for (const annot of annotations) {
446
- // Only process text markup annotations (Highlight, Underline, StrikeOut, Squiggly)
447
- if (!['Highlight', 'Underline', 'StrikeOut', 'Squiggly'].includes(annot.type)) {
448
- results.push({ ...annot, highlightedText: '' });
449
- continue;
450
- }
451
-
452
- if (!annot.quadPoints || annot.quadPoints.length < 8) {
453
- results.push({ ...annot, highlightedText: '' });
454
- continue;
455
- }
456
-
457
- try {
458
- const page = await pdfDoc.getPage(annot.page);
459
- const textItems = await getPageTextItems(page);
460
-
461
- // Split quadPoints into individual quads (8 numbers each)
462
- const quads: number[][] = [];
463
- for (let i = 0; i < annot.quadPoints.length; i += 8) {
464
- quads.push(annot.quadPoints.slice(i, i + 8));
465
- }
466
-
467
- // Find text items that fall within any of the quads
468
- const matchedText: string[] = [];
469
- for (const item of textItems) {
470
- // Check if text item center is in any quad
471
- const centerX = item.x + (item.width || 0) / 2;
472
- const centerY = item.y + (item.height || 0) / 2;
473
-
474
- for (const quad of quads) {
475
- if (isPointInQuad(centerX, centerY, quad) || isPointInQuad(item.x, item.y, quad)) {
476
- matchedText.push(item.str);
477
- break;
478
- }
479
- }
480
- }
481
-
482
- results.push({
483
- ...annot,
484
- highlightedText: matchedText.join(' ').trim(),
485
- });
486
- } catch (err) {
487
- // If text extraction fails, just return empty
488
- results.push({ ...annot, highlightedText: '' });
489
- }
490
- }
491
-
492
- return results;
493
- }
494
-
495
- /**
496
- * Extract annotations with highlighted text in one call
497
- * @param pdfPath - Path to PDF file
498
- * @returns Annotations with highlighted text
499
- */
500
- export async function extractPdfAnnotationsWithText(pdfPath: string): Promise<PdfAnnotationWithText[]> {
501
- const annotations = await extractPdfAnnotations(pdfPath);
502
- return extractHighlightedText(pdfPath, annotations);
503
- }
504
-
505
- /**
506
- * Format annotation with highlighted text for display
507
- * @param annot - Annotation with highlightedText
508
- * @returns Formatted string
509
- */
510
- export function formatAnnotationWithText(annot: PdfAnnotationWithText): string {
511
- const typeIcon = getTypeIcon(annot.type);
512
- const author = annot.author || 'Unknown';
513
- const parts: string[] = [`${typeIcon} [${author}]`];
514
-
515
- if (annot.highlightedText) {
516
- parts.push(`"${annot.highlightedText}"`);
517
- }
518
-
519
- if (annot.contents) {
520
- parts.push(`→ ${annot.contents}`);
521
- }
522
-
523
- return parts.join(' ');
524
- }