rbook 0.7.1

A fast, format-agnostic, ergonomic ebook library for reading, building, and editing EPUB 2 and 3.
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
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
//! EPUB-specific metadata content.
//!
//! # See Also
//! - [`ebook::metadata`](crate::ebook::metadata) for the general metadata module.

#[cfg(feature = "write")]
mod write;

use crate::ebook::element::{
    Attribute, Attributes, AttributesData, Href, Name, Properties, TextDirection,
};
use crate::ebook::epub::consts::{dc, opf};
use crate::ebook::epub::metadata::macros::{impl_meta_entry, impl_meta_entry_abstraction};
use crate::ebook::epub::package::{EpubPackageData, EpubPackageMetaContext};
use crate::ebook::metadata::datetime::DateTime;
use crate::ebook::metadata::{
    AlternateScript, Contributor, Identifier, Language, LanguageKind, LanguageTag, MetaEntry,
    Metadata, Scheme, Tag, Title, TitleKind, Version,
};
use crate::ebook::resource::ResourceKind;
use crate::util::{self, Sealed};
use indexmap::IndexMap;
use std::fmt::Display;
use std::iter::{Enumerate, FlatMap};
use std::slice::Iter as SliceIter;

#[cfg(feature = "write")]
pub use write::{
    DetachedEpubMetaEntry, EpubMetaEntryMut, EpubMetadataIterMut, EpubMetadataMut,
    EpubRefinementsIterMut, EpubRefinementsMut, marker,
};

////////////////////////////////////////////////////////////////////////////////
// PRIVATE API
////////////////////////////////////////////////////////////////////////////////

pub(super) type EpubMetaGroups = IndexMap<String, Vec<EpubMetaEntryData>>;

#[derive(Debug, PartialEq)]
pub(super) struct EpubMetadataData {
    pub(super) entries: EpubMetaGroups,
}

impl EpubMetadataData {
    pub(super) fn new(entries: EpubMetaGroups) -> Self {
        Self { entries }
    }

    pub(super) fn empty() -> Self {
        Self::new(IndexMap::new())
    }

    pub(super) fn epub2_cover_image_id(&self) -> Option<&str> {
        self.entries
            .get(opf::COVER)
            .and_then(|group| group.first())
            .map(|cover| cover.value.as_str())
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct EpubRefinementsData(Vec<EpubMetaEntryData>);

impl EpubRefinementsData {
    pub(crate) fn new(refinements: Vec<EpubMetaEntryData>) -> Self {
        Self(refinements)
    }

    fn get_schemes(&self, key: &str) -> impl Iterator<Item = Scheme<'_>> {
        self.by_refinements(key).map(|(_, key_item)| {
            // Note: There is usually a `scheme` associated with the `value`,
            // although it's not always guaranteed
            let scheme = key_item.attributes.get_value(opf::SCHEME);
            Scheme::new(scheme, &key_item.value)
        })
    }

    fn by_refinements(&self, property: &str) -> impl Iterator<Item = (usize, &EpubMetaEntryData)> {
        self.0
            .iter()
            .enumerate()
            .filter(move |(_, refinement)| refinement.property == property)
    }

    pub(crate) fn has_refinement(&self, property: &str) -> bool {
        self.0
            .iter()
            .any(|refinement| refinement.property == property)
    }

    pub(crate) fn by_refinement(&self, property: &str) -> Option<&EpubMetaEntryData> {
        self.0
            .iter()
            .find(|refinement| refinement.property == property)
    }
}

impl std::ops::Deref for EpubRefinementsData {
    type Target = Vec<EpubMetaEntryData>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for EpubRefinementsData {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(super) struct EpubMetaEntryData {
    pub(super) id: Option<String>,
    pub(super) property: String,
    pub(super) value: String,
    pub(super) language: Option<String>,
    pub(super) text_direction: TextDirection,
    pub(super) attributes: AttributesData,
    pub(super) refinements: EpubRefinementsData,
    pub(super) kind: EpubMetaEntryKind,
}

impl Default for EpubMetaEntryData {
    fn default() -> Self {
        Self {
            id: None,
            property: String::new(),
            value: String::new(),
            language: None,
            text_direction: TextDirection::Auto,
            attributes: AttributesData::default(),
            refinements: EpubRefinementsData::default(),
            // A placeholder until the proper kind is provided during parsing
            kind: EpubMetaEntryKind::Meta {
                version: EpubVersion::EPUB3,
            },
        }
    }
}

impl EpubMetaEntryData {
    fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }
}

////////////////////////////////////////////////////////////////////////////////
// PUBLIC API
////////////////////////////////////////////////////////////////////////////////

/// EPUB metadata accessible via [`Epub::metadata`](super::Epub::metadata).
/// See [`Metadata`] for more details.
///
/// # Behavior
/// `rbook` supports arbitrary refinements for any metadata element,
/// including `item` and `itemref` elements.
/// Refinement chains of arbitrary length are supported as well.
///
/// Elements and ID references within the `<package>` element are **not** required
/// to be in chronological order, so refinements are allowed to come before parent elements.
///
/// # Legacy Metadata Attributes
/// [Legacy `opf:*` attributes](https://www.w3.org/submissions/2017/SUBM-epub-packages-20170125/#sec-shared-attrs)
/// on metadata elements are supported.
///
/// Legacy attributes are mapped to the following when the newer
/// [refinement](https://www.w3.org/TR/epub/#app-meta-property-vocab)
/// equivalent is ***not*** present:
/// - [`opf:scheme`](Identifier::scheme)
/// - [`opf:role`](Contributor::main_role)
/// - [`opf:file-as`](MetaEntry::file_as)
/// - [`opf:authority + opf:term`](Tag::scheme)
/// - [`opf:alt-rep + opf:alt-rep-lang`](MetaEntry::alternate_scripts)
///
/// # See Also
/// - [`EpubMetadataMut`] for a mutable view.
#[derive(Copy, Clone, Debug)]
pub struct EpubMetadata<'ebook> {
    ctx: EpubPackageMetaContext<'ebook>,
    package: &'ebook EpubPackageData,
    data: &'ebook EpubMetadataData,
}

impl<'ebook> EpubMetadata<'ebook> {
    pub(super) fn new(package: &'ebook EpubPackageData, data: &'ebook EpubMetadataData) -> Self {
        Self {
            ctx: EpubPackageMetaContext::new(package),
            package,
            data,
        }
    }

    fn data_by_property(
        &self,
        property: &str,
    ) -> impl Iterator<Item = (usize, &'ebook EpubMetaEntryData)> + 'ebook {
        self.data
            .entries
            .get(property)
            .map_or::<&[_], _>(&[], Vec::as_slice)
            .iter()
            .enumerate()
    }

    /// Returns an iterator over non-refining [entries](EpubMetaEntry) whose
    /// [`property`](EpubMetaEntry::property) matches the given one.
    ///
    /// This method is especially useful for retrieving metadata
    /// not explicitly provided from [`EpubMetadata`]:
    /// - `belongs-to-collection`
    /// - `dc:coverage`
    /// - `dc:format`
    /// - `dc:relation`
    /// - `dc:rights`
    /// - `dc:source`
    /// - `dc:type`
    ///
    /// For more information regarding EPUB metadata see:
    /// <https://www.w3.org/TR/epub/#sec-pkg-metadata>
    ///
    /// # Excluded Entries
    /// Refining entries, `<meta>` elements with a `refines` field, are excluded:
    /// ```xml
    /// <meta refines="#parent-id">…</meta>
    /// ```
    ///
    /// # See Also
    /// - [`Self::iter`] to iterate over non-refining metadata entries.
    pub fn by_property(
        &self,
        property: &str,
    ) -> impl Iterator<Item = EpubMetaEntry<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(property)
            .map(move |(i, data)| ctx.create_entry(data, i))
    }

    /// Searches the metadata hierarchy, including refinements, and returns the
    /// [`EpubMetaEntry`] matching the given `id`, or [`None`] if not found.
    ///
    /// # Performance Implications
    /// This is a recursive linear operation as the underlying structure
    /// is ***not*** a hashmap with `id` as the key.
    /// Generally, the number of metadata entries is small (<20).
    /// However, for larger sets, frequent lookups can impede performance.
    ///
    /// # Note
    /// Refinements on
    /// [`EpubManifestEntry`](super::manifest::EpubManifestEntry::refinements) and
    /// [`EpubSpineEntry`](super::spine::EpubSpineEntry::refinements)
    /// are not searched.
    ///
    /// # Examples
    /// - Retrieving a creator by ID:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::ebook::toc::TocEntryKind;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let metadata = epub.metadata();
    ///
    /// // Retrieve the author
    /// let author = metadata.creators().next().unwrap();
    /// // Retrieve the same entry by ID
    /// let author_by_id = metadata.by_id("author").unwrap();
    ///
    /// assert_eq!(author, author_by_id);
    /// assert_eq!(Some("author"), author_by_id.id());
    ///
    /// // Attempt to retrieve a non-existent author
    /// assert_eq!(None, metadata.by_id("other-author"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn by_id(&self, id: &str) -> Option<EpubMetaEntry<'ebook>> {
        // Returns the matched entry along with its local `index` and `refines` field:
        // `(index, refines, entry)`
        fn dfs_by_id<'a>(
            id: &str,
            entry: &'a EpubMetaEntryData,
            // The index of `entry` within its parent collection.
            // - The index is passed in by the caller because entries do not store
            //   their position within the parent collection.
            //   The index is a required field for `EpubMetaEntry` views.
            index: usize,
        ) -> Option<(usize, Option<&'a str>, &'a EpubMetaEntryData)> {
            if entry.id.as_deref() == Some(id) {
                return Some((index, None, entry));
            }

            for (i, refinement) in entry.refinements.iter().enumerate() {
                if let Some(mut found) = dfs_by_id(id, refinement, i) {
                    // Set the refines field if the found entry is a direct refinement
                    if refinement == found.2 {
                        found.1 = entry.id.as_deref();
                    }
                    return Some(found);
                }
            }
            None
        }

