pdfium-native 0.10.0 → 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.
@@ -266,8 +266,8 @@ async function createTaggedPdf() {
266
266
  }
267
267
 
268
268
  // --- PDF with an embedded image ---
269
- async function createImagePdf() {
270
- const doc = await PDFDocument.create();
269
+ // a 2x2 PNG, red over blue, built by hand
270
+ async function twoByTwoPng() {
271
271
  // create a minimal 2x2 red PNG manually (smallest valid PNG)
272
272
  const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
273
273
  // IHDR chunk: 2x2, 8-bit RGB
@@ -305,8 +305,12 @@ async function createImagePdf() {
305
305
  idat.writeUInt32BE(crc32(idat.subarray(4, 8 + compressed.length)) >>> 0, 8 + compressed.length);
306
306
  // IEND chunk
307
307
  const iend = Buffer.from([0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
308
- const pngData = Buffer.concat([signature, ihdr, idat, iend]);
308
+ return Buffer.concat([signature, ihdr, idat, iend]);
309
+ }
309
310
 
311
+ async function createImagePdf() {
312
+ const doc = await PDFDocument.create();
313
+ const pngData = await twoByTwoPng();
310
314
  const img = await doc.embedPng(pngData);
311
315
  const page = doc.addPage([612, 792]);
312
316
  page.drawImage(img, { x: 50, y: 600, width: 100, height: 100 });
@@ -493,6 +497,174 @@ async function createEInvoicePdf() {
493
497
  return doc.save();
494
498
  }
495
499
 
500
+ // --- PDF whose /EmbeddedFiles name tree points at a missing object ---
501
+ // Regression fixture for issue #34. FPDFDoc_GetAttachmentCount counts the slots
502
+ // in the name tree, but FPDFDoc_GetAttachment resolves each one and returns
503
+ // NULL when that fails. Pointing the first filespec at an object that does not
504
+ // exist makes the two disagree: the count still says 2, while only the second
505
+ // attachment loads. getAttachments() used to drop the failed entry silently, so
506
+ // the array came back shorter than metadata.attachmentCount with no way for a
507
+ // caller to tell damage from a document that simply has no embedded files.
508
+ async function createDamagedAttachmentPdf() {
509
+ const { AFRelationship, PDFName, PDFDict, PDFRef } = await import('pdf-lib');
510
+ const doc = await PDFDocument.create();
511
+ doc.setTitle('Damaged embedded-file name tree');
512
+ doc.setProducer('pdfium-native test');
513
+ const page = doc.addPage([612, 792]);
514
+ const font = await doc.embedFont(StandardFonts.Helvetica);
515
+ page.drawText('Invoice RE-2025-0002', { x: 50, y: 700, size: 16, font });
516
+ page.drawText('factur-x.xml is present but unreachable', { x: 50, y: 670, size: 11, font });
517
+
518
+ const dates = {
519
+ creationDate: new Date('2025-01-01T12:00:00Z'),
520
+ modificationDate: new Date('2025-01-01T12:00:00Z'),
521
+ };
522
+ await doc.attach(Buffer.from(FACTUR_X_XML, 'utf8'), 'factur-x.xml', {
523
+ mimeType: 'text/xml',
524
+ description: 'Factur-X invoice',
525
+ afRelationship: AFRelationship.Alternative,
526
+ ...dates,
527
+ });
528
+ await doc.attach(Buffer.from('Human-readable notes.\n', 'utf8'), 'notes.txt', {
529
+ mimeType: 'text/plain',
530
+ description: 'Supplementary notes',
531
+ afRelationship: AFRelationship.Supplement,
532
+ ...dates,
533
+ });
534
+
535
+ // Reload so the name tree exists as a concrete object, then dangle the first
536
+ // filespec reference. /Names alternates [name, filespec, name, filespec], so
537
+ // slot 1 is the file specification for attachment index 0.
538
+ const reloaded = await PDFDocument.load(await doc.save({ useObjectStreams: false }));
539
+ reloaded.catalog
540
+ .lookup(PDFName.of('Names'), PDFDict)
541
+ .lookup(PDFName.of('EmbeddedFiles'), PDFDict)
542
+ .lookup(PDFName.of('Names'))
543
+ .set(1, PDFRef.of(9999, 0));
544
+
545
+ return reloaded.save({ useObjectStreams: false });
546
+ }
547
+
548
+ // --- page whose middle /Annots entry points at a missing object ---
549
+ // FPDFPage_GetAnnotCount counts the raw /Annots array, but FPDFPage_GetAnnot
550
+ // resolves each slot and returns NULL when it does not yield a dictionary. The
551
+ // page below reports three annotations while only slots 0 and 2 load, so the
552
+ // listing used to come back with an unexplained gap at index 1.
553
+ async function createDanglingAnnotationPdf() {
554
+ const { PDFName, PDFRef, PDFString } = await import('pdf-lib');
555
+ const doc = await PDFDocument.create();
556
+ const page = doc.addPage([612, 792]);
557
+ const font = await doc.embedFont(StandardFonts.Helvetica);
558
+ page.drawText('Page with a dangling annotation', { x: 50, y: 700, size: 16, font });
559
+
560
+ const annot = (subtype, rect, contents, color) =>
561
+ doc.context.register(
562
+ doc.context.obj({
563
+ Type: 'Annot',
564
+ Subtype: subtype,
565
+ Rect: rect,
566
+ Contents: PDFString.of(contents),
567
+ C: color,
568
+ }),
569
+ );
570
+
571
+ page.node.set(
572
+ PDFName.of('Annots'),
573
+ doc.context.obj([
574
+ annot('Text', [100, 600, 120, 620], 'sticky note', [1, 0, 0]),
575
+ annot('Square', [150, 600, 200, 650], 'square', [0, 1, 0]),
576
+ annot('Circle', [250, 600, 300, 650], 'circle', [0, 0, 1]),
577
+ ]),
578
+ );
579
+
580
+ // re-open so /Annots is a concrete array, then dangle the middle slot
581
+ const reloaded = await PDFDocument.load(await doc.save({ useObjectStreams: false }));
582
+ reloaded.getPages()[0].node.lookup(PDFName.of('Annots')).set(1, PDFRef.of(9999, 0));
583
+ return reloaded.save({ useObjectStreams: false });
584
+ }
585
+
586
+ // --- document-open JavaScript whose middle action reference dangles ---
587
+ // The /Names /JavaScript tree has the same [name, ref, name, ref] shape as
588
+ // /EmbeddedFiles, and fails the same way: FPDFDoc_GetJavaScriptActionCount
589
+ // counts three actions while FPDFDoc_GetJavaScriptAction resolves only one.
590
+ // A script a triage tool cannot read is worth more attention than no script.
591
+ // Two of the three are dangled, and one of them is the LAST entry: a trailing
592
+ // failure is the shape most likely to be lost, since the array length is
593
+ // carried by the allocation rather than by the final Set.
594
+ async function createDanglingJavaScriptPdf() {
595
+ const { PDFName, PDFDict, PDFArray, PDFRef, PDFString } = await import('pdf-lib');
596
+ const doc = await PDFDocument.create();
597
+ doc.addPage([612, 792]);
598
+
599
+ const action = (src) =>
600
+ doc.context.register(doc.context.obj({ S: 'JavaScript', JS: PDFString.of(src) }));
601
+
602
+ // name-tree entries must be sorted by name
603
+ const jsLeaf = doc.context.obj({
604
+ Names: [
605
+ PDFString.of('script_alpha'),
606
+ action('app.alert("alpha");'),
607
+ PDFString.of('script_beta'),
608
+ action('app.alert("beta");'),
609
+ PDFString.of('script_gamma'),
610
+ action('app.alert("gamma");'),
611
+ ],
612
+ });
613
+ doc.catalog.set(
614
+ PDFName.of('Names'),
615
+ doc.context.register(doc.context.obj({ JavaScript: doc.context.register(jsLeaf) })),
616
+ );
617
+
618
+ // slots 3 and 5 are the action references for indices 1 and 2
619
+ const broken = await PDFDocument.load(await doc.save({ useObjectStreams: false }));
620
+ const names = broken.catalog
621
+ .lookup(PDFName.of('Names'), PDFDict)
622
+ .lookup(PDFName.of('JavaScript'), PDFDict)
623
+ .lookup(PDFName.of('Names'), PDFArray);
624
+ names.set(3, PDFRef.of(9999, 0));
625
+ names.set(5, PDFRef.of(9999, 0));
626
+ return broken.save({ useObjectStreams: false });
627
+ }
628
+
629
+ // --- form page that counts a widget it cannot load ---
630
+ // The page's /Annots array keeps all its entries, so FPDFPage_GetAnnotCount is
631
+ // unchanged, but two slots point at objects that do not exist. Because the
632
+ // annotation subtype is only readable through the handle that failed, an
633
+ // unloadable slot cannot be ruled out as a non-widget, and this fixture makes
634
+ // that distinction observable: one damaged slot was the 'fullName' widget, so
635
+ // a form field really is missing (its AcroForm /Fields entry is deliberately
636
+ // left intact, so the document still declares a field the page cannot hand
637
+ // out); the other was a plain Text annotation, which would have been filtered
638
+ // out anyway, so its null marks nothing. Nothing in the result can tell them
639
+ // apart, which is exactly what getFormFields() promises and no all-widget
640
+ // fixture can exercise.
641
+ async function createDamagedWidgetPdf() {
642
+ const { PDFName, PDFArray, PDFRef, PDFString } = await import('pdf-lib');
643
+ const doc = await PDFDocument.load(await createFormFieldsPdf());
644
+ const annots = doc.getPage(0).node.lookup(PDFName.of('Annots'), PDFArray);
645
+
646
+ // two non-widget annotations, appended after the nine widgets
647
+ for (const [y, note] of [
648
+ [520, 'a plain note, not a form field'],
649
+ [480, 'another non-widget annotation'],
650
+ ]) {
651
+ annots.push(
652
+ doc.context.register(
653
+ doc.context.obj({
654
+ Type: 'Annot',
655
+ Subtype: 'Text',
656
+ Rect: [400, y, 420, y + 20],
657
+ Contents: PDFString.of(note),
658
+ }),
659
+ ),
660
+ );
661
+ }
662
+
663
+ annots.set(0, PDFRef.of(9999, 0)); // the 'fullName' text-field widget
664
+ annots.set(9, PDFRef.of(9999, 0)); // the first Text annotation
665
+ return doc.save({ useObjectStreams: false });
666
+ }
667
+
496
668
  // --- PDF containing a non-BMP (astral) character ---
497
669
  // PDFium reports one UTF-16 code unit per character index, so an emoji arrives
498
670
  // as two consecutive lone surrogates. A ToUnicode CMap mapping the glyph for
@@ -717,6 +889,64 @@ async function createNavigationPdf() {
717
889
  return doc.save();
718
890
  }
719
891
 
892
+ // --- PDF whose legacy /Dests values are indirect references ---
893
+ // FPDF_CountNamedDests counts every key in the catalog's legacy /Dests
894
+ // dictionary, but FPDF_GetNamedDest resolves those keys without dereferencing
895
+ // an indirect value, so it returns neither a destination nor a name for them.
896
+ // The three legacy entries here are therefore counted and unlistable, while
897
+ // the single name-tree entry lists normally — the mismatch between
898
+ // metadata.namedDestinationCount (4) and getNamedDestinations().length (1) is
899
+ // what the fixture exists to pin. Nothing about this document is malformed:
900
+ // ISO 32000-1 allows an indirect reference wherever a direct object is
901
+ // allowed, and FPDF_GetNamedDestByName resolves all four names.
902
+ async function createIndirectLegacyDestsPdf() {
903
+ const doc = await PDFDocument.create();
904
+ const font = await doc.embedFont(StandardFonts.Helvetica);
905
+ const pages = [];
906
+ for (let i = 1; i <= 3; i++) {
907
+ const page = doc.addPage([300, 400]);
908
+ page.drawText(`Section ${i}`, { x: 50, y: 300, size: 20, font });
909
+ pages.push(page);
910
+ }
911
+
912
+ const { PDFName, PDFString } = await import('pdf-lib');
913
+
914
+ // one modern name-tree entry, written inline so it resolves by index
915
+ const destsTree = doc.context.obj({
916
+ Names: [PDFString.of('Tree'), [pages[0].ref, 'XYZ', 50, 700, 2]],
917
+ });
918
+ doc.catalog.set(PDFName.of('Names'), doc.context.obj({ Dests: destsTree }));
919
+
920
+ // legacy /Dests, every value an indirect reference. The dictionary itself is
921
+ // indirect either way, so the indirection of the values is the only variable.
922
+ const ref = (arr) => doc.context.register(doc.context.obj(arr));
923
+ const legacy = doc.context.register(
924
+ doc.context.obj({
925
+ Alpha: ref([pages[0].ref, PDFName.of('XYZ'), 50, 700, 0]),
926
+ Beta: ref([pages[1].ref, PDFName.of('Fit')]),
927
+ Gamma: ref([pages[2].ref, PDFName.of('FitH'), 500]),
928
+ }),
929
+ );
930
+ doc.catalog.set(PDFName.of('Dests'), legacy);
931
+
932
+ // link annotations targeting those same names by the legacy /Dest spelling,
933
+ // so the document reads as one a viewer would actually navigate
934
+ const annots = ['Alpha', 'Beta', 'Gamma'].map((name, i) =>
935
+ doc.context.register(
936
+ doc.context.obj({
937
+ Type: 'Annot',
938
+ Subtype: 'Link',
939
+ Rect: [50, 200 - i * 40, 200, 230 - i * 40],
940
+ Border: [0, 0, 0],
941
+ Dest: PDFName.of(name),
942
+ }),
943
+ ),
944
+ );
945
+ pages[0].node.set(PDFName.of('Annots'), doc.context.obj(annots));
946
+
947
+ return doc.save({ useObjectStreams: false });
948
+ }
949
+
720
950
  // --- Four-page PDF whose pages identify themselves ---
721
951
  // Each page carries its own number as text, so assembly tests can verify
722
952
  // order, selection and duplication by reading the pages back.
@@ -954,6 +1184,70 @@ async function createFormFieldsPdf() {
954
1184
  }
955
1185
 
956
1186
  // Generate all fixtures
1187
+ // --- PDF whose text and image are drawn inside nested form XObjects ---
1188
+ // Some producers (an EDEKA e-receipt among them) draw a whole page inside one
1189
+ // form XObject. PDFium lists only the form on the page, so `objects` on the
1190
+ // form is the one way to its text objects and the images beside them. The
1191
+ // inner page is embedded twice over, scaled and moved each time, so the
1192
+ // fixture also pins the matrix math that maps nested bounds to the page.
1193
+ async function createFormXObjectsPdf() {
1194
+ const inner = await PDFDocument.create();
1195
+ const innerPage = inner.addPage([200, 200]);
1196
+ const font = await inner.embedFont(StandardFonts.Helvetica);
1197
+ innerPage.drawText('Total 12,50', { x: 20, y: 150, size: 20, font });
1198
+ const image = await inner.embedPng(await twoByTwoPng());
1199
+ innerPage.drawImage(image, { x: 20, y: 20, width: 40, height: 40 });
1200
+
1201
+ const middle = await PDFDocument.create();
1202
+ const middlePage = middle.addPage([300, 300]);
1203
+ middlePage.drawPage(
1204
+ await middle.embedPage((await PDFDocument.load(await inner.save())).getPage(0)),
1205
+ {
1206
+ x: 50,
1207
+ y: 50,
1208
+ xScale: 0.5,
1209
+ yScale: 0.5,
1210
+ },
1211
+ );
1212
+
1213
+ const doc = await PDFDocument.create();
1214
+ const page = doc.addPage([400, 400]);
1215
+ page.drawPage(await doc.embedPage((await PDFDocument.load(await middle.save())).getPage(0)), {
1216
+ x: 100,
1217
+ y: 20,
1218
+ });
1219
+ return doc.save();
1220
+ }
1221
+
1222
+ // --- PDF whose forms nest deeper than the walk follows ---
1223
+ // Forty form XObjects, each drawing the next, the last drawing a rectangle.
1224
+ async function createFormDepthBombPdf() {
1225
+ const doc = await PDFDocument.create();
1226
+ const page = doc.addPage([200, 200]);
1227
+ const { PDFName } = await import('pdf-lib');
1228
+ let ref = doc.context.register(
1229
+ doc.context.stream('0 0 10 10 re f', {
1230
+ Type: 'XObject',
1231
+ Subtype: 'Form',
1232
+ BBox: [0, 0, 200, 200],
1233
+ }),
1234
+ );
1235
+ for (let i = 0; i < 40; i++) {
1236
+ ref = doc.context.register(
1237
+ doc.context.stream('/F Do', {
1238
+ Type: 'XObject',
1239
+ Subtype: 'Form',
1240
+ BBox: [0, 0, 200, 200],
1241
+ Resources: { XObject: { F: ref } },
1242
+ }),
1243
+ );
1244
+ }
1245
+ page.node.setXObject(PDFName.of('F'), ref);
1246
+ const content = doc.context.register(doc.context.stream('/F Do'));
1247
+ page.node.set(PDFName.of('Contents'), content);
1248
+ return doc.save();
1249
+ }
1250
+
957
1251
  const fixtures = [
958
1252
  ['metadata.pdf', createMetadataPdf],
959
1253
  ['annotations.pdf', createAnnotationPdf],
@@ -971,14 +1265,21 @@ const fixtures = [
971
1265
  ['border-annotations.pdf', createBorderAnnotationPdf],
972
1266
  ['form-fields.pdf', createFormFieldsPdf],
973
1267
  ['einvoice-zugferd.pdf', createEInvoicePdf],
1268
+ ['damaged-attachment.pdf', createDamagedAttachmentPdf],
1269
+ ['dangling-annotation.pdf', createDanglingAnnotationPdf],
1270
+ ['dangling-javascript.pdf', createDanglingJavaScriptPdf],
1271
+ ['damaged-widget.pdf', createDamagedWidgetPdf],
974
1272
  ['file-attachment-annotation.pdf', createFileAttachmentAnnotationPdf],
975
1273
  ['signed.pdf', createSignedPdf],
976
1274
  ['positioned-text.pdf', createPositionedTextPdf],
977
1275
  ['four-page.pdf', createFourPagePdf],
978
1276
  ['navigation.pdf', createNavigationPdf],
1277
+ ['indirect-legacy-dests.pdf', createIndirectLegacyDestsPdf],
979
1278
  ['struct-tree.pdf', createStructTreePdf],
980
1279
  ['astral-text.pdf', createAstralTextPdf],
981
1280
  ['struct-tree-bomb.pdf', createStructTreeBombPdf],
1281
+ ['form-xobjects.pdf', createFormXObjectsPdf],
1282
+ ['form-depth-bomb.pdf', createFormDepthBombPdf],
982
1283
  ];
983
1284
 
984
1285
  for (const [name, generator] of fixtures) {
@@ -1,12 +1,12 @@
1
1
  {
2
- "darwin-arm64": "78c5d4a91d187790d17c0b5641c04c99929cc2e312d5831fe9ddf8cb9c7b873a",
3
- "darwin-x64": "e8472aa6e372ec2d58fd2afc411c4f79dbd34d848e0f08a1343b95f6f223ba2e",
4
- "linux-arm": "f053989d5a64abb4ab1ba4b61b78b64f9d3c5612b03b6760e28111d9183e2135",
5
- "linux-arm64": "80752d0a66c9c4f7acb9ff61f17991f4e41b3d297d69d5f2a8f6b789ac53decf",
6
- "linux-musl-arm64": "5f271caaee4d66369c92a74d5d063ec5696f604365fd97c412d246d1059f378a",
7
- "linux-musl-x64": "41c72cbe0ee59cee73e97b25dad1cb0de5a68d9ee5a3a08ce497f95e8f557646",
8
- "linux-ppc64": "6a8ff6ab81578b2fb47321695c0d7185d16d0b1445c7c600cbe99463909ef73e",
9
- "linux-x64": "9166a2993e1948e34a08c191b953f70490a6a648c0d076f92c44a064ccd21f5a",
10
- "win32-arm64": "b03ab956a5c2398c1c633e269d755badbfbb2497ab122b6a9392c7959432291b",
11
- "win32-x64": "dd006906854326f75d19a321faddacdbb05e9915753d52e9efa4ce58d4cf6dfb"
2
+ "darwin-arm64": "4d5b42c9da6cc884baf0984d71c61704d1efe4e0609a48cd22bc8bd24a863d0b",
3
+ "darwin-x64": "fd111f51716012b0189faaa222ab41a50bc3902fd3b8ce643ab65e2cfe5c863a",
4
+ "linux-arm": "61d5206459e0665d67f8a59493e0ee4be682990046c5863e350cd7d7b2be63a3",
5
+ "linux-arm64": "9eaa4f63f41a70f4482c0fad97e6ec2f209485ee56145125c2e552c512f7fb85",
6
+ "linux-musl-arm64": "358e81e011e22efd44aa46c3014aef13442aa40957d3034f15e028cf0ae7c50e",
7
+ "linux-musl-x64": "dc74e582ff1a717f8f743c6e8ffe2db438ca33db43aa759c2b95046400d4b983",
8
+ "linux-ppc64": "fde61a5c02acd387336367acf659e807d1a56c79a12508fcb108e70fa561054b",
9
+ "linux-x64": "7353c2e101e0ad95b7e3289ba2064023d40243d1a2952af0764e98fafc0ae149",
10
+ "win32-arm64": "ead027cf4f582c86fcfe49681f513ad4b7ab33d6c342099804855bc025f2184b",
11
+ "win32-x64": "8f5664e5c9b86646bd46af70eacb663214ef2a2f5ea4a27db0557f8ef384052d"
12
12
  }
@@ -16,6 +16,11 @@
16
16
 
17
17
  struct AnnotationData {
18
18
  int index = 0;
19
+ // FPDFPage_GetAnnot returned NULL for this index -- documented as "NULL on
20
+ // failure", so the annotation is counted on the page but could not be
21
+ // loaded. Serialized as a null entry rather than dropped, which would leave
22
+ // an unexplained gap in the `index` sequence.
23
+ bool failed = false;
19
24
  std::string type;
20
25
  double left = 0, bottom = 0, right = 0, top = 0;
21
26
  bool hasBounds = false;
@@ -55,10 +60,21 @@ protected:
55
60
  CHECK_ALIVE();
56
61
 
57
62
  int count = FPDFPage_GetAnnotCount(page_);
63
+ // reserve up front: every index now yields an entry, a failed one
64
+ // included, so the final size is known
65
+ if (count > 0)
66
+ annotations_.reserve(count);
58
67
  for (int i = 0; i < count; i++) {
59
68
  FPDF_ANNOTATION annot = FPDFPage_GetAnnot(page_, i);
60
- if (!annot)
69
+ if (!annot) {
70
+ // The count promised this index, so a NULL handle is damage,
71
+ // not absence. Dropping it silently shortened the array.
72
+ AnnotationData missing;
73
+ missing.index = i;
74
+ missing.failed = true;
75
+ annotations_.push_back(std::move(missing));
61
76
  continue;
77
+ }
62
78
 
63
79
  AnnotationData data;
64
80
  data.index = i;
@@ -224,6 +240,10 @@ protected:
224
240
  Napi::Array arr = Napi::Array::New(env, annotations_.size());
225
241
  for (uint32_t i = 0; i < annotations_.size(); i++) {
226
242
  auto &d = annotations_[i];
243
+ if (d.failed) {
244
+ arr.Set(i, env.Null());
245
+ continue;
246
+ }
227
247
  Napi::Object obj = Napi::Object::New(env);
228
248
  obj.Set("index", Napi::Number::New(env, d.index));
229
249
  obj.Set("type", Napi::String::New(env, d.type));
@@ -14,9 +14,17 @@
14
14
  // ---------------------------------------------------------------------------
15
15
  // PDF/A-3 documents (ZUGFeRD / Factur-X / XRechnung e-invoices) carry the
16
16
  // structured invoice as an embedded XML file in the /EmbeddedFiles name tree.
17
- // FPDFDoc_GetAttachmentCount already surfaces detection via metadata; these
18
- // workers add the ability to enumerate attachment metadata and read the raw
19
- // bytes so callers can pull out factur-x.xml / zugferd-invoice.xml / etc.
17
+ // FPDFDoc_GetAttachmentCount surfaces detection via metadata; these workers
18
+ // add the ability to enumerate attachment metadata and read the raw bytes so
19
+ // callers can pull out factur-x.xml / zugferd-invoice.xml / etc.
20
+ //
21
+ // Detection and enumeration can disagree. The count is the number of slots in
22
+ // the name tree, but FPDFDoc_GetAttachment resolves each slot and is
23
+ // documented to return NULL "on failure" -- a filespec reference pointing at a
24
+ // missing object is counted yet does not load. Such an index is reported as a
25
+ // null entry rather than dropped, so the array stays index-aligned, its length
26
+ // keeps matching metadata.attachmentCount, and a caller deciding whether a
27
+ // destructive operation is safe cannot read damage as "no attachments".
20
28
 
21
29
  // read a UTF-16LE string value from an attachment's params dictionary
22
30
  inline std::u16string ReadAttachmentStringValue(FPDF_ATTACHMENT attachment,
@@ -78,6 +86,9 @@ inline bool ReadAttachmentFileBytes(FPDF_ATTACHMENT attachment,
78
86
 
79
87
  struct AttachmentInfo {
80
88
  int index = 0;
89
+ // FPDFDoc_GetAttachment returned NULL for this index: the name tree counted
90
+ // the slot but PDFium could not resolve it. Serialized as a null entry.
91
+ bool failed = false;
81
92
  std::u16string name;
82
93
  std::u16string mimeType;
83
94
  std::u16string afRelationship;
@@ -109,8 +120,16 @@ protected:
109
120
  attachments_.reserve(count);
110
121
  for (int i = 0; i < count; i++) {
111
122
  FPDF_ATTACHMENT attachment = FPDFDoc_GetAttachment(doc_, i);
112
- if (!attachment)
123
+ if (!attachment) {
124
+ // The count promised this index, so a NULL handle is damage, not
125
+ // absence. Dropping it made getAttachments() contradict
126
+ // metadata.attachmentCount with no way for a caller to tell.
127
+ AttachmentInfo missing;
128
+ missing.index = i;
129
+ missing.failed = true;
130
+ attachments_.push_back(std::move(missing));
113
131
  continue;
132
+ }
114
133
 
115
134
  AttachmentInfo info;
116
135
  info.index = i;
@@ -157,6 +176,10 @@ protected:
157
176
  Napi::Array arr = Napi::Array::New(env, attachments_.size());
158
177
  for (uint32_t i = 0; i < attachments_.size(); i++) {
159
178
  const auto &info = attachments_[i];
179
+ if (info.failed) {
180
+ arr.Set(i, env.Null());
181
+ continue;
182
+ }
160
183
  Napi::Object obj = Napi::Object::New(env);
161
184
  obj.Set("index", Napi::Number::New(env, info.index));
162
185
  SetU16(obj, "name", env, info.name);