pdfcer-model 0.155.0

pdfcer COS model layer: objects, lexer, parser, filters, xref, object streams, recovery, Document/DocumentView, the full and incremental writer, standard-handler crypto, content parsing and the page tree. Depends on nothing else in the workspace; re-exported by pdfcer-core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
//! # Page tree walk + attribute inheritance (ISO 32000-1 §7.7.3, §7.9.5)
//!
//! Flattens the document's page tree into ordered, fully-resolved
//! [`Page`]s. Spec sources: `iso32000__s__7.7.3.md` (tree structure,
//! Tables 29/30, the inheritance rules) and `iso32000__s__7.9.5.md`
//! (rectangle corner normalization) in the PDF-spec RAG. Clause
//! numbers are ISO 32000-1:2008.
//!
//! ## The four inheritable attributes (§7.7.3.4 — exactly four)
//!
//! `Resources`, `MediaBox`, `CropBox`, `Rotate` — verified in the RAG
//! by exhaustive search of Table 30's inheritable markers. Nothing
//! else inherits; in particular `BleedBox`/`TrimBox`/`ArtBox` do NOT
//! walk ancestors (they default to the resolved `CropBox`).
//!
//! Resolution, per attribute (§7.7.3.4):
//! - `Resources`: own → nearest ancestor; **required** to resolve.
//!   **Present-but-empty `<< >>` means "no resources" and STOPS
//!   inheritance — different from absent (absent = inherit).** This
//!   normative distinction is a common implementation bug (RAG note).
//! - `MediaBox`: own → nearest ancestor; required to resolve.
//! - `CropBox`: own → nearest ancestor → default = resolved `MediaBox`.
//! - `Rotate`: own → nearest ancestor → default = 0. Shall be a
//!   multiple of 90; negative multiples are legal and normalize via
//!   positive modulo (`-90` → `270`).
//!
//! Inheritance is resolved **top-down during the walk** (O(n), needs
//! no `Parent` chasing), not bottom-up via `/Parent`.
//!
//! ## Structure tolerance and guards
//!
//! "Conforming products shall be prepared to handle any form of tree
//! structure" (§7.7.3.1) — so no shape assumptions. Node kind is
//! dispatched on `/Type` where present, falling back to structural
//! detection (`Kids` present ⇒ intermediate node) where absent —
//! Table 29/30 mark `/Type` Required, so absence is malformed but
//! recoverable, and §7.3.7 says type is "almost always inferable from
//! context". `Count` is a cross-check only, never trusted — a damaged
//! `Count` must not truncate the walk (RAG guard note). `Kids` cycles
//! and hostile depth are guarded ([`MAX_TREE_DEPTH`], [`MAX_PAGES`],
//! plus a visited-set — ARCHITECTURE.md §10 policy values, not spec).

use std::collections::HashSet;

use crate::document::Document;
use crate::graph::ObjectGraph;
use crate::object::{Dict, ObjId, Object};
use crate::view::DocumentView;

/// Maximum page-tree nesting depth (pdfcer policy, ARCHITECTURE.md
/// §10): legitimate trees are shallow (balanced fan-out ~25–50); a
/// deeper chain is damage or hostility.
pub const MAX_TREE_DEPTH: usize = 64;

/// Maximum number of pages walked (pdfcer policy, ARCHITECTURE.md
/// §10.1): bounds allocation against a hostile tree. Far beyond any
/// legitimate document.
pub const MAX_PAGES: usize = 1_000_000;

/// A rectangle normalized per §7.9.5: the array `[x1 y1 x2 y2]` gives
/// two diagonally opposite corners **in either order**, so consumers
/// must normalize — this type stores (min, min) → (max, max) always.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
    /// Lower-left x (the smaller x).
    pub llx: f64,
    /// Lower-left y (the smaller y).
    pub lly: f64,
    /// Upper-right x (the larger x).
    pub urx: f64,
    /// Upper-right y (the larger y).
    pub ury: f64,
}

impl Rect {
    /// Normalize two arbitrary diagonal corners into a `Rect`
    /// (§7.9.5's corners-in-any-order rule).
    #[must_use]
    pub fn from_corners(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
        Self {
            llx: x1.min(x2),
            lly: y1.min(y2),
            urx: x1.max(x2),
            ury: y1.max(y2),
        }
    }

    /// Width (always non-negative by construction).
    #[must_use]
    pub fn width(&self) -> f64 {
        self.urx - self.llx
    }

    /// Height (always non-negative by construction).
    #[must_use]
    pub fn height(&self) -> f64 {
        self.ury - self.lly
    }

    /// Whether `other` lies wholly inside this rectangle, edges included.
    ///
    /// **Inclusive on every edge**, which is the answer the page-boundary
    /// questions want: §14.11.2's boxes routinely coincide exactly (Table
    /// 30 makes `CropBox` *default* to `MediaBox`, and the defaulted case
    /// must not report itself as "outside"), and a page whose crop box
    /// equals its media box is the overwhelmingly common shape.
    ///
    /// Both rectangles are assumed §7.9.5-normalized — true by
    /// construction for anything from [`Rect::from_corners`] or from the
    /// page-tree walk, which is every `Rect` pdfcer produces.
    #[must_use]
    pub fn contains(&self, other: &Self) -> bool {
        other.llx >= self.llx
            && other.lly >= self.lly
            && other.urx <= self.urx
            && other.ury <= self.ury
    }

    /// The overlap of two rectangles, or `None` when it has no area
    /// (disjoint, or touching only along an edge or at a corner).
    ///
    /// A zero-area overlap is `None` rather than a degenerate `Rect`
    /// because every caller is resolving a page box, and a page box with
    /// no area frames nothing (ISO 32000-2 §14.11.2.1 leaves that case
    /// undefined — ambiguity PB-A1).
    #[must_use]
    pub fn intersection(&self, other: &Self) -> Option<Self> {
        let r = Self {
            llx: self.llx.max(other.llx),
            lly: self.lly.max(other.lly),
            urx: self.urx.min(other.urx),
            ury: self.ury.min(other.ury),
        };
        (r.urx > r.llx && r.ury > r.lly).then_some(r)
    }
}

/// How a resolved page box ([`Page::crop_box`], [`Page::bleed_box`],
/// [`Page::trim_box`], [`Page::art_box`]) relates to what the file wrote.
///
/// ISO 32000-2 §14.11.2.1: "If the bounds of the crop, trim, bleed or art
/// box extends outside of the bounds of the media box, a processor shall
/// treat the box as its intersection with the media box." Every resolved
/// box is therefore already clipped to [`Page::media_box`]; this says
/// whether that changed anything. Report anything but `Defaulted` /
/// `AsWritten` off-canvas (project rule 4) — the file is not rewritten.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum BoxResolution {
    /// The file wrote no such box (nor, for `CropBox`, did an ancestor);
    /// the Table 30 default is in use.
    #[default]
    Defaulted,
    /// The written box lies inside the media box and is used unchanged.
    AsWritten,
    /// The written box extended beyond the media box and was reduced to
    /// the intersection.
    Clipped,
    /// The written box could not be used and the Table 30 default is in
    /// use instead: its intersection with the media box has no area
    /// (the spec leaves this undefined, PB-A1), or — for the three
    /// non-inheritable boxes only — it is not a four-number array.
    ///
    /// Falling back to the default rather than framing an empty page is
    /// pdfcer's choice for PB-A1; a caller that wants the other answer
    /// (render nothing) can act on this variant.
    Unusable,
}