        self.data
            .entries
            .values()
            .flat_map(|group| group.iter().enumerate())
            .find_map(|(i, entry)| dfs_by_id(id, entry, i))
            .map(|(i, refines, data)| self.ctx.create_refining_entry(refines, data, i))
    }

    /// The [`Epub`](super::Epub) version (e.g., `2.0`, `3.2`, etc.).
    ///
    /// The returned version may be [`EpubVersion::Unknown`] if
    /// [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is disabled.
    ///
    /// See [`EpubMetadata::version_str`] for the original representation.
    ///
    /// # Note
    /// This method is equivalent to calling
    /// [`EpubPackage::version`](super::EpubPackage::version).
    pub fn version(&self) -> EpubVersion {
        self.package.version.parsed
    }

    /// The underlying [`Epub`](super::Epub) version string.
    ///
    /// # Note
    /// This method is equivalent to calling
    /// [`EpubPackage::version_str`](super::EpubPackage::version_str).
    pub fn version_str(&self) -> &'ebook str {
        self.package.version.raw.as_str()
    }

    /// Returns an iterator over non-refining link entries.
    /// Only entries which have a [`kind`](EpubMetaEntry::kind) of [`EpubMetaEntryKind::Link`]
    /// are included in the iterator.
    ///
    /// # Excluded Entries
    /// Refining entries, `<link>` elements with a `refines` field are excluded, for example:
    /// ```xml
    /// <link refines="#parent-id" … />
    /// ```
    ///
    /// # See Also
    /// - [`Self::iter`] to iterate over **non-refining** metadata entries, including links.
    pub fn links(&self) -> impl Iterator<Item = EpubLink<'ebook>> + 'ebook {
        self.iter().filter_map(|entry| entry.as_link())
    }

    /// The publication date; when an [`Epub`](super::Epub) was published.
    #[doc = util::inherent_doc!(Metadata, published)]
    /// # See Also
    /// - [`Self::published_entry`] to retrieve the source [`EpubMetaEntry`] instead.
    pub fn published(&self) -> Option<DateTime> {
        self.published_entry()
            .and_then(|entry| DateTime::parse(entry.value()))
    }

    /// The last modified date; when an [`Epub`](super::Epub) was last modified.
    #[doc = util::inherent_doc!(Metadata, modified)]
    /// # See Also
    /// - [`Self::modified_entry`] to retrieve the source [`EpubMetaEntry`] instead.
    pub fn modified(&self) -> Option<DateTime> {
        self.modified_entry()
            .and_then(|entry| DateTime::parse(entry.value()))
    }

    /// The publication date entry; when an [`Epub`](super::Epub) was published.
    ///
    /// # Date Value
    /// The contained date [value](EpubMetaEntry::value) is non-parsed,
    /// typically in [**ISO 8601-1**](https://www.iso.org/iso-8601-date-and-time-format.html) format.
    ///
    /// The value may be in different formats across various EPUBs:
    /// - `2025-12-01` (ISO 8601-1)
    /// - `2025-12-01T00:40:51Z` (ISO 8601-1)
    /// - `2025-12-01 00:00:00+03:27` (RFC 3339)
    ///
    /// Rare and generally not recommended, although possible:
    /// - `December 2025`
    /// - `1.12.2025`
    ///
    /// # See Also
    /// - [`Self::published`] to retrieve the parsed date.
    pub fn published_entry(&self) -> Option<EpubMetaEntry<'ebook>> {
        let mut inferred_date = None;

        for (i, date) in self.data_by_property(dc::DATE) {
            match date.attributes.by_name(opf::OPF_EVENT) {
                Some(opf_event) if opf_event.value() == opf::PUBLICATION => {
                    return Some(self.ctx.create_entry(date, i));
                }
                // If the attribute is not present, infer as the publication date for now
                None if inferred_date.is_none() => inferred_date = Some((i, date)),
                _ => {}
            }
        }

        // Fallback to `dc:date` without `opf:event=publication`
        inferred_date.map(|(i, date)| self.ctx.create_entry(date, i))
    }

    /// The last modified date entry; when an [`Epub`](super::Epub) was last modified.
    ///
    /// # See Also
    /// - [`Self::published_entry`] to retrieve the publication date entry.
    /// - [`Self::modified`] to retrieve the parsed date.
    pub fn modified_entry(&self) -> Option<EpubMetaEntry<'ebook>> {
        // Attempt to retrieve `dcterms:modified` first
        if let Some((i, modified_date)) = self.data_by_property(dc::MODIFIED).next() {
            return Some(self.ctx.create_entry(modified_date, i));
        }

        // Fallback to `dc:date` with `opf:event=modification`
        self.data_by_property(dc::DATE)
            .find(|(_, date)| {
                date.attributes
                    .get_value(opf::OPF_EVENT)
                    .is_some_and(|opf_event| opf_event == opf::MODIFICATION)
            })
            .map(|(i, date)| self.ctx.create_entry(date, i))
    }

    /// The primary unique [identifier](EpubIdentifier) of an [`Epub`](super::Epub).
    ///
    /// Returns [`None`] if there is no primary unique identifier when
    /// [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is disabled.
    ///
    /// As EPUBs may include multiple identifiers (`<dc:identifier>` elements),
    /// this method is for retrieval of the primary identifier as declared in
    /// the `<package>` element by the `unique-identifier` attribute.
    #[doc = util::inherent_doc!(Metadata, identifier)]
    pub fn identifier(&self) -> Option<EpubIdentifier<'ebook>> {
        self.data_by_property(dc::IDENTIFIER)
            .find(|(_, data)| data.id.as_ref() == Some(&self.package.unique_identifier))
            .map(|(i, data)| EpubIdentifier::new(self.ctx.create_entry(data, i)))
    }

    /// Returns an iterator over **all** [identifiers](EpubIdentifier)
    /// by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, identifiers)]
    pub fn identifiers(&self) -> impl Iterator<Item = EpubIdentifier<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::IDENTIFIER)
            .map(move |(i, data)| EpubIdentifier::new(ctx.create_entry(data, i)))
    }

    /// The main [language](EpubLanguage) of an [`Epub`](super::Epub).
    ///
    /// Returns [`None`] if there is no language specified when
    /// [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is disabled.
    #[doc = util::inherent_doc!(Metadata, language)]
    pub fn language(&self) -> Option<EpubLanguage<'ebook>> {
        self.languages().next()
    }

    /// Returns an iterator over **all** [languages](EpubLanguage)
    /// by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, languages)]
    pub fn languages(&self) -> impl Iterator<Item = EpubLanguage<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::LANGUAGE)
            .map(move |(i, data)| EpubLanguage::new(ctx.create_entry(data, i)))
    }

    /// The main [title](EpubTitle) of an [`Epub`](super::Epub).
    ///
    /// Returns [`None`] if there is no title specified when
    /// [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is disabled.
    #[doc = util::inherent_doc!(Metadata, title)]
    pub fn title(&self) -> Option<EpubTitle<'ebook>> {
        self.titles().find(|title| title.is_main_title)
    }

    /// Returns an iterator over **all** [titles](EpubTitle)
    /// by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, titles)]
    pub fn titles(&self) -> impl Iterator<Item = EpubTitle<'ebook>> + 'ebook {
        let ctx = self.ctx;
        // Although caching the inferred main title is possible,
        // this is generally inexpensive (nearly all publications only have one title).
        // Caching also complicates write-back of EPUB metadata.
        let inferred_main_title_index = self
            .data_by_property(dc::TITLE)
            // First, try to find if a main `title-type` exists
            .position(|(_, title)| {
                title
                    .refinements
                    .by_refinement(opf::TITLE_TYPE)
                    .is_some_and(|title_type| title_type.value == opf::MAIN_TITLE_TYPE)
            })
            // If not, retrieve the first title
            .unwrap_or(0);

        self.data_by_property(dc::TITLE).map(move |(i, data)| {
            EpubTitle::new(ctx.create_entry(data, i), i == inferred_main_title_index)
        })
    }

    /// The main description with an [`order`](EpubMetaEntry::order) of `0`.
    #[doc = util::inherent_doc!(Metadata, description)]
    pub fn description(&self) -> Option<EpubMetaEntry<'ebook>> {
        self.descriptions().next()
    }

    /// Returns an iterator over **all** descriptions by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, descriptions)]
    pub fn descriptions(&self) -> impl Iterator<Item = EpubMetaEntry<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::DESCRIPTION)
            .map(move |(i, data)| ctx.create_entry(data, i))
    }

    /// Returns an iterator over **all** [creators](EpubContributor)
    /// by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, creators)]
    pub fn creators(&self) -> impl Iterator<Item = EpubContributor<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::CREATOR)
            .map(move |(i, data)| EpubContributor::new(ctx.create_entry(data, i)))
    }

    /// Returns an iterator over **all** [contributors](EpubContributor)
    /// by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, contributors)]
    pub fn contributors(&self) -> impl Iterator<Item = EpubContributor<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::CONTRIBUTOR)
            .map(move |(i, data)| EpubContributor::new(ctx.create_entry(data, i)))
    }

    /// Returns an iterator over **all** [publishers](EpubContributor)
    /// by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, publishers)]
    pub fn publishers(&self) -> impl Iterator<Item = EpubContributor<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::PUBLISHER)
            .map(move |(i, data)| EpubContributor::new(ctx.create_entry(data, i)))
    }

    /// Returns an iterator over **all** generators by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, generators)]
    pub fn generators(&self) -> impl Iterator<Item = EpubMetaEntry<'ebook>> + 'ebook {
        self.by_property(opf::GENERATOR)
    }

    /// Returns an iterator over **all** [tags](EpubTag) by [`order`](EpubMetaEntry::order).
    #[doc = util::inherent_doc!(Metadata, tags)]
    pub fn tags(&self) -> impl Iterator<Item = EpubTag<'ebook>> + 'ebook {
        let ctx = self.ctx;

        self.data_by_property(dc::SUBJECT)
            .map(move |(i, data)| EpubTag::new(ctx.create_entry(data, i)))
    }

    /// Returns an iterator over non-refining metadata entries.
    #[doc = util::inherent_doc!(Metadata, iter)]
    /// # See Also
    /// - [`EpubMetadataIter`] for important details.
    pub fn iter(&self) -> EpubMetadataIter<'ebook> {
        EpubMetadataIter {
            ctx: self.ctx,
            iter: self
                .data
                .entries
                .values()
                .flat_map(|group| group.iter().enumerate()),
        }
    }
}

