@shuji-bonji/pdf-reader-mcp 0.9.2 → 0.11.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 (40) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.ja.md +41 -2
  3. package/README.md +43 -2
  4. package/dist/schemas/tier2.d.ts +18 -0
  5. package/dist/schemas/tier2.d.ts.map +1 -1
  6. package/dist/schemas/tier2.js +23 -0
  7. package/dist/schemas/tier2.js.map +1 -1
  8. package/dist/services/object-locator.d.ts +33 -0
  9. package/dist/services/object-locator.d.ts.map +1 -0
  10. package/dist/services/object-locator.js +340 -0
  11. package/dist/services/object-locator.js.map +1 -0
  12. package/dist/services/pdfjs-service.d.ts +61 -0
  13. package/dist/services/pdfjs-service.d.ts.map +1 -1
  14. package/dist/services/pdfjs-service.js +160 -0
  15. package/dist/services/pdfjs-service.js.map +1 -1
  16. package/dist/services/struct-tree-service.d.ts +13 -1
  17. package/dist/services/struct-tree-service.d.ts.map +1 -1
  18. package/dist/services/struct-tree-service.js +208 -5
  19. package/dist/services/struct-tree-service.js.map +1 -1
  20. package/dist/services/struct-tree-walker.d.ts +13 -0
  21. package/dist/services/struct-tree-walker.d.ts.map +1 -1
  22. package/dist/services/struct-tree-walker.js +77 -3
  23. package/dist/services/struct-tree-walker.js.map +1 -1
  24. package/dist/tools/index.d.ts.map +1 -1
  25. package/dist/tools/index.js +2 -0
  26. package/dist/tools/index.js.map +1 -1
  27. package/dist/tools/tier2/extract-structured-text.d.ts.map +1 -1
  28. package/dist/tools/tier2/extract-structured-text.js +30 -2
  29. package/dist/tools/tier2/extract-structured-text.js.map +1 -1
  30. package/dist/tools/tier2/locate-objects.d.ts +6 -0
  31. package/dist/tools/tier2/locate-objects.d.ts.map +1 -0
  32. package/dist/tools/tier2/locate-objects.js +61 -0
  33. package/dist/tools/tier2/locate-objects.js.map +1 -0
  34. package/dist/types.d.ts +95 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/utils/formatter.d.ts +10 -1
  37. package/dist/utils/formatter.d.ts.map +1 -1
  38. package/dist/utils/formatter.js +71 -0
  39. package/dist/utils/formatter.js.map +1 -1
  40. package/package.json +1 -1