/// One page, fully resolved: every inheritable attribute has its final
/// value, defaults applied.
#[derive(Debug, Clone)]
pub struct Page {
    /// The page object's identity (pages are always reached through
    /// indirect `Kids` references, so this is always known).
    pub id: ObjId,
    /// Resolved `Resources` (§7.8.3) — own, inherited, the page's
    /// explicit empty dictionary, or (when the attribute is on neither the
    /// page nor any ancestor) the empty dictionary pdfcer supplied, which
    /// [`Self::resources_defaulted`] discloses.
    pub resources: Dict,
    /// `true` when `/Resources` was on **neither the page nor any
    /// ancestor**, and this page's [`Self::resources`] is therefore the
    /// empty dictionary pdfcer supplied rather than one the file wrote.
    ///
    /// # Why this is a disclosure rather than a refusal
    ///
    /// §7.7.3.3 Table 30 lists `/Resources` as *required; inheritable*, and
    /// §7.7.3.4 says a value "shall be supplied in an ancestor node" when a
    /// page has none of its own. A file that satisfies neither is
    /// non-conforming — but non-conforming is not the same as unreadable,
    /// and until `Pass 290.0` this attribute alone cost the operator every
    /// page of the document, including the well-formed ones, because the
    /// walk returns one `Result` for the whole page tree.
    ///
    /// Two files make the case concretely:
    ///
    ///   * **Acrobat writes pages like this.** A user-created stamp
    ///     collection under `%APPDATA%\Adobe\Acrobat\DC\Stamps\` holds a
    ///     blank spacer page with no `/Contents` and no `/Resources`
    ///     between two complete stamp pages. The file is what Acrobat uses
    ///     to sign a document; every reader opens it; pdfcer refused all
    ///     three pages.
    ///   * **`fixtures/synthetic/minimal.pdf` — pdfcer's own smallest legal
    ///     fixture — has no `/Resources`**, so the project shipped a page
    ///     tree walk that could not read its own minimal file.
    ///
    /// # What is and is not claimed when this is `true`
    ///
    /// Nothing is invented, and the value is the standard's own: Table 30's
    /// `/Resources` row says "If the page requires no resources, the value
    /// of this entry shall be an empty dictionary". A name looked up in the
    /// dictionary pdfcer supplies fails exactly as it fails in an explicit
    /// `<< >>` that any file could have written legally — and those failures
    /// are already counted, one by one, by the renderer
    /// (`fonts_unsupported`, `cs_unresolved`, unpainted forms) and by the
    /// extractor. **This flag is the single cause behind them.**
    ///
    /// ⚠ It is NOT a claim that the page was harmless. In particular, do not
    /// reason that a page with no `/Contents` can name nothing: §7.8.3's
    /// third bullet lets form XObjects and Type 3 fonts omit their own
    /// `/Resources` and inherit the page's, and ISO 32000-2's erratum
    /// extends that to **annotation appearance streams**. A page whose only
    /// marks are annotation `/AP` forms — the shape that motivated this
    /// Pass — is therefore a page that can genuinely need the dictionary it
    /// does not have.
    ///
    /// # And the file is definitely non-conforming
    ///
    /// ISO considered conditioning the requirement on `/Contents` and
    /// decided against it (`pdf-issues` #81, ISO approved), adding a NOTE to
    /// ISO 32000-2's `/Contents` row: a `/Resources` dictionary must still
    /// be present, directly or by inheritance. pdfcer says so rather than
    /// pretending otherwise — it just does not make the operator pay for it
    /// with the document. §2.2 scopes a reader's rendering duty to
    /// *conforming* files and §1 excludes conformance validation from the
    /// standard's scope, so refusal was never owed; it was chosen.
    ///
    /// # For a shell
    ///
    /// Report it off-canvas (project rule 4): the page renders normally,
    /// and the fact that pdfcer supplied the dictionary belongs in a status
    /// line or a report, never as a mark on the page.
    pub resources_defaulted: bool,
    /// Resolved `MediaBox`, normalized (§7.9.5).
    pub media_box: Rect,
    /// The effective `CropBox`: the resolved entry intersected with
    /// [`Self::media_box`] (§14.11.2.1), or `media_box` when absent or
    /// unusable. Content is clipped to this at display time (Table 30),
    /// so this is the rectangle a renderer frames the page by. What the
    /// file itself wrote is left in the file; see
    /// [`Self::crop_box_resolution`].
    pub crop_box: Rect,
    /// How [`Self::crop_box`] was obtained from the file.
    pub crop_box_resolution: BoxResolution,
    /// The effective `BleedBox` (PDF 1.3, not inheritable): the page's own
    /// entry intersected with [`Self::media_box`], else [`Self::crop_box`].
    pub bleed_box: Rect,
    /// How [`Self::bleed_box`] was obtained.
    pub bleed_box_resolution: BoxResolution,
    /// The effective `TrimBox` — the finished page after trimming; same
    /// resolution rule as [`Self::bleed_box`].
    pub trim_box: Rect,
    /// How [`Self::trim_box`] was obtained.
    pub trim_box_resolution: BoxResolution,
    /// The effective `ArtBox` — the creator's meaningful content; same
    /// resolution rule as [`Self::bleed_box`].
    pub art_box: Rect,
    /// How [`Self::art_box`] was obtained.
    pub art_box_resolution: BoxResolution,
    /// Resolved `Rotate`, normalized to {0, 90, 180, 270} — clockwise
    /// display rotation (Table 30).
    pub rotate: u16,
    /// The `Contents` streams, in order (Table 30: a single stream or
    /// an array whose streams concatenate; streams are always indirect
    /// per §7.3.8.1, so these are always resolvable ids). Empty =
    /// an empty page (absent `Contents` is NOT an error).
    pub contents: Vec<ObjId>,
    /// How many `Contents` entries named an object that is **not in the
    /// file**, and therefore contribute nothing to this page.
    ///
    /// §7.3.10: "An indirect reference to an undefined object is not an
    /// error; it shall be treated as a reference to the null object."
    /// Table 30 then makes the consequence explicit for this key —
    /// `Contents` is optional, and "if this entry is absent, the page
    /// shall be empty". A dangling element is therefore a page that is
    /// *incomplete*, not a document that is *invalid*, and refusing the
    /// whole document over one would violate the §10 fail-clean posture
    /// (a damaged part must not cost the operator the whole file).
    ///
    /// Non-zero means content the page asked for could not be drawn or
    /// extracted. It is counted rather than silently swallowed because
    /// "fuzzy, never sneaky" applies to omissions as much as to
    /// suggestions: a silently-empty page is indistinguishable from a
    /// genuinely blank one, and the operator would have no way to tell
    /// that text they expected is missing.
    ///
    /// Note what this does **not** cover: an entry of the wrong *type* —
    /// a number, a dictionary, an array element that is not a reference —
    /// is a genuine structural error and still yields
    /// [`PageTreeError::BadContents`]. Only "the reference resolves to
    /// null" degrades.
    pub contents_unresolved: usize,
    /// How many **nested arrays** were flattened out of this page's
    /// `/Contents` on the way in — the count of a specific, recognisable
    /// damage that **pdfcer itself wrote** (`Pass 111.0`).
    ///
    /// # What the damage is, and why the repair is exact rather than a guess
    ///
    /// Until 2026-08-20, appending a content stream to a page whose
    /// `/Contents` was an *indirect reference to an array* wrapped that
    /// reference instead of splicing into it, producing
    /// `/Contents [38 0 R, new]` where `38 0 R` dereferences to
    /// `[7 0 R, 37 0 R]`. Nothing in Table 30 permits an array inside the
    /// `/Contents` array, so this walker rejected the page with
    /// [`PageTreeError::BadContents`] — and the file was one pdfcer had just
    /// written and reported `Ok` for.
    ///
    /// **The repair is deterministic, which is the whole reason it is
    /// allowed.** Flattening `[[a, b], c]` to `[a, b, c]` recovers exactly the
    /// streams the page had, in exactly the order Table 30 concatenates them.
    /// Nothing is inferred, chosen, or approximated — the nesting is pure
    /// noise, and the correct reading is the only reading. Contrast
    /// [`Self::contents_unresolved`], where content genuinely IS missing.
    ///
    /// # It is READ-side only — nothing is rewritten
    ///
    /// This makes a damaged document open, render and extract. It does **not**
    /// repair the file: `ARCHITECTURE.md` §5 forbids normalising structure as
    /// a side effect of reading, and an incremental save with no edits still
    /// emits nothing. The page is repaired in the file only when something
    /// else legitimately rewrites that page dictionary — at which point the
    /// overlay append ([`plan_overlay_append`]) writes the flat form.
    ///
    /// Non-zero therefore means: *this document was damaged by a pdfcer build
    /// older than `Pass 111.0`, and other readers may still refuse it.* That
    /// is worth surfacing to an operator, which is why it is a counted
    /// disclosure and not a silent kindness.
    pub contents_flattened: usize,
    /// The page's `/UserUnit` (PDF 1.6, ISO 32000-1 §14.11.2 Table 30):
    /// the size of one default user space unit, in multiples of 1/72 inch.
    /// The boxes above are in those units, so the page's physical size is
    /// a box times this. Not inheritable. `1.0` when absent, or when the
    /// value is not a finite positive number (the supported range is
    /// implementation-dependent; pdfcer reads such a value as the default).
    pub user_unit: f64,
}

/// Page-tree structural errors.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PageTreeError {
    /// The catalog has no usable `/Pages` entry.
    #[error("catalog /Pages missing or not a dictionary")]
    NoPageTreeRoot,
    /// A `Kids` element resolved to something that is not a
    /// dictionary (including a dangling reference's null).
    #[error("page tree kid is not a dictionary (object {0})")]
    BadKid(ObjId),
    /// A node was visited twice — the tree has a cycle.
    #[error("page tree cycle at object {0}")]
    Cycle(ObjId),
    /// Nesting exceeded [`MAX_TREE_DEPTH`] (pdfcer guard).
    #[error("page tree exceeds MAX_TREE_DEPTH ({MAX_TREE_DEPTH})")]
    TooDeep,
    /// More than [`MAX_PAGES`] leaves (pdfcer guard).
    #[error("page tree exceeds MAX_PAGES ({MAX_PAGES})")]
    TooManyPages,
    /// A required inheritable attribute resolved nowhere on the path to
    /// the root (§7.7.3.4: "a value shall be supplied in an ancestor
    /// node").
    ///
    /// **`MediaBox` only, since `Pass 290.0`.** `Resources` used to
    /// produce this too, and it was the wrong severity for the wrong
    /// attribute: an absent resource dictionary means "no named resource is
    /// available", which is a statement the empty dictionary makes exactly,
    /// whereas an absent `MediaBox` means the page has **no geometry** and
    /// any value pdfcer chose (Letter? A4? the previous page's?) would be
    /// invented. Continuing requires inventing nothing; that is the line
    /// decision 145 draws, and `MediaBox` is on the other side of it. See
    /// [`Page::resources_defaulted`].
    #[error("required page attribute {0} missing on page and all ancestors")]
    MissingRequired(&'static str),
    /// `/Resources` was present but resolved to something that is **not a
    /// dictionary** — a number, a name, an array, a string or a stream.
    ///
    /// Deliberately narrower than "the attribute is unusable": an absent
    /// `/Resources`, and one whose reference dangles (§7.3.10 makes that
    /// the null object; §7.3.9 makes null "equivalent to omitting the
    /// entry"), are **not** this error. Those degrade to the empty
    /// dictionary and are disclosed through [`Page::resources_defaulted`].
    /// This variant is reserved for a value with no spec-sanctioned
    /// reading, which is a real structural defect and must not be laundered
    /// into a page that merely renders emptier — the same split
    /// [`Self::BadContents`] makes, for the same reason.
    #[error("page /Resources is not a dictionary")]
    BadResources,
    /// A rectangle entry wasn't an array of four numbers.
    #[error("malformed rectangle in page attribute {0}")]
    BadRectangle(&'static str),
    /// `Rotate` was not an integer multiple of 90 (Table 30 "shall").
    #[error("page /Rotate value {0} is not a multiple of 90")]
    BadRotate(i64),
    /// `Contents` held a value of the wrong **type** — something that is
    /// neither a stream reference, an array of them, nor null.
    ///
    /// Deliberately narrower than it looks: an element that resolves to
    /// **null** (a dangling reference to an object the file does not
    /// contain) is NOT this error. §7.3.10 defines such a reference to be
    /// the null object and Table 30 makes an absent `Contents` an empty
    /// page, so that case degrades — the element contributes nothing and
    /// the omission is counted in [`Page::contents_unresolved`]. This
    /// variant is reserved for values with no spec-sanctioned reading (a
    /// number, a name, a dictionary, a non-reference array element), which
    /// are real structural defects and must not be laundered into a silent
    /// blank page.
    #[error("page /Contents is neither a stream nor an array of streams")]
    BadContents,
}

/// Inheritable-attribute state carried down the walk (raw objects —
/// resolution to `Rect`/`Dict` happens once, at the leaf, so an
/// intermediate node's malformed value only errors if a page actually
/// inherits it).
#[derive(Clone, Default)]
struct Inherited<'a> {
    resources: Option<&'a Object>,
    media_box: Option<&'a Object>,
    crop_box: Option<&'a Object>,
    rotate: Option<&'a Object>,
}