impl Sealed for EpubMetadata<'_> {}

#[allow(refining_impl_trait)]
impl<'ebook> Metadata<'ebook> for EpubMetadata<'ebook> {
    fn version_str(&self) -> Option<&'ebook str> {
        Some(self.version_str())
    }

    fn version(&self) -> Option<Version> {
        Some(self.version().version())
    }

    fn published(&self) -> Option<DateTime> {
        self.published()
    }

    fn modified(&self) -> Option<DateTime> {
        self.modified()
    }

    fn identifier(&self) -> Option<EpubIdentifier<'ebook>> {
        self.identifier()
    }

    fn identifiers(&self) -> impl Iterator<Item = EpubIdentifier<'ebook>> + 'ebook {
        self.identifiers()
    }

    fn language(&self) -> Option<EpubLanguage<'ebook>> {
        self.language()
    }

    fn languages(&self) -> impl Iterator<Item = EpubLanguage<'ebook>> + 'ebook {
        self.languages()
    }

    fn title(&self) -> Option<EpubTitle<'ebook>> {
        self.title()
    }

    fn titles(&self) -> impl Iterator<Item = EpubTitle<'ebook>> + 'ebook {
        self.titles()
    }

    fn description(&self) -> Option<EpubMetaEntry<'ebook>> {
        self.description()
    }

    fn descriptions(&self) -> impl Iterator<Item = EpubMetaEntry<'ebook>> + 'ebook {
        self.descriptions()
    }

    fn creators(&self) -> impl Iterator<Item = EpubContributor<'ebook>> + 'ebook {
        self.creators()
    }

    fn contributors(&self) -> impl Iterator<Item = EpubContributor<'ebook>> + 'ebook {
        self.contributors()
    }

    fn publishers(&self) -> impl Iterator<Item = EpubContributor<'ebook>> + 'ebook {
        self.publishers()
    }

    fn generators(&self) -> impl Iterator<Item = impl MetaEntry<'ebook> + 'ebook> + 'ebook {
        self.generators()
    }

    fn tags(&self) -> impl Iterator<Item = EpubTag<'ebook>> + 'ebook {
        self.tags()
    }

    fn iter(&self) -> EpubMetadataIter<'ebook> {
        self.iter()
    }
}

impl PartialEq for EpubMetadata<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<'ebook> IntoIterator for &EpubMetadata<'ebook> {
    type Item = EpubMetaEntry<'ebook>;
    type IntoIter = EpubMetadataIter<'ebook>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'ebook> IntoIterator for EpubMetadata<'ebook> {
    type Item = EpubMetaEntry<'ebook>;
    type IntoIter = EpubMetadataIter<'ebook>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

pub(super) type InnerMetadataIter<ValuesIter, SliceIter, MapArgs> =
    FlatMap<ValuesIter, Enumerate<SliceIter>, fn(MapArgs) -> Enumerate<SliceIter>>;

/// An iterator over non-refining metadata [entries](EpubMetaEntry)
/// contained within [`EpubMetadata`].
///
/// Each entry is first grouped by its [`property`](EpubMetadata::by_property),
/// then [`order`](MetaEntry::order) before being flattened into a single iterator.
/// As grouping by property relies on a hash map, the order in which property groups appear
/// is arbitrary; non-deterministic.
///
/// # Included Entries
/// All the following types retrievable via [`EpubMetaEntry::kind`] are included
/// in the iterator:
/// - [`EpubMetaEntryKind::DublinCore`]
/// - [`EpubMetaEntryKind::Meta`]
/// - [`EpubMetaEntryKind::Link`]
///
/// # Excluded Entries
/// Refining entries elements with a `refines` field are excluded, for example:
/// ```xml
/// <meta refines="#parent-id" …>…</meta>
/// <link refines="#parent-id" … />
/// ```
///
/// # See Also
/// - [`EpubMetadata::by_property`] to iterate over **non-refining** metadata entries by property.
/// - [`EpubMetadata::links`] to iterate over **non-refining** link entries.
/// - [`EpubMetadata::iter`] to create an instance of this struct.
///
/// # Examples
/// - Iterating over metadata entries:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
///
/// // Iterate over all non-refining metadata elements
/// for entry in epub.metadata() {
///     // Access refinements
///     for refinement in entry.refinements() {
///         // A refinement references its parent by id
///         assert_eq!(entry.id(), refinement.refines());
///
///         // Although rare, a refinement can also have refinements
///         let nested_refinements = refinement.refinements();
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub struct EpubMetadataIter<'ebook> {
    ctx: EpubPackageMetaContext<'ebook>,
    iter: InnerMetadataIter<
        indexmap::map::Values<'ebook, String, Vec<EpubMetaEntryData>>,
        SliceIter<'ebook, EpubMetaEntryData>,
        &'ebook Vec<EpubMetaEntryData>,
    >,
}

impl<'ebook> Iterator for EpubMetadataIter<'ebook> {
    type Item = EpubMetaEntry<'ebook>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|(i, data)| self.ctx.create_entry(data, i))
    }
}

/// A collection of [`EpubMetaEntry`] refinements providing further clarifying detail.
///
/// Refinements, such as `alternate-script`, `title-type`, and `media:duration`,
/// provide additional details for their parent
/// (metadata entries, manifest entries, or spine entries).
///
/// For more information regarding refinements, see:
/// <https://www.w3.org/TR/epub/#attrdef-refines>
///
/// # See Also
/// - [`EpubRefinementsMut`] for a mutable view.
#[derive(Copy, Clone, Debug)]
pub struct EpubRefinements<'ebook> {
    ctx: EpubPackageMetaContext<'ebook>,
    /// When modifying refinements, the `parent_id` may be [`None`].
    ///
    /// See [`EpubMetaEntryMut::refinements_mut`].
    parent_id: Option<&'ebook str>,
    data: &'ebook EpubRefinementsData,
}

impl<'ebook> EpubRefinements<'ebook> {
    pub(super) fn new(
        ctx: EpubPackageMetaContext<'ebook>,
        parent_id: Option<&'ebook str>,
        data: &'ebook EpubRefinementsData,
    ) -> Self {
        Self {
            ctx,
            parent_id,
            data,
        }
    }

