Skip to main content

latexml_post/manifest/
epub.rs

1//! EPUB manifest creation.
2//!
3//! Port of `LaTeXML::Post::Manifest::Epub` (252 lines of Perl).
4//! Creates the EPUB 3.2 package structure:
5//! - `mimetype` file
6//! - `META-INF/container.xml`
7//! - `OPS/content.opf` (spine + manifest)
8//! - Indexes all content files with correct media types
9
10use std::{
11  fs,
12  path::{Path, PathBuf},
13};
14
15use latexml_core::common::xml::name_is;
16
17/// The OPF package namespace (EPUB 3).
18const OPF_NS: &str = "http://www.idpf.org/2007/opf";
19/// Dublin Core, the metadata vocabulary an OPF's `<metadata>` carries.
20const DC_NS: &str = "http://purl.org/dc/elements/1.1/";
21
22/// EPUB 3.2 container.xml content.
23const CONTAINER_XML: &str = r#"<?xml version="1.0"?>
24<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
25    <rootfiles>
26        <rootfile full-path="OPS/content.opf" media-type="application/oebps-package+xml"/>
27   </rootfiles>
28</container>"#;
29
30/// Error context for a libxml call.
31///
32/// Generic over the error type on purpose: `rust-libxml` returns
33/// `Box<dyn Error>` from some constructors and `String` from others, so one
34/// fixed-argument closure cannot serve both.
35fn ctx<E>(what: impl Into<String>) -> impl Fn(E) -> String {
36  let what = what.into();
37  move |_| format!("couldn't create {what}")
38}
39
40/// Core Media Types as per EPUB 3.2 spec.
41fn core_media_type(ext: &str) -> &'static str {
42  match ext.to_lowercase().as_str() {
43    "gif" => "image/gif",
44    "jpg" | "jpeg" => "image/jpeg",
45    "png" => "image/png",
46    "svg" => "image/svg+xml",
47    "mp3" => "audio/mpeg",
48    "mp4" | "mpg4" => "audio/mp4",
49    "css" => "text/css",
50    "ttf" => "font/ttf",
51    "otf" => "font/otf",
52    "woff" => "font/woff",
53    "woff2" => "font/woff2",
54    "xhtml" => "application/xhtml+xml",
55    "js" => "text/javascript",
56    "ncx" => "application/x-dtbncx+xml",
57    "smi" | "smil" => "application/smil+xml",
58    "pls" => "application/pls+xml",
59    _ => "application/octet-stream",
60  }
61}
62
63/// EPUB manifest builder.
64///
65/// Port of `LaTeXML::Post::Manifest::Epub`.
66pub struct EpubManifest {
67  site_directory:    String,
68  unique_identifier: Option<String>,
69}
70
71impl EpubManifest {
72  pub fn new(site_directory: &str) -> Self {
73    EpubManifest {
74      site_directory:    site_directory.to_string(),
75      unique_identifier: None,
76    }
77  }
78
79  /// Initialize the EPUB directory structure.
80  ///
81  /// Port of `Epub::initialize`.
82  pub fn initialize(&mut self) -> Result<(), String> {
83    let dir = &self.site_directory;
84
85    // 1. Create mimetype file
86    let mime_path = format!("{}/mimetype", dir);
87    fs::write(&mime_path, "application/epub+zip")
88      .map_err(|e| format!("Couldn't write mimetype: {}", e))?;
89
90    // 2. Create META-INF/container.xml
91    let meta_inf = format!("{}/META-INF", dir);
92    fs::create_dir_all(&meta_inf).map_err(|e| format!("Couldn't create META-INF: {}", e))?;
93    fs::write(format!("{}/container.xml", meta_inf), CONTAINER_XML)
94      .map_err(|e| format!("Couldn't write container.xml: {}", e))?;
95
96    // 3. Create OPS directory
97    let ops_dir = format!("{}/OPS", dir);
98    fs::create_dir_all(&ops_dir).map_err(|e| format!("Couldn't create OPS: {}", e))?;
99
100    // Generate a UUID for the publication
101    self.unique_identifier = Some(format!("urn:uuid:{}", generate_uuid()));
102
103    Ok(())
104  }
105
106  /// Port of `Epub::process`: the package for the content documents `documents` (their destinations, in reading
107  /// order) under `OPS/`, every other file there a resource, `content.opf` written unless the user supplied one.
108  pub fn process(&mut self, documents: &[PathBuf], title: Option<&str>) -> Result<(), String> {
109    self.initialize()?;
110    let ops = Path::new(&self.site_directory).join("OPS");
111    let spine: Vec<SpineEntry> = documents
112      .iter()
113      .map(|doc| {
114        let (has_math, has_svg, has_nav) = content_properties(doc);
115        let relative = doc.strip_prefix(&ops).unwrap_or(doc);
116        self.add_document(&relative.to_string_lossy(), has_math, has_svg, has_nav)
117      })
118      .collect();
119    // Epub::finalize: every non-XHTML file under OPS/, in name order.
120    let mut files = Vec::new();
121    collect_files(&ops, &mut files);
122    files.sort();
123    let resources: Vec<ResourceEntry> = files
124      .iter()
125      .filter_map(|path| {
126        // A manifest href is a URL: `/` separates its segments on every OS.
127        let href = path
128          .strip_prefix(&ops)
129          .ok()?
130          .to_string_lossy()
131          .replace(std::path::MAIN_SEPARATOR, "/");
132        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
133        // Perl `Manifest/Epub.pm` L205 skips `LaTeXML.cache`; ours and its SQLite side files likewise.
134        let cache = path
135          .file_name()
136          .and_then(|name| name.to_str())
137          .is_some_and(|name| name == "LaTeXML.cache" || crate::document::is_cache_file(name));
138        if ext == "xhtml" || href == "content.opf" || cache {
139          return None;
140        }
141        let media_type = core_media_type(ext);
142        if media_type == "application/octet-stream" {
143          crate::Info!(
144            "unexpected",
145            ext.to_lowercase(),
146            "resource '{}' is not of a core media type, assigning type application/octet-stream",
147            href
148          );
149        }
150        Some(ResourceEntry {
151          id: url_to_id(&href),
152          href,
153          media_type: media_type.to_string(),
154        })
155      })
156      .collect();
157    let content_path = ops.join("content.opf");
158    if content_path.is_file() {
159      crate::Info!(
160        "note",
161        "content.opf",
162        "using the manifest supplied by the user"
163      );
164      return Ok(());
165    }
166    // Perl reads the title from the ObjectDB's SITE_ROOT entry, which carries no authors or language.
167    let opf = self.generate_opf(title.unwrap_or("No Title"), &[], "en", &spine, &resources);
168    fs::write(&content_path, opf).map_err(|e| format!("Couldn't write content.opf: {e}"))
169  }
170
171  /// Add a document to the EPUB spine; `href` is its path relative to `OPS/`.
172  ///
173  /// Port of `Epub::process` per-document loop.
174  pub fn add_document(
175    &self,
176    href: &str,
177    has_math: bool,
178    has_svg: bool,
179    has_nav: bool,
180  ) -> SpineEntry {
181    let href = href.replace(std::path::MAIN_SEPARATOR, "/");
182    let mut properties = Vec::new();
183    if has_math {
184      properties.push("mathml");
185    }
186    if has_svg {
187      properties.push("svg");
188    }
189    if has_nav {
190      properties.push("nav");
191    }
192
193    SpineEntry {
194      id: url_to_id(&href),
195      href,
196      media_type: "application/xhtml+xml".to_string(),
197      properties: if properties.is_empty() {
198        None
199      } else {
200        Some(properties.join(" "))
201      },
202    }
203  }
204
205  /// Generate the content.opf package document.
206  ///
207  /// Port of `Epub::finalize`. Built through the libxml DOM rather than by
208  /// `push_str`, because an OPF is parsed by strict readers: one unescaped `&`
209  /// in a single `href` invalidates the whole package, not one entry.
210  ///
211  /// That was reachable. `href` is `format!("{}.{}", name, ext)` over a split
212  /// document's file stem, and `--splitnaming=label` takes that stem from the
213  /// author's `\label{...}` — `\label{Fisher&Yates}` really does produce a file
214  /// named `Fisher&Yates.xhtml`. The old builder escaped 2 of 12 interpolated
215  /// values and `href` was not one of them. libxml escapes on set, so the
216  /// question no longer arises for any of them. (Issue 386 item 2.)
217  pub fn generate_opf(
218    &self,
219    title: &str,
220    authors: &[String],
221    language: &str,
222    spine: &[SpineEntry],
223    resources: &[ResourceEntry],
224  ) -> String {
225    let uid = self
226      .unique_identifier
227      .as_deref()
228      .unwrap_or("urn:uuid:00000000-0000-0000-0000-000000000000");
229
230    match self.build_opf_dom(title, authors, language, uid, spine, resources) {
231      Ok(xml) => xml,
232      // A DOM allocation failure is not something a caller can act on, and an
233      // empty package is a clearer failure than a half-built one.
234      Err(e) => {
235        crate::Error!(
236          "epub",
237          "opf",
238          "Couldn't build the EPUB package document: {}",
239          e
240        );
241        String::new()
242      },
243    }
244  }
245
246  fn build_opf_dom(
247    &self,
248    title: &str,
249    authors: &[String],
250    language: &str,
251    uid: &str,
252    spine: &[SpineEntry],
253    resources: &[ResourceEntry],
254  ) -> Result<String, String> {
255    use libxml::tree::{Document as XmlDoc, Namespace, Node};
256
257    let mut doc = XmlDoc::new().map_err(|_| "couldn't create the OPF document".to_string())?;
258
259    let mut package = Node::new("package", None, &doc).map_err(ctx("<package>"))?;
260    let opf_ns = Namespace::new("", OPF_NS, &mut package).map_err(ctx("the OPF namespace"))?;
261    package
262      .set_namespace(&opf_ns)
263      .map_err(ctx("the OPF namespace"))?;
264    package
265      .set_attribute("unique-identifier", "pub-id")
266      .map_err(ctx("@unique-identifier"))?;
267    package
268      .set_attribute("version", "3.0")
269      .map_err(ctx("@version"))?;
270    doc.set_root_element(&package);
271
272    // ---- metadata ----
273    let mut metadata = Node::new("metadata", None, &doc).map_err(ctx("<metadata>"))?;
274    // `dc:` is declared HERE, matching the shape readers expect, and the
275    // Dublin Core children below are created in it.
276    let dc_ns = Namespace::new("dc", DC_NS, &mut metadata).map_err(ctx("the dc namespace"))?;
277    package
278      .add_child(&mut metadata)
279      .map_err(ctx("<metadata>"))?;
280
281    // A closure would hold `metadata` borrowed across every call, so the
282    // Dublin Core children are appended inline through one small helper.
283    fn dc_child(
284      doc: &XmlDoc,
285      dc_ns: &Namespace,
286      metadata: &mut Node,
287      name: &str,
288      text: &str,
289    ) -> Result<Node, String> {
290      let mut n = Node::new(name, Some(dc_ns.clone()), doc).map_err(ctx(name))?;
291      n.set_content(text).map_err(ctx(name))?;
292      metadata.add_child(&mut n).map_err(ctx(name))?;
293      Ok(n)
294    }
295    dc_child(&doc, &dc_ns, &mut metadata, "title", title)?;
296    for author in authors {
297      dc_child(&doc, &dc_ns, &mut metadata, "creator", author)?;
298    }
299    dc_child(&doc, &dc_ns, &mut metadata, "language", language)?;
300
301    let mut modified = Node::new("meta", None, &doc).map_err(ctx("<meta>"))?;
302    modified
303      .set_attribute("property", "dcterms:modified")
304      .map_err(ctx("@property"))?;
305    modified
306      .set_content(&chrono_like_now())
307      .map_err(ctx("<meta>"))?;
308    metadata.add_child(&mut modified).map_err(ctx("<meta>"))?;
309
310    let mut identifier = dc_child(&doc, &dc_ns, &mut metadata, "identifier", uid)?;
311    identifier
312      .set_attribute("id", "pub-id")
313      .map_err(ctx("@id"))?;
314
315    // ---- manifest ----
316    let mut manifest = Node::new("manifest", None, &doc).map_err(ctx("<manifest>"))?;
317    package
318      .add_child(&mut manifest)
319      .map_err(ctx("<manifest>"))?;
320    let mut item =
321      |id: &str, href: &str, media_type: &str, properties: Option<&str>| -> Result<(), String> {
322        let mut n = Node::new("item", None, &doc).map_err(ctx("<item>"))?;
323        n.set_attribute("id", id).map_err(ctx("@id"))?;
324        n.set_attribute("href", href).map_err(ctx("@href"))?;
325        n.set_attribute("media-type", media_type)
326          .map_err(ctx("@media-type"))?;
327        if let Some(props) = properties {
328          n.set_attribute("properties", props)
329            .map_err(ctx("@properties"))?;
330        }
331        manifest.add_child(&mut n).map_err(ctx("<item>"))
332      };
333    for entry in spine {
334      item(
335        &entry.id,
336        &entry.href,
337        &entry.media_type,
338        entry.properties.as_deref(),
339      )?;
340    }
341    for res in resources {
342      item(&res.id, &res.href, &res.media_type, None)?;
343    }
344
345    // ---- spine ----
346    let mut spine_el = Node::new("spine", None, &doc).map_err(ctx("<spine>"))?;
347    package.add_child(&mut spine_el).map_err(ctx("<spine>"))?;
348    for entry in spine {
349      let mut itemref = Node::new("itemref", None, &doc).map_err(ctx("<itemref>"))?;
350      itemref
351        .set_attribute("idref", &entry.id)
352        .map_err(ctx("@idref"))?;
353      spine_el.add_child(&mut itemref).map_err(ctx("<itemref>"))?;
354    }
355
356    Ok(doc.to_string())
357  }
358}
359
360/// An entry in the EPUB spine (content document).
361#[derive(Debug)]
362pub struct SpineEntry {
363  pub id:         String,
364  pub href:       String,
365  pub media_type: String,
366  pub properties: Option<String>,
367}
368
369/// A resource entry (CSS, images, fonts).
370#[derive(Debug)]
371pub struct ResourceEntry {
372  pub id:         String,
373  pub href:       String,
374  pub media_type: String,
375}
376
377/// Convert a URL/filename to a valid NCName for use as an XML id.
378///
379/// Port of `url_id`: a character outside NCName becomes `_xN_` (N its uppercase hex codepoint), and an `_` that
380/// opens such a sequence is itself escaped first.
381fn url_to_id(name: &str) -> String {
382  let chars: Vec<char> = name.chars().collect();
383  let mut result = String::from("_");
384  for (i, &ch) in chars.iter().enumerate() {
385    if ch == '_' && opens_escape(&chars[i + 1..]) {
386      result.push_str("_x5F_");
387    } else if is_ncname_char(ch) {
388      result.push(ch);
389    } else {
390      result.push_str(&format!("_x{:X}_", ch as u32));
391    }
392  }
393  result
394}
395
396/// Whether `rest` (the text after an `_`) reads `x<HEX>+_`, Perl's `_(x[0-9A-F]+)(?=_)`.
397fn opens_escape(rest: &[char]) -> bool {
398  let hex = rest
399    .iter()
400    .skip(1)
401    .take_while(|c| matches!(c, '0'..='9' | 'A'..='F'))
402    .count();
403  rest.first() == Some(&'x') && hex > 0 && rest.get(1 + hex) == Some(&'_')
404}
405
406/// The NCName character class of Perl's `url_id`.
407fn is_ncname_char(ch: char) -> bool {
408  matches!(ch,
409    'A'..='Z' | '_' | 'a'..='z' | '-' | '.' | '0'..='9' | '\u{B7}'
410    | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}' | '\u{300}'..='\u{36F}'
411    | '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}' | '\u{203F}'..='\u{2040}'
412    | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}' | '\u{F900}'..='\u{FDCF}'
413    | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
414}
415
416/// The OPF item properties of a content document: (MathML, SVG, the navigation TOC), Perl `Epub::process`.
417fn content_properties(path: &Path) -> (bool, bool, bool) {
418  let Ok(doc) = libxml::parser::Parser::default().parse_file(&path.to_string_lossy()) else {
419    return (false, false, false);
420  };
421  let Ok(mut xpath) = libxml::xpath::Context::new(&doc) else {
422    return (false, false, false);
423  };
424  let mut has = |query: &str| {
425    xpath
426      .findnodes(query, None)
427      .is_ok_and(|nodes| !nodes.is_empty())
428  };
429  (
430    has(r#"//*[local-name() = "math"]"#),
431    has(r#"//*[local-name() = "svg"]"#),
432    has(r#"//*[@class="ltx_toclist"]"#),
433  )
434}
435
436/// Every file under `dir`, recursively.
437fn collect_files(dir: &Path, files: &mut Vec<PathBuf>) {
438  let Ok(entries) = fs::read_dir(dir) else {
439    return;
440  };
441  for entry in entries.flatten() {
442    let path = entry.path();
443    if path.is_dir() {
444      collect_files(&path, files);
445    } else if path.is_file() {
446      files.push(path);
447    }
448  }
449}
450
451/// The text content of `node` without its `ltx:indexmark`s (Perl Scan.pm `cleanNode`, then `textContent`); the
452/// serializer's indentation (blank text in element-only content) is not text.
453fn text_without_indexmarks(node: &libxml::tree::Node) -> String {
454  use libxml::tree::NodeType;
455  let is_text = |n: &libxml::tree::Node| {
456    matches!(
457      n.get_type(),
458      Some(NodeType::TextNode | NodeType::CDataSectionNode)
459    )
460  };
461  let mixed = node
462    .get_child_nodes()
463    .iter()
464    .any(|n| is_text(n) && !n.get_content().trim().is_empty());
465  let mut text = String::new();
466  let mut child = node.get_first_child();
467  while let Some(current) = child {
468    if is_text(&current) && !mixed {
469      child = current.get_next_sibling();
470      continue;
471    }
472    match current.get_type() {
473      Some(NodeType::ElementNode) if !name_is(&current, "indexmark") => {
474        text.push_str(&text_without_indexmarks(&current));
475      },
476      Some(NodeType::TextNode | NodeType::CDataSectionNode) => {
477        text.push_str(&current.get_content());
478      },
479      _ => {},
480    }
481    child = current.get_next_sibling();
482  }
483  text
484}
485
486/// The parts of the core XML an EPUB needs before post-processing.
487pub struct EpubSource {
488  /// The core XML with a navigation TOC, when `check_toc` had to add one.
489  pub xml:   Option<String>,
490  /// The document's title text (Scan's `cleanNode`: its index marks removed).
491  pub title: Option<String>,
492}
493
494/// Port of `LaTeXML.pm` `check_TOC` (an EPUB requires a TOC: add a full, undisplayed one unless the document has
495/// one) together with the title the manifest reads from the document.
496pub fn prepare_source(core_xml: &str) -> Result<EpubSource, String> {
497  const LTX_NS: &str = "http://dlmf.nist.gov/LaTeXML";
498  let doc = libxml::parser::Parser::default()
499    .parse_string(core_xml)
500    .map_err(|e| format!("couldn't parse the document: {e:?}"))?;
501  let mut root = doc
502    .get_root_element()
503    .ok_or("the document has no root element")?;
504  let mut xpath =
505    libxml::xpath::Context::new(&doc).map_err(|_| "couldn't create an XPath context")?;
506  xpath
507    .register_namespace("ltx", LTX_NS)
508    .map_err(|_| "couldn't register the ltx namespace")?;
509  let title = xpath
510    .findnodes("/*/ltx:title", None)
511    .ok()
512    .and_then(|nodes| nodes.into_iter().next())
513    .map(|title| text_without_indexmarks(&title));
514  let has_toc = xpath
515    .findnodes(r#"//ltx:TOC[@lists="toc"]"#, None)
516    .is_ok_and(|nodes| !nodes.is_empty());
517  let xml = if has_toc {
518    None
519  } else {
520    let ns = root.get_namespace();
521    let mut toc = libxml::tree::Node::new("TOC", ns, &doc).map_err(ctx("<TOC>"))?;
522    for (name, value) in [
523      ("lists", "toc"),
524      ("scope", "global"),
525      (
526        "select",
527        "ltx:part | ltx:chapter | ltx:section | ltx:subsection | ltx:subsubsection | ltx:paragraph | \
528         ltx:subparagraph | ltx:appendix | ltx:index | ltx:bibliography",
529      ),
530      ("class", "ltx_nodisplay"),
531    ] {
532      toc
533        .set_attribute(name, value)
534        .map_err(ctx("a TOC attribute"))?;
535    }
536    match root.get_first_child() {
537      Some(mut first) => first.add_prev_sibling(&mut toc).map_err(ctx("<TOC>"))?,
538      None => root.add_child(&mut toc).map(|_| ()).map_err(ctx("<TOC>"))?,
539    };
540    Some(doc.to_string())
541  };
542  Ok(EpubSource { xml, title })
543}
544
545/// Generate a UUID v4 string.
546fn generate_uuid() -> String {
547  // Simple random UUID v4 (no external dependency)
548  use std::time::{SystemTime, UNIX_EPOCH};
549  let seed = SystemTime::now()
550    .duration_since(UNIX_EPOCH)
551    .unwrap_or_default()
552    .as_nanos();
553  // LCG-based pseudo-random for simplicity
554  let mut state = seed as u64;
555  let mut bytes = [0u8; 16];
556  for b in &mut bytes {
557    state = state
558      .wrapping_mul(6364136223846793005)
559      .wrapping_add(1442695040888963407);
560    *b = (state >> 33) as u8;
561  }
562  bytes[6] = (bytes[6] & 0x0F) | 0x40; // version 4
563  bytes[8] = (bytes[8] & 0x3F) | 0x80; // variant 1
564  format!(
565    "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
566    bytes[0],
567    bytes[1],
568    bytes[2],
569    bytes[3],
570    bytes[4],
571    bytes[5],
572    bytes[6],
573    bytes[7],
574    bytes[8],
575    bytes[9],
576    bytes[10],
577    bytes[11],
578    bytes[12],
579    bytes[13],
580    bytes[14],
581    bytes[15]
582  )
583}
584
585/// Generate an ISO 8601 timestamp (CCYY-MM-DDThh:mm:ssZ), at `SOURCE_DATE_EPOCH` when set (Perl Epub.pm).
586fn chrono_like_now() -> String {
587  use std::time::{SystemTime, UNIX_EPOCH};
588  let secs = std::env::var("SOURCE_DATE_EPOCH")
589    .ok()
590    .and_then(|s| s.trim().parse::<u64>().ok())
591    .unwrap_or_else(|| {
592      SystemTime::now()
593        .duration_since(UNIX_EPOCH)
594        .unwrap_or_default()
595        .as_secs()
596    });
597  // Simple UTC timestamp computation (no chrono dependency)
598  let days = secs / 86400;
599  let time_of_day = secs % 86400;
600  let hours = time_of_day / 3600;
601  let minutes = (time_of_day % 3600) / 60;
602  let seconds = time_of_day % 60;
603  // Rough date from epoch days (good enough for timestamps)
604  let (year, month, day) = days_to_ymd(days as i64);
605  format!(
606    "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
607    year, month, day, hours, minutes, seconds
608  )
609}
610
611/// Convert days since Unix epoch to (year, month, day).
612fn days_to_ymd(days: i64) -> (i64, u32, u32) {
613  // Algorithm from https://howardhinnant.github.io/date_algorithms.html
614  let z = days + 719468;
615  let era = if z >= 0 { z } else { z - 146096 } / 146097;
616  let doe = (z - era * 146097) as u32;
617  let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
618  let y = yoe as i64 + era * 400;
619  let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
620  let mp = (5 * doy + 2) / 153;
621  let d = doy - (153 * mp + 2) / 5 + 1;
622  let m = if mp < 10 { mp + 3 } else { mp - 9 };
623  (y + if m <= 2 { 1 } else { 0 }, m, d)
624}
625
626#[cfg(test)]
627mod tests {
628  use super::*;
629
630  fn spine_entry(id: &str, href: &str, properties: Option<&str>) -> SpineEntry {
631    SpineEntry {
632      id:         id.to_string(),
633      href:       href.to_string(),
634      media_type: "application/xhtml+xml".to_string(),
635      properties: properties.map(str::to_string),
636    }
637  }
638
639  /// The package document must be well-formed for **author-controlled** input.
640  ///
641  /// Issue 386 item 2. An OPF is read by strict parsers, so one unescaped `&`
642  /// invalidates the whole book rather than one entry — and `&` is reachable:
643  /// `href` is built from a split document's file stem, and `--splitnaming=label`
644  /// takes that stem from the author's `\label{...}`, so `\label{Fisher&Yates}`
645  /// yields a file named `Fisher&Yates.xhtml`. The old `push_str` builder escaped
646  /// 2 of 12 interpolated values and `href` was not among them.
647  ///
648  /// The assertion is deliberately "it parses", not "it contains `&amp;`":
649  /// well-formedness is the property that matters, and it cannot be satisfied by
650  /// accident.
651  #[test]
652  fn opf_stays_well_formed_when_author_input_carries_xml_specials() {
653    let mut manifest = EpubManifest::new("/tmp/does-not-need-to-exist");
654    manifest.unique_identifier = Some("urn:uuid:test".to_string());
655
656    let spine = vec![
657      spine_entry(
658        "_Fisher_x26_Yates.xhtml",
659        "Fisher&Yates.xhtml",
660        Some("mathml"),
661      ),
662      spine_entry("_quote_x22_.xhtml", "a\"quote\".xhtml", None),
663      spine_entry("_lt_x3C_.xhtml", "a<less>.xhtml", None),
664    ];
665    let resources = vec![ResourceEntry {
666      id:         "_css".to_string(),
667      href:       "LaTeXML&core.css".to_string(),
668      media_type: "text/css".to_string(),
669    }];
670
671    let opf = manifest.generate_opf(
672      "Tom & Jerry: a <study> of \"conflict\"",
673      &["Ampersand & Co.".to_string()],
674      "en",
675      &spine,
676      &resources,
677    );
678
679    let parser = libxml::parser::Parser::default();
680    let doc = parser.parse_string(&opf).unwrap_or_else(|e| {
681      panic!("the OPF is not well-formed XML ({e:?}) — an unescaped special reached it:\n{opf}")
682    });
683    let root = doc.get_root_element().expect("a root element");
684    assert_eq!(root.get_name(), "package");
685
686    // The values must round-trip to their ORIGINAL text, not to an escaped or
687    // truncated form — well-formedness alone would also be satisfied by dropping
688    // the offending characters.
689    let hrefs: Vec<String> = crate::document::element_children(
690      &crate::document::element_children(&root)
691        .into_iter()
692        .find(|n| name_is(n, "manifest"))
693        .expect("a <manifest>"),
694    )
695    .iter()
696    .filter_map(|n| n.get_attribute("href"))
697    .collect();
698    assert!(
699      hrefs.iter().any(|h| h == "Fisher&Yates.xhtml"),
700      "the ampersand href did not survive the round-trip: {hrefs:?}"
701    );
702    assert!(
703      hrefs.iter().any(|h| h == "a\"quote\".xhtml") && hrefs.iter().any(|h| h == "a<less>.xhtml"),
704      "a quote/less-than href did not survive the round-trip: {hrefs:?}"
705    );
706    assert!(
707      hrefs.iter().any(|i| i == "LaTeXML&core.css"),
708      "a RESOURCE href is interpolated by the same code path and must be escaped too: {hrefs:?}"
709    );
710  }
711
712  /// Perl `url_id`: NCName letters beyond ASCII stay, an `_` opening an `_xN_` is escaped.
713  #[test]
714  fn url_id_follows_perl() {
715    assert_eq!(
716      url_to_id("Gödel_x41_ a.xhtml"),
717      "_Gödel_x5F_x41__x20_a.xhtml"
718    );
719  }
720
721  /// Structure the readers rely on, so the DOM rewrite cannot quietly drop a
722  /// required element or attribute.
723  #[test]
724  fn opf_carries_the_structure_epub_readers_require() {
725    let mut manifest = EpubManifest::new("/tmp/does-not-need-to-exist");
726    manifest.unique_identifier = Some("urn:uuid:abc".to_string());
727    let spine = vec![spine_entry("_a.xhtml", "a.xhtml", Some("nav"))];
728
729    let opf = manifest.generate_opf("T", &["A".to_string()], "en", &spine, &[]);
730    let parser = libxml::parser::Parser::default();
731    let doc = parser.parse_string(&opf).expect("well-formed");
732    let root = doc.get_root_element().expect("root");
733
734    assert_eq!(root.get_attribute("version").as_deref(), Some("3.0"));
735    assert_eq!(
736      root.get_attribute("unique-identifier").as_deref(),
737      Some("pub-id")
738    );
739
740    let kids = crate::document::element_children(&root);
741    let names: Vec<String> = kids.iter().map(|n| n.get_name()).collect();
742    assert_eq!(
743      names,
744      vec!["metadata", "manifest", "spine"],
745      "OPF child order"
746    );
747
748    // The identifier the package points at must actually carry that id.
749    let meta = kids.iter().find(|n| name_is(n, "metadata")).unwrap();
750    let ident = crate::document::element_children(meta)
751      .into_iter()
752      .find(|n| n.with_attribute(c"id", |v| v == "pub-id") == Some(true))
753      .expect("a <dc:identifier id='pub-id'>");
754    assert_eq!(ident.get_content(), "urn:uuid:abc");
755
756    // `properties` is optional and must be emitted only when present.
757    let item =
758      crate::document::element_children(kids.iter().find(|n| name_is(n, "manifest")).unwrap())
759        .into_iter()
760        .next()
761        .expect("an <item>");
762    assert_eq!(item.get_attribute("properties").as_deref(), Some("nav"));
763
764    let itemref =
765      crate::document::element_children(kids.iter().find(|n| name_is(n, "spine")).unwrap())
766        .into_iter()
767        .next()
768        .expect("an <itemref>");
769    assert_eq!(itemref.get_attribute("idref").as_deref(), Some("_a.xhtml"));
770  }
771}