/// Walk the **loaded file's** page tree and return its pages in
/// document order, attributes fully resolved.
///
/// A thin wrapper over [`pages_in`]. Kept as a named function because
/// "the pages of this document" is what the renderer and every read-only
/// consumer actually want, and spelling it `pages_in(doc)` at forty call
/// sites would obscure that the interesting case is the *other* one.
///
/// ⚠️ **This is the base revision, not the edited state.** Anything that
/// must see unsaved structural edits calls
/// `EditSession::pages`, which walks
/// the overlay through the same code.
///
/// # Errors
///
/// [`PageTreeError`] — structural damage, guard violations, or
/// unresolvable required attributes. A well-formed empty tree
/// (`/Count 0`, empty `Kids`) returns an empty vec, not an error.
pub fn pages(doc: &Document) -> Result<Vec<Page>, PageTreeError> {
    pages_in(doc)
}

/// Walk any [`ObjectGraph`]'s page tree and return its pages in document
/// order, attributes fully resolved.
///
/// The generic form exists for exactly one reason, recorded in
/// [`crate::graph`]'s module docs: from Pass 3.2 an edit can change the
/// page tree's **shape**, so the walk must be able to run over the
/// session overlay rather than over the base file. There is deliberately
/// only one walk — a session-specialised copy is how a build eventually
/// renders a page the operator deleted.
///
/// # Errors
///
/// [`PageTreeError`] — as [`pages`].
pub fn pages_in<G: ObjectGraph + ?Sized>(graph: &G) -> Result<Vec<Page>, PageTreeError> {
    let catalog = graph.catalog_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
    let root_obj = catalog
        .get(b"Pages")
        .map(|o| graph.resolve(o))
        .ok_or(PageTreeError::NoPageTreeRoot)?;
    let root = root_obj.as_dict().ok_or(PageTreeError::NoPageTreeRoot)?;

    // The root's id (for cycle tracking) if it was reached by
    // reference — it always is in well-formed files (`/Pages` "shall
    // be an indirect reference", Table 15/28).
    let root_id = catalog.get(b"Pages").and_then(Object::as_reference);

    let mut out = Vec::new();
    let mut visited: HashSet<ObjId> = root_id.into_iter().collect();
    walk(graph, root, Inherited::default(), 0, &mut visited, &mut out)?;
    Ok(out)
}

/// One page's **structural** position in the tree: which node holds it,
/// where in that node's `Kids`, and what its ancestors are.
///
/// [`Page`] answers *"what does this page look like?"*; this answers
/// *"where does this page live?"*, which is the only question a
/// structural operation asks. Splitting them keeps the renderer's type
/// free of bookkeeping it has no use for, and keeps this type free of
/// the expensive attribute resolution a delete does not need.
///
/// `inherited` carries the **raw, unresolved** values an ancestor
/// supplies for the four inheritable attributes (§7.7.3.4), and it is
/// the reason this type is worth building at all. When a page moves to a
/// different parent — a reorder across nodes, an extract into a fresh
/// document — the attributes it used to inherit may no longer reach it.
/// Writing the *raw* value back onto the page (usually a single
/// reference) preserves rendering exactly, whereas writing a *resolved*
/// value would inline an entire resource dictionary and change bytes far
/// beyond the edit.
#[derive(Debug, Clone)]
pub struct PageSlot {
    /// The page object's identity.
    pub id: ObjId,
    /// The `Pages` node whose `Kids` array holds this page, if the walk
    /// reached that node by reference (it always does in a well-formed
    /// file — Table 29 requires `Kids` elements to be indirect).
    pub parent: Option<ObjId>,
    /// This page's index within `parent`'s `Kids` array.
    pub index_in_parent: usize,
    /// Every ancestor `Pages` node, **root first**, excluding the page
    /// itself. A delete must decrement `/Count` on all of them.
    pub ancestors: Vec<ObjId>,
    /// What the ancestors supply for the four inheritable attributes,
    /// unresolved. `None` for an attribute no ancestor sets.
    pub inherited: InheritedRaw,
}

/// The raw inheritable-attribute values an ancestor chain supplies
/// (§7.7.3.4 — exactly four attributes; see the module docs).
///
/// Deliberately **not** merged with the page's own entries: the whole
/// point is to know what would be *lost* if the page left this chain.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InheritedRaw {
    /// Nearest ancestor `/Resources`.
    pub resources: Option<Object>,
    /// Nearest ancestor `/MediaBox`.
    pub media_box: Option<Object>,
    /// Nearest ancestor `/CropBox`.
    pub crop_box: Option<Object>,
    /// Nearest ancestor `/Rotate`.
    pub rotate: Option<Object>,
}

impl InheritedRaw {
    /// The `(key, value)` pairs a page would need written onto it to
    /// keep these attributes after leaving this ancestor chain.
    ///
    /// Only entries the page does not already carry itself are
    /// returned, because a page's own entry always wins (§7.7.3.4) and
    /// restating it would modify an object pdfcer was not asked to
    /// modify (§5).
    #[must_use]
    pub fn materialize_for(&self, page: &Dict) -> Vec<(&'static [u8], Object)> {
        let mut out = Vec::new();
        for (key, value) in [
            (&b"Resources"[..], &self.resources),
            (&b"MediaBox"[..], &self.media_box),
            (&b"CropBox"[..], &self.crop_box),
            (&b"Rotate"[..], &self.rotate),
        ] {
            // `contains_key` collapses a null-valued entry to absent
            // (§7.3.7), which is the right test: a page carrying
            // `/Rotate null` inherits, exactly as one with no entry does.
            if let Some(v) = value
                && !page.contains_key(key)
            {
                out.push((key, v.clone()));
            }
        }
        out
    }
}

/// Walk the page tree recording each page's **structural position**
/// rather than its resolved appearance.
///
/// Same traversal, same guards, same tolerance as [`pages_in`] — and
/// deliberately a separate function rather than an extra field on
/// [`Page`], because resolving `Resources`/`MediaBox` can *fail* for a
/// damaged file (`MissingRequired`) and a structural operation should
/// not be blocked by an attribute it never reads. A page with no
/// `MediaBox` anywhere is still a page that can be deleted.
///
/// # Errors
///
/// [`PageTreeError`] — structural damage or a guard violation. Notably
/// **not** [`PageTreeError::MissingRequired`], which this walk cannot
/// produce.
pub fn page_slots<G: ObjectGraph + ?Sized>(graph: &G) -> Result<Vec<PageSlot>, PageTreeError> {
    let catalog = graph.catalog_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
    let root_id = catalog
        .get(b"Pages")
        .and_then(Object::as_reference)
        .ok_or(PageTreeError::NoPageTreeRoot)?;
    let root = graph
        .resolved(root_id)
        .as_dict()
        .ok_or(PageTreeError::NoPageTreeRoot)?;

    let mut out = Vec::new();
    let mut visited: HashSet<ObjId> = [root_id].into_iter().collect();
    walk_slots(
        graph,
        root_id,
        root,
        &InheritedRaw::default(),
        &[],
        0,
        &mut visited,
        &mut out,
    )?;
    Ok(out)
}