    /// The number of refinement entries contained within.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if there are no refinements.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Returns the associated refinement ([`EpubMetaEntry`])
    /// if the given `index` is less than [`Self::len`], otherwise [`None`].
    pub fn get(&self, index: usize) -> Option<EpubMetaEntry<'ebook>> {
        self.data
            .get(index)
            .map(|data| self.ctx.create_entry(data, index))
    }

    /// Returns an iterator over all **direct** refining [`EpubMetaEntry`] entries.
    ///
    /// # Nested Refinements
    /// The returned iterator is not recursive.
    /// To iterate over nested refinements, call [`Self::iter`] on yielded entries.
    pub fn iter(&self) -> EpubRefinementsIter<'ebook> {
        EpubRefinementsIter {
            ctx: self.ctx,
            parent_id: self.parent_id,
            iter: self.data.iter().enumerate(),
        }
    }

    /// Returns an iterator over all **direct** refinements matching the specified `property`.
    ///
    /// # Examples
    /// - Retrieving the `role` refinement for a creator:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let author = epub.metadata().creators().next().unwrap();
    /// let role = author.refinements().by_property("role").next().unwrap();
    ///
    /// assert_eq!("aut", role.value());
    /// # Ok(())
    /// # }
    /// ```
    pub fn by_property(
        &self,
        property: &'ebook str,
    ) -> impl Iterator<Item = EpubMetaEntry<'ebook>> + 'ebook {
        let ctx = self.ctx;
        let parent_id = self.parent_id;

        self.data
            .by_refinements(property)
            .map(move |(i, data)| ctx.create_refining_entry(parent_id, data, i))
    }

    /// Returns `true` if the `property` is present.
    ///
    /// # Examples
    /// - Checking if a refinement exists:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let author = epub.metadata().creators().next().unwrap();
    /// let refinements = author.refinements();
    ///
    /// assert!(refinements.has_property("file-as"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn has_property(&self, property: &str) -> bool {
        self.data.has_refinement(property)
    }
}

impl PartialEq for EpubRefinements<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<'ebook> IntoIterator for &EpubRefinements<'ebook> {
    type Item = EpubMetaEntry<'ebook>;
    type IntoIter = EpubRefinementsIter<'ebook>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'ebook> IntoIterator for EpubRefinements<'ebook> {
    type Item = EpubMetaEntry<'ebook>;
    type IntoIter = EpubRefinementsIter<'ebook>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An iterator over all direct [entries](EpubMetaEntry) contained within [`EpubRefinements`].
///
/// # See Also
/// - [`EpubRefinements::iter`] to create an instance of this struct.
///
/// # Examples
/// - Iterating over all refinements of a metadata entry:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
/// let source = epub.metadata().by_property("dc:source").next().unwrap();
///
/// for refinement in source.refinements() {
///     // process refinement //
/// }
/// # Ok(())
/// # }
/// ```
pub struct EpubRefinementsIter<'ebook> {
    ctx: EpubPackageMetaContext<'ebook>,
    parent_id: Option<&'ebook str>,
    iter: Enumerate<std::slice::Iter<'ebook, EpubMetaEntryData>>,
}

impl<'ebook> Iterator for EpubRefinementsIter<'ebook> {
    type Item = EpubMetaEntry<'ebook>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|(i, data)| self.ctx.create_refining_entry(self.parent_id, data, i))
    }
}

/// A [`MetaEntry`] within [`EpubMetadata`].
///
/// A metadata entry is an element that appears within `<metadata>`
/// inside an EPUB's package.opf file, specifically:
/// - Dublin Core elements: `<dc:*>`
/// - `meta` elements: `<meta>`
/// - `link` elements: `<link>`
///
/// # See Also
/// - [`EpubMetaEntryMut`] for a mutable view.
/// - [`EpubMetaEntryKind`] for more info regarding the different kinds of metadata entries.
/// - [`EpubLink`] for metadata regarding potentially linked external content.
#[derive(Copy, Clone, Debug)]
pub struct EpubMetaEntry<'ebook> {
    ctx: EpubPackageMetaContext<'ebook>,
    /// The "parent id" of refining meta entries.
    refines: Option<&'ebook str>,
    data: &'ebook EpubMetaEntryData,
    index: usize,
}

impl_meta_entry!(EpubMetaEntry);

impl<'ebook> EpubMetaEntry<'ebook> {
    pub(super) fn new(
        ctx: EpubPackageMetaContext<'ebook>,
        refines: Option<&'ebook str>,
        data: &'ebook EpubMetaEntryData,
        index: usize,
    ) -> Self {
        Self {
            ctx,
            refines,
            data,
            index,
        }
    }

    // `data` and `index` provide a common accessor between
    // `EpubMetaEntry` and more specialized views (e.g., EpubContributor).
    //
    // Mainly assists within the `impl_meta_entry` macro.
    fn data(&self) -> &'ebook EpubMetaEntryData {
        self.data
    }

    fn index(&self) -> usize {
        self.index
    }

    /// The unique `id` of a metadata entry.
    pub fn id(&self) -> Option<&'ebook str> {
        self.data.id.as_deref()
    }

    /// The associated element `id` a metadata entry refines.
    ///
    /// Returns [`Some`] if an entry is refining another, otherwise [`None`].
    ///
    /// This is akin to a parent-child relationship where children are
    /// [refinements](Self::refinements),
    /// referring to their parent by `id` through the `refines` field.
    ///
    /// Referenced entries by `id` can be the following:
    /// - [`EpubSpineEntry`](super::spine::EpubSpineEntry::refinements)
    /// - [`EpubManifestEntry`](super::manifest::EpubManifestEntry::refinements)
    /// - [`EpubMetaEntry`](Self::refinements)
    ///
    /// # Example
    /// - Accessing a refinement and inspecting its `refines` field:
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    ///
    /// // metadata().creators() can be called alternatively as well
    /// let author = epub.metadata().by_property("dc:creator").next().unwrap();
    /// assert_eq!(Some("author"), author.id());
    /// assert_eq!("John Doe", author.value());
    ///
    /// // Occasionally, metadata entries have refinements:
    /// let refinement1 = author.refinements().iter().next().unwrap();
    /// // All refinement refers to their "parent" via id:
    /// assert_eq!(Some("author"), refinement1.refines());
    ///
    /// // Inspecting a refinement's property and value:
    /// assert_eq!("alternate-script", refinement1.property());
    /// assert_eq!("山田太郎", refinement1.value());
    /// # Ok(())
    /// # }
    /// ```
    pub fn refines(&self) -> Option<&'ebook str> {
        self.refines
    }

    /// The `property`, such as `dc:title`, `media:duration`, `file-as`, etc.
    ///
    /// # Property Mapping
    /// Depending on the underlying element type and EPUB version, this field may be mapped
    /// differently:
    ///
    /// | Element Type         | Mapped From                                                        |
    /// |----------------------|--------------------------------------------------------------------|
    /// | Dublin Core `<dc:*>` | Element tag (`<dc:title>…</dc:title>`)                           |
    /// | EPUB 2 `<meta>`      | `name` attribute (`<meta name="cover" content="…"/>`)            |
    /// | EPUB 3 `<meta>`      | `property` attribute (`<meta property="media:duration">…</meta>`)|
    pub fn property(&self) -> Name<'ebook> {
        Name::new(&self.data.property)
    }

    /// The [`Scheme`] of an entry.
    ///
    /// # Scheme Mapping
    /// The behavior of this method changes depending on an entry’s immediate attributes
    /// ([`Self::attributes`]).
    ///
    /// | Attribute presence  | [`Scheme::source`] Mapping | [`Scheme::code`] Mapping |
    /// |---------------------|----------------------------|--------------------------|
    /// | Legacy `opf:scheme` | [`None`]                   | value of `opf:scheme`    |
    /// | `scheme`            | value of `scheme`          | [`Self::value`]          |
    /// | None of the above   | [`None`]                   | [`Self::value`]          |
    ///
    /// # Examples
    /// - Legacy `opf:scheme` attribute present:
    /// ```xml
    /// <dc:identifier id="uid" opf:scheme="URL">
    ///     https://github.com/devinsterling/rbook
    /// </dc:identifier>
    /// ```
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let metadata = epub.metadata();
    /// // metadata.identifier()?.scheme() may be used alternatively for a higher level view,
    /// // which also takes the `identifier-type` refinement into account unlike here.
    /// let identifier_scheme = metadata.by_property("dc:identifier").next().unwrap().scheme();
    ///
    /// assert_eq!(None, identifier_scheme.source());
    /// assert_eq!("URL", identifier_scheme.code());
    /// # Ok(())
    /// # }
    /// ```
    /// - `scheme` attribute present:
    /// ```xml
    /// <meta property="role" refines="#author" scheme="marc:relators">
    ///     aut
    /// </meta>
    /// ```
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// # let epub = Epub::open("tests/ebooks/example_epub")?;
    /// # let metadata = epub.metadata();
    /// // metadata.creators().next()?.main_role() may be used alternatively for a higher level view,
    /// // which also takes the `role` refinement into account unlike here.
    /// let author = metadata.by_property("dc:creator").next().unwrap();
    /// let role_scheme = author.refinements().by_property("role").next().unwrap().scheme();
    ///
    /// assert_eq!(Some("marc:relators"), role_scheme.source());
    /// assert_eq!("aut", role_scheme.code());
    /// # Ok(())
    /// # }
    /// ```
    /// - No scheme attribute present:
    /// ```xml
    /// <dc:language>
    ///     en
    /// </dc:language>
    /// ```
    /// ```
    /// # use rbook::Epub;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// # let epub = Epub::open("tests/ebooks/example_epub")?;
    /// # let metadata = epub.metadata();
    /// // metadata.language() may be used alternatively for a higher level view
    /// let language_scheme = metadata.by_property("dc:language").next().unwrap().scheme();
    ///
    /// assert_eq!(None, language_scheme.source());
    /// assert_eq!("en", language_scheme.code());
    /// # Ok(())
    /// # }
    /// ```
    pub fn scheme(&self) -> Scheme<'ebook> {
        if let Some(code) = self.data.attributes.get_value(opf::OPF_SCHEME) {
            return Scheme::new(None, code);
        }

        Scheme::new(self.data.attributes.get_value(opf::SCHEME), self.value())
    }

    /// The specified or inherited language in `BCP 47` format.
    ///
    /// [`None`] is returned if the element contains no `xml:lang` attribute
    /// (and the `<package>` has none).
    ///
    /// # See Also
    /// - [`EpubLink::href_lang`] for the language of the linked resource.
    ///   `<link>` elements do not formally support the `xml:lang` attribute.
    pub fn xml_language(&self) -> Option<LanguageTag<'ebook>> {
        self.data
            .language()
            .or_else(|| self.ctx.package_language())
            .map(|code| LanguageTag::new(code, LanguageKind::Bcp47))
    }

    /// The specified or inherited text direction (`ltr`, `rtl`, or `auto`).
    ///
    /// [`TextDirection::Auto`] is returned if any of the following conditions are met:
    /// - The `<package>` and specified element contains no `dir` attribute.
    /// - [`Self::kind`] is [`EpubMetaEntryKind::Link`], as `<link>`
    ///   elements do not formally support the `dir` attribute.
    pub fn text_direction(&self) -> TextDirection {
        match self.data.text_direction {
            TextDirection::Auto => self.ctx.package_text_direction(),
            text_direction => text_direction,
        }
    }

    /// All additional XML [`Attributes`].
    ///
    /// # Omitted Attributes
    /// The following attributes will **not** be found within the returned collection:
    /// - [`id`](Self::id)
    /// - [`xml:lang`](Self::xml_language)
    /// - [`dir`](Self::text_direction)
    /// - [`property`](Self::property)
    /// - [`refines`](Self::refines)
    /// - [`name`](Self::property) (EPUB 2; legacy)
    /// - [`content`](Self::value) (EPUB 2; legacy)
    pub fn attributes(&self) -> &'ebook Attributes {
        &self.data.attributes
    }

    /// Complementary refinement metadata entries.
    ///
    /// # See Also
    /// - [`Self::refines`] to inspect which entry (by `id`) a metadata entry refines.
    /// - [`EpubManifestEntry::refinements`](super::manifest::EpubManifestEntry::refinements)
    ///   for manifest entry refinements.
    /// - [`EpubSpineEntry::refinements`](super::spine::EpubSpineEntry::refinements)
    ///   for spine entry refinements.
    pub fn refinements(&self) -> EpubRefinements<'ebook> {
        self.ctx
            .create_refinements(self.id(), &self.data.refinements)
    }

    /// The kind of metadata entry.
    pub fn kind(&self) -> EpubMetaEntryKind {
        self.data.kind
    }

    /// Returns an [`EpubLink`] view of a metadata entry,
    /// otherwise [`None`] if the entry is not a `<link>` element.
    ///
    /// This method provides convenient access to link-specific attributes
    /// (e.g., `href`, `hreflang`, `rel`).
    ///
    /// # See Also
    /// - [`EpubMetadata::links`] to iterate over non-refining link entries.
    ///
    /// # Examples
    /// - Converting to [`EpubLink`]:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::ebook::element::Href;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let meta_entry = epub.metadata().by_id("example-link").unwrap();
    ///
    /// // Convert to link view
    /// let link = meta_entry.as_link().unwrap();
    /// assert_eq!("https://github.com/devinsterling/rbook", link.href().unwrap().as_str());
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_link(&self) -> Option<EpubLink<'ebook>> {
        self.kind().is_link().then_some(EpubLink(*self))
    }
}