@@ -0,0 +1,340 @@
1
+ /**
2
+ * Object number → drawing coordinates (Issue #20 / family gap G-A).
3
+ *
4
+ * `pdf-verify-mcp` can say *which objects* an incremental update rewrote, and
5
+ * `pdf-writer-mcp`'s `add_annotation` wants a page number and a rectangle. This
6
+ * service is the bridge between the two: given object numbers, it reports where
7
+ * on the page each object is, in the coordinate system the writer expects
8
+ * (PDF user space, origin bottom-left, pt).
9
+ *
10
+ * It OBSERVES. Nothing here judges whether an object should have changed —
11
+ * that is a question the family answers elsewhere, and mostly not at all.
12
+ *
13
+ * What it cannot do, and says so instead of guessing:
14
+ *
15
+ * - **A content stream draws the whole page.** Narrowing "obj 6 changed" to
16
+ * the paragraph that moved needs a content-stream walk with the graphics
17
+ * state carried along; that is the second half of Issue #20 (structure
18
+ * element → bbox) and is not implemented here. The page box is returned
19
+ * with the basis saying exactly that.
20
+ * - **Resources (fonts, images, colour spaces) have no coordinates.** The
21
+ * page that uses them is reported; the rectangle stays null.
22
+ * - **An object that no longer exists** — freed by a later revision, which is
23
+ * precisely what a diff may hand over — is reported as `found: false`, not
24
+ * as "no coordinates".
25
+ */
26
+ import { PDFArray, PDFDict, PDFHexString, PDFName, PDFNumber, PDFRef, PDFString, } from 'pdf-lib';
27
+ import { loadWithPdfLib } from './pdflib-service.js';
28
+ /** Resource categories whose entries are reachable from a page. */
29
+ const RESOURCE_CATEGORIES = [
30
+ 'XObject',
31
+ 'Font',
32
+ 'ExtGState',
33
+ 'Shading',
34
+ 'Pattern',
35
+ 'ColorSpace',
36
+ 'Properties',
37
+ ];
38
+ /**
39
+ * Normalise a `/Rect` array. ISO 32000-1 §7.9.5: a rectangle is written as two
40
+ * diagonally opposite corners in either order, and "shall be normalised" before
41
+ * use. `add_annotation` requires x1 < x2 and y1 < y2, so this is what makes the
42
+ * result directly usable there.
43
+ */
44
+ function normaliseRect(values) {
45
+ if (values.length !== 4 || values.some((v) => !Number.isFinite(v)))
46
+ return null;
47
+ const [a, b, c, d] = values;
48
+ return {
49
+ x1: Math.min(a, c),
50
+ y1: Math.min(b, d),
51
+ x2: Math.max(a, c),
52
+ y2: Math.max(b, d),
53
+ };
54
+ }
55
+ function numberArray(value, doc) {
56
+ const resolved = value instanceof PDFRef ? doc.context.lookup(value) : value;
57
+ if (!(resolved instanceof PDFArray))
58
+ return null;
59
+ const numbers = [];
60
+ for (let i = 0; i < resolved.size(); i += 1) {
61
+ const item = resolved.lookup(i);
62
+ if (!(item instanceof PDFNumber))
63
+ return null;
64
+ numbers.push(item.asNumber());
65
+ }
66
+ return numbers;
67
+ }
68
+ function nameOf(dict, key) {
69
+ const value = dict.get(PDFName.of(key));
70
+ return value instanceof PDFName ? value.decodeText() : null;
71
+ }
72
+ function push(map, key, page) {
73
+ const list = map.get(key);
74
+ if (list) {
75
+ if (!list.includes(page))
76
+ list.push(page);
77
+ }
78
+ else {
79
+ map.set(key, [page]);
80
+ }
81
+ }
82
+ function buildPageIndex(doc) {
83
+ const index = {
84
+ pageNumberByRef: new Map(),
85
+ boxByPage: new Map(),
86
+ annotationPages: new Map(),
87
+ contentPages: new Map(),
88
+ resourcePages: new Map(),
89
+ };
90
+ let pages = [];
91
+ try {
92
+ pages = doc.getPages();
93
+ }
94
+ catch {
95
+ // A page tree pdf-lib cannot walk (linearised hint streams, damaged trees)
96
+ // leaves the index empty; objects then resolve without a page rather than
97
+ // with a wrong one.
98
+ return index;
99
+ }
100
+ pages.forEach((page, i) => {
101
+ const pageNumber = i + 1;
102
+ index.pageNumberByRef.set(page.ref.tag, pageNumber);
103
+ try {
104
+ // pdf-lib's getCropBox already falls back to the media box when no crop
105
+ // box is set, which is the inheritance rule of ISO 32000-1 §7.7.3.3.
106
+ const box = page.getCropBox();
107
+ index.boxByPage.set(pageNumber, {
108
+ x1: box.x,
109
+ y1: box.y,
110
+ x2: box.x + box.width,
111
+ y2: box.y + box.height,
112
+ });
113
+ }
114
+ catch {
115
+ // no box: the object still gets a page number, just no rectangle
116
+ }
117
+ const node = page.node;
118
+ const annots = node.get(PDFName.of('Annots'));
119
+ const annotsArray = annots instanceof PDFRef ? doc.context.lookup(annots) : annots;
120
+ if (annotsArray instanceof PDFArray) {
121
+ for (let n = 0; n < annotsArray.size(); n += 1) {
122
+ const entry = annotsArray.get(n);
123
+ if (entry instanceof PDFRef)
124
+ push(index.annotationPages, entry.tag, pageNumber);
125
+ }
126
+ }
127
+ const contents = node.get(PDFName.of('Contents'));
128
+ if (contents instanceof PDFRef) {
129
+ push(index.contentPages, contents.tag, pageNumber);
130
+ }
131
+ else if (contents instanceof PDFArray) {
132
+ for (let n = 0; n < contents.size(); n += 1) {
133
+ const entry = contents.get(n);
134
+ if (entry instanceof PDFRef)
135
+ push(index.contentPages, entry.tag, pageNumber);
136
+ }
137
+ }
138
+ const resourcesValue = node.get(PDFName.of('Resources'));
139
+ const resources = resourcesValue instanceof PDFRef ? doc.context.lookup(resourcesValue) : resourcesValue;
140
+ if (resources instanceof PDFDict) {
141
+ if (resourcesValue instanceof PDFRef) {
142
+ push(index.resourcePages, resourcesValue.tag, pageNumber);
143
+ }
144
+ for (const category of RESOURCE_CATEGORIES) {
145
+ const groupValue = resources.get(PDFName.of(category));
146
+ const group = groupValue instanceof PDFRef ? doc.context.lookup(groupValue) : groupValue;
147
+ if (!(group instanceof PDFDict))
148
+ continue;
149
+ if (groupValue instanceof PDFRef)
150
+ push(index.resourcePages, groupValue.tag, pageNumber);
151
+ for (const [, value] of group.entries()) {
152
+ if (value instanceof PDFRef)
153
+ push(index.resourcePages, value.tag, pageNumber);
154
+ }
155
+ }
156
+ }
157
+ });
158
+ return index;
159
+ }
160
+ /** Page number an annotation names through `/P`, when it names one. */
161
+ function pageFromAnnotationParent(dict, index) {
162
+ const parent = dict.get(PDFName.of('P'));
163
+ if (!(parent instanceof PDFRef))
164
+ return null;
165
+ return index.pageNumberByRef.get(parent.tag) ?? null;
166
+ }
167
+ function locateDict(doc, ref, dict, index) {
168
+ const locations = [];
169
+ const type = nameOf(dict, 'Type');
170
+ // 1. Anything carrying a /Rect states its own rectangle. Annotations are the
171
+ // case that matters: this is the coordinate add_annotation wants.
172
+ const rect = normaliseRect(numberArray(dict.get(PDFName.of('Rect')), doc) ?? []);
173
+ if (rect) {
174
+ const pages = index.annotationPages.get(ref.tag) ??
175
+ (() => {
176
+ const viaParent = pageFromAnnotationParent(dict, index);
177
+ return viaParent === null ? [] : [viaParent];
178
+ })();
179
+ if (pages.length === 0) {
180
+ locations.push({ page: null, rect, basis: 'annotation-rect' });
181
+ }
182
+ else {
183
+ for (const page of pages)
184
+ locations.push({ page, rect, basis: 'annotation-rect' });
185
+ }
186
+ return { locations, reason: null };
187
+ }
188
+ // 2. The page object itself.
189
+ const asPage = index.pageNumberByRef.get(ref.tag);
190
+ if (asPage !== undefined) {
191
+ locations.push({ page: asPage, rect: index.boxByPage.get(asPage) ?? null, basis: 'page-box' });
192
+ return { locations, reason: null };
193
+ }
194
+ // 3. Structural objects with no place on any page.
195
+ if (type === 'Catalog' || type === 'Pages' || type === 'StructTreeRoot' || type === 'Metadata') {
196
+ return {
197
+ locations: [],
198
+ reason: `${type} is a document-level object and is not drawn anywhere`,
199
+ };
200
+ }
201
+ return { locations: [], reason: null };
202
+ }
203
+ /**
204
+ * Locate the given object numbers. Objects are matched by number: the
205
+ * generation actually present in the document is reported back, so a caller
206
+ * holding a stale generation still gets an answer rather than a miss.
207
+ */
208
+ export async function locateObjects(filePath, objectNumbers) {
209
+ const doc = await loadWithPdfLib(filePath);
210
+ const index = buildPageIndex(doc);
211
+ const notes = [];
212
+ const wanted = new Set(objectNumbers);
213
+ const byNumber = new Map();
214
+ for (const [ref, object] of doc.context.enumerateIndirectObjects()) {
215
+ if (wanted.has(ref.objectNumber))
216
+ byNumber.set(ref.objectNumber, { ref, object });
217
+ }
218
+ if (index.pageNumberByRef.size === 0) {
219
+ notes.push('The page tree could not be walked, so no object could be tied to a page number. ' +
220
+ "Rectangles read from an object's own /Rect are still reported.");
221
+ }
222
+ if (doc.isEncrypted) {
223
+ notes.push('The document is encrypted. Numbers and names are not encrypted (ISO 32000-1 §7.6.2), so ' +
224
+ 'coordinates and types are reliable, but strings are not decrypted here — field names are ' +
225
+ 'reported as null rather than as mojibake.');
226
+ }
227
+ const objects = objectNumbers.map((objectNumber) => {
228
+ const hit = byNumber.get(objectNumber);
229
+ if (!hit) {
230
+ return {
231
+ objectNumber,
232
+ generation: null,
233
+ found: false,
234
+ type: null,
235
+ subtype: null,
236
+ fieldName: null,
237
+ locations: [],
238
+ reason: 'No object with this number exists in the document as parsed. An object freed by a ' +
239
+ 'later revision is expected to look like this.',
240
+ };
241
+ }
242
+ const { ref, object } = hit;
243
+ if (!(object instanceof PDFDict)) {
244
+ // Streams are PDFStream, whose dictionary is reachable; everything else
245
+ // (numbers, arrays) has no location of its own.
246
+ const streamDict = object?.dict;
247
+ const contentPages = index.contentPages.get(ref.tag) ?? [];
248
+ const resourcePages = index.resourcePages.get(ref.tag) ?? [];
249
+ if (contentPages.length > 0) {
250
+ return {
251
+ objectNumber,
252
+ generation: ref.generationNumber,
253
+ found: true,
254
+ type: streamDict ? nameOf(streamDict, 'Type') : null,
255
+ subtype: streamDict ? nameOf(streamDict, 'Subtype') : null,
256
+ fieldName: null,
257
+ locations: contentPages.map((page) => ({
258
+ page,
259
+ rect: index.boxByPage.get(page) ?? null,
260
+ basis: 'page-content-stream',
261
+ })),
262
+ reason: "This is the page's content stream, so the rectangle is the whole page. Narrowing it " +
263
+ 'to the part that changed needs a content-stream walk, which this tool does not do.',
264
+ };
265
+ }
266
+ if (resourcePages.length > 0) {
267
+ return {
268
+ objectNumber,
269
+ generation: ref.generationNumber,
270
+ found: true,
271
+ type: streamDict ? nameOf(streamDict, 'Type') : null,
272
+ subtype: streamDict ? nameOf(streamDict, 'Subtype') : null,
273
+ fieldName: null,
274
+ locations: resourcePages.map((page) => ({
275
+ page,
276
+ rect: null,
277
+ basis: 'page-resource',
278
+ })),
279
+ reason: 'A resource (font, image, colour space, …) is used by the page but has no rectangle ' +
280
+ 'of its own; where it is drawn is decided by the content stream.',
281
+ };
282
+ }
283
+ return {
284
+ objectNumber,
285
+ generation: ref.generationNumber,
286
+ found: true,
287
+ type: streamDict ? nameOf(streamDict, 'Type') : null,
288
+ subtype: streamDict ? nameOf(streamDict, 'Subtype') : null,
289
+ fieldName: null,
290
+ locations: [],
291
+ reason: 'No page references this object, so it has no place on any page.',
292
+ };
293
+ }
294
+ const { locations, reason } = locateDict(doc, ref, object, index);
295
+ let finalReason = reason;
296
+ if (locations.length === 0) {
297
+ const contentPages = index.contentPages.get(ref.tag) ?? [];
298
+ const resourcePages = index.resourcePages.get(ref.tag) ?? [];
299
+ if (contentPages.length > 0) {
300
+ for (const page of contentPages) {
301
+ locations.push({
302
+ page,
303
+ rect: index.boxByPage.get(page) ?? null,
304
+ basis: 'page-content-stream',
305
+ });
306
+ }
307
+ finalReason =
308
+ "This is the page's content stream, so the rectangle is the whole page. Narrowing it to " +
309
+ 'the part that changed needs a content-stream walk, which this tool does not do.';
310
+ }
311
+ else if (resourcePages.length > 0) {
312
+ for (const page of resourcePages) {
313
+ locations.push({ page, rect: null, basis: 'page-resource' });
314
+ }
315
+ finalReason =
316
+ 'A resource is used by the page but has no rectangle of its own; where it is drawn is ' +
317
+ 'decided by the content stream.';
318
+ }
319
+ else if (finalReason === null) {
320
+ finalReason = 'No page references this object, so it has no place on any page.';
321
+ }
322
+ }
323
+ const titleValue = object.get(PDFName.of('T'));
324
+ const fieldName = !doc.isEncrypted && (titleValue instanceof PDFString || titleValue instanceof PDFHexString)
325
+ ? titleValue.decodeText()
326
+ : null;
327
+ return {
328
+ objectNumber,
329
+ generation: ref.generationNumber,
330
+ found: true,
331
+ type: nameOf(object, 'Type'),
332
+ subtype: nameOf(object, 'Subtype'),
333
+ fieldName,
334
+ locations,
335
+ reason: finalReason,
336
+ };
337
+ });
338
+ return { objects, isEncrypted: doc.isEncrypted, notes };
339
+ }
340
+ //# sourceMappingURL=object-locator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"object-locator.js","sourceRoot":"","sources":["../../src/services/object-locator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EACL,QAAQ,EACR,OAAO,EAEP,YAAY,EACZ,OAAO,EACP,SAAS,EACT,MAAM,EACN,SAAS,GACV,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,mEAAmE;AACnE,MAAM,mBAAmB,GAAG;IAC1B,SAAS;IACT,MAAM;IACN,WAAW;IACX,SAAS;IACT,SAAS;IACT,YAAY;IACZ,YAAY;CACJ,CAAC;AAEX;;;;;GAKG;AACH,SAAS,aAAa,CAAC,MAAgB;IACrC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAChF,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC;IAC5B,OAAO;QACL,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;QAClB,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;QAClB,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;QAClB,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;KACnB,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,KAAc,EAAE,GAAgB;IACnD,MAAM,QAAQ,GAAG,KAAK,YAAY,MAA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IAAI,IAAI,aAAa,EAAE,CAAC;oBACjC,SAAS,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,CAAC;gBAC/D,CAAC;gBACD,WAAW;oBACT,uFAAuF;wBACvF,gCAAgC,CAAC;YACrC,CAAC;iBAAM,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;gBAChC,WAAW,GAAG,iEAAiE,CAAC;YAClF,CAAC;QACH,CAAC;QAED,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAC/C,MAAM,SAAS,GACb,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,UAAU,YAAY,SAAS,IAAI,UAAU,YAAY,YAAY,CAAC;YACzF,CAAC,CAAC,UAAU,CAAC,UAAU,EAAE;YACzB,CAAC,CAAC,IAAI,CAAC;QAEX,OAAO;YACL,YAAY;YACZ,UAAU,EAAE,GAAG,CAAC,gBAAgB;YAChC,KAAK,EAAE,IAAI;YACX,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;YAC5B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC;YAClC,SAAS;YACT,SAAS;YACT,MAAM,EAAE,WAAW;SACpB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,CAAC,WAAW,EAAE,KAAK,EAAE,CAAC;AAC1D,CAAC"}
@@ -197,6 +197,67 @@ export declare function resolveLineBreaks(text: string): string;
197
197
  * (`p7R_mc0`) — so merging the per-page maps is safe.