/// Recursive half of [`page_slots`].
#[allow(clippy::too_many_arguments)] // every argument is walk state; a
// struct here would only rename the same eight values.
fn walk_slots<G: ObjectGraph + ?Sized>(
    graph: &G,
    node_id: ObjId,
    node: &Dict,
    inherited: &InheritedRaw,
    ancestors: &[ObjId],
    depth: usize,
    visited: &mut HashSet<ObjId>,
    out: &mut Vec<PageSlot>,
) -> Result<(), PageTreeError> {
    if depth > MAX_TREE_DEPTH {
        return Err(PageTreeError::TooDeep);
    }
    let here = InheritedRaw {
        resources: node
            .get(b"Resources")
            .cloned()
            .or_else(|| inherited.resources.clone()),
        media_box: node
            .get(b"MediaBox")
            .cloned()
            .or_else(|| inherited.media_box.clone()),
        crop_box: node
            .get(b"CropBox")
            .cloned()
            .or_else(|| inherited.crop_box.clone()),
        rotate: node
            .get(b"Rotate")
            .cloned()
            .or_else(|| inherited.rotate.clone()),
    };
    let mut chain = ancestors.to_vec();
    chain.push(node_id);

    let Some(kids) = node
        .get(b"Kids")
        .map(|o| graph.resolve(o))
        .and_then(Object::as_array)
    else {
        return Err(PageTreeError::NoPageTreeRoot);
    };

    for (index, kid) in kids.iter().enumerate() {
        let Some(kid_id) = kid.as_reference() else {
            return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
        };
        if !visited.insert(kid_id) {
            return Err(PageTreeError::Cycle(kid_id));
        }
        let Some(kid_dict) = graph.resolved(kid_id).as_dict() else {
            return Err(PageTreeError::BadKid(kid_id));
        };
        if is_pages_node(graph, kid_dict) {
            walk_slots(
                graph,
                kid_id,
                kid_dict,
                &here,
                &chain,
                depth + 1,
                visited,
                out,
            )?;
        } else {
            if out.len() >= MAX_PAGES {
                return Err(PageTreeError::TooManyPages);
            }
            out.push(PageSlot {
                id: kid_id,
                parent: Some(node_id),
                index_in_parent: index,
                ancestors: chain.clone(),
                inherited: here.clone(),
            });
        }
    }
    Ok(())
}

/// Node-kind dispatch: `/Type` where present, structural fallback
/// (`Kids` present ⇒ intermediate node) where absent.
///
/// Shared by both walks so the two cannot disagree about what a node
/// with no `/Type` is — a disagreement that would show up as a page
/// count that changes depending on which walk asked.
fn is_pages_node<G: ObjectGraph + ?Sized>(graph: &G, node: &Dict) -> bool {
    match node
        .get(b"Type")
        .map(|o| graph.resolve(o))
        .and_then(Object::as_name)
        .map(crate::object::Name::as_bytes)
    {
        Some(b"Pages") => true,
        Some(b"Page") => false,
        _ => node.contains_key(b"Kids"),
    }
}

/// Recursive top-down walk (see module docs for why top-down).
fn walk<'a, G: ObjectGraph + ?Sized>(
    doc: &'a G,
    node: &'a Dict,
    inherited: Inherited<'a>,
    depth: usize,
    visited: &mut HashSet<ObjId>,
    out: &mut Vec<Page>,
) -> Result<(), PageTreeError> {
    if depth > MAX_TREE_DEPTH {
        return Err(PageTreeError::TooDeep);
    }

    // Layer this node's own inheritable entries over what came down.
    // Values stay raw here; leaves resolve them (module docs).
    let inherited = Inherited {
        resources: node.get(b"Resources").or(inherited.resources),
        media_box: node.get(b"MediaBox").or(inherited.media_box),
        crop_box: node.get(b"CropBox").or(inherited.crop_box),
        rotate: node.get(b"Rotate").or(inherited.rotate),
    };

    // Node-kind dispatch: /Type where present, structural fallback
    // (Kids ⇒ intermediate) where absent (module docs).
    let type_name = node
        .get(b"Type")
        .map(|o| doc.resolve(o))
        .and_then(Object::as_name)
        .map(crate::object::Name::as_bytes);
    let is_pages_node = match type_name {
        Some(b"Pages") => true,
        Some(b"Page") => false,
        _ => node.contains_key(b"Kids"),
    };

    if !is_pages_node {
        return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
        // unreachable in practice: leaves are emitted by the caller
        // below; kept as a defensive arm for a root that is itself a
        // Page (malformed — a root must be a Pages node).
    }

    let kids = node
        .get(b"Kids")
        .map(|o| doc.resolve(o))
        .and_then(Object::as_array)
        .ok_or(PageTreeError::NoPageTreeRoot)?;

    for kid in kids {
        // Kids "shall only be page objects or other page tree nodes",
        // referenced indirectly (Table 29).
        let Some(kid_id) = kid.as_reference() else {
            return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
        };
        if !visited.insert(kid_id) {
            return Err(PageTreeError::Cycle(kid_id));
        }
        let Some(kid_dict) = doc.resolve(kid).as_dict() else {
            return Err(PageTreeError::BadKid(kid_id));
        };

        let kid_type = kid_dict
            .get(b"Type")
            .map(|o| doc.resolve(o))
            .and_then(Object::as_name)
            .map(crate::object::Name::as_bytes);
        let kid_is_pages = match kid_type {
            Some(b"Pages") => true,
            Some(b"Page") => false,
            _ => kid_dict.contains_key(b"Kids"),
        };

        if kid_is_pages {
            walk(doc, kid_dict, inherited.clone(), depth + 1, visited, out)?;
        } else {
            if out.len() >= MAX_PAGES {
                return Err(PageTreeError::TooManyPages);
            }
            out.push(resolve_page(doc, kid_id, kid_dict, &inherited)?);
        }
    }
    Ok(())
}