impl PartialEq for EpubMetaEntry<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

/// A specialized view of [`EpubMetaEntry`] for `<link>` elements.
///
/// Link elements provide associations to resources related to the EPUB publication
/// (e.g., metadata records, alternate representations, related resources).
///
/// # Examples
/// - Accessing link metadata:
/// ```
/// # use rbook::Epub;
/// # fn main() -> rbook::ebook::errors::EbookResult<()> {
/// let epub = Epub::open("tests/ebooks/example_epub")?;
///
/// for link in epub.metadata().links() {
///     if let Some(href) = link.href() {
///         println!("Link to: {}", href.as_str());
///     }
///
///     if let Some(media_type) = link.media_type() {
///         println!("Media type: {}", media_type);
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// # See Also
/// - [`DetachedEpubMetaEntry::link`] to create a link metadata entry.
/// - [`EpubMetaEntry::as_link`] to convert from [`EpubMetaEntry`].
/// - <https://www.w3.org/TR/epub/#sec-link-elem> for official EPUB `<link>` documentation
pub struct EpubLink<'ebook>(EpubMetaEntry<'ebook>);

impl<'ebook> EpubLink<'ebook> {
    /// The location of the specified resource a link points to.
    ///
    /// Returns [`None`] if not present.
    pub fn href(&self) -> Option<Href<'ebook>> {
        self.0.data.attributes.get_value(opf::HREF).map(Href::new)
    }

    /// The language of the resource referenced by [`Self::href`].
    ///
    /// Returns [`None`] if not present.
    pub fn href_lang(&self) -> Option<LanguageTag<'ebook>> {
        self.0
            .data
            .attributes
            .get_value(opf::HREFLANG)
            .map(|hreflang| LanguageTag::new(hreflang, LanguageKind::Bcp47))
    }

    /// The `MIME` identifying the media type
    /// of the resource referenced by [`Self::href`].
    ///
    /// Returns [`None`] if not present.
    ///
    /// This method is a lower-level call than [`Self::kind`].
    pub fn media_type(&self) -> Option<&'ebook str> {
        self.0.data.attributes.get_value(opf::MEDIA_TYPE)
    }

    /// The [`ResourceKind`] identifying the media type
    /// of the resource referenced by [`Self::href`].
    ///
    /// Returns [`None`] if not present.
    pub fn kind(&self) -> Option<ResourceKind<'ebook>> {
        self.media_type().map(Into::into)
    }

    /// List of property values.
    pub fn properties(&self) -> &'ebook Properties {
        self.0
            .data
            .attributes
            .by_name(opf::PROPERTIES)
            .map_or(Properties::EMPTY_REFERENCE, Attribute::as_properties)
    }

    /// List of relationship values describing the linked resource.
    ///
    /// Common values include:
    /// - `alternate`: Alternate representation
    /// - `record`: Metadata record
    /// - `xml-signature`: XML signature
    pub fn rel(&self) -> &'ebook Properties {
        self.0
            .data
            .attributes
            .by_name(opf::REL)
            .map_or(Properties::EMPTY_REFERENCE, Attribute::as_properties)
    }

    /// Returns the underlying [`EpubMetaEntry`] to access generic metadata details
    /// such as id, refinements, and attributes.
    pub fn as_meta(&self) -> EpubMetaEntry<'_> {
        self.0
    }
}

/// Contains the kinds of metadata entries that can be found within an
/// [`Epub`](super::Epub)'s `<metadata>` element:
/// - [`DublinCore`](EpubMetaEntryKind::DublinCore)
/// - [`Meta`](EpubMetaEntryKind::Meta)
/// - [`Link`](EpubMetaEntryKind::Link)
///
/// # See Also
/// - [`EpubMetaEntry::kind`] to retrieve the kind from an [`EpubMetaEntry`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum EpubMetaEntryKind {
    /// A set of standardized metadata elements that provide a common vocabulary
    /// for describing relevant information about a publication
    /// (e.g., `dc:title`, `dc:creator`, `dc:publisher`).
    ///
    /// **Dublin Core (`<dc:title>`) element structure example**:
    /// ```xml
    /// <dc:title>
    ///   rbook
    /// </dc:title>
    /// ```
    ///
    /// # See Also
    /// <https://www.w3.org/TR/epub/#sec-opf-dcmes-hd> for official EPUB Dublin Core documentation.
    #[non_exhaustive]
    DublinCore {},

    /// General metadata packaged within an [`Epub`](super::Epub).
    ///
    /// - **Legacy EPUB 2 (OPF2) `<meta>` element structure example**:
    /// ```xml
    /// <meta name="cover" content="c0" />
    /// ```
    /// - **EPUB 3 `<meta>` element structure example**:
    /// ```xml
    /// <meta property="display-seq" refines="#parent">
    ///   0
    /// </meta>
    /// ```
    ///
    /// # Examples
    /// - Pattern Matching:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::{EpubMetaEntryKind, EpubVersion};
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let source = epub.metadata().by_property("dc:source").next().unwrap();
    ///
    /// match source.kind() {
    ///     EpubMetaEntryKind::Meta { version: EpubVersion::EPUB3, ..} => {},
    ///     EpubMetaEntryKind::Meta { version: EpubVersion::EPUB2, ..} => {},
    ///     EpubMetaEntryKind::Meta { .. } => {},
    ///     _ => {/* Other kind (i.e., Dublin Core, link) */},
    /// };
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # See Also
    /// <https://www.w3.org/TR/epub/#sec-meta-elem> for official EPUB `<meta>` documentation.
    #[non_exhaustive]
    Meta {
        /// Structural version associated with a `<meta>` element.
        ///
        /// # See Also
        /// - [`EpubMetaEntryKind::version`]
        version: EpubVersion,
    },

    /// A link element pertaining to a task such as resource associations,
    /// linkage to external resources, etc.
    ///
    /// **`<link>` element structure example**:
    /// ```xml
    /// <link rel="record" href="meta/133333333337.xml" media-type="application/marc" />
    /// ```
    ///
    /// # See Also
    /// <https://www.w3.org/TR/epub/#sec-link-elem> for official EPUB `<link>` documentation.
    #[non_exhaustive]
    Link {},
}