198
198
  */
199
199
  export declare function buildDocumentIdToTextMap(doc: PDFDocumentProxy): Promise<Map<string, string>>;
200
+ /** An axis-aligned rectangle accumulated in default user space. */
201
+ export interface RunBox {
202
+ minX: number;
203
+ minY: number;
204
+ maxX: number;
205
+ maxY: number;
206
+ }
207
+ /** What a marked-content sequence's text occupies, and what could not be measured. */
208
+ export interface MarkedContentExtent {
209
+ /** null when nothing measurable was found inside the sequence. */
210
+ box: RunBox | null;
211
+ /**
212
+ * True when a run in vertical writing mode was seen. Vertical runs are NOT
213
+ * folded into `box` — pdfjs reports the advance in `height` rather than
214
+ * `width` for them, and guessing which way the glyphs grow would produce a
215
+ * rectangle that is wrong rather than absent. The flag makes the caller
216
+ * suppress the box instead of returning a silently shrunken one.
217
+ */
218
+ hasUnmeasurableRun: boolean;
219
+ }
220
+ /** A `getTextContent` item, with the geometry fields this module needs. */
221
+ interface PositionedTextItem extends TextContentItemLike {
222
+ transform?: number[];
223
+ width?: number;
224
+ height?: number;
225
+ fontName?: string;
226
+ }
227
+ /** `styles` from `getTextContent`: font metrics, normalised to the em square. */
228
+ export interface TextStyleLike {
229
+ ascent?: number;
230
+ descent?: number;
231
+ vertical?: boolean;
232
+ }
233
+ /**
234
+ * Build a map from a marked-content `id` to the rectangle its text occupies.
235
+ *
236
+ * The same walk as `buildIdToTextMap`, and deliberately the same skips, so that
237
+ * "the text of this element" and "where that text is" cannot disagree: nested
238
+ * sequences count toward every active id, and `Artifact` sequences are excluded
239
+ * (§14.8.2.5 NOTE 3 puts artifacts outside the logical content order).
240
+ *
241
+ * Two further exclusions belong to geometry rather than text:
242
+ *
243
+ * - **Whitespace-only runs.** Table 379 defines `BBox` as the rectangle that
244
+ * "completely encloses its **visible** content", and a run of spaces is not
245
+ * visible. pdfjs does emit wide ones for inter-cell gaps: measured on
246
+ * `spanning-table.pdf`, a `TH` carries a 75 pt run of spaces that reaches
247
+ * into the neighbouring column. That particular one arrives with
248
+ * `height: 0` and `runBox` rejects it on those grounds alone; this check is
249
+ * what covers a spacer that comes with a height.
250
+ * - **EOL markers** (`str: ''`, `hasEOL: true`), which carry no geometry.
251
+ */
252
+ export declare function buildIdToBoxMap(items: PositionedTextItem[], styles?: Record<string, TextStyleLike>): Map<string, MarkedContentExtent>;
253
+ /**
254
+ * Build the marked-content id → rectangle map across the whole document.
255
+ *
256
+ * Document-wide for the same reason as `buildDocumentIdToTextMap`: a structure
257
+ * element can own content on several pages (§14.8.2.5 NOTE 2), and the ids are
258
+ * globally unique because pdfjs builds them from the page object number.
259
+ */
260
+ export declare function buildDocumentIdToBoxMap(doc: PDFDocumentProxy): Promise<Map<string, MarkedContentExtent>>;
200
261
  /**
201
262
  * Normalise raw cell text:
202
263
  * 0. Resolve line breaks (CJK-aware) — a break between two CJK characters is
@@ -1 +1 @@
1
- {"version":3,"file":"pdfjs-service.d.ts","sourceRoot":"","sources":["../../src/services/pdfjs-service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EAIL,KAAK,gBAAgB,EAEtB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,KAAK,EAEV,mBAAmB,EAEnB,qBAAqB,EACrB,QAAQ,EACR,WAAW,EACX,WAAW,EAEX,YAAY,EACb,MAAM,aAAa,CAAC;AAyBrB;;GAEG;AACH,wBAAsB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAI9E;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAGtF;AAED;;GAEG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAOxE;AAED;;;GAGG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,gBAAgB,EACrB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,WAAW,CAAC,CA6BtB;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,kBAAkB;IACjC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;GAKG;AACH,UAAU,oBAAoB;I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,mBAAmB;IACtD,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AA8ED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,kBAAkB,EAAE,EAC3B,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAM,GACzC,GAAG,CAAC,MAAM,EAAE,mBAAmB,CAAC,CA+ClC;AAED;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,gBAAgB,GACpB,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAiB3C;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAcjD;AA4CD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,MAAM,EAChB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,mBAAmB,CAAC,CAgF9B"}
@@ -762,6 +762,166 @@ export async function buildDocumentIdToTextMap(doc) {
762
762
  }
763
763
  return merged;
764
764
  }
765
+ /** Default em-square ascent/descent, used when pdfjs reports none for a font. */
766
+ const FALLBACK_ASCENT = 0.75;
767
+ const FALLBACK_DESCENT = -0.25;
768
+ /**
769
+ * The rectangle one text run occupies, in default user space.
770
+ *
771
+ * `item.transform` is the run's mapping from em units to user space — §9.4.4's
772
+ * Trm without the device transform, so its translation is the baseline origin
773
+ * and its linear part carries font size, horizontal scaling and any rotation.
774
+ * Measured against pdfjs-dist 4.10: text drawn at 45° reports
775
+ * `[14.14, 14.14, -14.14, 14.14, x, y]` for a 20 pt font, i.e. `|(a,b)| = 20`.
776
+ *
777
+ * So the box is built along the run's own axes rather than the page's:
778
+ *
779
+ * - **u** = `(a,b)` normalised — the baseline direction; the run extends
780
+ * `item.width` along it (pdfjs reports the advance already in user space).
781
+ * - **v** = `(c,d)` normalised — the up direction; the run extends from
782
+ * `descent × height` to `ascent × height` along it.
783
+ *
784
+ * The vertical extent therefore comes from the font's ascent/descent, not from
785
+ * glyph outlines: a glyph that overshoots its ascent (an accent, a swash) can
786
+ * exceed this rectangle. It is the line box, measured, not the ink.
787
+ */
788
+ function runBox(item, style) {
789
+ const t = item.transform;
790
+ if (!t || t.length < 6 || t.some((v) => !Number.isFinite(v)))
791
+ return null;
792
+ const width = item.width ?? 0;
793
+ const height = item.height ?? 0;
794
+ if (!Number.isFinite(width) || !Number.isFinite(height))
795
+ return null;
796
+ const [a, b, c, d, e, f] = t;
797
+ const baselineLength = Math.hypot(a, b);
798
+ const upLength = Math.hypot(c, d);
799
+ // A degenerate matrix draws nothing measurable; a zero-height run is a pdfjs
800
+ // spacing artefact (str: " " with height 0), not visible content.
801
+ if (baselineLength === 0 || upLength === 0 || height === 0)
802
+ return null;
803
+ const ux = a / baselineLength;
804
+ const uy = b / baselineLength;
805
+ const vx = c / upLength;
806
+ const vy = d / upLength;
807
+ const ascent = style?.ascent ?? FALLBACK_ASCENT;
808
+ const descent = style?.descent ?? FALLBACK_DESCENT;
809
+ const top = ascent * height;
810
+ const bottom = descent * height;
811
+ const xs = [];
812
+ const ys = [];
813
+ for (const along of [0, width]) {
814
+ for (const up of [bottom, top]) {
815
+ xs.push(e + ux * along + vx * up);
816
+ ys.push(f + uy * along + vy * up);
817
+ }
818
+ }
819
+ return {
820
+ minX: Math.min(...xs),
821
+ minY: Math.min(...ys),
822
+ maxX: Math.max(...xs),
823
+ maxY: Math.max(...ys),
824
+ };
825
+ }
826
+ function mergeBox(into, add) {
827
+ if (!into)
828
+ return { ...add };
829
+ return {
830
+ minX: Math.min(into.minX, add.minX),
831
+ minY: Math.min(into.minY, add.minY),
832
+ maxX: Math.max(into.maxX, add.maxX),
833
+ maxY: Math.max(into.maxY, add.maxY),
834
+ };
835
+ }
836
+ /**
837
+ * Build a map from a marked-content `id` to the rectangle its text occupies.
838
+ *
839
+ * The same walk as `buildIdToTextMap`, and deliberately the same skips, so that
840
+ * "the text of this element" and "where that text is" cannot disagree: nested
841
+ * sequences count toward every active id, and `Artifact` sequences are excluded
842
+ * (§14.8.2.5 NOTE 3 puts artifacts outside the logical content order).
843
+ *
844
+ * Two further exclusions belong to geometry rather than text:
845
+ *
846
+ * - **Whitespace-only runs.** Table 379 defines `BBox` as the rectangle that
847
+ * "completely encloses its **visible** content", and a run of spaces is not
848
+ * visible. pdfjs does emit wide ones for inter-cell gaps: measured on
849
+ * `spanning-table.pdf`, a `TH` carries a 75 pt run of spaces that reaches
850
+ * into the neighbouring column. That particular one arrives with
851
+ * `height: 0` and `runBox` rejects it on those grounds alone; this check is
852
+ * what covers a spacer that comes with a height.
853
+ * - **EOL markers** (`str: ''`, `hasEOL: true`), which carry no geometry.
854
+ */
855
+ export function buildIdToBoxMap(items, styles = {}) {
856
+ const map = new Map();
857
+ const stack = [];
858
+ const touch = (id) => {
859
+ const existing = map.get(id);
860
+ if (existing)
861
+ return existing;
862
+ const created = { box: null, hasUnmeasurableRun: false };
863
+ map.set(id, created);
864
+ return created;
865
+ };
866
+ for (const item of items) {
867
+ const t = item.type;
868
+ if (t === 'beginMarkedContent' || t === 'beginMarkedContentProps') {
869
+ stack.push({ id: item.id ?? null, isArtifact: item.tag === 'Artifact' });
870
+ continue;
871
+ }
872
+ if (t === 'endMarkedContent') {
873
+ stack.pop();
874
+ continue;
875
+ }
876
+ if (t !== undefined)
877
+ continue; // unknown marker
878
+ if (stack.some((s) => s.isArtifact))
879
+ continue;
880
+ if (item.hasEOL)
881
+ continue;
882
+ const str = item.str ?? '';
883
+ if (str.trim() === '')
884
+ continue;
885
+ const style = item.fontName ? styles[item.fontName] : undefined;
886
+ if (style?.vertical) {
887
+ for (const frame of stack) {
888
+ if (frame.id)
889
+ touch(frame.id).hasUnmeasurableRun = true;
890
+ }
891
+ continue;
892
+ }
893
+ const box = runBox(item, style);
894
+ if (!box)
895
+ continue;
896
+ for (const frame of stack) {
897
+ if (frame.id) {
898
+ const extent = touch(frame.id);
899
+ extent.box = mergeBox(extent.box, box);
900
+ }
901
+ }
902
+ }
903
+ return map;
904
+ }
905
+ /**
906
+ * Build the marked-content id → rectangle map across the whole document.
907
+ *
908
+ * Document-wide for the same reason as `buildDocumentIdToTextMap`: a structure
909
+ * element can own content on several pages (§14.8.2.5 NOTE 2), and the ids are
910
+ * globally unique because pdfjs builds them from the page object number.
911
+ */
912
+ export async function buildDocumentIdToBoxMap(doc) {
913
+ const perPage = await Promise.all(Array.from({ length: doc.numPages }, async (_, i) => {
914
+ const page = await doc.getPage(i + 1);
915
+ const content = await page.getTextContent({ includeMarkedContent: true });
916
+ return buildIdToBoxMap(content.items, content.styles);
917
+ }));
918
+ const merged = new Map();
919
+ for (const map of perPage) {
920
+ for (const [id, extent] of map)
921
+ merged.set(id, extent);
922
+ }
923
+ return merged;
924
+ }
765
925
  /**
766
926
  * Normalise raw cell text:
767
927
  * 0. Resolve line breaks (CJK-aware) — a break between two CJK characters is