/// Resolve one leaf into a [`Page`], applying the §7.7.3.4 resolution
/// order and defaults documented in the module docs.
fn resolve_page<G: ObjectGraph + ?Sized>(
    doc: &G,
    id: ObjId,
    page: &Dict,
    inherited: &Inherited<'_>,
) -> Result<Page, PageTreeError> {
    // Resources: own → ancestor; §7.7.3.3 Table 30 calls it "required;
    // inheritable". NOTE the empty-vs-absent distinction is preserved
    // automatically here: a page with `/Resources << >>` has an OWN entry
    // (empty dict), which wins over any ancestor value.
    //
    // ABSENT EVERYWHERE IS THE EMPTY RESOURCE DICTIONARY, NOT A REFUSAL.
    //
    // This used to be `.ok_or(MissingRequired("Resources"))?` — and the `?`
    // is on a walk that returns `Result<Vec<Page>, _>` for the WHOLE
    // document, so one page missing the attribute cost every other page in
    // the file. Two facts settle which reading is right:
    //
    //   * **Acrobat writes such pages.** A user-authored stamp collection in
    //     Acrobat's own preferences folder carries a blank spacer page with
    //     no `/Contents` and no `/Resources`, alongside two complete pages;
    //     pdfcer refused all three. The reference implementation opens it,
    //     and it is the file an operator signs drawings with.
    //   * **pdfcer's own `fixtures/synthetic/minimal.pdf` has no
    //     `/Resources` either**, so this walk could not render the smallest
    //     legal file the project ships. `plan_paste_at` had already grown a
    //     hand-written bypass around this exact refusal for annotation-only
    //     pastes — a guard a caller has to route around is the defect, not
    //     the caller.
    //
    // THE FILE IS CERTAINLY NON-CONFORMING, AND THAT STRENGTHENS THE CASE
    // RATHER THAN WEAKENING IT. ISO considered conditioning `/Resources` on
    // `/Contents` and decided AGAINST it: `pdf-issues` #81 ("Are Page node
    // Resources required even if Contents is not present?", ISO approved,
    // Feb 2022 submission) resolved by appending a NOTE to ISO 32000-2's
    // `/Contents` row — "If the Contents key is not present, a Resources
    // dictionary must still be present, either directly or through
    // inheritance, in the pages tree." So this is not a grey area pdfcer
    // gets to read generously.
    //
    // It is a conformance judgement, not a behaviour: §2.1 binds the FILE,
    // §2.3 the WRITER, and §2.2 scopes the reader's rendering duty to
    // "conforming files" — while §1 Scope excludes "methods for validating
    // the conformance of PDF files or readers" outright. Nothing in ISO
    // 32000 says what a reader does with a file that violates a `shall`.
    // Refusing is therefore a choice pdfcer made, never one it was owed, and
    // the erratum's own motivation was "some issues with some PDF parsers
    // not liking no Contents keys" — the reader is the known failure mode.
    //
    // Nothing is invented by defaulting, and the standard supplies the value:
    // Table 30's own `/Resources` row says "If the page requires no
    // resources, the value of this entry shall be an empty dictionary". A
    // name looked up in the dictionary pdfcer supplies therefore fails
    // exactly as it fails in an explicit `<< >>` a file could have written
    // legally — the renderer and the extractor count those failures already.
    // Refusing the document instead is the "fail-clean never meant refuse"
    // mistake decision 145 corrected one attribute along, and it escalates a
    // ONE-PAGE, ONE-ATTRIBUTE defect to the whole file, which §7.7.3.4 never
    // asks for.
    //
    // ⚠ Do NOT rebuild this argument on "a page with no `/Contents` can
    // never name a resource" — that reading is false and the spec librarian
    // caught it here. §7.8.3's third bullet: files written to earlier PDF
    // versions "may have omitted the Resources entry in all form XObjects
    // and Type 3 fonts used on a page", and those resources "shall be
    // inherited from the resource dictionary of the page on which they are
    // used" — which ISO 32000-2's erratum extends explicitly to annotation
    // appearance streams. A page whose only marks are annotation `/AP`
    // forms is exactly the shape that motivated this Pass, so the
    // contentless case is not self-evidently harmless; it is merely one
    // more failed lookup, disclosed like the rest.
    //
    // The disclosure is [`Page::resources_defaulted`] — R20 /
    // fuzzy-never-sneaky: the operator learns the page was incomplete, and
    // does not lose the file to learn it.
    //
    // The absent/null vs wrong-type split is the same one `/Contents` makes
    // below, for the same reason. A reference to an object the file does not
    // contain IS the null object (§7.3.10), and a null value is "equivalent
    // to omitting the entry" (§7.3.9), so both degrade. A number, a name, an
    // array or a stream has no spec-sanctioned reading and still fails the
    // page — laundering those into an empty dictionary would hide a real
    // structural defect behind a page that merely renders emptier.
    let (resources, resources_defaulted) = match page
        .get(b"Resources")
        .or(inherited.resources)
        .map(|o| doc.resolve(o))
    {
        Some(Object::Dict(d)) => (d.clone(), false),
        None | Some(Object::Null) => (Dict::new(), true),
        Some(_) => return Err(PageTreeError::BadResources),
    };

    let media_box = page
        .get(b"MediaBox")
        .or(inherited.media_box)
        .ok_or(PageTreeError::MissingRequired("MediaBox"))
        .and_then(|o| parse_rect(doc, o, "MediaBox"))?;

    // CropBox: own → ancestor → default = resolved MediaBox, then clipped to
    // the media box (§14.11.2.1). A malformed CropBox still fails the page,
    // as it always has; only the three production boxes below degrade.
    let (crop_box, crop_box_resolution) = match page.get(b"CropBox").or(inherited.crop_box) {
        Some(o) => clip_to_media(parse_rect(doc, o, "CropBox")?, media_box, media_box),
        None => (media_box, BoxResolution::Defaulted),
    };
    // Bleed/Trim/Art: own only (not inheritable, Table 30) → default =
    // effective CropBox.
    let production_box = |key: &[u8]| match page.get(key) {
        None => (crop_box, BoxResolution::Defaulted),
        Some(o) => match parse_rect(doc, o, "BleedBox") {
            Ok(r) => clip_to_media(r, media_box, crop_box),
            Err(_) => (crop_box, BoxResolution::Unusable),
        },
    };
    let (bleed_box, bleed_box_resolution) = production_box(b"BleedBox");
    let (trim_box, trim_box_resolution) = production_box(b"TrimBox");
    let (art_box, art_box_resolution) = production_box(b"ArtBox");

    // Rotate: own → ancestor → 0; multiple of 90; positive modulo.
    let rotate = match page
        .get(b"Rotate")
        .or(inherited.rotate)
        .map(|o| doc.resolve(o))
    {
        None => 0,
        Some(Object::Integer(v)) if v % 90 == 0 => u16::try_from(v.rem_euclid(360)).unwrap_or(0),
        Some(Object::Integer(v)) => return Err(PageTreeError::BadRotate(*v)),
        Some(_) => return Err(PageTreeError::BadRotate(i64::MIN)),
    };

    // Contents: absent = empty page; single stream ref; or array of
    // stream refs (streams are always indirect, §7.3.8.1).
    //
    // The two failure modes are deliberately NOT treated alike:
    //
    //   * A reference that resolves to **null** — because the object is
    //     absent from the file, or because the file explicitly wrote
    //     `null` — is not an error at all. §7.3.10 makes a reference to an
    //     undefined object *be* the null object, and §7.3.9 makes a null
    //     value equivalent to omitting the entry; Table 30 then says an
    //     absent `Contents` means an empty page. So it degrades: that
    //     element contributes nothing, the rest of the page still loads,
    //     and the omission is COUNTED into `contents_unresolved` for
    //     disclosure.
    //   * A value of the wrong **type** — a number, a name, a dictionary,
    //     a direct non-reference array element — is a genuine structural
    //     error with no spec-sanctioned reading, and still fails the page
    //     with `BadContents`. Degrading these too would convert a real
    //     defect into a silent blank page, which is precisely the outcome
    //     "fuzzy, never sneaky" forbids.
    let (contents, contents_unresolved, contents_flattened) = match page.get(b"Contents") {
        None => (Vec::new(), 0, 0),
        // A direct `null` value: §7.3.9 "equivalent to omitting the entry",
        // so this is a well-formed empty page, not a degradation — nothing
        // is missing, so nothing is counted.
        Some(Object::Null) => (Vec::new(), 0, 0),
        Some(entry @ Object::Reference(r)) => match doc.resolve(entry) {
            Object::Stream(_) => (vec![*r], 0, 0),
            // A reference to an ARRAY of streams is also legal
            // (substitutability, §7.3.10) — recurse into the array.
            Object::Array(items) => contents_from_array(doc, items, 0)?,
            // §7.3.10 + Table 30: the whole `Contents` value is the null
            // object, which reads as absent — an empty page, disclosed.
            Object::Null => (Vec::new(), 1, 0),
            _ => return Err(PageTreeError::BadContents),
        },
        Some(Object::Array(items)) => contents_from_array(doc, items, 0)?,
        Some(_) => return Err(PageTreeError::BadContents),
    };

    Ok(Page {
        id,
        resources,
        resources_defaulted,
        media_box,
        crop_box,
        crop_box_resolution,
        bleed_box,
        bleed_box_resolution,
        trim_box,
        trim_box_resolution,
        art_box,
        art_box_resolution,
        rotate,
        contents,
        contents_unresolved,
        contents_flattened,
        user_unit: user_unit_of(doc, page),
    })
}

/// Table 30 `/UserUnit`, or `1.0` when absent or not a finite positive number.
fn user_unit_of<G: ObjectGraph + ?Sized>(doc: &G, page: &Dict) -> f64 {
    page.get(b"UserUnit")
        .and_then(|o| doc.resolve(o).as_number())
        .filter(|u| u.is_finite() && *u > 0.0)
        .unwrap_or(1.0)
}

impl Page {
    /// A page that states no production boxes, as [`pages`] resolves one:
    /// `crop_box` is the effective box, bleed, trim and art equal it (Table
    /// 30 defaults), every resolution is [`BoxResolution::Defaulted`], and
    /// resources and contents are empty (`resources_defaulted` `false`).
    ///
    /// `crop_box` is taken as given, not intersected with `media_box`.
    /// `rotate` is normalized as the page tree normalizes it: a multiple of
    /// 90 reduced into {0, 90, 180, 270}, anything else 0.
    ///
    /// Set any other field afterwards, or with struct-update syntax: new
    /// fields added to `Page` are then filled here and do not break callers.
    ///
    /// # Examples
    ///
    /// ```
    /// use pdfcer_model::object::ObjId;
    /// use pdfcer_model::page_tree::{BoxResolution, Page, Rect};
    ///
    /// let media = Rect::from_corners(0.0, 0.0, 612.0, 792.0);
    /// let page = Page {
    ///     contents: vec![ObjId::new(4, 0)],
    ///     ..Page::with_boxes(ObjId::new(3, 0), media, media, 450)
    /// };
    /// assert_eq!(page.rotate, 90);
    /// assert_eq!(page.trim_box, media);
    /// assert_eq!(page.art_box_resolution, BoxResolution::Defaulted);
    /// ```
    #[must_use]
    pub fn with_boxes(id: ObjId, media_box: Rect, crop_box: Rect, rotate: u16) -> Self {
        let rotate = if rotate.is_multiple_of(90) {
            rotate % 360
        } else {
            0
        };
        Self {
            id,
            resources: Dict::new(),
            resources_defaulted: false,
            media_box,
            crop_box,
            crop_box_resolution: BoxResolution::Defaulted,
            bleed_box: crop_box,
            bleed_box_resolution: BoxResolution::Defaulted,
            trim_box: crop_box,
            trim_box_resolution: BoxResolution::Defaulted,
            art_box: crop_box,
            art_box_resolution: BoxResolution::Defaulted,
            rotate,
            contents: Vec::new(),
            contents_unresolved: 0,
            contents_flattened: 0,
            user_unit: 1.0,
        }
    }
}

/// Resolve a written page box against the media box (§14.11.2.1), falling
/// back to `default` when the intersection has no area (PB-A1).
fn clip_to_media(written: Rect, media_box: Rect, default: Rect) -> (Rect, BoxResolution) {
    match media_box.intersection(&written) {
        Some(r) if r == written => (r, BoxResolution::AsWritten),
        Some(r) => (r, BoxResolution::Clipped),
        None => (default, BoxResolution::Unusable),
    }
}

/// The deepest nesting [`contents_from_array`] will flatten before refusing.
///
/// Realistically the damage is ONE level deep — a wrapped reference — and two
/// only if a damaged page was damaged again. The bound is generous rather than
/// tight because its job is to stop unbounded recursion on hostile input, not
/// to second-guess an unusual file (`ARCHITECTURE.md` §10).
const MAX_CONTENTS_NESTING: usize = 8;