impl EpubMetaEntryKind {
    /// Returns `true` if the kind is [`Self::DublinCore`].
    ///
    /// # Examples
    /// - Assessing a Dublin Core (`<dc:*>`) element:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::EpubMetaEntryKind;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let title = epub.metadata().title().unwrap();
    /// let kind = title.as_meta().kind();
    ///
    /// assert!(matches!(kind, EpubMetaEntryKind::DublinCore { .. }));
    /// assert!(kind.is_dublin_core());
    ///
    /// // Kinds are mutually exclusive (Below will always resolve to `false`)
    /// assert!(!kind.is_meta());
    /// assert!(!kind.is_link());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_dublin_core(&self) -> bool {
        matches!(self, Self::DublinCore { .. })
    }

    /// Returns `true` if the kind is [`Self::Meta`].
    ///
    /// # See Also
    /// - [`Self::version`] for the structural version of a `<meta>` element.
    /// - [`Self::is_epub2_meta`] to check if the structural version is legacy EPUB 2.
    /// - [`Self::is_epub3_meta`] to check if the structural version is EPUB 3.
    ///
    /// # Examples
    /// - Assessing a `meta` element:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::{EpubMetaEntryKind, EpubVersion};
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let cover_meta = epub.metadata().by_property("cover").next().unwrap();
    /// let kind = cover_meta.kind();
    ///
    /// assert!(matches!(kind, EpubMetaEntryKind::Meta { version: EpubVersion::EPUB2, .. }));
    /// assert!(kind.is_meta());
    ///
    /// // Kinds are mutually exclusive (Below will always resolve to `false`)
    /// assert!(!kind.is_dublin_core());
    /// assert!(!kind.is_link());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_meta(&self) -> bool {
        matches!(self, Self::Meta { .. })
    }

    /// Returns `true` if the kind is legacy EPUB 2 [`Self::Meta`].
    ///
    /// # See Also
    /// - [`Self::version`] for the structural version of a `<meta>` element.
    ///
    /// # Examples
    /// - Assessing a legacy EPUB 2 `meta` element:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::{EpubMetaEntryKind, EpubVersion};
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let cover_meta = epub.metadata().by_property("cover").next().unwrap();
    /// let kind = cover_meta.kind();
    ///
    /// assert!(kind.is_meta());
    /// assert!(kind.is_epub2_meta());
    ///
    /// // Kinds are mutually exclusive (Below will always resolve to `false`)
    /// assert!(!kind.is_epub3_meta());
    /// assert!(!kind.is_dublin_core());
    /// assert!(!kind.is_link());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_epub2_meta(&self) -> bool {
        matches!(
            self,
            Self::Meta {
                version: EpubVersion::Epub2(_),
            }
        )
    }

    /// Returns `true` if the kind is EPUB 3 [`Self::Meta`].
    ///
    /// # See Also
    /// - [`Self::version`] for the structural version of a `<meta>` element.
    ///
    /// # Examples
    /// - Assessing an EPUB 3 `meta` element:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::{EpubMetaEntryKind, EpubVersion};
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let title = epub.metadata().title().unwrap();
    ///
    /// // Retrieve the `title-type` refinement
    /// let refinement = title.refinements().by_property("title-type").next().unwrap();
    /// let kind = refinement.kind();
    ///
    /// assert!(kind.is_meta());
    /// assert!(kind.is_epub3_meta());
    ///
    /// // Kinds are mutually exclusive (Below will always resolve to `false`)
    /// assert!(!kind.is_epub2_meta());
    /// assert!(!kind.is_dublin_core());
    /// assert!(!kind.is_link());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_epub3_meta(&self) -> bool {
        matches!(
            self,
            Self::Meta {
                version: EpubVersion::Epub3(_),
            }
        )
    }

    /// Returns `true` if the kind is [`Self::Link`].
    ///
    /// # Examples
    /// - Assessing a `link` element:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::EpubMetaEntryKind;
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let link = epub.metadata().by_id("example-link").unwrap();
    /// let kind = link.kind();
    ///
    /// assert!(matches!(kind, EpubMetaEntryKind::Link { .. }));
    /// assert!(kind.is_link());
    ///
    /// // Kinds are mutually exclusive (Below will always resolve to `false`)
    /// assert!(!kind.is_dublin_core());
    /// assert!(!kind.is_meta());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_link(&self) -> bool {
        matches!(self, Self::Link { .. })
    }

    /// The structural [`EpubVersion`] a metadata entry is associated with.
    ///
    /// # Note
    /// This method is applicable if [`EpubMetaEntryKind`] is [`EpubMetaEntryKind::Meta`].
    ///
    /// For all other kinds ([`DublinCore`](EpubMetaEntryKind::DublinCore),
    /// [`Link`](EpubMetaEntryKind::Link)),
    /// the returned version is **always** [`None`]
    /// as their main structure remains the same between EPUB 2 and 3.
    ///
    /// # See Also
    /// - [`Self::Meta`] for the structural differences between EPUB 2 and 3 `<meta>` elements.
    ///
    /// # Examples
    /// - Retrieving the structural version:
    /// ```
    /// # use rbook::Epub;
    /// # use rbook::epub::metadata::{EpubMetaEntryKind, EpubVersion};
    /// # fn main() -> rbook::ebook::errors::EbookResult<()> {
    /// let epub = Epub::open("tests/ebooks/example_epub")?;
    /// let metadata = epub.metadata();
    ///
    /// let cover = metadata.by_property("cover").next().unwrap();
    /// let title = metadata.title().unwrap();
    /// let link = metadata.by_id("example-link").unwrap();
    ///
    /// // `<meta>` elements always have a structural version
    /// assert_eq!(cover.kind().version(), Some(EpubVersion::EPUB2));
    ///
    /// // Dublin Core `<dc:*>` elements never have an associated structural version
    /// assert_eq!(title.as_meta().kind().version(), None);
    ///
    /// // `<link>` elements never have an associated structural version
    /// assert_eq!(link.kind().version(), None);
    /// # Ok(())
    /// # }
    /// ```
    pub fn version(&self) -> Option<EpubVersion> {
        match self {
            Self::Meta { version, .. } => Some(*version),
            _ => None,
        }
    }
}

/// The version of an [`Epub`](super::Epub).
///
/// # Versions
/// - [`Epub2`](EpubVersion::Epub2) (Legacy)
/// - [`Epub3`](EpubVersion::Epub3)
/// - [`Unknown`](EpubVersion::Unknown)
///
/// # See Also
/// - [`EpubMetadata::version_str`] for the original representation.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum EpubVersion {
    /// [`Epub`](super::Epub) Version `2.*` **(Legacy)**
    Epub2(Version),
    /// [`Epub`](super::Epub) Version `3.*`
    ///
    /// Epubs with this version may be backwards compatible with version 2,
    /// `rbook` handles such scenarios behind-the-scenes.
    ///
    /// # See Also
    /// - [`EpubOpenOptions`](super::EpubOpenOptions) for preferences between versions 2 and 3.
    Epub3(Version),
    /// An unknown [`Epub`](super::Epub) version
    ///
    /// An [`Epub`](super::Epub) may contain this version when
    /// [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is set to `false`.
    Unknown(Version),
}

impl EpubVersion {
    /// Utility to retrieve the major of each compatible EPUB versions.
    pub(crate) const VERSIONS: [EpubVersion; 2] = [Self::EPUB2, Self::EPUB3];

    /// [`EpubVersion::Epub2`] constant with a predefined [`Version`] of `2.0`.
    pub const EPUB2: Self = Self::Epub2(Version(2, 0));

    /// [`EpubVersion::Epub3`] constant with a predefined [`Version`] of `3.0`.
    pub const EPUB3: Self = Self::Epub3(Version(3, 0));

