Skip to main content

latexml_post/
xslt.rs

1//! XSLT transformation processor.
2//!
3//! Port of `LaTeXML::Post::XSLT`.
4//! Applies an XSLT stylesheet to transform the document (e.g., LaTeXML XML → HTML5).
5//! Handles CSS/JS/icon resource copying.
6
7use std::{
8  cell::{Cell, RefCell},
9  collections::HashSet,
10  fs,
11  path::{Path, PathBuf},
12  sync::LazyLock,
13};
14
15use latexml_core::{
16  document::resource::{BINDING_RESOURCE_CLASS, is_remote},
17  util::pathname,
18};
19use libxml::tree::{Namespace, Node, NodeType};
20use regex::Regex;
21use rustc_hash::FxHashMap as HashMap;
22
23use crate::{
24  document::{PostDocument, PostDocumentOptions},
25  processor::{PostError, ProcessResult, Processor},
26};
27
28/// Set libxslt's global template-recursion cap to Perl's value (1000) exactly
29/// once per process. Mirrors `XML::LibXSLT->max_depth(1000)` in
30/// `LaTeXML::Post::XSLT`. Prevents deeply-recursive stylesheet templates from
31/// exhausting the C call stack (SIGSEGV) or RAM on pathological documents,
32/// aborting the transform gracefully like Perl instead.
33fn set_xslt_max_depth() {
34  static SET_MAX_DEPTH: std::sync::Once = std::sync::Once::new();
35  SET_MAX_DEPTH.call_once(|| {
36    // SAFETY: `xsltMaxDepth` is libxslt's process-global recursion cap
37    // (a plain C `int`, declared below with its C type). The libxslt crate
38    // exposes no safe setter. `Once` guarantees a single writer; libxslt only
39    // ever READS this value (when creating each transform context), so there
40    // is no data race with concurrent transforms.
41    #[cfg(any(unix, windows))]
42    unsafe {
43      xsltMaxDepth = 1000;
44    }
45    // Any other platform: skip the write; libxslt's built-in default cap
46    // of 3000 still bounds recursion, just above Perl's 1000.
47  });
48}
49
50// libxslt's recursion cap (`XSLTPUBVAR int xsltMaxDepth`), declared here rather
51// than taken from the crate's `libxslt::bindings::xsltMaxDepth`. Those
52// pregenerated (bindgen-on-Linux) bindings pin the raw ELF symbol name with
53// `#[link_name = "\u{1}xsltMaxDepth"]`, which fails to LINK on Mach-O where the
54// C symbol is `_xsltMaxDepth` (macOS probe 2026-06-07 — the sole undefined
55// symbol in the whole workspace link; see
56// docs/archive/PORTABILITY_MACOS_PROBE_2026-06-07.md, WISDOM #56). A plain
57// declaration gets the platform's own C-symbol decoration from rustc on ELF and
58// Mach-O, dynamic or static, and on x64 COFF for the static vcpkg libxslt we
59// link there (a DLL's data would need a `dllimport`, `#[link(kind = "dylib")]`);
60// the libxslt crate's build script already puts the library on the link line.
61//
62// The reference is resolved at LINK time. The runtime lookup it replaces on
63// unix, `dlsym(RTLD_DEFAULT, "xsltMaxDepth")`, only searches DYNAMIC symbol
64// tables, so it silently skipped the write — leaving libxslt's 3000 — whenever
65// the symbol was not in one: libxslt linked statically (the `LIBXSLT_STATIC`
66// release binary, where the executable does not export the global), or not
67// loaded at all (the `latexml_post` unit-test binary with dependencies at
68// opt-level 1, whose live code has no other libxslt reference, so the linker's
69// `--as-needed` dropped the library). A static libxslt 1.1.42 (the release
70// build's, tools/build_static_libxml.sh) linked into a C program: `dlsym` NULL,
71// the linked global 3000. `GetProcAddress` fails on Windows' static vcpkg
72// libxslt for the same reason (WINDOWS_COMPATIBILITY_PLAN Phase 2.3).
73#[cfg(any(unix, windows))]
74#[allow(non_upper_case_globals)]
75unsafe extern "C" {
76  static mut xsltMaxDepth: std::os::raw::c_int;
77}
78
79#[cfg(all(test, any(unix, windows)))]
80mod max_depth_tests {
81  use crate::{
82    document::{PostDocument, PostDocumentOptions},
83    processor::Processor,
84  };
85
86  /// The write lands in the global libxslt reads: after `set_xslt_max_depth`
87  /// it holds Perl's value (1000), not libxslt's compiled-in 3000.
88  #[test]
89  fn extern_static_sets_perl_parity_cap() {
90    super::set_xslt_max_depth();
91    // SAFETY: a by-value read of the process-global int after the Once-guarded
92    // write; the declaration matches libxslt's C type.
93    let val = unsafe { super::xsltMaxDepth };
94    assert_eq!(val, 1000);
95  }
96
97  /// A named template that calls itself `$n` times, applied through the
98  /// production `XSLT::process` path (which sets the cap under `XSLT_LOCK`).
99  /// libxslt spends two depth units per level of this template (measured:
100  /// `xsltproc --maxdepth 1000` aborts from n = 499, the default 3000 from
101  /// n = 1499).
102  fn apply_recursion(n: u32) -> bool {
103    const RECURSION_XSL: &str = r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
104  <xsl:param name="n" select="0"/>
105  <xsl:template match="/">
106    <out><xsl:call-template name="down"><xsl:with-param name="k" select="$n"/></xsl:call-template></out>
107  </xsl:template>
108  <xsl:template name="down">
109    <xsl:param name="k"/>
110    <xsl:if test="$k &gt; 0">
111      <xsl:call-template name="down"><xsl:with-param name="k" select="$k - 1"/></xsl:call-template>
112    </xsl:if>
113  </xsl:template>
114</xsl:stylesheet>
115"#;
116    let dir = tempfile::tempdir().expect("tempdir");
117    let xsl = dir.path().join("recursion.xsl");
118    std::fs::write(&xsl, RECURSION_XSL).expect("write recursion.xsl");
119    let mut params = rustc_hash::FxHashMap::default();
120    params.insert("n".to_string(), n.to_string());
121    let mut xslt =
122      super::XSLT::new(xsl.to_str().unwrap(), params, true, None, vec![]).expect("XSLT processor");
123    let doc =
124      PostDocument::new_from_string("<a/>", PostDocumentOptions::default()).expect("parse <a/>");
125    xslt.process(doc, vec![]).is_ok()
126  }
127
128  /// End to end: a transform recursing past Perl's cap but within libxslt's
129  /// default aborts, so the cap is the one libxslt applies; a shallower one
130  /// completes, so the abort is the cap and not the stylesheet.
131  #[test]
132  fn transform_aborts_past_perls_recursion_depth() {
133    assert!(
134      apply_recursion(400),
135      "a 400-level recursion (800 of 1000 depth units) must transform"
136    );
137    let (completed, libxslt_says) = with_fd2_captured(|| apply_recursion(700));
138    assert!(
139      !completed,
140      "a 700-level recursion (1400 depth units) must abort at Perl's cap of 1000, \
141       not run on to libxslt's default of 3000"
142    );
143    if let Some(said) = libxslt_says {
144      assert!(
145        said.contains("potential infinite template recursion"),
146        "{said}"
147      );
148    }
149  }
150
151  /// Run `f` with file descriptor 2 pointed at a temporary file, and return what
152  /// was written there: libxslt reports the aborted recursion (and its template
153  /// stack) with C `fprintf(stderr, …)`, below any Rust output capture, so without
154  /// this the report would reach the terminal of whoever runs the suite.
155  #[cfg(unix)]
156  fn with_fd2_captured<T>(f: impl FnOnce() -> T) -> (T, Option<String>) {
157    use std::{
158      io::{Read, Seek},
159      os::fd::OwnedFd,
160    };
161    /// Points fd 2 back at its saved copy when dropped — on a panic in `f` too; the copy closes after.
162    struct Restore(OwnedFd);
163    impl Drop for Restore {
164      fn drop(&mut self) { let _ = rustix::stdio::dup2_stderr(&self.0); }
165    }
166    let mut sink = tempfile::tempfile().expect("tempfile");
167    let restore = Restore(rustix::io::dup(std::io::stderr()).expect("dup(2)"));
168    rustix::stdio::dup2_stderr(&sink).expect("dup2 onto fd 2");
169    let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
170    drop(restore);
171    let mut text = String::new();
172    sink.rewind().expect("rewind");
173    sink.read_to_string(&mut text).expect("read captured fd 2");
174    match out {
175      Ok(out) => (out, Some(text)),
176      Err(panic) => {
177        // The panic message went to the captured fd 2: show it before unwinding on.
178        eprint!("{text}");
179        std::panic::resume_unwind(panic)
180      },
181    }
182  }
183  #[cfg(not(unix))]
184  fn with_fd2_captured<T>(f: impl FnOnce() -> T) -> (T, Option<String>) { (f(), None) }
185}
186
187#[cfg(test)]
188mod local_stylesheet_tests {
189  use crate::{
190    document::{PostDocument, PostDocumentOptions},
191    processor::Processor,
192  };
193
194  fn marker_xsl(marker: &str) -> String {
195    format!(
196      r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
197  <xsl:template match="/"><out>{marker}</out></xsl:template>
198</xsl:stylesheet>
199"#
200    )
201  }
202
203  fn apply(xsl: &std::path::Path) -> String {
204    let mut xslt = super::XSLT::new(
205      xsl.to_str().unwrap(),
206      Default::default(),
207      true,
208      None,
209      vec![],
210    )
211    .expect("XSLT");
212    let doc = PostDocument::new_from_string("<a/>", PostDocumentOptions::default()).expect("<a/>");
213    let out = xslt.process(doc, vec![]).expect("transform");
214    out[0].to_xml_string()
215  }
216
217  /// #806: a `--stylesheet` path naming a file on disk is that file, even when its basename is
218  /// one of the embedded engine sheets; so is an engine-named sibling a user sheet imports.
219  #[test]
220  fn a_stylesheet_on_disk_wins_over_the_embedded_copy() {
221    let dir = tempfile::tempdir().expect("tempdir");
222    let html5 = dir.path().join("LaTeXML-html5.xsl");
223    std::fs::write(&html5, marker_xsl("LOCAL-HTML5")).unwrap();
224    assert!(apply(&html5).contains("<out>LOCAL-HTML5</out>"));
225
226    let common = dir.path().join("LaTeXML-common.xsl");
227    std::fs::write(&common, marker_xsl("LOCAL-COMMON")).unwrap();
228    let mine = dir.path().join("mine.xsl");
229    std::fs::write(
230      &mine,
231      r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
232  <xsl:import href="LaTeXML-common.xsl"/>
233</xsl:stylesheet>
234"#,
235    )
236    .unwrap();
237    assert!(apply(&mine).contains("<out>LOCAL-COMMON</out>"));
238  }
239
240  /// #806: a user's sheet in a directory whose name needs escaping still imports its sibling from
241  /// disk; an absolute or `file:` URL names the file, a relative or bare engine name never does
242  /// (the default stylesheet's imports cannot be replaced by a copy in the cwd).
243  #[test]
244  fn only_a_named_file_is_read_from_disk() {
245    let dir = tempfile::tempdir().expect("tempdir");
246    let spaced = dir.path().join("a b");
247    std::fs::create_dir(&spaced).unwrap();
248    let common = spaced.join("LaTeXML-common.xsl");
249    std::fs::write(&common, marker_xsl("SPACED-COMMON")).unwrap();
250    let mine = spaced.join("mine.xsl");
251    std::fs::write(
252      &mine,
253      r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
254  <xsl:import href="LaTeXML-common.xsl"/>
255</xsl:stylesheet>
256"#,
257    )
258    .unwrap();
259    assert!(apply(&mine).contains("<out>SPACED-COMMON</out>"));
260
261    // A path as a `file:` URL's path: `/`-separated and rooted, `/C:/…` on Windows (`file:///C:/…`).
262    let file_url_path = |path: &std::path::Path| {
263      let path = path.to_str().unwrap().replace('\\', "/");
264      if path.starts_with('/') {
265        path
266      } else {
267        format!("/{path}")
268      }
269    };
270    let abs = common.to_str().unwrap();
271    let escaped = file_url_path(&common).replace(' ', "%20");
272    for url in [
273      abs.to_string(),
274      format!("file://{escaped}"),
275      format!("file://localhost{escaped}"),
276      format!("file:{escaped}"),
277    ] {
278      assert!(super::embedded_xslt::resolve(&url).is_none(), "{url}");
279    }
280    // A literal `%` in a plain path is not an escape: the user's engine-named sheet and its sibling.
281    for name in ["100%", "%41"] {
282      let pct = dir.path().join(name);
283      std::fs::create_dir(&pct).unwrap();
284      let html5 = pct.join("LaTeXML-html5.xsl");
285      std::fs::write(&html5, marker_xsl("PCT-HTML5")).unwrap();
286      assert!(apply(&html5).contains("<out>PCT-HTML5</out>"), "{name}");
287      std::fs::write(pct.join("LaTeXML-common.xsl"), marker_xsl("PCT-COMMON")).unwrap();
288      std::fs::copy(&mine, pct.join("mine.xsl")).unwrap();
289      assert!(
290        apply(&pct.join("mine.xsl")).contains("<out>PCT-COMMON</out>"),
291        "{name}"
292      );
293      // In a `file:` URL the `%` is escaped.
294      let url = format!("file://{}", file_url_path(&html5).replace('%', "%25"));
295      // (`Path` equality is by component: Windows' `C:/…` is `C:\…`.)
296      assert_eq!(super::embedded_xslt::disk_path(&url), Some(html5), "{url}");
297    }
298    // A host other than localhost is a UNC share, which only Windows paths can name (the mapping
299    // alone: a share is no file of this host).
300    let unc = "file://server/share/a%20b/LaTeXML-common.xsl";
301    assert_eq!(
302      super::embedded_xslt::url_path(unc),
303      cfg!(windows).then(|| std::path::PathBuf::from("//server/share/a b/LaTeXML-common.xsl")),
304      "{unc}"
305    );
306    // Relative to this crate's directory, where the engine's own sources sit.
307    for url in [
308      "resources/XSLT/LaTeXML-all-xhtml.xsl",
309      "embed:///LaTeXML-html5.xsl",
310      "urn:x-LaTeXML:XSLT:LaTeXML-html5.xsl",
311    ] {
312      assert!(super::embedded_xslt::resolve(url).is_some(), "{url}");
313    }
314  }
315}
316
317/// Resource type information.
318struct ResourceInfo {
319  extension: &'static str,
320  subdir:    &'static str,
321}
322
323const RESOURCE_CSS: ResourceInfo = ResourceInfo {
324  extension: "css",
325  subdir:    "resources/CSS",
326};
327const RESOURCE_JS: ResourceInfo = ResourceInfo {
328  extension: "js",
329  subdir:    "resources/javascript",
330};
331
332/// XSLT post-processor: applies a stylesheet transformation.
333///
334/// Port of `LaTeXML::Post::XSLT`.
335pub struct XSLT {
336  name:               String,
337  /// Path to the XSLT stylesheet.
338  stylesheet_path:    Option<String>,
339  /// Parameters to pass to the XSLT stylesheet.
340  parameters:         HashMap<String, String>,
341  /// Whether to remove resource requests (CSS/JS not copied), a binding's remote style sheet kept (OD #1249).
342  no_resources:       bool,
343  /// Resource directory for copied resources.
344  resource_directory: Option<String>,
345  /// Search paths for finding resources.
346  searchpaths:        Vec<String>,
347  /// Whether a stand-in's twin becomes its `data-standin` attribute before the transform ([`standin_to_attribute`]).
348  standin_attribute:  bool,
349  /// The resources this processor already put in place, as (source, type, destination, whether its
350  /// `@import`s were followed too): a split run asks for the same CSS/JS on every page, and the search
351  /// (~35 `statx` a page) and the copy are made once per conversion (Nasser's 71,476-page document, #777
352  /// FAQ).
353  copied:             RefCell<HashSet<ResourceKey>>,
354}
355
356/// A placed resource: (source, type, destination, `@import`s followed).
357type ResourceKey = (String, Option<String>, String, bool);
358
359std::thread_local! {
360  static RESOURCE_COPIES: Cell<usize> = const { Cell::new(0) };
361}
362
363/// How many resource files this thread has copied or written into a destination (a test seam).
364pub fn resource_copy_count() -> usize { RESOURCE_COPIES.get() }
365fn note_resource_copy() { RESOURCE_COPIES.set(RESOURCE_COPIES.get() + 1); }
366
367impl XSLT {
368  pub fn new(
369    stylesheet: &str,
370    parameters: HashMap<String, String>,
371    no_resources: bool,
372    resource_directory: Option<String>,
373    searchpaths: Vec<String>,
374  ) -> Result<Self, PostError> {
375    if stylesheet.is_empty() {
376      // Perl XSLT.pm:36 — Error('expected', 'stylesheet', undef,
377      //   "No stylesheet specified!")
378      Error!("expected", "stylesheet", "No stylesheet specified!");
379      return Err(PostError::Processing(
380        "No stylesheet specified!".to_string(),
381      ));
382    }
383
384    // Find the stylesheet file
385    let stylesheet_path = match find_stylesheet(stylesheet, &searchpaths) {
386      Ok(p) => p,
387      Err(e) => {
388        // Perl XSLT.pm:42 — Error('missing-file', $stylesheet, undef,
389        //   "No stylesheet '$stylesheet' found!")
390        Error!(
391          "missing-file",
392          stylesheet,
393          "No stylesheet '{}' found!",
394          stylesheet
395        );
396        return Err(e);
397      },
398    };
399
400    // The html5 sheets turn a `data:` attribute into `data-*` (LaTeXML-common.xsl `USE_DATA_ATTRIBUTES`); epub
401    // (USE_HTML5 too) keeps the twin as text, as it links no remote style sheet (OD #1249).
402    let sheet = stylesheet
403      .rsplit(['/', '\\', ':'])
404      .next()
405      .unwrap_or(stylesheet);
406    let standin_attribute = matches!(sheet, "LaTeXML-html5.xsl" | "LaTeXML-xhtml5.xsl");
407    Ok(XSLT {
408      name: format!(
409        "XSLT[using {}]",
410        stylesheet
411          .strip_prefix(embedded_xslt::URL_PREFIX)
412          .unwrap_or(stylesheet)
413      ),
414      stylesheet_path: Some(stylesheet_path),
415      parameters,
416      no_resources,
417      resource_directory,
418      searchpaths,
419      standin_attribute,
420      copied: RefCell::default(),
421    })
422  }
423
424  /// Copy a resource file and return the path relative to the destination.
425  ///
426  /// Port of `XSLT::copyResource`.
427  fn copy_resource(&self, doc: &PostDocument, src: &str, resource_type: Option<&str>) -> String {
428    self.copy_resource_following(doc, src, resource_type, None)
429  }
430
431  /// [`copy_resource`](Self::copy_resource), and with `imports` (the `--css` route) also the copied CSS's local
432  /// `@import` chain (beyond Perl, [`copy_css_imports`]); `imports` dedups across one parameter's entries.
433  fn copy_resource_following(
434    &self,
435    doc: &PostDocument,
436    src: &str,
437    resource_type: Option<&str>,
438    imports: Option<&mut HashSet<PathBuf>>,
439  ) -> String {
440    // If it's a URL, return as-is
441    if is_remote(src) {
442      return src.to_string();
443    }
444
445    let info = match resource_type {
446      Some("text/css") => Some(&RESOURCE_CSS),
447      Some("text/javascript") => Some(&RESOURCE_JS),
448      _ => None,
449    };
450
451    // Try to find the file
452    let search_paths: Vec<&str> = doc
453      .get_search_paths()
454      .iter()
455      .chain(self.searchpaths.iter())
456      .map(String::as_str)
457      .collect();
458
459    let basename = Path::new(src)
460      .file_name()
461      .and_then(|f| f.to_str())
462      .unwrap_or(src);
463
464    // The path (relative to the destination base) the resource is copied to.
465    // Perl `copyResource`: with a `resource_directory`, flatten into it; otherwise
466    // PRESERVE the src's path relative to the source directory — provided it stays
467    // BELOW the destination (a plain relative path, not escaping via `../` or
468    // absolute), else flatten to the basename. So `subdir/foo.css` lands at
469    // `<dest>/subdir/foo.css`, matching the `<link>`/`<script>` href, instead of a
470    // flattened `foo.css` the tag can no longer resolve (#662).
471    let rel_dest: String = if self.resource_directory.is_some() {
472      basename.to_string()
473    } else {
474      let relpath = pathname::relative(src, doc.get_source_directory());
475      if relpath.starts_with("../") || Path::new(&relpath).is_absolute() {
476        basename.to_string()
477      } else {
478        relpath
479      }
480    };
481
482    // Determine destination once — same logic regardless of whether
483    // the resource ends up on disk or comes from the embedded table.
484    // `root` is the directory it is built on, which the copy and its `@import` copies stay in.
485    let (root, dest) = if let Some(ref rd) = self.resource_directory {
486      if let Some(site_dir) = doc.get_site_directory() {
487        (site_dir, format!("{}/{}/{}", site_dir, rd, rel_dest))
488      } else {
489        (rd.as_str(), format!("{}/{}", rd, rel_dest))
490      }
491    } else if let Some(base) = doc
492      .get_site_directory()
493      .or_else(|| doc.get_destination_directory())
494    {
495      (base, format!("{}/{}", base, rel_dest))
496    } else {
497      (".", rel_dest)
498    };
499    let ensure_parent = |dest: &str| {
500      if let Some(parent) = Path::new(dest).parent() {
501        let _ = fs::create_dir_all(parent);
502      }
503    };
504    let follows = imports.is_some() && info.is_some_and(|i| i.extension == "css");
505    let mut key = (
506      src.to_string(),
507      resource_type.map(str::to_string),
508      dest.clone(),
509      true,
510    );
511    // A copy whose imports were followed also serves a request that does not follow them.
512    let done = self.copied.borrow().contains(&key) || {
513      key.3 = follows;
514      self.copied.borrow().contains(&key)
515    };
516    if done {
517      return relative_to_destination(doc, dest);
518    }
519    // A symbolic link in the destination would carry the copy out of it (OXIDIZED_DESIGN_DIVERGENCES #1166).
520    if pathname::is_contained_resolved(&dest, root).is_none() {
521      Warn!(
522        "unexpected",
523        src,
524        "{} would be copied to {} outside {}; not copied",
525        src,
526        dest,
527        root
528      );
529      return src.to_string();
530    }
531    // A failed write (of the file or of an `@import`) warns and is retried on the next page, as before.
532    let mut placed = true;
533
534    match find_resource_file(src, info, &search_paths) {
535      Some((path, found_under)) => {
536        if crate::writer::same_file(&path, &dest) {
537          // The search-path match IS the destination: it is used as-is (Perl skips the copy, XSLT.pm:118) unless
538          // it is #312's empty leftover, which the embedded bytes repair.
539          if let Some(bytes) = embedded_resources::bundled(src, basename)
540            && crate::writer::needs_write(Path::new(&dest))
541          {
542            ensure_parent(&dest);
543            note_resource_copy();
544            if let Err(e) = crate::writer::write_atomic(Path::new(&dest), bytes) {
545              placed = false;
546              Warn!(
547                "I/O",
548                dest,
549                "Couldn't rewrite embedded {} to {}: {}",
550                basename,
551                dest,
552                e
553              );
554            }
555          }
556        } else {
557          ensure_parent(&dest);
558          note_resource_copy();
559          if let Err(e) = crate::writer::copy_atomic(Path::new(&path), Path::new(&dest)) {
560            placed = false;
561            Warn!("I/O", dest, "Couldn't copy {} to {}: {}", path, dest, e);
562          }
563        }
564        if let Some(seen) = imports
565          && follows
566        {
567          placed &= copy_css_imports(
568            Path::new(&path),
569            Path::new(&dest),
570            &Roots {
571              dest:   root,
572              source: &found_under,
573            },
574            seen,
575          );
576        }
577      },
578      None => {
579        // Not on disk — try the embedded table: CSS/JS assets baked into the binary, written straight to the
580        // destination unless a non-empty file is already there (a user's own, or an older release's, is kept; OD #1165).
581        if let Some(bytes) = embedded_resources::bundled(src, basename) {
582          if crate::writer::needs_write(Path::new(&dest)) {
583            ensure_parent(&dest);
584            note_resource_copy();
585            if let Err(e) = crate::writer::write_atomic(Path::new(&dest), bytes) {
586              placed = false;
587              Warn!(
588                "I/O",
589                dest,
590                "Couldn't write embedded resource {} to {}: {}",
591                basename,
592                dest,
593                e
594              );
595            }
596          }
597        } else if src == embedded_resources::AR5IV_CSS_NAME {
598          // The bare name only: a path the user wrote that is missing gets the plain message below.
599          Warn!(
600            "missing_file",
601            src,
602            "{} is bundled only in release builds; pass a path to a local copy",
603            src
604          );
605          return src.to_string();
606        } else {
607          Warn!(
608            "missing_file",
609            src,
610            "Couldn't find resource file {} in paths {:?}",
611            src,
612            search_paths
613          );
614          return src.to_string();
615        }
616      },
617    }
618    if placed {
619      self.copied.borrow_mut().insert(key);
620    }
621    relative_to_destination(doc, dest)
622  }
623
624  /// The `CSS`/`JAVASCRIPT`/`ICON` stylesheet parameter (a `"a|b|c"` quoted pipe-list) with each entry copied
625  /// and replaced by the path `copy_resource` returns (Perl `XSLT::process` L71-78). This runs regardless of
626  /// `no_resources`: `--nodefaultresources` drops only `<ltx:resource>` nodes (Perl L62-78, OD #1249).
627  fn copy_param_resources(
628    &self,
629    doc: &PostDocument,
630    value: &str,
631    resource_type: Option<&str>,
632  ) -> String {
633    if doc
634      .get_site_directory()
635      .or_else(|| doc.get_destination_directory())
636      .is_none()
637    {
638      return value.to_string();
639    }
640    let mut seen: HashSet<PathBuf> = HashSet::new();
641    let entries: Vec<String> = value
642      .trim_matches('"')
643      .split('|')
644      .map(str::trim)
645      .filter(|entry| !entry.is_empty())
646      .map(|entry| self.copy_resource_following(doc, entry, resource_type, Some(&mut seen)))
647      .collect();
648    format!("\"{}\"", entries.join("|"))
649  }
650}
651
652/// Perl `pathname_relative($dest, $doc->getDestinationDirectory)`: `../x.css` from a split sub-page.
653fn relative_to_destination(doc: &PostDocument, dest: String) -> String {
654  if let Some(dest_dir) = doc.get_destination_directory() {
655    pathname::relative(&pathname::absolute(&dest), &pathname::absolute(dest_dir))
656  } else {
657    dest
658  }
659}
660
661/// The directories a stylesheet's `@import` copies stay in: `dest`, the one it was copied under, and `source`, the
662/// one [`find_resource_file`] found it under.
663struct Roots<'a> {
664  dest:   &'a str,
665  source: &'a str,
666}
667
668/// Extract the targets of CSS `@import` rules from stylesheet source.
669///
670/// Block comments are stripped first (so a commented-out `@import` is ignored),
671/// then the common forms are matched: `@import "x.css";`, `@import url("x");`,
672/// `@import url('x');`, and bare `@import url(x);`, each with an optional
673/// trailing `layer(...)` / media / `supports(...)` tail (only the URL token is
674/// captured). One target per `@import` (CSS allows a single URL per rule).
675fn parse_css_imports(css: &str) -> Vec<String> {
676  static COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)/\*.*?\*/").unwrap());
677  static IMPORT: LazyLock<Regex> =
678    LazyLock::new(|| Regex::new(r#"(?i)@import\s+(?:url\(\s*)?["']?([^"')\s;]+)"#).unwrap());
679  let stripped = COMMENT.replace_all(css, "");
680  IMPORT
681    .captures_iter(&stripped)
682    .filter_map(|c| c.get(1).map(|m| m.as_str().to_string()))
683    .collect()
684}
685
686/// After a CSS file is copied from `src` to `dest`, recursively copy the LOCAL
687/// resources it `@import`s, preserving each import's relative subpath so the
688/// cascade still resolves at the destination.
689///
690/// BEYOND PERL: `copyResource` copies only the named file. ar5iv-style
691/// stylesheets split themselves across `@import url("./layer/part.css")`
692/// sub-files; without following those, the copied top-level CSS renders
693/// unstyled. Each target is resolved relative to the importing file — for both
694/// the on-disk source and the destination, so the same relative path is
695/// recreated under the destination — copied, and (if itself a `.css`) recursed
696/// into. Remote (`http(s)://`, `//`, `data:`, any `scheme://`) and absolute
697/// (`/…`) targets are left untouched. Each target is named as its URL resolves (`a/../b` is `b`), and one whose
698/// copy would land outside `roots.dest` or whose source resolves outside `roots.source`, a symbolic link followed on
699/// either side, is neither read nor written, with a Warning (OXIDIZED_DESIGN_DIVERGENCES #1166). `seen` (keyed on
700/// the absolute source path) guards against import cycles and redundant copies. Returns false when an import target
701/// was missing or could not be copied (each warned), so the caller retries it on the next page.
702fn copy_css_imports(src: &Path, dest: &Path, roots: &Roots, seen: &mut HashSet<PathBuf>) -> bool {
703  let content = match fs::read_to_string(src) {
704    Ok(c) => c,
705    Err(_) => return true,
706  };
707  let (Some(src_dir), Some(dest_dir)) = (src.parent(), dest.parent()) else {
708    return true;
709  };
710  let mut placed = true;
711  for target in parse_css_imports(&content) {
712    let t = target.trim();
713    // Skip remote / non-copyable targets — only local relative paths are ours.
714    if t.is_empty()
715      || t.starts_with('/')
716      || t.starts_with("//")
717      || t.starts_with("data:")
718      || t.contains("://")
719    {
720      continue;
721    }
722    let lexical = |dir: &Path| PathBuf::from(pathname::absolute(&dir.join(t).to_string_lossy()));
723    let import_src = lexical(src_dir);
724    let import_dest = lexical(dest_dir);
725    if pathname::is_contained_resolved(&import_dest.to_string_lossy(), roots.dest).is_none() {
726      Warn!(
727        "unexpected",
728        t,
729        "@import {} in {} would be copied outside {}; not copied",
730        t,
731        src.display(),
732        roots.dest
733      );
734      continue;
735    }
736    if !resolves_inside(&import_src, roots.source) {
737      Warn!(
738        "unexpected",
739        t,
740        "@import {} in {} resolves outside {}; not copied",
741        t,
742        src.display(),
743        roots.source
744      );
745      continue;
746    }
747    // Skip if already handled (shared import or cycle).
748    if !seen.insert(import_src.clone()) {
749      continue;
750    }
751    if !import_src.is_file() {
752      Warn!(
753        "missing_file",
754        t,
755        "Couldn't find @import target {} referenced by {}",
756        t,
757        src.display()
758      );
759      placed = false;
760      continue;
761    }
762    if !crate::writer::same_file(&import_src, &import_dest) {
763      if let Some(parent) = import_dest.parent() {
764        let _ = fs::create_dir_all(parent);
765      }
766      if let Err(e) = crate::writer::copy_atomic(&import_src, &import_dest) {
767        Warn!(
768          "I/O",
769          t,
770          "Couldn't copy @import {} to {}: {}",
771          import_src.display(),
772          import_dest.display(),
773          e
774        );
775        placed = false;
776        continue;
777      }
778    }
779    // Recurse into nested CSS imports only (not imported fonts/images).
780    if import_src
781      .extension()
782      .and_then(|e| e.to_str())
783      .is_some_and(|e| e.eq_ignore_ascii_case("css"))
784    {
785      placed &= copy_css_imports(&import_src, &import_dest, roots, seen);
786    }
787  }
788  placed
789}
790
791/// LaTeXML's `data:` namespace, whose attributes the html5 sheets copy as `data-*` (LaTeXML-common.xsl
792/// copy-attribute).
793const DATA_NS: &str = "http://dlmf.nist.gov/LaTeXML/data";
794
795/// A stand-in (class token `ltx_standin`, whatever element an icon's text collapsed into) gives its own text to
796/// `data:standin`, which the html5 sheets write as `data-standin` and LaTeXML.css draws with a zero-specificity
797/// `::before`, so a style sheet drawing the element itself (Font Awesome) wins (DG 2026-12-05, OD #1249). Done here,
798/// once per stand-in, so the transform pays no per-node test.
799fn standin_to_attribute(doc: &mut PostDocument) {
800  let owners = doc.findnodes("//*[contains(@class,'ltx_standin')]");
801  if owners.is_empty() {
802    return;
803  }
804  let Some(mut root) = doc.get_document_element() else {
805    return;
806  };
807  // Fail-safe: with no `data` prefix to write under, every twin stays as text.
808  let Some(ns) = root
809    .get_namespace_declarations()
810    .into_iter()
811    .find(|ns| ns.get_prefix() == "data" && ns.get_href() == DATA_NS)
812    .or_else(|| Namespace::new("data", DATA_NS, &mut root).ok())
813  else {
814    return;
815  };
816  for mut owner in owners {
817    if !owner
818      .get_attribute("class")
819      .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_standin"))
820    {
821      continue;
822    }
823    let texts: Vec<Node> = owner
824      .get_child_nodes()
825      .into_iter()
826      .filter(|child| child.get_type() == Some(NodeType::TextNode))
827      .collect();
828    let twin: String = texts.iter().map(Node::get_content).collect();
829    if twin.is_empty() || owner.set_attribute_ns("standin", &twin, &ns).is_err() {
830      continue;
831    }
832    for mut text in texts {
833      text.unlink_node();
834      doc.discard_subtree(text);
835    }
836  }
837}
838
839impl Processor for XSLT {
840  fn get_name(&self) -> &str { &self.name }
841
842  fn process(&mut self, mut doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
843    let stylesheet_path = match &self.stylesheet_path {
844      Some(p) => p.clone(),
845      None => return Ok(vec![doc]),
846    };
847
848    Info!(
849      "xslt",
850      "stylesheet",
851      "Applying XSLT stylesheet: {}",
852      stylesheet_path
853    );
854
855    // Handle resource elements first (before transformation removes them)
856    let resource_nodes = doc.findnodes("//ltx:resource[@src]");
857    if self.no_resources {
858      // Perl L64-65 removes every resource node. Kept (DG rulings 2026-12-05, OD #1249): a remote style sheet a compiled
859      // binding required, which ar5iv.sty's rewrite keeps for the ar5iv profile (no default resources); never one the
860      // document asked for, nor a remote script.
861      for mut node in resource_nodes {
862        let keep = node.get_attribute("type").as_deref() == Some("text/css")
863          && node.get_attribute("src").is_some_and(|src| is_remote(&src))
864          && node.get_attribute("class").is_some_and(|class| {
865            class
866              .split_whitespace()
867              .any(|c| c == BINDING_RESOURCE_CLASS)
868          });
869        if !keep {
870          node.unlink_node();
871        }
872      }
873    } else {
874      for node in &resource_nodes {
875        if let Some(src) = node.get_attribute("src") {
876          let resource_type = node.get_attribute("type");
877          let path = self.copy_resource(&doc, &src, resource_type.as_deref());
878          // Perl XSLT.pm:70 — rewrite `@src` to where the file was actually copied,
879          // so the `<link>`/`<script>` the stylesheet emits resolves (#662). Node is
880          // a shared handle, so mutating the clone edits the real node.
881          if path != src {
882            node.clone().set_attribute("src", &path).ok();
883          }
884        }
885      }
886    }
887
888    if self.standin_attribute {
889      standin_to_attribute(&mut doc);
890    }
891
892    // Perl XSLT.pm:71-78: the --css/--javascript/icon params carry where copyResource put each file, relative
893    // to this page (`../x.css` from a split sub-page).
894    let mut per_doc_params = self.parameters.clone();
895    for (key, resource_type) in [
896      ("CSS", Some("text/css")),
897      ("JAVASCRIPT", Some("text/javascript")),
898      ("ICON", None),
899    ] {
900      if let Some(value) = self.parameters.get(key) {
901        // (the operator's --css/--javascript/--icon files: read on its behalf, never confined, OD #1183)
902        let copied = pathname::own_behalf(|| self.copy_param_resources(&doc, value, resource_type));
903        per_doc_params.insert(key.to_string(), copied);
904      }
905    }
906
907    // Serialize the entire libxslt-touching critical section process-wide.
908    // libxslt/libxml2 keep NON-thread-safe process-global state — the input-
909    // callback + EXSLT registries, the generic error context, and the
910    // namespace-internalisation / dictionary caches that `xsltApplyStylesheet
911    // User` and stylesheet parsing mutate (the hidden mutation this file's
912    // per-thread-cache note already anticipates). Two conversion threads
913    // transforming concurrently DEADLOCK on that state: witnessed as the
914    // `52_source_map` XSLT tests hanging forever on a futex under
915    // `cargo test --tests` (all threads `futex_do_wait`, 0% CPU). The thread-
916    // local stylesheet cache below removes cross-thread *cache* sharing but not
917    // this shared C-library state, so a process-global lock is required for
918    // correctness. Cost: NONE in production — the CLI and the cortex fleet run
919    // one conversion per process (single thread), so this is never contended;
920    // only the multi-threaded test harness (or a hypothetical in-process pool)
921    // ever serializes here. Poison-tolerant: a transform that panicked while
922    // holding the lock didn't corrupt anything we read, so recover the guard.
923    static XSLT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
924    let _xslt_guard = XSLT_LOCK
925      .lock()
926      .unwrap_or_else(|poisoned| poisoned.into_inner());
927
928    // Register EXSLT extension functions (str:tokenize, math:*, etc.)
929    // used by LaTeXML stylesheets. Safe-wrapped upstream in
930    // rust-libxslt — `register_exslt()` is Once-guarded.
931    libxslt::register_exslt();
932
933    // Faithful port of Perl `XML::LibXSLT->max_depth(1000)`
934    // (LaTeXML::Post::XSLT.pm L48): cap libxslt's template-recursion depth.
935    // libxslt's compiled-in default is 3000; lowering to Perl's 1000 makes a
936    // runaway / deeply-recursive stylesheet apply ABORT gracefully (matching
937    // Perl) instead of growing the C call stack until SIGSEGV/OOM on
938    // pathological input. `xsltMaxDepth` is a process-global libxslt static
939    // read when each transform context is created, so setting it once is
940    // sufficient. See docs/performance/STABILITY_WITNESSES.md (Cluster A, hypothesis 3).
941    set_xslt_max_depth();
942
943    // Hand the source tree to libxslt WITHOUT a deep copy. `transform()`
944    // takes its `Document` by value (the moved handle's Drop would free the
945    // tree), so earlier code `dup()`'d (xmlCopyDoc — a full deep copy) to keep
946    // this PostDocument's own tree alive. On a large-math document the DOM is
947    // multi-GB, and that deep copy TRANSIENTLY DOUBLES peak RSS during the
948    // transform — the dominant driver of post-processing OOM on the canvas
949    // sweep (docs/performance/STABILITY_WITNESSES.md, Cluster A / hypothesis 1).
950    //
951    // `libxml::Document` is `Rc<RefCell<_Document>>` and the underlying
952    // `xmlDoc` is freed only when the LAST handle drops, so an Rc `clone()`
953    // (a refcount bump, no copy) is the right tool: libxslt reads the shared
954    // tree to build a SEPARATE result tree (`xsltApplyStylesheetUser` does not
955    // free its source), the moved clone's Drop just decrements the count, and
956    // `doc`'s own handle (dropped at function end) performs the single real
957    // free. We never read `doc`'s tree again after this point — only its
958    // string metadata below — so libxslt mutating the shared source while
959    // applying is harmless. This mirrors Perl, which passes
960    // `$doc->getDocument` straight to `transform` with no pre-copy
961    // (LaTeXML::Post::XSLT.pm L79).
962    let transform_doc = doc.get_document().clone();
963
964    let params: Vec<(&str, &str)> = per_doc_params
965      .iter()
966      .map(|(k, v)| (k.as_str(), v.as_str()))
967      .collect();
968
969    // Apply the transformation. The parsed `Stylesheet` lives in a
970    // per-thread cache (`with_cached_stylesheet`) — `libxslt::parser::
971    // parse_file` runs once per (thread, stylesheet path) instead of
972    // once per conversion. The cache is thread-local, not shared, so
973    // we don't lean on libxslt's undocumented thread-safety (mirroring
974    // the caution that resolved KWARC/rust-libxslt issue #6).
975    let result_doc = with_cached_stylesheet(&stylesheet_path, |stylesheet| {
976      stylesheet
977        .transform(transform_doc, params)
978        .map_err(|e| PostError::Processing(format!("XSLT transformation failed: {}", e)))
979    })?;
980    // Transform done — the libxslt-global critical section is over. Release the
981    // lock BEFORE wrapping the result: `result_doc` is the transform's fresh,
982    // unshared output tree, so building the `PostDocument` around it touches no
983    // shared libxslt/libxml2 state. Narrowing the hold keeps a hypothetical
984    // in-process pool serialized only over the actual transform, not the cheap
985    // wrapping. (No effect on the one-conversion-per-process production path,
986    // where the lock is never contended anyway.)
987    drop(_xslt_guard);
988
989    // XSLT returns a libxml `Document` directly — wrap it into a
990    // PostDocument without the serialize → reparse roundtrip the
991    // earlier code did. Saves ~10-30 ms on a typical mid-size paper
992    // (XML serialize + libxml2 reparse of ~100-500 KB markup).
993    if result_doc.get_root_element().is_none() {
994      return Err(PostError::Processing(
995        "XSLT produced empty output".to_string(),
996      ));
997    }
998
999    let result_doc = PostDocument::new_transformed(result_doc, PostDocumentOptions {
1000      destination: doc.destination.clone(),
1001      destination_directory: doc.destination_directory.clone(),
1002      site_directory: doc.site_directory.clone(),
1003      source: doc.source.clone(),
1004      source_directory: doc.source_directory.clone(),
1005      searchpaths: Some(doc.searchpaths.clone()),
1006      ..PostDocumentOptions::default()
1007    });
1008
1009    Ok(vec![result_doc])
1010  }
1011}
1012
1013// ======================================================================
1014// Per-thread cache of parsed stylesheets.
1015//
1016// `libxslt::parser::parse_file` reads the .xsl from disk and compiles
1017// it. For LaTeXML-html5.xsl that's ~5–10 ms including its xsl:imports.
1018// On a single CLI run that's once per process — fine. On a daemon-mode
1019// `cortex_worker` chewing through 10 000 papers from a thread pool of
1020// 8 workers, naive code re-parses once per paper. With this cache,
1021// each worker thread parses each unique stylesheet path *once* and
1022// reuses the compiled artefact for the rest of its lifetime.
1023//
1024// ## Why thread-local (and not process-wide + Arc/Mutex)?
1025//
1026// libxslt is not documented as thread-safe. `xsltApplyStylesheetUser`
1027// is not audited to be read-only on the stylesheet — it may write
1028// back into namespace-internalisation caches, error context fields,
1029// or other internal state. This is the same kind of hidden mutation
1030// that issue KWARC/rust-libxslt#6 punctured for the input `Document`
1031// (libxslt silently mutates docs during whitespace stripping). A
1032// process-wide cache shared across worker threads via `Arc` would
1033// either need a `Mutex` (serialising transforms — defeats the
1034// throughput benefit) or rely on libxslt's undocumented thread-safety
1035// (the same bet that #6 retired).
1036//
1037// Thread-local keeps the safety story simple: each thread owns its
1038// own `Stylesheet` for its lifetime, no cross-thread sharing, and the
1039// `&mut Stylesheet` requirement is satisfied by `RefCell::borrow_mut`.
1040// Worst case: 8 worker threads × 1 parse per unique stylesheet =
1041// 8 parses per process, instead of N parses per N papers.
1042
1043fn cache_key(path: &str) -> String {
1044  // Embedded virtual URLs never exist on the filesystem; skip `fs::canonicalize`
1045  // to avoid failing `statx`/`readlink` syscalls on every page of a large split.
1046  if path.starts_with(embedded_xslt::URL_PREFIX) {
1047    return path.to_string();
1048  }
1049  // Canonicalise so `./resources/XSLT/foo.xsl` and
1050  // `/abs/.../resources/XSLT/foo.xsl` hit the same entry. Falls back
1051  // to the raw path on canonicalisation failure (the file might not
1052  // exist yet — let parse_file emit its own error in that case).
1053  fs::canonicalize(path)
1054    .map(|p| p.to_string_lossy().into_owned())
1055    .unwrap_or_else(|_| path.to_string())
1056}
1057
1058thread_local! {
1059  static STYLESHEET_CACHE: RefCell<HashMap<String, libxslt::stylesheet::Stylesheet>> =
1060    RefCell::new(HashMap::default());
1061}
1062
1063/// Borrow a `&mut Stylesheet` from the per-thread cache, parsing on
1064/// miss. The closure runs while the cache is mutably borrowed, so
1065/// nested calls (which the LaTeXML pipeline never makes) would
1066/// `RefCell::borrow_mut`-panic — a deliberate single-borrow contract.
1067fn with_cached_stylesheet<F, R>(path: &str, f: F) -> Result<R, PostError>
1068where F: FnOnce(&mut libxslt::stylesheet::Stylesheet) -> Result<R, PostError> {
1069  let key = cache_key(path);
1070  // A user `--stylesheet` (parsed from disk, below) may `xsl:import` the engine
1071  // by `urn:x-LaTeXML:XSLT:` — install the embedded-XSLT input callback for
1072  // every parse, not just the embed:/// fallback path (issue #292). Idempotent.
1073  embedded_xslt::install_callback_once();
1074  STYLESHEET_CACHE.with(|cache| {
1075    let mut map = cache.borrow_mut();
1076    if !map.contains_key(&key) {
1077      let parsed = if let Some(name) = path.strip_prefix(embedded_xslt::URL_PREFIX) {
1078        // `embed:///<name>` sentinel from `find_stylesheet`. Parse the
1079        // root stylesheet from the embedded byte table; libxslt's
1080        // `xsl:import` machinery will then re-enter our libxml2 input
1081        // callback for every referenced URL.
1082        let bytes = embedded_xslt::lookup(name).ok_or_else(|| {
1083          PostError::Processing(format!("Embedded XSLT stylesheet {} not found", name))
1084        })?;
1085        libxslt::parser::parse_bytes(bytes.to_vec(), path)
1086          .map_err(|e| PostError::Processing(format!("Failed to parse embedded XSLT: {}", e)))?
1087      } else {
1088        libxslt::parser::parse_file(path)
1089          .map_err(|e| PostError::Processing(format!("Failed to parse XSLT stylesheet: {}", e)))?
1090      };
1091      map.insert(key.clone(), parsed);
1092    }
1093    let entry = map
1094      .get_mut(&key)
1095      .expect("cache entry just inserted is missing");
1096    f(entry)
1097  })
1098}
1099
1100// ======================================================================
1101// Embedded XSLT stylesheets — bundled at compile time for portable binary.
1102// When the resources/XSLT/ directory is not available on disk, these are
1103// extracted to a temp directory so libxslt can resolve xsl:import chains.
1104
1105mod embedded_xslt {
1106  pub const FILES: &[(&str, &str)] = &[
1107    (
1108      "LaTeXML-html5.xsl",
1109      include_str!("../resources/XSLT/LaTeXML-html5.xsl"),
1110    ),
1111    (
1112      "LaTeXML-all-xhtml.xsl",
1113      include_str!("../resources/XSLT/LaTeXML-all-xhtml.xsl"),
1114    ),
1115    (
1116      "LaTeXML-bib-xhtml.xsl",
1117      include_str!("../resources/XSLT/LaTeXML-bib-xhtml.xsl"),
1118    ),
1119    (
1120      "LaTeXML-block-xhtml.xsl",
1121      include_str!("../resources/XSLT/LaTeXML-block-xhtml.xsl"),
1122    ),
1123    (
1124      "LaTeXML-common.xsl",
1125      include_str!("../resources/XSLT/LaTeXML-common.xsl"),
1126    ),
1127    (
1128      "LaTeXML-epub3.xsl",
1129      include_str!("../resources/XSLT/LaTeXML-epub3.xsl"),
1130    ),
1131    (
1132      "LaTeXML-html4.xsl",
1133      include_str!("../resources/XSLT/LaTeXML-html4.xsl"),
1134    ),
1135    (
1136      "LaTeXML-inline-xhtml.xsl",
1137      include_str!("../resources/XSLT/LaTeXML-inline-xhtml.xsl"),
1138    ),
1139    (
1140      "LaTeXML-jats.xsl",
1141      include_str!("../resources/XSLT/LaTeXML-jats.xsl"),
1142    ),
1143    (
1144      "LaTeXML-math-xhtml.xsl",
1145      include_str!("../resources/XSLT/LaTeXML-math-xhtml.xsl"),
1146    ),
1147    (
1148      "LaTeXML-meta-xhtml.xsl",
1149      include_str!("../resources/XSLT/LaTeXML-meta-xhtml.xsl"),
1150    ),
1151    (
1152      "LaTeXML-misc-xhtml.xsl",
1153      include_str!("../resources/XSLT/LaTeXML-misc-xhtml.xsl"),
1154    ),
1155    (
1156      "LaTeXML-para-xhtml.xsl",
1157      include_str!("../resources/XSLT/LaTeXML-para-xhtml.xsl"),
1158    ),
1159    (
1160      "LaTeXML-picture-xhtml.xsl",
1161      include_str!("../resources/XSLT/LaTeXML-picture-xhtml.xsl"),
1162    ),
1163    (
1164      "LaTeXML-structure-xhtml.xsl",
1165      include_str!("../resources/XSLT/LaTeXML-structure-xhtml.xsl"),
1166    ),
1167    (
1168      "LaTeXML-tabular-xhtml.xsl",
1169      include_str!("../resources/XSLT/LaTeXML-tabular-xhtml.xsl"),
1170    ),
1171    (
1172      "LaTeXML-tei.xsl",
1173      include_str!("../resources/XSLT/LaTeXML-tei.xsl"),
1174    ),
1175    (
1176      "LaTeXML-webpage-xhtml.xsl",
1177      include_str!("../resources/XSLT/LaTeXML-webpage-xhtml.xsl"),
1178    ),
1179    (
1180      "LaTeXML-xhtml5.xsl",
1181      include_str!("../resources/XSLT/LaTeXML-xhtml5.xsl"),
1182    ),
1183    (
1184      "LaTeXML-xhtml.xsl",
1185      include_str!("../resources/XSLT/LaTeXML-xhtml.xsl"),
1186    ),
1187  ];
1188
1189  use std::sync::OnceLock;
1190
1191  /// URL scheme through which our embedded stylesheets are served to
1192  /// libxslt. Any URL starting with this prefix is intercepted by the
1193  /// input callback we install in [`install_callback_once`] and
1194  /// resolved against the [`FILES`] table.
1195  pub const URL_PREFIX: &str = "embed:///";
1196
1197  /// Look up the embedded XSLT bytes by basename, or `None` if the
1198  /// stylesheet is not bundled.
1199  pub fn lookup(name: &str) -> Option<&'static [u8]> {
1200    FILES
1201      .iter()
1202      .find_map(|(n, c)| (*n == name).then_some(c.as_bytes()))
1203  }
1204
1205  /// Map any URL libxml2 hands us to an embedded XSLT file, or `None` if we
1206  /// don't serve it. We key purely on the **final path segment**, because a
1207  /// user `--stylesheet` imports the engine by the LaTeXML-canonical
1208  /// `urn:x-LaTeXML:XSLT:X` scheme (Perl resolves it via an XML catalog), and
1209  /// libxml2 versions then resolve that root's *relative* child imports
1210  /// differently against the opaque `urn:` base: Linux composes
1211  /// `urn:LaTeXML-all-xhtml.xsl`, macOS drops to a bare `LaTeXML-all-xhtml.xsl`
1212  /// (CI witness, issue #292). Keying on the basename resolves `embed:///X`,
1213  /// `urn:x-LaTeXML:XSLT:X`, `urn:X`, and bare `X` uniformly. Only our
1214  /// distinctive `LaTeXML-*.xsl` names are in [`FILES`], so a user's own
1215  /// relative import (a different basename) still loads from disk.
1216  ///
1217  /// An absolute path or `file:` URL naming a file on disk is that file (#806): only a stylesheet
1218  /// the user named is made absolute (`find_stylesheet`), so it and an engine-named sibling it
1219  /// imports load from disk as in Perl, while a relative or bare engine name never reads the cwd.
1220  pub fn resolve(url: &str) -> Option<&'static [u8]> {
1221    if disk_path(url).is_some() {
1222      return None;
1223    }
1224    let name = url.rsplit(['/', ':']).next().unwrap_or(url);
1225    lookup(name)
1226  }
1227
1228  /// The file an absolute path or a `file:` URL names, when it exists (`url_path`).
1229  pub fn disk_path(url: &str) -> Option<std::path::PathBuf> {
1230    url_path(url).filter(|path| path.is_absolute() && path.is_file())
1231  }
1232
1233  /// The path an absolute path or a `file:` URL (`file:///p`, `file://localhost/p`, `file:/p`,
1234  /// percent-encoded; `file://server/share/p` on Windows) names. A plain path is taken as written:
1235  /// its `%` is a character, not an escape (`/w/100%/LaTeXML-html5.xsl`).
1236  pub(super) fn url_path(url: &str) -> Option<std::path::PathBuf> {
1237    let path = match url.strip_prefix("file:") {
1238      None => url.to_string(),
1239      Some(rest) => {
1240        let path = match rest.strip_prefix("//") {
1241          Some(auth) => match auth.strip_prefix("localhost").unwrap_or(auth) {
1242            local if local.starts_with('/') => local,
1243            // `file://server/share/p` is the UNC path `//server/share/p`.
1244            _ if cfg!(windows) => rest,
1245            _ => return None,
1246          },
1247          None => rest,
1248        };
1249        let path = percent_decode(path)?;
1250        // `file:///C:/x` names `C:/x`.
1251        match path.strip_prefix('/') {
1252          Some(rest) if cfg!(windows) && rest.as_bytes().get(1) == Some(&b':') => rest.to_string(),
1253          _ => path,
1254        }
1255      },
1256    };
1257    Some(std::path::PathBuf::from(path))
1258  }
1259
1260  fn percent_decode(s: &str) -> Option<String> {
1261    if !s.contains('%') {
1262      return Some(s.to_string());
1263    }
1264    let mut bytes = Vec::with_capacity(s.len());
1265    let mut it = s.bytes();
1266    while let Some(b) = it.next() {
1267      if b == b'%' {
1268        let hex = [it.next()?, it.next()?];
1269        bytes.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
1270      } else {
1271        bytes.push(b);
1272      }
1273    }
1274    String::from_utf8(bytes).ok()
1275  }
1276
1277  /// Install the libxml2 input callback that serves `embed:///`
1278  /// URLs from [`FILES`]. Called once per process; subsequent calls
1279  /// are no-ops. The callback fires whenever libxml2 itself opens a
1280  /// URL — including `xsl:import` / `xsl:include` resolution from
1281  /// inside `libxslt::parser::parse_bytes`. Result: every stylesheet
1282  /// (root + imports) is loaded from the binary's own `.rodata`
1283  /// section, no disk extraction required.
1284  pub fn install_callback_once() {
1285    static INSTALLED: OnceLock<()> = OnceLock::new();
1286    INSTALLED.get_or_init(|| {
1287      libxml::io::register_input_callback(
1288        // Serve any URL whose basename is one of our embedded engine files —
1289        // `embed:///X`, a user stylesheet's `urn:x-LaTeXML:XSLT:X`, and the
1290        // relative child imports libxml2 composes from it (`urn:X` on Linux, a
1291        // bare `X` on macOS). A non-engine basename, or a user-named file on disk (#806),
1292        // resolves to None, so the callback declines it and libxml2 loads it from disk (#292).
1293        |url| resolve(url).is_some(),
1294        |url| resolve(url).map(|s| s.to_vec()),
1295      );
1296    });
1297  }
1298}
1299
1300// ======================================================================
1301// Embedded CSS / JavaScript resources — bundled at compile time so a
1302// single-binary distribution can serve them without an accompanying
1303// `resources/` tree on disk.
1304//
1305// Unlike XSLT (which libxslt needs as files on disk to resolve
1306// `xsl:import` chains), CSS and JS are pure leaf assets — the
1307// post-processor's job is to put a copy next to the output HTML so
1308// `<link rel="stylesheet">` resolves. We can write the embedded
1309// bytes straight to the destination directory, skipping the
1310// extract-to-temp-then-copy round-trip entirely.
1311
1312mod embedded_resources {
1313  pub const CSS_FILES: &[(&str, &str)] = &[
1314    (
1315      "LaTeXML-blue.css",
1316      include_str!("../resources/CSS/LaTeXML-blue.css"),
1317    ),
1318    (
1319      "LaTeXML-epub.css",
1320      include_str!("../resources/CSS/LaTeXML-epub.css"),
1321    ),
1322    (
1323      "LaTeXML-marginpar.css",
1324      include_str!("../resources/CSS/LaTeXML-marginpar.css"),
1325    ),
1326    (
1327      "LaTeXML-navbar-left.css",
1328      include_str!("../resources/CSS/LaTeXML-navbar-left.css"),
1329    ),
1330    (
1331      "LaTeXML-navbar-right.css",
1332      include_str!("../resources/CSS/LaTeXML-navbar-right.css"),
1333    ),
1334    ("LaTeXML.css", include_str!("../resources/CSS/LaTeXML.css")),
1335    (
1336      "ltx-amsart.css",
1337      include_str!("../resources/CSS/ltx-amsart.css"),
1338    ),
1339    ("ltx-apj.css", include_str!("../resources/CSS/ltx-apj.css")),
1340    (
1341      "ltx-article.css",
1342      include_str!("../resources/CSS/ltx-article.css"),
1343    ),
1344    (
1345      "ltx-book.css",
1346      include_str!("../resources/CSS/ltx-book.css"),
1347    ),
1348    ("ltx-cv.css", include_str!("../resources/CSS/ltx-cv.css")),
1349    (
1350      "ltx-listings.css",
1351      include_str!("../resources/CSS/ltx-listings.css"),
1352    ),
1353    (
1354      "ltx-report.css",
1355      include_str!("../resources/CSS/ltx-report.css"),
1356    ),
1357    (
1358      "ltx-svjour.css",
1359      include_str!("../resources/CSS/ltx-svjour.css"),
1360    ),
1361    (
1362      "ltx-ulem.css",
1363      include_str!("../resources/CSS/ltx-ulem.css"),
1364    ),
1365    (
1366      "relaxng-schema-rustdoc-theme.css",
1367      include_str!("../resources/CSS/relaxng-schema-rustdoc-theme.css"),
1368    ),
1369  ];
1370
1371  pub const JS_FILES: &[(&str, &str)] = &[
1372    (
1373      "LaTeXML-maybeMathjax.js",
1374      include_str!("../resources/javascript/LaTeXML-maybeMathjax.js"),
1375    ),
1376    (
1377      "relaxng-schema-rustdoc-theme.js",
1378      include_str!("../resources/javascript/relaxng-schema-rustdoc-theme.js"),
1379    ),
1380  ];
1381
1382  // `AR5IV_CSS`: ar5iv-css's `dist/ar5iv.min.css`, embedded only where the release fetched it (latexml_post/build.rs).
1383  include!(concat!(env!("OUT_DIR"), "/embedded_ar5iv_css.rs"));
1384
1385  /// The name `--css` requests the bundled ar5iv-css stylesheet by.
1386  pub const AR5IV_CSS_NAME: &str = "ar5iv.css";
1387
1388  /// Return the embedded bytes for `basename` if it's one of the
1389  /// bundled CSS/JS assets, or `None` otherwise. Callers write the
1390  /// returned slice straight to the destination directory — no temp
1391  /// dir, no intermediate copy.
1392  pub fn lookup(basename: &str) -> Option<&'static [u8]> {
1393    CSS_FILES
1394      .iter()
1395      .chain(JS_FILES.iter())
1396      .find_map(|(n, c)| (*n == basename).then_some(c.as_bytes()))
1397  }
1398
1399  /// [`lookup`] for the resource `src` names, plus the bundled `ar5iv.css` for exactly that bare name: a path the
1400  /// user wrote (`nosuch/ar5iv.css`) names their own file.
1401  pub fn bundled(src: &str, basename: &str) -> Option<&'static [u8]> {
1402    lookup(basename).or_else(|| {
1403      AR5IV_CSS
1404        .filter(|_| src == AR5IV_CSS_NAME)
1405        .map(str::as_bytes)
1406    })
1407  }
1408}
1409
1410/// The `ar5iv.css` this build embeds (release builds; `tools/ar5iv-css.pin`), so `--css=ar5iv.css` needs no file.
1411pub fn ar5iv_css_bundled() -> Option<&'static str> { embedded_resources::AR5IV_CSS }
1412
1413// ======================================================================
1414// File search helpers
1415
1416/// The stylesheet a name resolves to: an `embed:///` name (the default for a format) is served from
1417/// the binary; a file the user named, found as given or under a search path, is made absolute, the
1418/// form [`embedded_xslt::resolve`] reads from disk with its imports (#806).
1419fn find_stylesheet(stylesheet: &str, searchpaths: &[String]) -> Result<String, PostError> {
1420  if let Some(name) = stylesheet.strip_prefix(embedded_xslt::URL_PREFIX)
1421    && embedded_xslt::lookup(name).is_some()
1422  {
1423    embedded_xslt::install_callback_once();
1424    return Ok(stylesheet.to_string());
1425  }
1426  if let Some(path) = embedded_xslt::disk_path(stylesheet) {
1427    return Ok(path.to_string_lossy().into_owned());
1428  }
1429  let candidates = std::iter::once(PathBuf::from(stylesheet))
1430    .chain(searchpaths.iter().map(|sp| Path::new(sp).join(stylesheet)));
1431  for candidate in candidates {
1432    if candidate.is_file() {
1433      let path = std::path::absolute(&candidate).unwrap_or(candidate);
1434      return Ok(path.to_string_lossy().into_owned());
1435    }
1436  }
1437  // 3. Fallback: serve from the embedded table via the libxml2 input callback. We return an
1438  //    `embed:///<basename>` URL sentinel that `with_cached_stylesheet` routes through
1439  //    `libxslt::parser:: parse_bytes`; subsequent `xsl:import` references inside that stylesheet
1440  //    compose against this base URI and re-enter our callback, so the whole chain stays in memory.
1441  let filename = Path::new(stylesheet)
1442    .file_name()
1443    .and_then(|f| f.to_str())
1444    .unwrap_or(stylesheet);
1445  if embedded_xslt::lookup(filename).is_some() {
1446    embedded_xslt::install_callback_once();
1447    return Ok(format!("{}{}", embedded_xslt::URL_PREFIX, filename));
1448  }
1449  Err(PostError::Processing(format!(
1450    "No stylesheet '{}' found!",
1451    stylesheet
1452  )))
1453}
1454
1455/// Disk-only lookup for a CSS/JS/icon resource — searches the literal
1456/// path, then `info.subdir`-prefixed variants, then each `search_paths`
1457/// entry. Embedded (compile-time-bundled) assets are handled by the
1458/// caller via `embedded_resources::lookup`; this function deliberately
1459/// does NOT check the embed, so on-disk overrides always win and the
1460/// "couldn't find" branch can fall through to the embed cleanly.
1461///
1462/// Returns the file and the directory it was found under (the working directory or the search path), which its
1463/// `@import`s are read from; a file named outside both is its own directory's. A file found under one that resolves
1464/// outside it, through a symbolic link, is skipped with a Warning (OXIDIZED_DESIGN_DIVERGENCES #1166).
1465fn find_resource_file(
1466  src: &str,
1467  info: Option<&ResourceInfo>,
1468  search_paths: &[&str],
1469) -> Option<(String, String)> {
1470  let name = Path::new(src).file_name()?.to_str()?;
1471  let mut candidates = vec![src.to_string()];
1472  if let Some(info) = info {
1473    candidates.push(format!("{}/{}", info.subdir, name));
1474    candidates.push(format!("{}/{}", info.subdir, src));
1475    candidates.dedup();
1476  }
1477  let found_under = |path: &str, base: &str| {
1478    if pathname::is_contained(path, base).is_none() {
1479      let own = Path::new(path)
1480        .parent()
1481        .map(Path::to_path_buf)
1482        .unwrap_or_default();
1483      return Some((path.to_string(), own.to_string_lossy().into_owned()));
1484    }
1485    if resolves_inside(Path::new(path), base) {
1486      return Some((path.to_string(), base.to_string()));
1487    }
1488    Warn!(
1489      "unexpected",
1490      src,
1491      "{} resolves outside {}; not used",
1492      path,
1493      base
1494    );
1495    None
1496  };
1497  // A confined conversion never looks outside its roots (OXIDIZED_DESIGN_DIVERGENCES #1183): a name that points out
1498  // of them (absolute, or with a `..` part), or through a link in a root that leads out, and is found nowhere inside
1499  // is refused when it names a file, else missing.
1500  let points_out = pathname::is_absolute(src) || src.split(['/', '\\']).any(|part| part == "..");
1501  let readable = |path: &str| {
1502    if pathname::read_allowed(path) {
1503      return Path::new(path).is_file();
1504    }
1505    if (points_out || pathname::refused_inside(path)) && pathname::refused_exists(path) {
1506      pathname::refuse(src);
1507    }
1508    false
1509  };
1510  pathname::requested_as(src, || {
1511    for candidate in &candidates {
1512      if readable(candidate)
1513        && let Some(found) = found_under(candidate, ".")
1514      {
1515        return Some(found);
1516      }
1517      for (i, sp) in search_paths.iter().enumerate() {
1518        let p = format!("{}/{}", sp, candidate);
1519        if !search_paths[..i].contains(sp)
1520          && readable(&p)
1521          && let Some(found) = found_under(&p, sp)
1522        {
1523          return Some(found);
1524        }
1525      }
1526    }
1527    None
1528  })
1529}
1530
1531/// Whether the file a read of `path` opens lies in `root`: an existing one as the system opens it
1532/// ([`pathname::opens_inside`]), a missing one through its existing parent.
1533fn resolves_inside(path: &Path, root: &str) -> bool {
1534  pathname::opens_inside(path, root).unwrap_or_else(|| {
1535    pathname::is_contained(
1536      &pathname::resolved(&path.to_string_lossy()),
1537      &pathname::resolved(root),
1538    )
1539    .is_some()
1540  })
1541}
1542
1543/// OD #1166: a stylesheet's `@import` copies stay in the destination and are read from inside the directory the
1544/// stylesheet was found under, a symbolic link followed on either side.
1545#[cfg(test)]
1546mod css_copy_containment_tests {
1547  use std::{collections::HashSet, fs, path::Path};
1548
1549  use latexml_core::common::error::{LogStatus, get_status};
1550
1551  use super::{RESOURCE_CSS, Roots, copy_css_imports, find_resource_file};
1552
1553  /// `src/top.css` holding `css` is copied to `out/top.css`; `victim/` and `secret.txt` lie outside both.
1554  struct Row {
1555    name:     &'static str,
1556    css:      &'static str,
1557    files:    &'static [(&'static str, &'static str)],
1558    /// (link, target), both under the work directory.
1559    links:    &'static [(&'static str, &'static str)],
1560    copied:   &'static [(&'static str, &'static str)],
1561    warnings: usize,
1562  }
1563
1564  const NESTED: &[(&str, &str)] = &[
1565    ("src/parts/a.css", "@import url(\"../b.css\");\n"),
1566    ("src/parts/deep/c.css", "@import url( \"../../b2.css\" );\n"),
1567    ("src/b.css", "/*b*/\n"),
1568    ("src/b2.css", "/*b2*/\n"),
1569  ];
1570
1571  fn rows() -> Vec<Row> {
1572    let mut rows = vec![Row {
1573      name:     "nested in-root ../ imports",
1574      css:      "@import url(\"parts/a.css\"); @import \"parts/deep/c.css\"; body{}\n",
1575      files:    NESTED,
1576      links:    &[],
1577      copied:   &[
1578        ("out/parts/a.css", "@import url(\"../b.css\");\n"),
1579        ("out/parts/deep/c.css", "@import url( \"../../b2.css\" );\n"),
1580        ("out/b.css", "/*b*/\n"),
1581        ("out/b2.css", "/*b2*/\n"),
1582      ],
1583      warnings: 0,
1584    }];
1585    if cfg!(unix) {
1586      rows.extend([
1587        Row {
1588          name:     "a link in the destination",
1589          css:      "@import url(\"L/evil.css\");\n",
1590          files:    &[("src/L/evil.css", "FROM-SRC\n")],
1591          links:    &[("out/L", "victim")],
1592          copied:   &[],
1593          warnings: 1,
1594        },
1595        // The URL names out/evil.css.
1596        Row {
1597          name:     "a link then .. in the destination",
1598          css:      "@import url(\"L/../evil.css\");\n",
1599          files:    &[("src/evil.css", "FROM-SRC\n"), ("src/L/keep", "")],
1600          links:    &[("out/L", "victim/sub")],
1601          copied:   &[("out/evil.css", "FROM-SRC\n")],
1602          warnings: 0,
1603        },
1604        Row {
1605          name:     "an import that links to a host file",
1606          css:      "@import url(\"s.css\");\n",
1607          files:    &[],
1608          links:    &[("src/s.css", "secret.txt")],
1609          copied:   &[],
1610          warnings: 1,
1611        },
1612        Row {
1613          name:     "an import through a folder link out of the source",
1614          css:      "@import url(\"L/secret.txt\");\n",
1615          files:    &[],
1616          links:    &[("src/L", "")],
1617          copied:   &[],
1618          warnings: 1,
1619        },
1620        // The URL names src/secret.txt, which is missing.
1621        Row {
1622          name:     "a link inside the source then ..",
1623          css:      "@import url(\"a/b/c/L/../../../../secret.txt\");\n",
1624          files:    &[("src/a/b/c/keep", ""), ("src/x/y/z/keep", "")],
1625          links:    &[("src/a/b/c/L", "src/x/y/z")],
1626          copied:   &[],
1627          warnings: 1,
1628        },
1629        Row {
1630          name:     "a link that stays in the source",
1631          css:      "@import \"alias.css\";\n",
1632          files:    &[("src/b.css", "/*b*/\n")],
1633          links:    &[("src/alias.css", "src/b.css")],
1634          copied:   &[("out/alias.css", "/*b*/\n")],
1635          warnings: 0,
1636        },
1637      ]);
1638    }
1639    rows
1640  }
1641
1642  fn write(path: &Path, body: &str) {
1643    fs::create_dir_all(path.parent().unwrap()).unwrap();
1644    fs::write(path, body).unwrap();
1645  }
1646
1647  #[cfg(unix)]
1648  fn link(at: &Path, target: &Path) {
1649    fs::create_dir_all(at.parent().unwrap()).unwrap();
1650    std::os::unix::fs::symlink(target, at).unwrap();
1651  }
1652  #[cfg(not(unix))]
1653  fn link(_: &Path, _: &Path) {}
1654
1655  #[test]
1656  fn css_imports_stay_inside_their_roots() {
1657    for row in rows() {
1658      let work = tempfile::tempdir().unwrap();
1659      let w = work.path();
1660      write(&w.join("victim/evil.css"), "ORIGINAL\n");
1661      fs::create_dir_all(w.join("victim/sub")).unwrap();
1662      write(&w.join("secret.txt"), "SECRET\n");
1663      write(&w.join("src/top.css"), row.css);
1664      write(&w.join("out/top.css"), row.css);
1665      for (path, body) in row.files {
1666        write(&w.join(path), body);
1667      }
1668      for (at, target) in row.links {
1669        link(&w.join(at), &w.join(target));
1670      }
1671      let (src, out) = (w.join("src"), w.join("out"));
1672      let roots = Roots {
1673        dest:   &out.to_string_lossy(),
1674        source: &src.to_string_lossy(),
1675      };
1676      let before = get_status(LogStatus::Warning);
1677      copy_css_imports(
1678        &src.join("top.css"),
1679        &out.join("top.css"),
1680        &roots,
1681        &mut HashSet::new(),
1682      );
1683      let name = row.name;
1684      assert_eq!(
1685        get_status(LogStatus::Warning) - before,
1686        row.warnings,
1687        "{name}"
1688      );
1689      assert_eq!(
1690        fs::read_to_string(w.join("victim/evil.css")).unwrap(),
1691        "ORIGINAL\n",
1692        "{name}"
1693      );
1694      for (path, body) in row.copied {
1695        assert_eq!(
1696          fs::read_to_string(w.join(path)).ok().as_deref(),
1697          Some(*body),
1698          "{name}: {path}"
1699        );
1700      }
1701      let mut written: Vec<String> = Vec::new();
1702      let mut stack = vec![out.clone(), w.join("victim")];
1703      while let Some(dir) = stack.pop() {
1704        for entry in fs::read_dir(&dir).unwrap().flatten() {
1705          let path = entry.path();
1706          if entry.file_type().unwrap().is_dir() {
1707            stack.push(path);
1708          } else if entry.file_type().unwrap().is_file() {
1709            assert_ne!(
1710              fs::read_to_string(&path).unwrap(),
1711              "SECRET\n",
1712              "{name}: {}",
1713              path.display()
1714            );
1715            written.push(
1716              path
1717                .strip_prefix(w)
1718                .unwrap()
1719                .to_string_lossy()
1720                .replace('\\', "/"),
1721            );
1722          }
1723        }
1724      }
1725      written.sort();
1726      let mut expected: Vec<String> = row
1727        .copied
1728        .iter()
1729        .map(|(path, _)| path.to_string())
1730        .collect();
1731      expected.extend(["out/top.css".to_string(), "victim/evil.css".to_string()]);
1732      expected.sort();
1733      assert_eq!(written, expected, "{name}");
1734    }
1735  }
1736
1737  /// The stylesheet itself: found under a search path only when it resolves inside it.
1738  #[test]
1739  fn a_found_stylesheet_resolves_inside_its_search_path() {
1740    let work = tempfile::tempdir().unwrap();
1741    let sp = work.path().join("paper");
1742    write(
1743      &sp.join("resources/CSS/containment-row-plain.css"),
1744      "/*plain*/\n",
1745    );
1746    let sp_str = sp.to_string_lossy().into_owned();
1747    let before = get_status(LogStatus::Warning);
1748    let found = find_resource_file("containment-row-plain.css", Some(&RESOURCE_CSS), &[&sp_str]);
1749    assert_eq!(
1750      found,
1751      Some((
1752        format!("{sp_str}/resources/CSS/containment-row-plain.css"),
1753        sp_str.clone()
1754      ))
1755    );
1756    assert_eq!(get_status(LogStatus::Warning), before);
1757    if cfg!(unix) {
1758      write(&work.path().join("secret.txt"), "SECRET\n");
1759      link(
1760        &sp.join("resources/CSS/containment-row-link.css"),
1761        &work.path().join("secret.txt"),
1762      );
1763      let found = find_resource_file("containment-row-link.css", Some(&RESOURCE_CSS), &[&sp_str]);
1764      assert_eq!(found, None);
1765      assert_eq!(get_status(LogStatus::Warning) - before, 1);
1766      // A link then `..` (Gemini A.2): `a/b/L/../../..` is `paper` as written, the work directory as opened.
1767      fs::create_dir_all(sp.join("a/b")).unwrap();
1768      fs::create_dir_all(sp.join("deep/er")).unwrap();
1769      link(&sp.join("a/b/L"), &sp.join("deep/er"));
1770      write(&work.path().join("containment-row-climb.css"), "SECRET\n");
1771      let found = find_resource_file("a/b/L/../../../containment-row-climb.css", None, &[&sp_str]);
1772      assert_eq!(found, None);
1773      assert_eq!(get_status(LogStatus::Warning) - before, 2);
1774    }
1775  }
1776}
1777
1778#[cfg(test)]
1779mod witnessed_css_delta {
1780  //! Guards the intentional non-vanilla rules in the bundled default
1781  //! `LaTeXML.css`: a tcolorbox/minipage foreignobject top-alignment rule
1782  //! (arXiv **2605.02240**) and the display-equation vertical margin
1783  //! (issue **#473**), and the dark-mode colours of the pop-up note boxes
1784  //! (issue **#1207**). The rest of the stylesheet is a straight adoption
1785  //! of upstream vanilla (#312), which we do NOT assert here — the Perl
1786  //! `LaTeXML/` reference tree is not shipped in the crate, so there is no
1787  //! ground truth to diff against, and re-sync fidelity is a human/`cp`
1788  //! responsibility. These tests exist only so that a future "re-vanilla"
1789  //! sweep can't silently drop a witnessed local delta.
1790  use super::embedded_resources;
1791
1792  fn bundled_latexml_css() -> &'static str {
1793    std::str::from_utf8(embedded_resources::lookup("LaTeXML.css").expect("LaTeXML.css is bundled"))
1794      .expect("LaTeXML.css is valid UTF-8")
1795  }
1796
1797  #[test]
1798  fn witnessed_minipage_delta_stays_present() {
1799    let css = bundled_latexml_css();
1800    assert!(
1801      css.contains("2605.02240")
1802        && css.contains(
1803          ".ltx_foreignobject_container:has( > .ltx_foreignobject_content > .ltx_minipage)"
1804        ),
1805      "the witnessed minipage top-alignment delta (2605.02240) is missing from LaTeXML.css",
1806    );
1807  }
1808
1809  #[test]
1810  fn dark_mode_note_popup_delta_stays_present() {
1811    let css = bundled_latexml_css();
1812    let start = css
1813      .find("@media (prefers-color-scheme: dark) {")
1814      .expect("LaTeXML.css has a dark-mode block");
1815    let mut depth = 0usize;
1816    let mut end = css.len();
1817    for (offset, ch) in css[start..].char_indices() {
1818      match ch {
1819        '{' => depth += 1,
1820        '}' => {
1821          depth -= 1;
1822          if depth == 0 {
1823            end = start + offset;
1824            break;
1825          }
1826        },
1827        _ => {},
1828      }
1829    }
1830    let dark = &css[start..end];
1831    assert!(
1832      dark.contains("#1207")
1833        && dark.contains("  .ltx_note_content,\n")
1834        && dark.contains(".ltx_author_notes:hover .ltx_author_notes_content,")
1835        && dark.contains(".ltx_pubnotes:hover .ltx_pubnotes_content,")
1836        && dark.contains("background-color: black;"),
1837      "the dark-mode pop-up note delta (issue #1207) is missing from LaTeXML.css's dark block: a note's \
1838       pop-up would keep its white box under the page's white text and read blank",
1839    );
1840  }
1841
1842  #[test]
1843  fn equation_display_margin_delta_stays_present() {
1844    let css = bundled_latexml_css();
1845    assert!(
1846      css.contains("#473")
1847        && css.contains(".ltx_eqn_table, .ltx_eqn_div { margin-top:1em; margin-bottom:1em; }"),
1848      "the display-equation vertical-margin delta (issue #473) is missing from LaTeXML.css: \
1849       adjacent display equations would render touching, unlike TeX's \\abovedisplayskip",
1850    );
1851  }
1852
1853  #[test]
1854  fn verbatim_whitespace_delta_stays_present() {
1855    let css = bundled_latexml_css();
1856    assert!(
1857      css.contains("#431")
1858        && css.contains(".ltx_verbatim { white-space:pre; }")
1859        && css.contains(".ltx_text.ltx_verbatim.ltx_inline-block"),
1860      "the verbatim whitespace/line-block delta (issue #431) is missing from LaTeXML.css: \
1861       plain verbatim would collapse to one line under vanilla's nowrap, and fancyvrb \
1862       source lines would reflow side-by-side with their indentation collapsed",
1863    );
1864    // Issues #431/#702 at a phone width: inline \verb wraps (not in a nowrap table
1865    // cell), a breaklines line's \parbox drops the markup's newlines while its text
1866    // keeps its spaces, and shrinks in a flex row (through an id-carrying ltx_text
1867    // wrapper too); lines and xleftmargin's wrapper are capped (Chrome at 375 px:
1868    // page 488 -> 375, frame scrollWidth 468 -> 330); the wrapper is a flex row, so
1869    // its U+2003 margin indents the line rather than take a row (issue 853: row
1870    // 30 -> 15 px). The browser half is `browser_render_verbatim_narrow`.
1871    for rule in [
1872      "code.ltx_verbatim { white-space:pre-wrap; overflow-wrap:break-word; }",
1873      ".ltx_td code.ltx_verbatim, .ltx_th code.ltx_verbatim { white-space:pre; }",
1874      ".ltx_verbatim .ltx_parbox { white-space:normal; }",
1875      ".ltx_verbatim .ltx_parbox .ltx_p { white-space:pre-wrap; }",
1876      ".ltx_text.ltx_verbatim.ltx_inline-block { display:block; text-indent:0; min-height:1lh; \
1877       max-width:100%; }",
1878      ".ltx_text.ltx_inline-block:has(> .ltx_text.ltx_verbatim.ltx_inline-block) { display:flex; \
1879       text-indent:0; max-width:100%; }",
1880      ".ltx_text.ltx_inline-block > .ltx_text.ltx_verbatim.ltx_inline-block { min-width:0; }",
1881      ".ltx_text.ltx_verbatim.ltx_inline-block:has(> .ltx_parbox, > .ltx_text > .ltx_parbox) { \
1882       display:flex; }",
1883      ".ltx_verbatim > .ltx_text:has(> .ltx_parbox) { display:contents; }",
1884      ".ltx_verbatim > .ltx_parbox, .ltx_verbatim > .ltx_text > .ltx_parbox { flex-shrink:1; \
1885       min-width:0; }",
1886      ".ltx_framed.ltx_framed_verbatim { display:block; width:fit-content; }",
1887    ] {
1888      assert!(
1889        css.contains(rule),
1890        "LaTeXML.css lost the verbatim rule `{rule}` (issues #431/#702/853)"
1891      );
1892    }
1893  }
1894
1895  #[test]
1896  fn dashed_border_delta_follows_the_border_rules() {
1897    // arydshln's dashed rules (`ltx_border_<side>_dashed`, OD #1025) set only the style, after every border shorthand
1898    // (`.ltx_border_tt` and the light `.ltx_border_T` reset it), so the width and a `cssstyle` rule colour stay.
1899    let css = bundled_latexml_css();
1900    let last_shorthand = css
1901      .find(".ltx_border_L  {")
1902      .expect("the light left border rule");
1903    for rule in [
1904      ".ltx_border_t_dashed { border-top-style:dashed; }",
1905      ".ltx_border_r_dashed { border-right-style:dashed; }",
1906      ".ltx_border_b_dashed { border-bottom-style:dashed; }",
1907      ".ltx_border_l_dashed { border-left-style:dashed; }",
1908    ] {
1909      let at = css
1910        .find(rule)
1911        .unwrap_or_else(|| panic!("LaTeXML.css lost the dashed border rule `{rule}`"));
1912      assert!(
1913        at > last_shorthand,
1914        "`{rule}` must follow the border shorthands"
1915      );
1916    }
1917  }
1918
1919  #[test]
1920  fn author_line_delta_stays_present() {
1921    // Issue #783 (OXIDIZED_DESIGN_DIVERGENCES #1051): an author whose contacts are all lines of the author block
1922    // (`ltx_author_line`) or notes shows the lines under the name, not behind the starred pop-up; a note keeps the star
1923    // (1112.2930), its notes shown in the card's flow on hover (math0111266); the browser half is
1924    // `cluster_cli::browser_render_author_lines`.
1925    const CARD: &str =
1926      ":not(:has(.ltx_contact:not(.ltx_author_line):not(.ltx_role_note):not(.ltx_role_thanks)))";
1927    let css = bundled_latexml_css();
1928    for rule in [
1929      format!("DOC .ltx_creator:has(.ltx_author_line){CARD} {{\n    display:inline-block;"),
1930      format!("DOC .ltx_author_notes{CARD}:has(.ltx_author_line) {{\n    display:inline; }}"),
1931      format!(
1932        "DOC .ltx_author_notes{CARD}:has(.ltx_author_line):not(:has(.ltx_role_note, \
1933         .ltx_role_thanks)):before {{\n    content:none; }}"
1934      ),
1935      format!(
1936        "DOC .ltx_author_notes{CARD}:has(.ltx_author_line) .ltx_contact:not(.ltx_author_line) {{\n    display:none; }}"
1937      ),
1938      // on hover a note joins the card's flow: two notes, or a note and the lines, never overlap (math0111266)
1939      format!(
1940        "DOC .ltx_author_notes{CARD}:has(.ltx_author_line):hover .ltx_contact:not(.ltx_author_line) {{\n    \
1941         display:block; position:static; contain:inline-size;"
1942      ),
1943      format!(
1944        "DOC .ltx_author_notes{CARD}:has(.ltx_author_line) .ltx_author_line .ltx_contact_name {{ display:none; }}"
1945      ),
1946    ] {
1947      let rule = rule.replace("DOC", ".ltx_document:not(.ltx_authors_multiline)");
1948      assert!(
1949        css.contains("#783") && css.contains(&rule),
1950        "LaTeXML.css lost the author-line rule `{rule}` (issue #783)"
1951      );
1952    }
1953    // a mixed author's pop-up keeps its "Affiliation:" labels: the label hide is scoped to the card
1954    assert!(
1955      !css.contains("\n.ltx_author_line .ltx_contact_name"),
1956      "an unscoped author-line label hide"
1957    );
1958  }
1959
1960  #[test]
1961  fn shared_author_note_delta_stays_present() {
1962    // OXIDIZED_DESIGN_DIVERGENCES #1052 (DG's rulings of 2026-11-16): a marked author note follows the name, set as
1963    // text; where an author's lines show under the name (the #783 card, ltx_authors_multiline) its marked notes show
1964    // there, each headed by its mark, one author's too (DG 2026-11-17, 2506.06941's †; 2606.00446, 2407.07614,
1965    // 1706.03762). An
1966    // unmarked note is no one author's (IEEEtran's \thanks, 1510.02728): no rule shows it under the name. A pure name's
1967    // mark-only note (ltx_role_footnotemark, 0801.1438) shows its mark there too; a body under the name floats, so the
1968    // marks after it stay on the name's line; consecutive marks are parted by a comma. The browser half is
1969    // `cluster_cli::browser_render_author_lines`. A shared note's other marks carry a hidden copy of it
1970    // (`ltx_note_copy`, DG 2026-11-17), which the card never floats under the name: its classic pop-up alone shows it.
1971    const CARD: &str = ".ltx_document:not(.ltx_authors_multiline) .ltx_creator:has(.ltx_author_line):not(:has(\
1972                        .ltx_contact:not(.ltx_author_line):not(.ltx_role_note):not(.ltx_role_thanks)))";
1973    let card = format!(":is({CARD}, .ltx_authors_multiline .ltx_creator)");
1974    let lines = format!("{card} .ltx_annotated_personname > .ltx_note");
1975    let body = ".ltx_note_outer:not(.ltx_note_copy)";
1976    let css = bundled_latexml_css();
1977    for rule in [
1978      ".ltx_annotated_personname:has(> .ltx_note) { display:inline; }".to_string(),
1979      ".ltx_note_shared > .ltx_note_mark > a { color:inherit; text-decoration:none; }".to_string(),
1980      format!("{lines} {{ display:inline; }}"),
1981      format!("{lines} > {body} .ltx_note_content {{\n    display:block; position:static; float:inline-start; clear:both; width:100%;"),
1982      format!("{lines} > {body} .ltx_note_content .ltx_note_mark {{ position:static; }}"),
1983      format!("{lines} > {body} .ltx_note_type {{ display:none; }}"),
1984      ".ltx_annotated_personname > .ltx_note:has(~ .ltx_note) > .ltx_note_mark::after { content:\",\"; }".to_string(),
1985    ] {
1986      assert!(
1987        css.contains("#1052") && css.contains(&rule),
1988        "LaTeXML.css lost the shared author note rule `{rule}` (#1052)"
1989      );
1990    }
1991    assert!(
1992      !css.contains(&format!(
1993        "{lines}:not(.ltx_note_shared):not(.ltx_role_footnotemark) .ltx_note_mark"
1994      )),
1995      "LaTeXML.css hides a one-author note's mark again (DG 2026-11-17: every marked note shows the mark the PDF prints)"
1996    );
1997    assert!(
1998      !css.contains(&format!("{card} > .ltx_note")),
1999      "LaTeXML.css shows an unmarked author note under the name (#1052, 1510.02728)"
2000    );
2001  }
2002
2003  #[test]
2004  fn constrained_equation_overflow_delta_stays_present() {
2005    // Issue #533: display math in a p{} cell, \parbox, minipage or table cell is a block within its box (it escaped
2006    // and scattered across the page). Issue #972: that block is no scroll box (Chrome drew a phantom vertical
2007    // scrollbar on every in-cell display, and a lowered \raisebox was clipped); the box grows to its display, and a
2008    // note scrolls a too-wide one. The browser half is `cluster_cli::browser_render_eqn_rows_in_cells`.
2009    let css = bundled_latexml_css();
2010    for rule in [
2011      ".ltx_inline-block .ltx_eqn_table,\n.ltx_td .ltx_eqn_table { display:block; max-width:100%; }",
2012      ":is(.ltx_inline-block, .ltx_inline-logical-block, .ltx_minipage, .ltx_parbox):has(.ltx_eqn_table) {\n  \
2013       min-width:min-content; }",
2014      ":is(.ltx_inline-block, .ltx_inline-logical-block, .ltx_minipage, .ltx_parbox, .ltx_td) :is(.ltx_eqn_center_padleft, .ltx_eqn_center_padright) {\n  \
2015       min-width:0; }",
2016      ".ltx_note_content:has(.ltx_eqn_table) { overflow-x:auto; }",
2017    ] {
2018      assert!(
2019        css.contains("#533") && css.contains("#972") && css.contains(rule),
2020        "LaTeXML.css lost the constrained-equation rule `{rule}` (issues #533, #972)"
2021      );
2022    }
2023    assert!(
2024      !css.contains("display:block; overflow-x:auto; max-width:100%;"),
2025      "a display in a box is a scroll container again (issue #972: phantom vertical scrollbars)"
2026    );
2027  }
2028
2029  #[test]
2030  fn equation_tag_and_mathjax_deltas_stay_present() {
2031    // Issues #810 (a one-row equation centred in the full line, its tag beside it: Chrome/Firefox at
2032    // 375 px, the long `\tag` over its formula -> beside it; multi-row tables keep a tag column) and
2033    // #475 (MathJax 2.1 offline: consecutive displays 53 -> 21 px apart, native 18, in a table or a
2034    // minipage); the browser half is `cluster_cli::browser_render_eqn_tags`.
2035    let css = bundled_latexml_css();
2036    for (issue, rule) in [
2037      ("#810", ".ltx_eqn_eqno { max-width:none; }"),
2038      (
2039        "#810",
2040        ".ltx_equation.ltx_eqn_table > * > .ltx_eqn_row:only-child:has(> .ltx_eqn_center_padleft) {\n  \
2041         display:grid; grid-template-columns:minmax(2em,1fr) auto 1fr; align-items:center; }",
2042      ),
2043      (
2044        "#475",
2045        ".ltx_eqn_table .ltx_eqn_cell > mjx-container[display=\"true\"],\n\
2046         .ltx_eqn_table .ltx_eqn_cell > .MathJax_Display { margin-top:0; margin-bottom:0; }",
2047      ),
2048    ] {
2049      assert!(
2050        css.contains(issue) && css.contains(rule),
2051        "LaTeXML.css lost the issue {issue} rule `{rule}`"
2052      );
2053    }
2054  }
2055
2056  #[test]
2057  fn equation_rows_in_inline_context_delta_stays_present() {
2058    // Issue #972: a display in a p{} cell, \parbox or minipage is written as spans; its tbody spans are row groups
2059    // (Chrome/Firefox: the rows of an `aligned` ran side by side, scrolled out of the cell), the tabular's cell padding
2060    // stays off its cells, and the align column gap is keyed on classes; its cells keep the UA's 1px <td> padding
2061    // (Chrome: a gather*'s rows touched) and a row of one colspan cell (\intertext) is a block (it wrapped in the first
2062    // column), as is the span table itself in a note or minipage, where no `ltx_inline-block`/`ltx_td` boxes it. The
2063    // browser half is `cluster_cli::browser_render_eqn_rows_in_cells`.
2064    let css = bundled_latexml_css();
2065    for rule in [
2066      "span.ltx_eqn_table > span:not([class]) { display:table-row-group; }",
2067      "span.ltx_eqn_table { display:block; max-width:100%; }",
2068      ".ltx_tabular .ltx_eqn_cell { padding:0; }",
2069      ".ltx_eqn_align .ltx_equation > .ltx_align_left + .ltx_align_right,",
2070      ".ltx_eqn_eqnarray .ltx_eqn_lefteqn + .ltx_eqn_row > .ltx_align_right { min-width:2em; }",
2071      "span.ltx_eqn_table .ltx_eqn_cell { padding:1px; }",
2072      "span.ltx_eqn_table > span:not([class]):has(> .ltx_eqn_row > .ltx_eqn_cell[colspan]:only-child),\n\
2073       span.ltx_eqn_table > span:not([class]) > .ltx_eqn_row:has(> .ltx_eqn_cell[colspan]:only-child),\n\
2074       span.ltx_eqn_table > span:not([class]) > .ltx_eqn_row > .ltx_eqn_cell[colspan]:only-child { display:block; }",
2075    ] {
2076      assert!(
2077        css.contains("#972") && css.contains(rule),
2078        "LaTeXML.css lost the issue #972 rule `{rule}`"
2079      );
2080    }
2081  }
2082
2083  #[test]
2084  fn framed_verbatim_responsive_delta_stays_present() {
2085    let css = bundled_latexml_css();
2086    assert!(
2087      css.contains("#525")
2088        && css.contains(
2089          ".ltx_framed_verbatim { max-width:100%; overflow-x:auto; box-sizing:border-box; }"
2090        ),
2091      "the framed-verbatim responsive-containment delta (issue #525) is missing from \
2092       LaTeXML.css: a fancyvrb frame=single box spans the print \\linewidth and would push \
2093       its border off-screen and scroll the whole page on a phone",
2094    );
2095  }
2096
2097  #[test]
2098  fn float_safe_center_delta_stays_present() {
2099    // Issue #1135 (OXIDIZED_DESIGN_DIVERGENCES #1199): the class stylesheets' column-flex float centres a child with
2100    // `safe center`, so one wider than the float starts at its left edge instead of spilling out of scroll reach; the
2101    // plain `center` comes first as the fallback. The browser half is `browser_render_float_overflow`.
2102    for name in ["ltx-article.css", "ltx-book.css", "ltx-report.css"] {
2103      let css =
2104        std::str::from_utf8(embedded_resources::lookup(name).expect("bundled")).expect("UTF-8");
2105      assert!(
2106        css.contains(
2107          ".ltx_table,\n.ltx_figure { display:flex; flex-direction:column; align-items:center; \
2108           align-items:safe center; }"
2109        ),
2110        "{name} lost the float's `align-items:safe center` after its `center` fallback (issue #1135)"
2111      );
2112    }
2113  }
2114
2115  #[test]
2116  fn title_pubnote_content_stays_collapsed() {
2117    // arXiv/html_feedback#6888 (+ #6886): a title footnote (`\thanks`/`\titlenote`,
2118    // role=note/thanks) stays in the `<h1>` as a `.ltx_pubnotes` block. The bundled
2119    // CSS must render ONLY the dagger MARK and keep the footnote CONTENT hidden by
2120    // default, so the title text is the sole rendered language — the reporter saw the
2121    // footnote text rendered inline in the title (an older deployed build). Guard both
2122    // halves so a re-vanilla / cleanup sweep cannot silently drop the collapse.
2123    let css = bundled_latexml_css();
2124    assert!(
2125      css.contains(".ltx_pubnotes:before {\n    content:\"\\24D8\""),
2126      "the title-footnote handle rule (.ltx_pubnotes:before, ⓘ since OXIDIZED_DESIGN_DIVERGENCES #1069) is missing \
2127       from LaTeXML.css (arXiv/html_feedback#6888)",
2128    );
2129    assert!(
2130      css.contains(".ltx_pubnotes .ltx_pubnotes_content")
2131        && css.contains("visibility:hidden; opacity:0"),
2132      "the title-footnote CONTENT-hidden rule (.ltx_pubnotes .ltx_pubnotes_content \
2133       {{ visibility:hidden }}) is missing from LaTeXML.css: the `\\thanks` text would \
2134       render inline in the title instead of collapsing to its handle \
2135       (arXiv/html_feedback#6888)",
2136    );
2137  }
2138
2139  #[test]
2140  fn no_xsl_key_match_has_a_predicated_descendant_step() {
2141    // libxslt builds every key at the first key() call, evaluating each `match` as an XPath; libxml2 runs `//X` as
2142    // one descendant pass only when X has no predicate, so `…//ltx:p[not(ancestor::…)]` ran once per root child:
2143    // O(children × nodes), a 180 s timeout on a document with no section (0707.2621, 0711.3849, 1806.00577; run 397;
2144    // WISDOM #105). Keep an exclusion in the key's `use`, not in a predicated `//` step.
2145    for (name, xsl) in [(
2146      "LaTeXML-meta-xhtml.xsl",
2147      include_str!("../resources/XSLT/LaTeXML-meta-xhtml.xsl"),
2148    )] {
2149      for key in xsl.split("<xsl:key ").skip(1) {
2150        let matched = key
2151          .split("match=\"")
2152          .nth(1)
2153          .and_then(|m| m.split('"').next())
2154          .unwrap_or("");
2155        let flat: String = matched.split_whitespace().collect::<Vec<_>>().join(" ");
2156        for step in flat.split("//").skip(1) {
2157          let head: String = step
2158            .chars()
2159            .take_while(|c| !matches!(c, '[' | '|' | '/' | ' '))
2160            .collect();
2161          assert!(
2162            !step[head.len()..].starts_with('['),
2163            "{name}: an xsl:key match has the predicated descendant step `//{head}[…]`: {flat}"
2164          );
2165        }
2166      }
2167    }
2168  }
2169
2170  #[test]
2171  fn css_draws_no_footnote_mark_glyph() {
2172    // DG 2026-11-17 (OXIDIZED_DESIGN_DIVERGENCES #1069): the page carries every mark the PDF prints, and a generated
2173    // mark only where it prints none, unique against them; a glyph the stylesheet draws is neither, so it is never one
2174    // of the marks' glyphs. The hover handles for an author's hidden contacts and for the title notes draw ⓘ (Perl:
2175    // `*` and `†`, which read as a second mark beside a printed one: 2606.00446's "Park**", 2605.10496's title †).
2176    let css = bundled_latexml_css();
2177    for glyph in [
2178      "*", "\\2217", "∗", "\\002020", "\\2020", "†", "\\2021", "‡", "\\00A7", "§", "\\00B6", "¶",
2179      "\\2016", "‖",
2180    ] {
2181      for spaced in ["", " "] {
2182        let rule = format!("content:{spaced}\"{glyph}\"");
2183        assert!(
2184          !css.contains(&rule),
2185          "LaTeXML.css draws the footnote-mark glyph `{rule}`"
2186        );
2187      }
2188    }
2189    for handle in [
2190      ".ltx_author_notes:before {\n    content:\"\\24D8\"",
2191      ".ltx_pubnotes:before {\n    content:\"\\24D8\"",
2192    ] {
2193      assert!(
2194        css.contains(handle),
2195        "LaTeXML.css lacks the ⓘ hover handle `{handle}`"
2196      );
2197    }
2198  }
2199}