/// Collect the stream ids of a `Contents` array, degrading unresolvable
/// elements, FLATTENING nested arrays, and rejecting wrong-typed ones.
///
/// Returns the ids that resolved to real streams, in order, plus the count
/// of elements that resolved to null (§7.3.10) and so contribute nothing.
/// The surviving elements still concatenate in order — Table 30's "the
/// division between streams may occur only at the boundaries between
/// lexical tokens" means a dropped element leaves a *shorter* content
/// stream, never a syntactically broken one.
///
/// # Errors
///
/// [`PageTreeError::BadContents`] if an element is not an indirect
/// reference at all, or resolves to something other than a stream or null
/// — a type error, which stays an error (see the caller's commentary).
fn contents_from_array<G: ObjectGraph + ?Sized>(
    doc: &G,
    items: &[Object],
    depth: usize,
) -> Result<(Vec<ObjId>, usize, usize), PageTreeError> {
    if depth > MAX_CONTENTS_NESTING {
        return Err(PageTreeError::BadContents);
    }
    let mut ids = Vec::with_capacity(items.len());
    let mut unresolved = 0usize;
    let mut flattened = 0usize;
    for item in items {
        match (item.as_reference(), doc.resolve(item)) {
            (Some(id), Object::Stream(_)) => ids.push(id),
            // A reference whose target is missing from the file: §7.3.10
            // says this IS the null object, not an error. Count and skip.
            (Some(_), Object::Null) => unresolved += 1,
            // A DIRECT null element (`[ 4 0 R null 6 0 R ]`): §7.3.9 makes
            // it equivalent to an omitted value. Nothing is missing from
            // the file, so it is skipped WITHOUT counting — the count is
            // reserved for content that should have been there and wasn't.
            (None, Object::Null) => {}
            // A NESTED ARRAY. Not legal, and specifically the damage a
            // pdfcer build older than `Pass 111.0` wrote into any page whose
            // `/Contents` was an indirect reference to an array (see
            // `Page::contents_flattened`). Flattened rather than refused,
            // because the repair is EXACT — the nesting carries no
            // information and the streams inside it are already in the order
            // Table 30 concatenates them — and because refusing costs the
            // operator a document pdfcer itself damaged.
            //
            // Depth-guarded (`MAX_CONTENTS_NESTING`) rather than trusted:
            // this is a recursive walk over attacker-controllable structure,
            // which `ARCHITECTURE.md` §10 requires a bound on. A cycle
            // (`38 0 obj [ 38 0 R ] endobj`) terminates by depth, not by
            // luck.
            (_, Object::Array(inner)) => {
                let (mut nested, unres, flat) = contents_from_array(doc, inner, depth + 1)?;
                ids.append(&mut nested);
                unresolved += unres;
                flattened += flat + 1;
            }
            // Anything else — a number, a dict, a reference to a non-stream
            // — is a type error.
            _ => return Err(PageTreeError::BadContents),
        }
    }
    Ok((ids, unresolved, flattened))
}

/// The first stream of pdfcer's overlay wrapper: a save (`q`) placed before a
/// page's original content. The comment ties the stream to pdfcer, so a
/// foreign stream that merely holds `q` is never taken for one.
#[doc(hidden)] // workspace-internal
pub const WRAP_SAVE: &[u8] = b"%pdfcer overlay wrap: save\nq\n";

/// The restore (`Q`) that closes [`WRAP_SAVE`] after the original content.
#[doc(hidden)] // workspace-internal
pub const WRAP_RESTORE: &[u8] = b"%pdfcer overlay wrap: restore\nQ\n";

/// Decoded content no larger than this is classified in full when a page is
/// not yet wrapped; a larger original is wrapped without being read.
const NEUTRAL_SCAN_LIMIT: usize = 64 * 1024;

/// A raw stream longer than this cannot be a wrapper stream, so it is never
/// decoded to ask.
const WRAPPER_RAW_LIMIT: usize = 256;

/// The object numbers of one [`WRAP_SAVE`] / [`WRAP_RESTORE`] stream pair. One
/// pair is shared by every page a single command wraps.
#[doc(hidden)] // workspace-internal
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WrapStreams {
    /// The [`WRAP_SAVE`] stream.
    pub save: ObjId,
    /// The [`WRAP_RESTORE`] stream.
    pub restore: ObjId,
}

/// How appending a self-contained overlay stream to one page's `/Contents`
/// will go: made by [`plan_overlay_append`], completed by
/// [`OverlayAppend::finish`].
///
/// A `/Contents` array is one content stream (ISO 32000-2 §7.8.2) and §8.4.2
/// requires only that `q`/`Q` balance across it, so a page may leave a `cm`,
/// clip, `gs`, colour or text-state operator in effect at its end, and a
/// stream appended after it would inherit that state. The plan therefore puts
/// the page's content between a [`WRAP_SAVE`]/[`WRAP_RESTORE`] pair unless it
/// can show nothing leaks: the page is already wrapped by pdfcer and only
/// state-neutral streams follow the restore, or the whole content is small
/// and state-neutral. Original streams are never rewritten; only the element
/// list changes. An original with unbalanced `q`/`Q` (non-conforming) is not
/// repaired. Design: `docs/decisions/039-overlay-wrap.md`.
///
/// Every append route in `pdfcer-core` goes through this type; there is no
/// public way to append without it.
#[doc(hidden)] // workspace-internal
#[derive(Debug, Clone, PartialEq)]
pub struct OverlayAppend {
    items: Vec<Object>,
    wrap: bool,
}

impl OverlayAppend {
    /// Whether [`Self::finish`] needs a [`WrapStreams`] pair.
    #[must_use]
    pub const fn needs_wrap(&self) -> bool {
        self.wrap
    }

    /// The new `/Contents` value with `new_id` appended: `[S, …, R, new]` when
    /// wrapping, else `[…, new]`. `None` when a wrap is needed and `wrap` is
    /// `None`.
    #[must_use]
    pub fn finish(&self, new_id: ObjId, wrap: Option<WrapStreams>) -> Option<Object> {
        let mut out = Vec::with_capacity(self.items.len() + 3);
        if self.wrap {
            let pair = wrap?;
            out.push(Object::Reference(pair.save));
            out.extend(self.items.iter().cloned());
            out.push(Object::Reference(pair.restore));
        } else {
            out.extend(self.items.iter().cloned());
        }
        out.push(Object::Reference(new_id));
        Some(Object::Array(out))
    }
}

/// Plan appending an overlay to a page whose `/Contents` is `before`.
///
/// `before` may be absent, a stream reference, an array, or a reference to an
/// array (resolved, depth-guarded per §7.3.10). The array's elements are
/// spliced into a new direct array, so a shared array object is never
/// extended onto another page. A value that is none of these is kept as the
/// first element rather than dropped.
#[doc(hidden)] // workspace-internal
#[must_use]
pub fn plan_overlay_append(view: &DocumentView<'_>, before: Option<&Object>) -> OverlayAppend {
    let items = contents_items(view, before);
    let wrap = !items.is_empty() && !leaves_no_state(view, &items);
    OverlayAppend { items, wrap }
}

/// Remove every stream of `before` for which `drop` returns `true` (given its
/// decoded bytes), then peel pdfcer wrapper pairs left with nothing after
/// them. Returns the new `/Contents` value, `None` when nothing is left.
/// Unchanged content returns `before` as-is, so a shared array reference stays
/// a reference. Removed stream objects are orphaned, not deleted: they may be
/// shared with another page.
#[doc(hidden)] // workspace-internal
#[must_use]
pub fn remove_overlays(
    view: &DocumentView<'_>,
    before: Option<&Object>,
    drop: impl Fn(&Object, &[u8]) -> bool,
) -> Option<Object> {
    let before = before?;
    let items = contents_items(view, Some(before));
    let mut kept: Vec<Object> = items
        .iter()
        .filter(|item| !decoded_item(view, item).is_some_and(|b| drop(item, &b)))
        .cloned()
        .collect();
    if kept.len() == items.len() {
        return Some(before.clone());
    }
    while kept.len() >= 2
        && is_exactly(view, kept.first(), WRAP_SAVE)
        && is_exactly(view, kept.last(), WRAP_RESTORE)
    {
        kept.pop();
        kept.remove(0);
    }
    (!kept.is_empty()).then_some(Object::Array(kept))
}

/// `true` when `content` leaves no graphics or text state behind: at `q`-depth
/// 0 it holds only `q`, marked-content operators, compatibility sections and
/// comments, its depth never goes negative and ends at 0, and it parses.
/// Conservative: anything uncertain is `false`, which costs a wrap, never a
/// leak.
#[doc(hidden)] // workspace-internal
#[must_use]
pub fn is_state_neutral(content: &[u8]) -> bool {
    let Ok(cs) = crate::content::ContentStream::parse(content.to_vec()) else {
        return false;
    };
    let buf = cs.buf.as_slice();
    let mut depth = 0_usize;
    for op in cs.operations() {
        match op.operator_name(buf) {
            Some(b"q") => depth += 1,
            Some(b"Q") => match depth.checked_sub(1) {
                Some(d) => depth = d,
                None => return false,
            },
            Some(b"BMC" | b"BDC" | b"EMC" | b"MP" | b"DP" | b"BX" | b"EX") => {}
            _ if depth > 0 => {}
            _ => return false,
        }
    }
    depth == 0
}

/// The elements of a `/Contents` value, as the append splices them.
fn contents_items(view: &DocumentView<'_>, before: Option<&Object>) -> Vec<Object> {
    let Some(before) = before else {
        return Vec::new();
    };
    match view.resolve(before) {
        Object::Array(items) => items.clone(),
        // A stream shall be indirect (§7.3.8), so `before` is kept verbatim.
        _ => vec![before.clone()],
    }
}

/// The decoded bytes of one `/Contents` element, or `None`.
fn decoded_item(view: &DocumentView<'_>, item: &Object) -> Option<Vec<u8>> {
    let Object::Stream(stream) = view.resolve(item) else {
        return None;
    };
    crate::filters::decode_stream(&stream.dict, view.slice(stream.data_span)?).ok()
}

/// Whether `item` is a stream decoding to exactly `bytes`.
fn is_exactly(view: &DocumentView<'_>, item: Option<&Object>, bytes: &[u8]) -> bool {
    let Some(item) = item else {
        return false;
    };
    let Object::Stream(stream) = view.resolve(item) else {
        return false;
    };
    stream.data_span.len <= WRAPPER_RAW_LIMIT && decoded_item(view, item).as_deref() == Some(bytes)
}