    /// Returns the major form of an epub version.
    ///
    /// If the contained [`Version`] is `3.3`, then the returned [`EpubVersion`]
    /// will have a contained value of `3.0`.
    ///
    /// # Examples
    /// - Retrieving the major:
    /// ```
    /// # use rbook::ebook::metadata::Version;
    /// # use rbook::ebook::epub::metadata::EpubVersion;
    /// let epub3 = EpubVersion::from(Version(3, 3));
    ///
    /// assert_eq!(Version(3, 3), epub3.version());
    /// assert_eq!(Version(3, 0), epub3.as_major().version());
    /// ```
    pub fn as_major(&self) -> Self {
        match self {
            Self::Epub2(_) => Self::EPUB2,
            Self::Epub3(_) => Self::EPUB3,
            Self::Unknown(version) => Self::Unknown(Version(version.0, 0)),
        }
    }

    /// The encapsulated version information.
    ///
    /// # Note
    /// If [`EpubOpenOptions::strict`](super::EpubOpenOptions::strict) is set to `false`,
    /// the returned [`Version`] may not be within the valid range: `2 <= version < 4`.
    pub fn version(&self) -> Version {
        match self {
            Self::Epub2(version) | Self::Epub3(version) | Self::Unknown(version) => *version,
        }
    }

    /// Returns `true` if the variant is [`EpubVersion::Epub2`].
    pub fn is_epub2(&self) -> bool {
        matches!(self, Self::Epub2(_))
    }

    /// Returns `true` if the variant is [`EpubVersion::Epub3`].
    pub fn is_epub3(&self) -> bool {
        matches!(self, Self::Epub3(_))
    }

    /// Returns `true` if the variant is [`EpubVersion::Unknown`].
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown(_))
    }
}

impl PartialOrd for EpubVersion {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EpubVersion {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.version().cmp(&other.version())
    }
}

impl<I: Into<Version>> From<I> for EpubVersion {
    fn from(version: I) -> Self {
        let version = version.into();

        match version.0 {
            2 => Self::Epub2(version),
            3 => Self::Epub3(version),
            _ => Self::Unknown(version),
        }
    }
}

impl Display for EpubVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.version().fmt(f)
    }
}

/// Implementation of [`Identifier`].
///
/// # See Also
/// - [`DetachedEpubMetaEntry::identifier`] to create an identifier metadata entry.
/// - [`Self::as_meta`] to access finer details such as attributes and refinements.
#[derive(Copy, Clone, Debug)]
pub struct EpubIdentifier<'ebook> {
    entry: EpubMetaEntry<'ebook>,
}

impl_meta_entry_abstraction!(EpubIdentifier);

impl<'ebook> EpubIdentifier<'ebook> {
    fn new(entry: EpubMetaEntry<'ebook>) -> Self {
        Self { entry }
    }

    /// Fallback when [`Self::get_modern_identifier_type`] is not available.
    fn get_legacy_identifier_type(&self) -> Option<Scheme<'ebook>> {
        self.entry
            .data
            .attributes
            .get_value(opf::OPF_SCHEME)
            .map(|identifier_type| Scheme::new(None, identifier_type))
    }

    fn get_modern_identifier_type(&self) -> Option<Scheme<'ebook>> {
        self.entry
            .data
            .refinements
            .get_schemes(opf::IDENTIFIER_TYPE)
            .next()
    }

    /// The identifier’s scheme or [`None`] if unspecified.
    #[doc = util::inherent_doc!(Identifier, scheme)]
    pub fn scheme(&self) -> Option<Scheme<'ebook>> {
        self.get_modern_identifier_type()
            .or_else(|| self.get_legacy_identifier_type())
    }
}

impl<'ebook> Identifier<'ebook> for EpubIdentifier<'ebook> {
    fn scheme(&self) -> Option<Scheme<'ebook>> {
        self.scheme()
    }
}

impl Eq for EpubIdentifier<'_> {}

impl PartialEq for EpubIdentifier<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.scheme() == other.scheme() && self.value() == other.value()
    }
}

impl std::hash::Hash for EpubIdentifier<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.value().hash(state);
        self.scheme().hash(state);
    }
}

/// Implementation of [`Title`].
///
/// # See Also
/// - [`DetachedEpubMetaEntry::title`] to create a title metadata entry.
/// - [`Self::as_meta`] to access finer details such as attributes and refinements.
#[derive(Copy, Clone, Debug)]
pub struct EpubTitle<'ebook> {
    entry: EpubMetaEntry<'ebook>,
    /// Whether the title is inferred as the main title.
    ///
    /// Based on the logic contained within [`Metadata::titles`],
    /// when a `title-type` of `main` is absent, infers the main `Title`
    /// by selecting the `<dc:title>` with the highest precedence (lowest display order).
    ///
    /// This guarantees consistent [`TitleKind::Main`] identification across all EPUBs via
    /// [`Title::kind`].
    is_main_title: bool,
}

impl_meta_entry_abstraction!(EpubTitle);

impl<'ebook> EpubTitle<'ebook> {
    fn new(entry: EpubMetaEntry<'ebook>, is_main_title: bool) -> Self {
        Self {
            entry,
            is_main_title,
        }
    }

    /// The title’s scheme or [`None`] if unspecified.
    #[doc = util::inherent_doc!(Title, scheme)]
    pub fn scheme(&self) -> Option<Scheme<'ebook>> {
        self.entry
            .data
            .refinements
            .by_refinement(opf::TITLE_TYPE)
            .map(|title_type| Scheme::new(None, &title_type.value))
    }

    /// The kind of title.
    #[doc = util::inherent_doc!(Title, kind)]
    pub fn kind(&self) -> TitleKind {
        if self.is_main_title {
            return TitleKind::Main;
        }
        self.entry
            .data
            .refinements
            .by_refinement(opf::TITLE_TYPE)
            .map_or(TitleKind::Unknown, |title_type| {
                TitleKind::from(&title_type.value)
            })
    }
}

impl<'ebook> Title<'ebook> for EpubTitle<'ebook> {
    fn scheme(&self) -> Option<Scheme<'ebook>> {
        self.scheme()
    }

    fn kind(&self) -> TitleKind {
        self.kind()
    }
}

impl PartialEq for EpubTitle<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.entry == other.entry
    }
}

/// Implementation of [`Tag`].
///
/// # See Also
/// - [`DetachedEpubMetaEntry::tag`] to create a tag (`dc:subject`) metadata entry.
/// - [`Self::as_meta`] to access finer details such as attributes and refinements.
#[derive(Copy, Clone, Debug)]
pub struct EpubTag<'ebook> {
    entry: EpubMetaEntry<'ebook>,
}

impl_meta_entry_abstraction!(EpubTag);

impl<'ebook> EpubTag<'ebook> {
    fn new(entry: EpubMetaEntry<'ebook>) -> Self {
        Self { entry }
    }

    /// Fallback when [`Self::get_modern_scheme`] is not available.
    fn get_legacy_scheme(&self) -> Option<Scheme<'ebook>> {
        let refinements = &self.entry.data.refinements;
        let auth = refinements.by_refinement(opf::AUTHORITY)?;
        let term = refinements.by_refinement(opf::TERM)?;
        Some(Scheme::new(Some(&auth.value), &term.value))
    }

    fn get_modern_scheme(&self) -> Option<Scheme<'ebook>> {
        let attributes = &self.entry.data.attributes;
        let authority = attributes.get_value(opf::OPF_AUTHORITY)?;
        let term = attributes.get_value(opf::OPF_TERM)?;
        Some(Scheme::new(Some(authority), term))
    }

    /// The tag’s scheme or [`None`] if unspecified.
    ///
    /// The **authority** is the [`Scheme::source`]
    /// and the **term** is the [`Scheme::code`].
    #[doc = util::inherent_doc!(Tag, scheme)]
    pub fn scheme(&self) -> Option<Scheme<'ebook>> {
        // A `term` must be present if there's an `authority`.
        // Otherwise, the element does not follow spec/malformed.
        self.get_modern_scheme()
            .or_else(|| self.get_legacy_scheme())
    }
}

impl<'ebook> Tag<'ebook> for EpubTag<'ebook> {
    fn scheme(&self) -> Option<Scheme<'ebook>> {
        self.scheme()
    }
}

impl PartialEq for EpubTag<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.entry == other.entry
    }
}

/// Implementation of [`Contributor`].
///
/// # marc:relators
/// While not guaranteed, if a [`role`](Contributor::roles)
/// has a [`Scheme::source`] of [`None`],
/// the value of [`Scheme::code`] may originate from `marc:relators` as the source.
/// This is typically the case for EPUB 2.
///
/// # See Also
/// - [`DetachedEpubMetaEntry::creator`] to create a **creator** metadata entry.
/// - [`DetachedEpubMetaEntry::contributor`] to create a **contributor** metadata entry.
/// - [`DetachedEpubMetaEntry::publisher`] to create a **publisher** metadata entry.
/// - [`Self::as_meta`] to access finer details such as attributes and refinements.
#[derive(Copy, Clone, Debug)]
pub struct EpubContributor<'ebook> {
    entry: EpubMetaEntry<'ebook>,
}

impl_meta_entry_abstraction!(EpubContributor);

impl<'ebook> EpubContributor<'ebook> {
    fn new(entry: EpubMetaEntry<'ebook>) -> Self {
        Self { entry }
    }

    /// Fallback when [`Self::get_modern_roles`] is not available.
    fn get_legacy_role(&self) -> Option<Scheme<'ebook>> {
        self.entry
            .data
            .attributes
            .by_name(opf::OPF_ROLE)
            .map(|role| Scheme::new(None, role.value()))
    }

    fn get_modern_roles(&self) -> impl Iterator<Item = Scheme<'ebook>> + 'ebook {
        self.entry.data.refinements.get_schemes(opf::ROLE)
    }

    /// The primary role of a contributor or [`None`] if unspecified.
    #[doc = util::inherent_doc!(Contributor, main_role)]
    pub fn main_role(&self) -> Option<Scheme<'ebook>> {
        self.roles().next()
    }

    /// Returns an iterator over **all** roles by the order of importance (display sequence).
    #[doc = util::inherent_doc!(Contributor, roles)]
    pub fn roles(&self) -> impl Iterator<Item = Scheme<'ebook>> + 'ebook {
        let roles = self.get_modern_roles().map(Some);
        // If the size hint is 0, attempt to retrieve legacy `opf:role` attribute
        // Note: `size_hint` **works** here as the underlying source is based
        // on a collection (Vec) with a reliable hint.
        let fallback = (roles.size_hint().0 == 0).then(|| self.get_legacy_role());

        roles.chain(std::iter::once(fallback.flatten())).flatten()
    }
}

impl<'ebook> Contributor<'ebook> for EpubContributor<'ebook> {
    fn main_role(&self) -> Option<Scheme<'ebook>> {
        self.main_role()
    }

    fn roles(&self) -> impl Iterator<Item = Scheme<'ebook>> + 'ebook {
        self.roles()
    }
}

impl PartialEq for EpubContributor<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.entry == other.entry
    }
}

/// Implementation of [`Language`].
///
/// EPUB language tags are always treated as `BCP 47` (EPUB 3),
/// even when originating from `RFC 3066` (EPUB 2) as:
/// 1. EPUB 3 requires the language scheme as BCP 47.
/// 2. EPUB 2 requires a subset of BCP 47, RFC 3066.
///
/// For simplicity, `rbook` treats RFC 3066 ***as*** BCP 47.
/// Both [`EpubLanguage::scheme`] and [`EpubLanguage::kind`]
/// will always report `BCP 47`.
///
/// # See Also
/// - [`DetachedEpubMetaEntry::language`] to create a language metadata entry.
/// - [`Self::as_meta`] to access finer details such as attributes and refinements.
#[derive(Copy, Clone, Debug)]
pub struct EpubLanguage<'ebook> {
    entry: EpubMetaEntry<'ebook>,
}

impl_meta_entry_abstraction!(EpubLanguage);

impl<'ebook> EpubLanguage<'ebook> {
    fn new(entry: EpubMetaEntry<'ebook>) -> Self {
        Self { entry }
    }
}

impl<'ebook> EpubLanguage<'ebook> {
    /// Always returns with [`Scheme::source`] always exactly as `BCP 47`.
    ///
    /// See [`EpubLanguage`] for more information.
    #[doc = util::inherent_doc!(Language, scheme)]
    /// # See Also
    /// - [`Language::scheme`]
    pub fn scheme(&self) -> Scheme<'ebook> {
        Scheme::new(Some(LanguageKind::Bcp47.as_str()), &self.entry.data.value)
    }

    /// Always returns [`LanguageKind::Bcp47`].
    ///
    /// See [`EpubLanguage`] for more information.
    #[doc = util::inherent_doc!(Language, kind)]
    /// # See Also
    /// - [`Language::kind`]
    pub fn kind(&self) -> LanguageKind {
        // Normalize both as BCP 47:
        // - EPUB-2 requires RFC 3066 (a subset of BCP 47)
        // - EPUB-3 requires BCP 47
        LanguageKind::Bcp47
    }
}

impl<'ebook> Language<'ebook> for EpubLanguage<'ebook> {
    fn scheme(&self) -> Scheme<'ebook> {
        self.scheme()
    }

    fn kind(&self) -> LanguageKind {
        self.kind()
    }
}

impl PartialEq for EpubLanguage<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.entry == other.entry
    }
}

mod macros {
    macro_rules! impl_meta_entry_abstraction {
        ($implementation:ident) => {
            impl<'ebook> $implementation<'ebook> {
                // `data` and `index` provide a common accessor between
                // `EpubMetaEntry` and more specialized views (e.g., EpubContributor).
                //
                // Mainly assists within the `impl_meta_entry` macro.
                fn data(&self) -> &'ebook EpubMetaEntryData {
                    &self.entry.data
                }

                fn index(&self) -> usize {
                    self.entry.index
                }

                /// Returns the [`EpubMetaEntry`] form to access additional
                /// metadata entry details, such as attributes and refinements.
                pub fn as_meta(&self) -> EpubMetaEntry<'ebook> {
                    self.entry
                }
            }

            impl PartialEq<EpubMetaEntry<'_>> for $implementation<'_> {
                fn eq(&self, other_entry: &EpubMetaEntry<'_>) -> bool {
                    &self.entry == other_entry
                }
            }

            impl<'ebook> std::ops::Deref for $implementation<'ebook> {
                type Target = EpubMetaEntry<'ebook>;

                fn deref(&self) -> &Self::Target {
                    &self.entry
                }
            }

            impl_meta_entry!($implementation);
        };
    }

    /// Implements [`MetaEntry`](super::MetaEntry) for the specified type.
    macro_rules! impl_meta_entry {
        ($implementation:ident) => {
            impl<'ebook> $implementation<'ebook> {
                fn get_modern_alt_script(
                    &self,
                ) -> impl Iterator<Item = AlternateScript<'ebook>> + 'ebook {
                    self.data()
                        .refinements
                        .by_refinements(opf::ALTERNATE_SCRIPT)
                        .map(|(_, script)| {
                            // xml:lang **should** be present on an alternate-script refinement.
                            // Otherwise, the EPUB is malformed.
                            let code = script.language().unwrap_or_default();
                            AlternateScript::new(
                                &script.value,
                                LanguageTag::new(code, LanguageKind::Bcp47),
                            )
                        })
                }

                fn get_legacy_alt_script(&self) -> Option<AlternateScript<'ebook>> {
                    let attributes = &self.data().attributes;
                    let script = attributes.by_name(opf::OPF_ALT_REP)?.value();
                    let code = attributes.by_name(opf::OPF_ALT_REP_LANG)?.value();
                    Some(AlternateScript::new(
                        script,
                        LanguageTag::new(code, LanguageKind::Bcp47),
                    ))
                }

                /// The plain text value of an entry.
                #[doc = util::inherent_doc!(MetaEntry, value)]
                pub fn value(&self) -> &'ebook str {
                    &self.data().value
                }

                /// The (0-based) order/display-sequence of an entry relative to another associated entry.
                #[doc = util::inherent_doc!(MetaEntry, order)]
                pub fn order(&self) -> usize {
                    self.index()
                }

                /// The `file-as` sort key, if present.
                #[doc = util::inherent_doc!(MetaEntry, file_as)]
                pub fn file_as(&self) -> Option<&'ebook str> {
                    self.data()
                        .refinements
                        .by_refinement(opf::FILE_AS)
                        .map(|refinement| refinement.value.as_str())
                        // Fallback to legacy `opf:file-as` attribute
                        .or_else(|| {
                            self.data()
                                .attributes
                                .by_name(opf::OPF_FILE_AS)
                                .map(|attribute| attribute.value())
                        })
                }

                /// Returns an iterator over **all** [`AlternateScript`].
                #[doc = util::inherent_doc!(MetaEntry, alternate_scripts)]
                pub fn alternate_scripts(
                    &self,
                ) -> impl Iterator<Item = AlternateScript<'ebook>> + 'ebook {
                    let mut scripts = self.get_modern_alt_script().peekable();

                    let fallback = scripts
                        .peek()
                        .is_none()
                        .then(|| self.get_legacy_alt_script())
                        .flatten();

                    scripts.chain(std::iter::once(fallback).flatten())
                }
            }

            impl Sealed for $implementation<'_> {}

            impl<'ebook> MetaEntry<'ebook> for $implementation<'ebook> {
                fn value(&self) -> &'ebook str {
                    self.value()
                }

                fn order(&self) -> usize {
                    self.order()
                }

                fn file_as(&self) -> Option<&'ebook str> {
                    self.file_as()
                }

                fn alternate_scripts(
                    &self,
                ) -> impl Iterator<Item = AlternateScript<'ebook>> + 'ebook {
                    self.alternate_scripts()
                }
            }
        };
    }

    pub(super) use {impl_meta_entry, impl_meta_entry_abstraction};
}