/// Whether appending after `items` needs no wrap (see [`OverlayAppend`]).
fn leaves_no_state(view: &DocumentView<'_>, items: &[Object]) -> bool {
    let neutral = |part: &[Object]| {
        let mut all = Vec::new();
        for item in part {
            let Some(bytes) = decoded_item(view, item) else {
                return false;
            };
            // Stream boundaries are token boundaries (§7.8.2).
            all.extend_from_slice(&bytes);
            all.push(b'\n');
        }
        is_state_neutral(&all)
    };
    if is_exactly(view, items.first(), WRAP_SAVE)
        && let Some(r) = items
            .iter()
            .rposition(|item| is_exactly(view, Some(item), WRAP_RESTORE))
        && r > 0
    {
        return neutral(items.get(r + 1..).unwrap_or_default());
    }
    let raw: usize = items
        .iter()
        .map(|item| match view.resolve(item) {
            Object::Stream(s) => s.data_span.len,
            _ => usize::MAX,
        })
        .fold(0, usize::saturating_add);
    raw <= NEUTRAL_SCAN_LIMIT && neutral(items)
}

/// Parse (and resolve) a rectangle attribute: an array of four
/// numbers, each possibly an indirect reference (§7.3.10
/// substitutability), normalized per §7.9.5.
#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
pub fn parse_rect<G: ObjectGraph + ?Sized>(
    doc: &G,
    obj: &Object,
    attr: &'static str,
) -> Result<Rect, PageTreeError> {
    let arr = doc
        .resolve(obj)
        .as_array()
        .ok_or(PageTreeError::BadRectangle(attr))?;
    let nums: Vec<f64> = arr
        .iter()
        .filter_map(|o| doc.resolve(o).as_number())
        .collect();
    match nums.as_slice() {
        &[x1, y1, x2, y2] => Ok(Rect::from_corners(x1, y1, x2, y2)),
        _ => Err(PageTreeError::BadRectangle(attr)),
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing
)]
mod tests {
    use super::*;

    /// Same builder as document::tests — duplicated deliberately so
    /// each module's tests stay self-contained and readable.
    fn build_pdf(objects: &[(u32, &str)]) -> Document {
        let mut buf = b"%PDF-1.4\n".to_vec();
        let mut offsets: Vec<(u32, usize)> = Vec::new();
        for (num, body) in objects {
            offsets.push((*num, buf.len()));
            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
        }
        let xref_at = buf.len();
        let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
        buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
        buf.extend_from_slice(b"0000000000 65535 f\r\n");
        for num in 1..=max_num {
            match offsets.iter().find(|(n, _)| *n == num) {
                Some((_, off)) => {
                    buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
                }
                None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
            }
        }
        buf.extend_from_slice(
            format!(
                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n",
                max_num + 1
            )
            .as_bytes(),
        );
        Document::from_bytes(buf).unwrap()
    }

    #[test]
    fn inheritance_spec_figure_6_style() {
        // Root sets MediaBox + Rotate 90; page 3 overrides Rotate to
        // 270; page 4 has its own MediaBox. Mirrors the §7.7.3.4
        // Figure 6 pattern.
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
                 /MediaBox [0 0 612 792] /Rotate 90 /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R >>"),
            (4, "<< /Type /Page /Parent 2 0 R /Rotate 270 >>"),
            (5, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >>"),
        ]);
        let pages = pages(&doc).unwrap();
        assert_eq!(pages.len(), 3);
        // Page 1: everything inherited.
        assert_eq!(pages[0].media_box.width(), 612.0);
        assert_eq!(pages[0].rotate, 90);
        // CropBox defaulted to the resolved MediaBox.
        assert_eq!(pages[0].crop_box, pages[0].media_box);
        // Page 2: Rotate overridden.
        assert_eq!(pages[1].rotate, 270);
        // Page 3: MediaBox overridden, Rotate still inherited.
        assert_eq!(pages[2].media_box.width(), 200.0);
        assert_eq!(pages[2].rotate, 90);
    }

    /// One page with MediaBox [0 0 100 100] and the given extra entries.
    fn one_page(extra: &str) -> Page {
        let page = format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] {extra} >>");
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
            ),
            (3, &page),
        ]);
        pages(&doc).unwrap().remove(0)
    }

    #[test]
    fn page_boxes_are_intersected_with_the_media_box() {
        let r = Rect::from_corners;
        // §14.11.2.1: a crop box overhanging the sheet frames the sheet.
        let p = one_page("/CropBox [-50 20 300 80]");
        assert_eq!(p.crop_box, r(0.0, 20.0, 100.0, 80.0));
        assert_eq!(p.crop_box_resolution, BoxResolution::Clipped);
        // A contained one is untouched, and says so.
        let p = one_page("/CropBox [10 10 90 90]");
        assert_eq!(p.crop_box, r(10.0, 10.0, 90.0, 90.0));
        assert_eq!(p.crop_box_resolution, BoxResolution::AsWritten);
        // PB-A1: no overlap falls back to the media box, disclosed.
        let p = one_page("/CropBox [200 200 300 300]");
        assert_eq!(p.crop_box, p.media_box);
        assert_eq!(p.crop_box_resolution, BoxResolution::Unusable);
        // Touching only along an edge has no area either.
        let p = one_page("/CropBox [100 0 200 100]");
        assert_eq!(p.crop_box_resolution, BoxResolution::Unusable);
        let p = one_page("");
        assert_eq!(p.crop_box_resolution, BoxResolution::Defaulted);
    }

    #[test]
    fn production_boxes_clip_to_the_media_box_and_default_to_the_crop_box() {
        let r = Rect::from_corners;
        let p = one_page(
            "/CropBox [10 10 90 90] /TrimBox [-5 -5 50 50] \
             /BleedBox [500 500 600 600] /ArtBox [1 2 3]",
        );
        // Clipped to the MEDIA box, not the crop box: the crop box "has no
        // defined relationship with any of the other boundaries".
        assert_eq!(p.trim_box, r(0.0, 0.0, 50.0, 50.0));
        assert_eq!(p.trim_box_resolution, BoxResolution::Clipped);
        // No overlap, and malformed, both fall back to the effective crop box.
        assert_eq!(p.bleed_box, p.crop_box);
        assert_eq!(p.bleed_box_resolution, BoxResolution::Unusable);
        assert_eq!(p.art_box, p.crop_box);
        assert_eq!(p.art_box_resolution, BoxResolution::Unusable);
        // Absent defaults to the effective (clipped) crop box.
        let p = one_page("/CropBox [50 50 500 500]");
        assert_eq!(p.trim_box, r(50.0, 50.0, 100.0, 100.0));
        assert_eq!(p.trim_box_resolution, BoxResolution::Defaulted);
    }

    #[test]
    fn production_boxes_are_not_inherited() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> \
                 /MediaBox [0 0 100 100] /TrimBox [10 10 20 20] >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R >>"),
        ]);
        let p = pages(&doc).unwrap().remove(0);
        assert_eq!(p.trim_box, p.media_box);
        assert_eq!(p.trim_box_resolution, BoxResolution::Defaulted);
    }

    #[test]
    fn deep_tree_and_intermediate_inheritance() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 100 100] /Resources << >> >>",
            ),
            (
                3,
                "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R] /Count 1 /Rotate 180 >>",
            ),
            (4, "<< /Type /Page /Parent 3 0 R >>"),
        ]);
        let pages = pages(&doc).unwrap();
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].rotate, 180);
        assert_eq!(pages[0].media_box.width(), 100.0);
    }

    #[test]
    fn empty_own_resources_beats_inherited() {
        // §7.7.3.3: an explicit empty /Resources means "no resources"
        // — it must NOT fall through to the ancestor's non-empty one.
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << /Font << >> >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Resources << >> >>"),
        ]);
        let pages = pages(&doc).unwrap();
        assert!(pages[0].resources.is_empty());
        // An explicit `<< >>` is the file's own statement, not pdfcer's.
        // The two must stay distinguishable or the disclosure would accuse
        // a well-formed file of being incomplete.
        assert!(!pages[0].resources_defaulted);
    }

    /// The Acrobat shape, and the regression this Pass exists for: a
    /// three-page file whose FIRST page is a blank spacer with no
    /// `/Contents` and no `/Resources`, and whose other two are complete.
    ///
    /// Before `Pass 290.0` `pages()` returned `Err(MissingRequired)` for the
    /// whole document, so one degenerate page cost the operator two perfect
    /// ones — in a real file (`%APPDATA%\Adobe\Acrobat\DC\Stamps\…`, his
    /// signature stamps) that every other reader opens.
    ///
    /// The assertions are deliberately three: that the walk SUCCEEDS,
    /// that the two good pages keep the resources the file gave them, and
    /// that the flag is `true` on exactly the page that lacked the
    /// attribute. Testing only the first would pass on a build that
    /// defaulted every page's resources to empty.
    #[test]
    fn a_resourceless_page_does_not_cost_its_siblings() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
                 /MediaBox [0 0 612 792] >>",
            ),
            // The spacer: no /Contents, so no resource can ever be named.
            (3, "<< /Type /Page /Parent 2 0 R >>"),
            (
                4,
                "<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 9 0 R >> >> >>",
            ),
            (
                5,
                "<< /Type /Page /Parent 2 0 R /Resources << /XObject << /Im0 9 0 R >> >> >>",
            ),
        ]);
        let pages = pages(&doc).unwrap();
        assert_eq!(pages.len(), 3);
        assert!(pages[0].resources_defaulted);
        assert!(pages[0].resources.is_empty());
        assert!(!pages[1].resources_defaulted);
        assert!(pages[1].resources.contains_key(b"Font"));
        assert!(!pages[2].resources_defaulted);
        assert!(pages[2].resources.contains_key(b"XObject"));
    }

    /// Defaulting must not shadow inheritance. A page with no `/Resources`
    /// of its own whose ANCESTOR has one still inherits it, and reports
    /// nothing — this is the ordinary well-formed shape, and a build that
    /// defaulted before consulting the ancestor would silently strip every
    /// font from every page of a file that inherits its resources (the
    /// §7.7.3.4 pattern, which is common).
    #[test]
    fn an_inherited_resource_dictionary_is_not_a_default() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] \
                 /Resources << /Font << /F1 9 0 R >> >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R >>"),
        ]);
        let pages = pages(&doc).unwrap();
        assert!(!pages[0].resources_defaulted);
        assert!(pages[0].resources.contains_key(b"Font"));
    }

    /// A `/Resources` whose reference names an object the file does not
    /// contain degrades exactly like an absent one: §7.3.10 makes such a
    /// reference the null object and §7.3.9 makes a null value equivalent
    /// to omitting the entry, so there is no third reading to invent.
    #[test]
    fn a_dangling_resources_reference_degrades_like_an_absent_one() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Resources 99 0 R >>"),
        ]);
        let pages = pages(&doc).unwrap();
        assert!(pages[0].resources_defaulted);
        assert!(pages[0].resources.is_empty());
    }

    /// …but a `/Resources` that is present and is NOT a dictionary still
    /// fails the page. There is no spec-sanctioned reading of `/Resources 42`,
    /// and laundering it into an empty dictionary would hide a real
    /// structural defect behind a page that merely renders emptier — the
    /// same split `/Contents` makes between a dangling reference and a value
    /// of the wrong type.
    #[test]
    fn a_resources_entry_of_the_wrong_type_still_fails_the_page() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Resources 42 >>"),
        ]);
        assert_eq!(pages(&doc).unwrap_err(), PageTreeError::BadResources);
    }

    /// `MediaBox` did NOT move with `Resources`, and the difference is the
    /// whole boundary decision 145 draws: an empty resource dictionary says
    /// what the file says, while any media box pdfcer picked would be a size
    /// nobody wrote. A future session tempted to "finish the job" by
    /// defaulting this one to Letter should read this test as the answer.
    #[test]
    fn a_missing_media_box_is_still_fatal_to_the_page() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
            (3, "<< /Type /Page /Parent 2 0 R >>"),
        ]);
        assert_eq!(
            pages(&doc).unwrap_err(),
            PageTreeError::MissingRequired("MediaBox")
        );
    }

    #[test]
    fn rectangle_corners_normalize_in_any_order() {
        // §7.9.5: corners may come in either order.
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /MediaBox [612 792 0 0] >>"),
        ]);
        let pages = pages(&doc).unwrap();
        assert_eq!(pages[0].media_box.llx, 0.0);
        assert_eq!(pages[0].media_box.urx, 612.0);
        assert_eq!(pages[0].media_box.height(), 792.0);
    }

    #[test]
    fn negative_rotate_normalizes_positive() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Rotate -90 >>"),
        ]);
        assert_eq!(pages(&doc).unwrap()[0].rotate, 270);
    }

    #[test]
    fn non_multiple_of_90_rotate_is_error() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Rotate 45 >>"),
        ]);
        assert_eq!(pages(&doc).unwrap_err(), PageTreeError::BadRotate(45));
    }

    #[test]
    fn missing_mediabox_everywhere_is_error() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R >>"),
        ]);
        assert_eq!(
            pages(&doc).unwrap_err(),
            PageTreeError::MissingRequired("MediaBox")
        );
    }

    #[test]
    fn kids_cycle_is_detected() {
        // Node 2's Kids points back at node 2.
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [2 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
        ]);
        assert_eq!(
            pages(&doc).unwrap_err(),
            PageTreeError::Cycle(ObjId::new(2, 0))
        );
    }

    #[test]
    fn count_is_not_trusted() {
        // Declared /Count 99 with one real page: the walk wins.
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 99 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R >>"),
        ]);
        assert_eq!(pages(&doc).unwrap().len(), 1);
    }

    #[test]
    fn contents_single_and_array_and_absent() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>"),
            (4, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 7 0 R] >>"),
            (5, "<< /Type /Page /Parent 2 0 R >>"),
            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
            (7, "<< /Length 2 >>\nstream\nQ \nendstream"),
        ]);
        let pages = pages(&doc).unwrap();
        assert_eq!(pages[0].contents, vec![ObjId::new(6, 0)]);
        assert_eq!(pages[1].contents, vec![ObjId::new(6, 0), ObjId::new(7, 0)]);
        assert!(pages[2].contents.is_empty(), "absent Contents = empty page");
        // Nothing degraded here: every named stream was present.
        assert!(pages.iter().all(|p| p.contents_unresolved == 0));
    }

    /// A **dangling element** in a `/Contents` array degrades: the element
    /// contributes nothing, the surviving streams still load in order, and
    /// the omission is disclosed via `contents_unresolved`.
    ///
    /// §7.3.10: "An indirect reference to an undefined object ... shall be
    /// treated as a reference to the null object." Object 7 is never
    /// defined, so `[6 0 R 7 0 R 8 0 R]` is `[stream, null, stream]` and
    /// the page's content is the concatenation of the two real streams.
    /// Before this fix the whole DOCUMENT was unopenable for this shape.
    #[test]
    fn contents_array_with_dangling_element_degrades_and_is_disclosed() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            // Object 7 is deliberately never defined.
            (
                3,
                "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 7 0 R 8 0 R] >>",
            ),
            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
            (8, "<< /Length 2 >>\nstream\nQ \nendstream"),
        ]);
        let pages = pages(&doc).expect("a dangling element must not fail the document");
        assert_eq!(pages.len(), 1);
        assert_eq!(
            pages[0].contents,
            vec![ObjId::new(6, 0), ObjId::new(8, 0)],
            "the streams that DO exist still load, in order"
        );
        assert_eq!(
            pages[0].contents_unresolved, 1,
            "the omission is counted, not swallowed"
        );
    }

    /// An **entirely unresolvable** `/Contents` (a single reference to an
    /// object the file does not contain) yields an empty page, disclosed —
    /// not a failed load.
    ///
    /// This is the dominant real-world shape: of 341 corpus files that
    /// failed with `BadContents`, ~300 were this single-reference form.
    /// §7.3.10 makes the value the null object; Table 30 then says
    /// "`Contents` ... if this entry is absent, the page shall be empty".
    #[test]
    fn contents_entirely_unresolvable_is_an_empty_page_disclosed() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            // Object 9 is never defined anywhere in the file.
            (3, "<< /Type /Page /Parent 2 0 R /Contents 9 0 R >>"),
        ]);
        let pages = pages(&doc).expect("an unresolvable /Contents must not fail the document");
        assert_eq!(pages.len(), 1);
        assert!(pages[0].contents.is_empty(), "empty page, per Table 30");
        assert_eq!(
            pages[0].contents_unresolved, 1,
            "an empty page from a MISSING stream is disclosed, unlike a genuinely blank one"
        );
    }

    /// A **wrong-typed** `/Contents` is still a hard error. This is the
    /// blast-radius guard: degrading a dangling reference must not also
    /// launder a value that has no spec-sanctioned reading into a silent
    /// blank page.
    #[test]
    fn contents_of_the_wrong_type_is_still_an_error() {
        // A direct integer — no reading under any clause.
        let numeric = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Contents 42 >>"),
        ]);
        assert_eq!(pages(&numeric).unwrap_err(), PageTreeError::BadContents);

        // A reference to a plain DICTIONARY (an object that exists, but is
        // not a stream): present, wrong type — distinct from absent.
        let dict_target = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>"),
            (6, "<< /NotAStream true >>"),
        ]);
        assert_eq!(pages(&dict_target).unwrap_err(), PageTreeError::BadContents);

        // A wrong-typed ELEMENT inside an otherwise fine array: one bad
        // element still condemns the page (it is not an omission).
        let bad_element = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 42] >>"),
            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
        ]);
        assert_eq!(pages(&bad_element).unwrap_err(), PageTreeError::BadContents);
    }

    /// An EXPLICIT `null` is equivalent to omitting the entry (§7.3.9), so
    /// it is a well-formed empty page and is NOT counted as a degradation
    /// — nothing is missing from the file. Distinguishing this from a
    /// dangling reference is what keeps `contents_unresolved` meaningful.
    #[test]
    fn explicit_null_contents_is_absent_not_a_degradation() {
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 \
                 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Type /Page /Parent 2 0 R /Contents null >>"),
            (4, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R null] >>"),
            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
        ]);
        let pages = pages(&doc).unwrap();
        assert!(pages[0].contents.is_empty());
        assert_eq!(
            pages[0].contents_unresolved, 0,
            "an explicit null is an omitted entry, not missing content"
        );
        assert_eq!(pages[1].contents, vec![ObjId::new(6, 0)]);
        assert_eq!(pages[1].contents_unresolved, 0);
    }

    #[test]
    fn missing_type_falls_back_to_structural_detection() {
        // Node 2 lacks /Type but has /Kids ⇒ treated as Pages node;
        // node 3 lacks /Type and has no /Kids ⇒ treated as Page.
        let doc = build_pdf(&[
            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
            (
                2,
                "<< /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] /Resources << >> >>",
            ),
            (3, "<< /Parent 2 0 R >>"),
        ]);
        assert_eq!(pages(&doc).unwrap().len(), 1);
    }
}