Skip to main content

dbmd_core/
extract.rs

1//! Document text extraction — the `dbmd extract` engine.
2//!
3//! `sources/` is where raw evidence lands: invoices, contracts, reports,
4//! exports. Most of it arrives as binary documents (PDF, Word, Excel, EPUB) or
5//! HTML, not markdown. Before an agent can reason over that evidence — wiki-link
6//! it, summarize it into the wiki layer, file a typed record that cites it — the
7//! text has to come out. This module is that step: a binary document in, plain
8//! UTF-8 text out, format chosen by file extension.
9//!
10//! # What this is, and is not
11//!
12//! - **Deterministic decoders only.** Every adapter is a format parser
13//!   (`pdf-extract`, `calamine`, `html2text`, `quick-xml`+`zip`). There is **no
14//!   AI, no OCR, no embeddings** here — consistent with the crate-wide invariant
15//!   (`lib.rs`). The agent driving `dbmd` is the semantic layer; this is plumbing.
16//! - **Text layer, not pixels.** A scanned PDF with no text layer yields the
17//!   empty string — *empty in, empty out, never hallucinated text.* OCR is an
18//!   explicit non-goal (a future `dbmd-ocr`).
19//! - **Single document, single call.** [`extract`] handles one file. Walking a
20//!   store and extracting every document is the caller's loop, not this module's.
21//!
22//! # Format dispatch
23//!
24//! [`Format::from_path`] maps the file extension to an adapter; [`extract`]
25//! dispatches:
26//!
27//! | Extension                | Format            | Adapter                          |
28//! |--------------------------|-------------------|----------------------------------|
29//! | `.pdf`                   | [`Format::Pdf`]   | `pdf-extract`                    |
30//! | `.docx`                  | [`Format::Docx`]  | `zip` + `quick-xml` (`w:t` runs) |
31//! | `.xlsx` / `.xlsm` / `.xlsb` / `.ods` | [`Format::Spreadsheet`] | `calamine` |
32//! | `.epub`                  | [`Format::Epub`]  | `zip` + `quick-xml` + `html2text`|
33//! | `.html` / `.htm` / `.xhtml` | [`Format::Html`] | `html2text`                    |
34//!
35//! Anything else is [`ExtractError::UnsupportedFormat`] — a typed refusal the
36//! CLI surfaces with a stable code, never a panic.
37
38use std::collections::BTreeMap;
39use std::io::Read;
40use std::panic::{catch_unwind, AssertUnwindSafe};
41use std::path::Path;
42
43use serde::Serialize;
44
45/// The result of extracting one document: the plain text plus a small,
46/// format-tagged metadata map.
47///
48/// This is the `--json` shape the CLI emits verbatim (`{text, metadata}`); in
49/// plain mode the CLI prints [`Extracted::text`] and discards the metadata.
50/// Metadata is intentionally minimal and best-effort — extraction never *fails*
51/// for want of a title; it just omits the key.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
53pub struct Extracted {
54    /// The extracted plain text (UTF-8), normalized to `\n` line endings with
55    /// trailing whitespace trimmed per line and a single trailing newline. For
56    /// a document with no recoverable text layer (e.g. a scanned, image-only
57    /// PDF) this is the empty string — the contract is "empty in, empty out."
58    pub text: String,
59
60    /// Best-effort key/value metadata. Always carries `format` (the adapter
61    /// that ran, e.g. `"pdf"`). Adapters add what they cheaply know:
62    /// `pages`/`sheets`/`sheet_names` (counts), `title` (when the container
63    /// declares one). A `BTreeMap` so `--json` output is key-ordered and stable.
64    pub metadata: BTreeMap<String, MetaValue>,
65}
66
67impl Extracted {
68    /// Build an [`Extracted`] from raw adapter text + the detected format,
69    /// applying the canonical text normalization ([`normalize_text`]) and
70    /// seeding the `format` metadata key.
71    fn new(raw_text: String, format: Format) -> Self {
72        let mut metadata = BTreeMap::new();
73        metadata.insert(
74            "format".to_string(),
75            MetaValue::Str(format.tag().to_string()),
76        );
77        Extracted {
78            text: normalize_text(&raw_text),
79            metadata,
80        }
81    }
82
83    /// Insert a string metadata key only when the value is non-empty (keeps the
84    /// map free of empty `title: ""` noise).
85    fn put_str(&mut self, key: &str, value: impl Into<String>) {
86        let v = value.into();
87        if !v.trim().is_empty() {
88            self.metadata.insert(key.to_string(), MetaValue::Str(v));
89        }
90    }
91
92    /// Insert a numeric (count) metadata key.
93    fn put_num(&mut self, key: &str, value: u64) {
94        self.metadata.insert(key.to_string(), MetaValue::Num(value));
95    }
96}
97
98/// A metadata value: a string (title, format tag, sheet name list joined) or a
99/// non-negative count (pages, sheets). Serializes to a bare JSON string or
100/// number — no wrapper object — so `{text, metadata}` stays flat and readable.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
102#[serde(untagged)]
103pub enum MetaValue {
104    /// A textual value (e.g. document title, the `format` tag).
105    Str(String),
106    /// A non-negative count (e.g. page count, sheet count).
107    Num(u64),
108}
109
110/// The document formats `dbmd extract` understands, one per adapter. Detected
111/// from the file extension by [`Format::from_path`].
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum Format {
114    /// Portable Document Format (`.pdf`) — text layer via `pdf-extract`.
115    Pdf,
116    /// Office Open XML WordprocessingML (`.docx`) — `w:t` runs via `quick-xml`.
117    Docx,
118    /// A spreadsheet (`.xlsx`/`.xlsm`/`.xlsb`/`.ods`) — cells via `calamine`.
119    Spreadsheet,
120    /// EPUB e-book (`.epub`) — spine XHTML via `zip` + `quick-xml` + `html2text`.
121    Epub,
122    /// HTML (`.html`/`.htm`/`.xhtml`) — plain text via `html2text`.
123    Html,
124}
125
126impl Format {
127    /// Detect the format from a path's extension (case-insensitive). Returns
128    /// `None` for an unrecognized or missing extension; [`extract`] turns that
129    /// into [`ExtractError::UnsupportedFormat`] with the offending extension.
130    pub fn from_path(path: &Path) -> Option<Format> {
131        let ext = path.extension()?.to_str()?.to_ascii_lowercase();
132        Some(match ext.as_str() {
133            "pdf" => Format::Pdf,
134            "docx" => Format::Docx,
135            "xlsx" | "xlsm" | "xlsb" | "ods" => Format::Spreadsheet,
136            "epub" => Format::Epub,
137            "html" | "htm" | "xhtml" => Format::Html,
138            _ => return None,
139        })
140    }
141
142    /// The short, stable tag recorded in `metadata.format` and used in error
143    /// messages. Distinct from the file extension (one tag can cover several
144    /// extensions, e.g. `spreadsheet`).
145    pub fn tag(self) -> &'static str {
146        match self {
147            Format::Pdf => "pdf",
148            Format::Docx => "docx",
149            Format::Spreadsheet => "spreadsheet",
150            Format::Epub => "epub",
151            Format::Html => "html",
152        }
153    }
154}
155
156/// Errors from document extraction. Every variant is a typed refusal the CLI
157/// maps to a stable machine code — extraction never panics on a bad or
158/// encrypted input.
159#[derive(Debug, thiserror::Error)]
160pub enum ExtractError {
161    /// The file extension is missing or not one of the supported document
162    /// formats. Carries the offending extension (or `""` when absent).
163    #[error("unsupported document format: {0:?} (supported: pdf, docx, xlsx/xlsm/xlsb/ods, epub, html/htm/xhtml)")]
164    UnsupportedFormat(String),
165
166    /// The document is encrypted/password-protected and could not be opened
167    /// without a password (or with the wrong one). A clean refusal — the
168    /// extractor must never emit partial/garbled bytes for a locked file.
169    #[error("document is encrypted or password-protected: {0}")]
170    Encrypted(String),
171
172    /// A format adapter failed to parse a structurally invalid or corrupt
173    /// document. Carries the adapter's diagnostic.
174    #[error("failed to parse {format} document: {message}")]
175    Parse {
176        /// The format tag whose adapter failed (e.g. `"pdf"`, `"docx"`).
177        format: &'static str,
178        /// The underlying parser diagnostic.
179        message: String,
180    },
181
182    /// An underlying I/O failure (file missing, unreadable, etc.).
183    #[error(transparent)]
184    Io(#[from] std::io::Error),
185}
186
187impl ExtractError {
188    /// A short, stable machine code for this error, mirrored at the CLI
189    /// boundary for `--json` output and exit-code mapping.
190    pub fn code(&self) -> &'static str {
191        match self {
192            ExtractError::UnsupportedFormat(_) => "UNSUPPORTED_FORMAT",
193            ExtractError::Encrypted(_) => "DOCUMENT_ENCRYPTED",
194            ExtractError::Parse { .. } => "EXTRACT_PARSE_ERROR",
195            ExtractError::Io(_) => "IO_ERROR",
196        }
197    }
198}
199
200/// Result alias for extraction operations.
201pub type Result<T> = std::result::Result<T, ExtractError>;
202
203/// Extract plain text (and best-effort metadata) from a document, choosing the
204/// adapter by the file's extension.
205///
206/// This is the single entry point the CLI calls. It reads exactly one file and
207/// returns one [`Extracted`]; there is no whole-store walk here (per the
208/// crate-wide O(changed) invariant — a store-wide extraction is the caller's
209/// loop). An unsupported extension is [`ExtractError::UnsupportedFormat`]; an
210/// encrypted PDF is [`ExtractError::Encrypted`]; neither panics.
211///
212/// # Examples
213///
214/// ```no_run
215/// use std::path::Path;
216/// let out = dbmd_core::extract::extract(Path::new("sources/docs/invoice.pdf"))?;
217/// println!("{}", out.text);
218/// # Ok::<(), dbmd_core::extract::ExtractError>(())
219/// ```
220pub fn extract(path: &Path) -> Result<Extracted> {
221    let format = Format::from_path(path).ok_or_else(|| {
222        let ext = path
223            .extension()
224            .and_then(|e| e.to_str())
225            .unwrap_or("")
226            .to_string();
227        ExtractError::UnsupportedFormat(ext)
228    })?;
229
230    match format {
231        Format::Pdf => extract_pdf(path),
232        Format::Docx => extract_docx(path),
233        Format::Spreadsheet => extract_spreadsheet(path),
234        Format::Epub => extract_epub(path),
235        Format::Html => extract_html(path),
236    }
237}
238
239// ─────────────────────────────────────────────────────────────────────────────
240// Text normalization
241// ─────────────────────────────────────────────────────────────────────────────
242
243/// Canonicalize extracted text so output is stable across adapters:
244///
245/// 1. Normalize line endings to `\n` (drop `\r`).
246/// 2. Trim trailing whitespace on each line.
247/// 3. Collapse three-or-more consecutive blank lines to a single blank line.
248/// 4. Trim leading/trailing blank lines, then append exactly one `\n` (unless
249///    the whole text is empty, which stays empty — the image-only-PDF contract).
250///
251/// This is *layout* tid-up only; it never reorders or drops words. Word-level
252/// content is whatever the adapter recovered.
253pub fn normalize_text(raw: &str) -> String {
254    let unix = raw.replace("\r\n", "\n").replace('\r', "\n");
255
256    let lines: Vec<&str> = unix.lines().map(|l| l.trim_end()).collect();
257
258    // Trim leading/trailing blank lines by locating the first and last
259    // non-blank line ONCE, then slicing. The previous `while … lines.remove(0)`
260    // shifted every remaining element on each removal — O(n²) when the document
261    // is dominated by leading blanks (e.g. an adapter that emits millions of
262    // empty paragraphs), letting a few-hundred-KB document hang extraction for
263    // minutes. Index-and-slice is O(n) regardless of how many blanks lead.
264    let Some(first) = lines.iter().position(|l| !l.is_empty()) else {
265        return String::new();
266    };
267    // `first` exists, so a last non-blank line exists too (rposition can't be None).
268    let last = lines
269        .iter()
270        .rposition(|l| !l.is_empty())
271        .expect("a non-blank line exists once `first` is found");
272    let lines = &lines[first..=last];
273
274    // Collapse runs of 2+ blank lines down to a single blank line.
275    let mut out = String::new();
276    let mut blank_run = 0usize;
277    for &line in lines {
278        if line.is_empty() {
279            blank_run += 1;
280            if blank_run >= 2 {
281                continue;
282            }
283        } else {
284            blank_run = 0;
285        }
286        out.push_str(line);
287        out.push('\n');
288    }
289    out
290}
291
292// ─────────────────────────────────────────────────────────────────────────────
293// PDF — pdf-extract
294// ─────────────────────────────────────────────────────────────────────────────
295
296/// Extract a PDF's text layer via `pdf-extract`.
297///
298/// A PDF with no text layer (a scanned image) yields the empty string — that is
299/// correct, not an error (OCR is out of scope). A password-protected PDF that
300/// cannot be opened is mapped to [`ExtractError::Encrypted`] rather than a raw
301/// parse error so the caller can branch on it. Metadata carries the page count
302/// when the document tree exposes it.
303///
304/// `pdf-extract`/`lopdf` `panic!` internally on some malformed-but-openable
305/// PDFs (e.g. an out-of-set base `/Encoding` name), so both parser calls are
306/// wrapped in [`std::panic::catch_unwind`]: an internal abort is contained and
307/// surfaced as [`ExtractError::Parse`], upholding this module's "never panics"
308/// contract on untrusted `sources/` input.
309fn extract_pdf(path: &Path) -> Result<Extracted> {
310    // Read the bytes ourselves so a missing/unreadable file is a clean
311    // `ExtractError::Io` (via `?`) before we hand anything to the PDF parser.
312    let bytes = std::fs::read(path)?;
313
314    let text = match guard_pdf_panic(|| pdf_extract::extract_text_from_mem(&bytes))? {
315        Ok(t) => t,
316        Err(e) => return Err(classify_pdf_error(e)),
317    };
318
319    let mut out = Extracted::new(text, Format::Pdf);
320
321    // Page count is best-effort; derive it from the parsed document. A parse
322    // failure OR an internal panic here is non-fatal — the text already
323    // succeeded — so a contained panic (outer `Err`) and a load failure (inner
324    // `Err`) are both silently skipped.
325    if let Ok(Ok(doc)) = guard_pdf_panic(|| pdf_extract::Document::load_mem(&bytes)) {
326        out.put_num("pages", doc.get_pages().len() as u64);
327    }
328
329    Ok(out)
330}
331
332/// Run a panic-prone `pdf-extract`/`lopdf` call, converting an internal unwind
333/// into a typed [`ExtractError::Parse`] tagged `pdf` so the module's "never
334/// panics" contract holds on adversarial PDFs. `AssertUnwindSafe` is sound: the
335/// closure borrows only `&[u8]`, and on a caught unwind we discard any partial
336/// state and return an owned error. The default panic hook still writes the
337/// panic line to stderr — library code must not mutate the process-global hook.
338fn guard_pdf_panic<T>(f: impl FnOnce() -> T) -> Result<T> {
339    catch_unwind(AssertUnwindSafe(f)).map_err(|_| ExtractError::Parse {
340        format: "pdf",
341        message: "pdf parser aborted on malformed input".to_string(),
342    })
343}
344
345/// Map a `pdf-extract` error onto the right [`ExtractError`] variant.
346/// Decryption failures become [`ExtractError::Encrypted`]; everything else is a
347/// [`ExtractError::Parse`] tagged `pdf`.
348fn classify_pdf_error(err: pdf_extract::OutputError) -> ExtractError {
349    let msg = err.to_string();
350    let lower = msg.to_ascii_lowercase();
351    if lower.contains("password") || lower.contains("decrypt") || lower.contains("encrypt") {
352        ExtractError::Encrypted(msg)
353    } else {
354        ExtractError::Parse {
355            format: "pdf",
356            message: msg,
357        }
358    }
359}
360
361// ─────────────────────────────────────────────────────────────────────────────
362// DOCX — zip + quick-xml (no docx-rs dependency; quick-xml is already needed
363// for epub, so docx, xlsx-via-calamine, and epub share one XML/zip surface)
364// ─────────────────────────────────────────────────────────────────────────────
365
366/// Extract a `.docx` (WordprocessingML) by unzipping `word/document.xml` and
367/// concatenating the `<w:t>` run text, one logical line per `<w:p>` paragraph.
368///
369/// `<w:tab/>` becomes a tab and `<w:br/>` / `<w:cr>` a newline so table-ish and
370/// line-broken content keeps its shape; everything else is structural and
371/// ignored. This is the same minimal-but-faithful path `docx-rs` takes for text
372/// extraction, without pulling in a second XML/zip stack.
373fn extract_docx(path: &Path) -> Result<Extracted> {
374    let file = std::fs::File::open(path)?;
375    let mut archive = open_zip(file, "docx")?;
376
377    let xml = read_zip_entry(&mut archive, "word/document.xml", "docx")?;
378    let text = wordprocessing_text(&xml, "docx")?;
379
380    Ok(Extracted::new(text, Format::Docx))
381}
382
383/// Pull paragraph text out of a WordprocessingML / DrawingML XML body.
384///
385/// Shared by [`extract_docx`]. Walks the event stream collecting `<w:t>` text;
386/// `<w:p>` ends a line, `<w:tab/>` is a tab, `<w:br>`/`<w:cr>` a newline.
387fn wordprocessing_text(xml: &str, format: &'static str) -> Result<String> {
388    use quick_xml::events::Event;
389    use quick_xml::reader::Reader;
390
391    let mut reader = Reader::from_str(xml);
392    let mut buf = Vec::new();
393    let mut out = String::new();
394    let mut in_text_run = false;
395
396    loop {
397        match reader.read_event_into(&mut buf) {
398            Ok(Event::Start(e)) => {
399                if local_name(e.name().as_ref()) == b"t" {
400                    in_text_run = true;
401                }
402            }
403            Ok(Event::End(e)) => {
404                let name = e.name();
405                match local_name(name.as_ref()) {
406                    b"t" => in_text_run = false,
407                    b"p" => out.push('\n'),
408                    _ => {}
409                }
410            }
411            Ok(Event::Empty(e)) => {
412                // Self-closing run-level breaks inside a paragraph.
413                match local_name(e.name().as_ref()) {
414                    b"tab" => out.push('\t'),
415                    b"br" | b"cr" => out.push('\n'),
416                    _ => {}
417                }
418            }
419            // quick-xml 0.40 surfaces text verbatim in `Event::Text` but routes
420            // every entity reference to a separate `Event::GeneralRef` and CDATA
421            // to `Event::CData` — all three carry run content.
422            Ok(Event::Text(t)) => {
423                if in_text_run {
424                    out.push_str(&String::from_utf8_lossy(&t.into_inner()));
425                }
426            }
427            // `Smith &amp; Co` arrives as Text("Smith ") + GeneralRef("amp") +
428            // Text(" Co"); resolve the ref so `&`/`<`/`>`/numeric chars survive.
429            Ok(Event::GeneralRef(r)) => {
430                if in_text_run {
431                    out.push_str(&resolve_entity_ref(&r));
432                }
433            }
434            // CDATA inside a `<w:t>` run is valid WordprocessingML; its payload
435            // is literal text and must be appended like `Event::Text`.
436            Ok(Event::CData(c)) => {
437                if in_text_run {
438                    out.push_str(&String::from_utf8_lossy(&c.into_inner()));
439                }
440            }
441            Ok(Event::Eof) => break,
442            Err(e) => {
443                return Err(ExtractError::Parse {
444                    format,
445                    message: format!("malformed XML: {e}"),
446                });
447            }
448            _ => {}
449        }
450        buf.clear();
451    }
452
453    Ok(out)
454}
455
456/// The local part of a possibly-namespaced XML name: `w:t` → `t`, `t` → `t`.
457/// docx/epub XML uses prefixes (`w:`, `dc:`) the writer chose; matching the
458/// local name is prefix-agnostic and robust to that choice.
459fn local_name(qname: &[u8]) -> &[u8] {
460    match qname.iter().rposition(|&b| b == b':') {
461        Some(i) => &qname[i + 1..],
462        None => qname,
463    }
464}
465
466/// Resolve a `quick_xml` general-entity / character reference to its literal
467/// text. quick-xml 0.40 does NOT inline-resolve entity references inside
468/// `Event::Text`; instead it surfaces each `&name;` / `&#nnn;` as a separate
469/// `Event::GeneralRef`. Routing those to a `_ => {}` arm silently drops `&`,
470/// `<`, `>`, numeric refs, etc. from extracted text — corrupting any title,
471/// company name, or amount that contains them. This resolves the five
472/// XML-predefined named entities and any numeric character reference; an
473/// unknown named entity falls back to its bare name (best-effort, never a
474/// panic), matching the "recover what we can" stance of `sources/` extraction.
475fn resolve_entity_ref(reference: &quick_xml::events::BytesRef<'_>) -> String {
476    // Numeric character reference (`&#8212;`, `&#x2014;`): resolve to the char.
477    if let Ok(Some(ch)) = reference.resolve_char_ref() {
478        return ch.to_string();
479    }
480    // Named entity: map the five XML-predefined names; fall back to the bare
481    // name for anything else (custom DTD entities are out of scope here).
482    match reference.decode().as_deref() {
483        Ok("amp") => "&".to_string(),
484        Ok("lt") => "<".to_string(),
485        Ok("gt") => ">".to_string(),
486        Ok("quot") => "\"".to_string(),
487        Ok("apos") => "'".to_string(),
488        Ok(other) => other.to_string(),
489        Err(_) => String::new(),
490    }
491}
492
493// ─────────────────────────────────────────────────────────────────────────────
494// Spreadsheet — calamine (xlsx / xlsm / xlsb / ods)
495// ─────────────────────────────────────────────────────────────────────────────
496
497/// Ceiling on a single sheet's dense cell grid (`rows × cols`). `calamine`
498/// materializes a worksheet as a DENSE `Vec<Data>` sized from the MIN/MAX cell
499/// positions (`Range::from_sparse`), so two cells at `A1` and `XFD1048576` in a
500/// few-hundred-byte file force a ~1.7e10-element (~400 GB) allocation that
501/// **aborts** the process — bypassing the docx/epub zip-entry cap and the
502/// PDF panic guard (an allocation failure aborts, it does not unwind, so
503/// `catch_unwind` cannot contain it). `sources/` is untrusted input, so we
504/// bound the read the same way docx/epub do: refuse before the allocation.
505///
506/// 50M cells is ~1.2 GB worst-case dense (`Data` ≈ 24 bytes) — far above any
507/// real spreadsheet's used range, far below the weaponizable extreme.
508const MAX_SPREADSHEET_CELLS: u64 = 50_000_000;
509
510/// Extract every sheet of a spreadsheet via `calamine`, rendering each row as
511/// tab-separated cells, one row per line, sheets in workbook order separated by
512/// a blank line.
513///
514/// Cell rendering: text verbatim; integers and whole-valued floats without a
515/// trailing `.0` (`1200`, not `1200.0`); other floats via their default
516/// formatting; booleans as `TRUE`/`FALSE`; empty/error cells as the empty
517/// string. Metadata carries the sheet count and the joined sheet-name list.
518///
519/// Before materializing each sheet, [`spreadsheet_dense_cells`] bounds the
520/// would-be dense grid against [`MAX_SPREADSHEET_CELLS`] and returns a typed
521/// [`ExtractError::Parse`] refusal rather than letting an attacker-supplied
522/// sheet OOM/abort the process — upholding the module's "never panics on
523/// untrusted `sources/` input" contract for the spreadsheet adapter.
524fn extract_spreadsheet(path: &Path) -> Result<Extracted> {
525    use calamine::{open_workbook_auto, Reader};
526
527    let mut workbook = open_workbook_auto(path).map_err(|e| ExtractError::Parse {
528        format: "spreadsheet",
529        message: e.to_string(),
530    })?;
531
532    let sheet_names = workbook.sheet_names().to_vec();
533    let mut text = String::new();
534
535    for (idx, name) in sheet_names.iter().enumerate() {
536        if idx > 0 {
537            text.push('\n'); // blank line between sheets
538        }
539
540        // Bound the dense grid BEFORE calamine allocates it. For the zip-XML /
541        // record backends that expose a sparse cell iterator (xlsx-family,
542        // xlsb) this never densely allocates; over-cap sheets refuse cleanly.
543        if let Some(cells) = spreadsheet_dense_cells(&mut workbook, name)? {
544            if cells > MAX_SPREADSHEET_CELLS {
545                return Err(ExtractError::Parse {
546                    format: "spreadsheet",
547                    message: format!(
548                        "sheet {name:?} declares a {cells}-cell grid, over the \
549                         {MAX_SPREADSHEET_CELLS}-cell cap (malformed or hostile spreadsheet)"
550                    ),
551                });
552            }
553        }
554
555        let range = workbook
556            .worksheet_range(name)
557            .map_err(|e| ExtractError::Parse {
558                format: "spreadsheet",
559                message: format!("sheet {name:?}: {e}"),
560            })?;
561
562        for row in range.rows() {
563            let cells: Vec<String> = row.iter().map(render_cell).collect();
564            text.push_str(&cells.join("\t"));
565            text.push('\n');
566        }
567    }
568
569    let mut out = Extracted::new(text, Format::Spreadsheet);
570    out.put_num("sheets", sheet_names.len() as u64);
571    if !sheet_names.is_empty() {
572        out.put_str("sheet_names", sheet_names.join(", "));
573    }
574    Ok(out)
575}
576
577/// Compute the would-be dense cell count (`rows × cols`) of one sheet WITHOUT
578/// the dense allocation, by streaming the sheet's sparse cells and tracking the
579/// MIN/MAX non-empty position — exactly the bounds `Range::from_sparse` uses.
580///
581/// Returns `Some(rows * cols)` for the formats that expose a sparse cell
582/// iterator (`.xlsx`/`.xlsm`/`.xlsb`/`.xlam`), which are the realistic
583/// decompression/dimension-bomb vectors (an OOXML/record sheet can place two
584/// cells 1e10 apart in a few hundred bytes). Returns `None` for `.xls` (BIFF,
585/// format-bounded to ≤ 65 536 × 256 ≈ 1.7e7 cells) and `.ods`, neither of which
586/// exposes a sparse iterator on the auto-detected reader; those fall through to
587/// the normal materialization path. A row/col delta is saturated into `u64` so
588/// the multiply cannot overflow.
589fn spreadsheet_dense_cells(
590    workbook: &mut calamine::Sheets<std::io::BufReader<std::fs::File>>,
591    name: &str,
592) -> Result<Option<u64>> {
593    use calamine::{DataRef, Sheets};
594
595    // Stream cells, tracking the non-empty MIN/MAX extent that `from_sparse`
596    // would allocate. Empty cells are excluded (calamine drops them before
597    // computing the dense bounds), matching the dense grid exactly.
598    fn extent<E: std::fmt::Display>(
599        mut next: impl FnMut() -> std::result::Result<Option<((u32, u32), bool)>, E>,
600    ) -> Result<Option<u64>> {
601        let (mut r0, mut r1, mut c0, mut c1) = (u32::MAX, 0u32, u32::MAX, 0u32);
602        let mut any = false;
603        loop {
604            match next() {
605                Ok(Some(((r, c), is_empty))) => {
606                    if is_empty {
607                        continue;
608                    }
609                    any = true;
610                    r0 = r0.min(r);
611                    r1 = r1.max(r);
612                    c0 = c0.min(c);
613                    c1 = c1.max(c);
614                }
615                Ok(None) => break,
616                Err(e) => {
617                    return Err(ExtractError::Parse {
618                        format: "spreadsheet",
619                        message: format!("scanning sheet dimensions: {e}"),
620                    })
621                }
622            }
623        }
624        if !any {
625            return Ok(Some(0));
626        }
627        let rows = u64::from(r1 - r0) + 1;
628        let cols = u64::from(c1 - c0) + 1;
629        Ok(Some(rows.saturating_mul(cols)))
630    }
631
632    match workbook {
633        Sheets::Xlsx(xlsx) => {
634            let mut reader =
635                xlsx.worksheet_cells_reader(name)
636                    .map_err(|e| ExtractError::Parse {
637                        format: "spreadsheet",
638                        message: format!("sheet {name:?}: {e}"),
639                    })?;
640            extent(|| {
641                reader.next_cell().map(|opt| {
642                    opt.map(|c| (c.get_position(), matches!(c.get_value(), DataRef::Empty)))
643                })
644            })
645        }
646        Sheets::Xlsb(xlsb) => {
647            let mut reader =
648                xlsb.worksheet_cells_reader(name)
649                    .map_err(|e| ExtractError::Parse {
650                        format: "spreadsheet",
651                        message: format!("sheet {name:?}: {e}"),
652                    })?;
653            extent(|| {
654                reader.next_cell().map(|opt| {
655                    opt.map(|c| (c.get_position(), matches!(c.get_value(), DataRef::Empty)))
656                })
657            })
658        }
659        // `.xls` (BIFF, format-bounded) and `.ods` expose no sparse iterator on
660        // the auto reader; let them materialize normally.
661        Sheets::Xls(_) | Sheets::Ods(_) => Ok(None),
662    }
663}
664
665/// Render one spreadsheet cell to its text form. Whole-valued floats drop the
666/// `.0` (so `3450.0` → `3450`), matching how spreadsheet apps display an
667/// integer-typed amount.
668fn render_cell(cell: &calamine::Data) -> String {
669    use calamine::Data;
670    match cell {
671        Data::Empty => String::new(),
672        Data::String(s) => s.clone(),
673        Data::Int(i) => i.to_string(),
674        Data::Float(f) => {
675            if f.fract() == 0.0 && f.is_finite() && f.abs() < 1e15 {
676                format!("{}", *f as i64)
677            } else {
678                f.to_string()
679            }
680        }
681        Data::Bool(b) => {
682            if *b {
683                "TRUE".to_string()
684            } else {
685                "FALSE".to_string()
686            }
687        }
688        // A date/datetime cell is an Excel SERIAL number (days since the 1900
689        // epoch, fractional part = time of day). `ExcelDateTime`'s `Display`
690        // writes the raw serial (`46188`, `46143.5`), which is meaningless to an
691        // agent filing the value into a record, so render the calendar date
692        // instead. `to_ymd_hms_milli` is available without the `chrono` feature.
693        Data::DateTime(dt) => render_excel_datetime(dt),
694        Data::DateTimeIso(s) => s.clone(),
695        Data::DurationIso(s) => s.clone(),
696        Data::Error(e) => format!("{e:?}"),
697    }
698}
699
700/// Render an Excel serial date/datetime to an ISO calendar string. A pure date
701/// (midnight, no sub-day component) renders `YYYY-MM-DD`; a datetime with a time
702/// component renders `YYYY-MM-DD HH:MM:SS`. A duration (Excel `[hh]:mm:ss`
703/// elapsed-time format) is not a calendar date, so it keeps its raw serial form
704/// (the prior behavior) rather than being misrendered as a date.
705fn render_excel_datetime(dt: &calamine::ExcelDateTime) -> String {
706    // Guard the serial BEFORE calling `to_ymd_hms_milli`. A date cell carries an
707    // arbitrary (attacker-controlled in `sources/`) f64; calamine's conversion is
708    // only defined over its calendar window (~1899-12-31..9999-12-31, i.e. serial
709    // 0..=2_958_465). Outside it, calamine saturates `floor() as u64` and then
710    // overflows on `days += 109_571` — a panic in debug (abort, exit 101) and a
711    // fabricated far-past date in release (`1e308` → `1899-12-29`), both of which
712    // violate the module contract ("never panics on untrusted input, never
713    // hallucinated text"). A duration is likewise not a calendar point. In every
714    // such case keep the raw serial, exactly as the duration branch always did.
715    let serial = dt.as_f64();
716    if dt.is_duration() || !(0.0..=2_958_465.0).contains(&serial) {
717        return serial.to_string();
718    }
719    let (y, mo, d, h, mi, s, _ms) = dt.to_ymd_hms_milli();
720    if h == 0 && mi == 0 && s == 0 {
721        format!("{y:04}-{mo:02}-{d:02}")
722    } else {
723        format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}:{s:02}")
724    }
725}
726
727// ─────────────────────────────────────────────────────────────────────────────
728// EPUB — zip + quick-xml (spine order) + html2text (per-chapter)
729// ─────────────────────────────────────────────────────────────────────────────
730//
731// We do NOT use the `epub` crate: it is GPL-3.0, which violates the toolkit's
732// permissive-only license rule. An EPUB is a zip whose OPF package declares a
733// reading-order `spine`; each spine item is an XHTML document. zip + quick-xml
734// (already dependencies) read the container/OPF, and html2text (already a
735// dependency for `.html`) flattens each chapter. Same machinery, no GPL.
736
737/// Max spine itemrefs an `.epub` may declare before extraction refuses it. The
738/// spine is attacker-controlled (`parse_opf` pushes every `<itemref>`), so a
739/// few-KB file can declare millions; this bounds the read loop. Far above any
740/// real book (which has well under a few hundred reading-order items).
741const MAX_EPUB_SPINE_ITEMS: usize = 10_000;
742
743/// Hard cap on the accumulated extracted-text bytes (EPUB chapter concatenation).
744/// The backstop for spine amplification: a long spine of distinct chapters, or a
745/// near-cap chapter referenced many times, can't balloon output without bound.
746const MAX_EXTRACT_OUTPUT_BYTES: usize = 64 * 1024 * 1024;
747
748/// Extract an EPUB's reading-order text:
749/// 1. read `META-INF/container.xml` → the OPF package path;
750/// 2. parse the OPF `manifest` (id→href) and `spine` (ordered idref list);
751/// 3. for each spine item, read its XHTML and flatten it with [`html_to_text`];
752/// 4. join chapters with a blank line.
753///
754/// Bounded against spine amplification: the spine length is capped, each
755/// distinct chapter is rendered at most once (memoized), and the total output is
756/// capped — so a tiny crafted `.epub` can neither peg a core nor balloon memory.
757///
758/// Metadata carries `title` (the OPF `dc:title`) and `chapters` (spine length).
759fn extract_epub(path: &Path) -> Result<Extracted> {
760    let file = std::fs::File::open(path)?;
761    let mut archive = open_zip(file, "epub")?;
762
763    // 1. container.xml → OPF path.
764    let container = read_zip_entry(&mut archive, "META-INF/container.xml", "epub")?;
765    let opf_path = epub_opf_path(&container)?;
766
767    // 2. OPF → base dir, manifest, spine, title.
768    let opf = read_zip_entry(&mut archive, &opf_path, "epub")?;
769    let parsed = parse_opf(&opf)?;
770    let base = opf_base_dir(&opf_path);
771
772    // Bound the spine length BEFORE the loop: `parse_opf` pushes every
773    // attacker-controlled `<itemref idref>` verbatim, so a tiny crafted .epub can
774    // declare millions of items. Even spine entries that render to empty text
775    // still cost a zip read each, so the output cap below can't bound the loop on
776    // its own — this guard does. Real books have well under a few hundred items.
777    if parsed.spine.len() > MAX_EPUB_SPINE_ITEMS {
778        return Err(ExtractError::Parse {
779            format: "epub",
780            message: format!(
781                "spine declares {} items, exceeding the {} cap",
782                parsed.spine.len(),
783                MAX_EPUB_SPINE_ITEMS
784            ),
785        });
786    }
787
788    // 3. Spine items in order → flattened chapter text.
789    let mut text = String::new();
790    let mut chapters = 0u64;
791    // Memoize rendered chapters by zip-entry path: a spine that references the
792    // SAME manifest item repeatedly must re-render it in O(1), not re-decode the
793    // zip entry and re-flatten its XHTML each time (the dominant CPU cost of the
794    // spine-amplification DoS — a few-KB file could peg a core indefinitely).
795    let mut rendered: std::collections::HashMap<String, String> = std::collections::HashMap::new();
796    for idref in &parsed.spine {
797        let Some(href) = parsed.manifest.get(idref) else {
798            continue; // dangling spine ref; skip rather than fail
799        };
800        let entry = join_zip_path(&base, href);
801        let chapter_text = match rendered.get(&entry) {
802            Some(cached) => cached.clone(),
803            None => {
804                // A missing spine target is skipped (best-effort), not fatal.
805                let Ok(chapter_xhtml) = read_zip_entry(&mut archive, &entry, "epub") else {
806                    continue;
807                };
808                let t = html_to_text(chapter_xhtml.as_bytes())?;
809                rendered.insert(entry.clone(), t.clone());
810                t
811            }
812        };
813        if !chapter_text.trim().is_empty() {
814            if chapters > 0 {
815                text.push('\n');
816            }
817            text.push_str(&chapter_text);
818            text.push('\n');
819            chapters += 1;
820            // Hard output backstop: a long spine of DISTINCT items, or a near-cap
821            // chapter referenced many times, must not balloon the extracted text
822            // (and stdout) without bound.
823            if text.len() > MAX_EXTRACT_OUTPUT_BYTES {
824                return Err(ExtractError::Parse {
825                    format: "epub",
826                    message: format!(
827                        "extracted text exceeds the {} byte cap",
828                        MAX_EXTRACT_OUTPUT_BYTES
829                    ),
830                });
831            }
832        }
833    }
834
835    let mut out = Extracted::new(text, Format::Epub);
836    out.put_num("chapters", chapters);
837    if let Some(title) = parsed.title {
838        out.put_str("title", title);
839    }
840    Ok(out)
841}
842
843/// The full-path of the OPF package file, read from `META-INF/container.xml`'s
844/// first `<rootfile full-path="…">`.
845fn epub_opf_path(container_xml: &str) -> Result<String> {
846    use quick_xml::events::Event;
847    use quick_xml::reader::Reader;
848
849    let mut reader = Reader::from_str(container_xml);
850    let mut buf = Vec::new();
851    loop {
852        match reader.read_event_into(&mut buf) {
853            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
854                if local_name(e.name().as_ref()) == b"rootfile" {
855                    if let Some(p) = attr_value(&e, b"full-path") {
856                        return Ok(p);
857                    }
858                }
859            }
860            Ok(Event::Eof) => break,
861            Err(e) => {
862                return Err(ExtractError::Parse {
863                    format: "epub",
864                    message: format!("container.xml: {e}"),
865                })
866            }
867            _ => {}
868        }
869        buf.clear();
870    }
871    Err(ExtractError::Parse {
872        format: "epub",
873        message: "container.xml has no <rootfile full-path>".to_string(),
874    })
875}
876
877/// The parsed-out pieces of an OPF package we need for reading-order text.
878struct OpfParsed {
879    /// Manifest: item id → href (relative to the OPF's directory).
880    manifest: BTreeMap<String, String>,
881    /// Spine: ordered list of manifest item ids (the reading order).
882    spine: Vec<String>,
883    /// `dc:title`, if present.
884    title: Option<String>,
885}
886
887/// Parse an OPF package document into its manifest, spine, and title.
888fn parse_opf(opf_xml: &str) -> Result<OpfParsed> {
889    use quick_xml::events::Event;
890    use quick_xml::reader::Reader;
891
892    let mut reader = Reader::from_str(opf_xml);
893    let mut buf = Vec::new();
894
895    let mut manifest = BTreeMap::new();
896    let mut spine = Vec::new();
897    let mut title: Option<String> = None;
898    // Whether we are inside the FIRST `<dc:title>` element, and the text we have
899    // accumulated for it. We accumulate across every Text/GeneralRef/CData event
900    // until the matching End so an entity, comment, or nested element inside the
901    // title does not truncate it.
902    let mut in_title = false;
903    let mut title_buf = String::new();
904
905    loop {
906        match reader.read_event_into(&mut buf) {
907            Ok(Event::Start(e)) => match local_name(e.name().as_ref()) {
908                b"item" => {
909                    if let (Some(id), Some(href)) = (attr_value(&e, b"id"), attr_value(&e, b"href"))
910                    {
911                        manifest.insert(id, href);
912                    }
913                }
914                b"itemref" => {
915                    if let Some(idref) = attr_value(&e, b"idref") {
916                        spine.push(idref);
917                    }
918                }
919                // Only a Start (not a self-closing Empty) opens the title: an
920                // Empty `<dc:title/>` has no content and produces no End event,
921                // so latching `in_title` on it would wrongly capture the next
922                // text node (e.g. the author) as the title.
923                b"title" if title.is_none() => in_title = true,
924                _ => {}
925            },
926            // Self-closing manifest/spine entries are Empty events; the title is
927            // never captured from Empty (see the Start arm's note).
928            Ok(Event::Empty(e)) => match local_name(e.name().as_ref()) {
929                b"item" => {
930                    if let (Some(id), Some(href)) = (attr_value(&e, b"id"), attr_value(&e, b"href"))
931                    {
932                        manifest.insert(id, href);
933                    }
934                }
935                b"itemref" => {
936                    if let Some(idref) = attr_value(&e, b"idref") {
937                        spine.push(idref);
938                    }
939                }
940                _ => {}
941            },
942            Ok(Event::End(e)) => {
943                if in_title && local_name(e.name().as_ref()) == b"title" {
944                    in_title = false;
945                    let s = title_buf.trim();
946                    if !s.is_empty() {
947                        title = Some(s.to_string());
948                    }
949                }
950            }
951            Ok(Event::Text(t)) => {
952                if in_title {
953                    title_buf.push_str(&String::from_utf8_lossy(&t.into_inner()));
954                }
955            }
956            // An entity (`&amp;`) or numeric ref inside the title resolves into
957            // the accumulated value rather than truncating it.
958            Ok(Event::GeneralRef(r)) => {
959                if in_title {
960                    title_buf.push_str(&resolve_entity_ref(&r));
961                }
962            }
963            // CDATA inside `<dc:title>` is literal title text.
964            Ok(Event::CData(c)) => {
965                if in_title {
966                    title_buf.push_str(&String::from_utf8_lossy(&c.into_inner()));
967                }
968            }
969            Ok(Event::Eof) => break,
970            Err(e) => {
971                return Err(ExtractError::Parse {
972                    format: "epub",
973                    message: format!("OPF: {e}"),
974                })
975            }
976            _ => {}
977        }
978        buf.clear();
979    }
980
981    Ok(OpfParsed {
982        manifest,
983        spine,
984        title,
985    })
986}
987
988/// The directory portion of an OPF path (`"OEBPS/content.opf"` → `"OEBPS"`,
989/// `"content.opf"` → `""`), used to resolve manifest hrefs against the OPF's own
990/// location inside the zip.
991fn opf_base_dir(opf_path: &str) -> String {
992    match opf_path.rfind('/') {
993        Some(i) => opf_path[..i].to_string(),
994        None => String::new(),
995    }
996}
997
998/// Join an OPF base dir with a (possibly `./`-prefixed) manifest href into a zip
999/// entry name. Forward-slash only — zip paths are always `/`-separated.
1000///
1001/// OPF manifest hrefs are URLs: the EPUB spec requires reserved characters
1002/// (spaces, non-ASCII) to be percent-encoded, but zip entry NAMES are raw. So an
1003/// href `my%20chapter.xhtml` must be percent-decoded to `my chapter.xhtml`
1004/// before it can match the zip entry, or the chapter is silently dropped. We
1005/// percent-decode the href and then normalize `.`/`..` segments so a relative
1006/// href like `../text/ch1.xhtml` resolves against the OPF's directory.
1007fn join_zip_path(base: &str, href: &str) -> String {
1008    let decoded = percent_decode(href);
1009    let combined = if base.is_empty() {
1010        decoded
1011    } else {
1012        format!("{base}/{decoded}")
1013    };
1014    normalize_zip_path(&combined)
1015}
1016
1017/// Percent-decode a URL path component (`%20` → space, `%C3%A9` → `é`).
1018/// Decodes byte-by-byte then UTF-8-lossy-reinterprets, so a multi-byte
1019/// percent-encoded codepoint (`%C3%A9`) round-trips. A stray `%` not followed by
1020/// two hex digits is emitted verbatim (best-effort, never a panic).
1021fn percent_decode(s: &str) -> String {
1022    let bytes = s.as_bytes();
1023    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
1024    let mut i = 0;
1025    while i < bytes.len() {
1026        if bytes[i] == b'%' && i + 2 < bytes.len() {
1027            let hi = (bytes[i + 1] as char).to_digit(16);
1028            let lo = (bytes[i + 2] as char).to_digit(16);
1029            if let (Some(hi), Some(lo)) = (hi, lo) {
1030                out.push((hi * 16 + lo) as u8);
1031                i += 3;
1032                continue;
1033            }
1034        }
1035        out.push(bytes[i]);
1036        i += 1;
1037    }
1038    String::from_utf8_lossy(&out).into_owned()
1039}
1040
1041/// Resolve `.` and `..` segments in a `/`-separated zip path so a manifest href
1042/// like `../text/ch1.xhtml` (relative to the OPF's directory) maps to the real
1043/// entry name. A leading `..` that would escape the archive root is dropped
1044/// (zip entries have no parent of the root).
1045fn normalize_zip_path(path: &str) -> String {
1046    let mut out: Vec<&str> = Vec::new();
1047    for seg in path.split('/') {
1048        match seg {
1049            "" | "." => {}
1050            ".." => {
1051                out.pop();
1052            }
1053            other => out.push(other),
1054        }
1055    }
1056    out.join("/")
1057}
1058
1059// ─────────────────────────────────────────────────────────────────────────────
1060// HTML — html2text + light markdown-decoration cleanup
1061// ─────────────────────────────────────────────────────────────────────────────
1062
1063/// Extract plain text from an `.html` file.
1064fn extract_html(path: &Path) -> Result<Extracted> {
1065    let bytes = std::fs::read(path)?;
1066    let text = html_to_text(&bytes)?;
1067    Ok(Extracted::new(text, Format::Html))
1068}
1069
1070/// Flatten an HTML/XHTML byte stream to clean plain text.
1071///
1072/// Renders with [`PlainContentDecorator`] — `html2text`'s plain renderer driven
1073/// by a decorator that emits **no** link brackets and **no** `#` heading
1074/// markers, while keeping list-item markers (`*` / `N.`). This removes the two
1075/// decorations at the source instead of post-stripping them: the previous
1076/// approach blindly deleted every `[bracketed]` substring and every leading `#`
1077/// run from the rendered text, which also destroyed *literal* content —
1078/// citation markers (`[1]`, `[sic]`), code subscripts (`x[i]`), and ranking
1079/// prose (`#1 in sales`). The renderer knows which `[`/`#` it produced; literal
1080/// brackets and hashes in the source now survive untouched.
1081///
1082/// A very wide wrap width (10_000) is used so paragraphs are not hard-wrapped by
1083/// the renderer; paragraph structure comes from the source's block elements, and
1084/// final layout is canonicalized by [`normalize_text`].
1085fn html_to_text(html: &[u8]) -> Result<String> {
1086    // Bound block-element nesting BEFORE handing the bytes to html2text. The
1087    // layout engine is super-linear in nesting depth (O(depth^2) observed), so a
1088    // tiny crafted file (`<div>`×40_000 …`</div>`×40_000`, ~440 KB) hangs
1089    // extraction for tens of seconds. `sources/` is untrusted, and every other
1090    // adapter bounds its untrusted input (MAX_ZIP_ENTRY_BYTES, MAX_SPREADSHEET_
1091    // CELLS); the HTML path is the lone unbounded one. This is the missing bound.
1092    // A pure byte cap can't distinguish a 440 KB bomb from a 440 KB legitimate
1093    // article, so we bound the structural cause (depth) rather than size. EPUB
1094    // chapters route through here too, so the guard covers them as well.
1095    if let Some(depth) = html_block_nesting_exceeds(html, MAX_HTML_NESTING_DEPTH) {
1096        return Err(ExtractError::Parse {
1097            format: "html",
1098            message: format!(
1099                "HTML block nesting depth exceeds the {MAX_HTML_NESTING_DEPTH} cap (reached {depth}; \
1100                 malformed or hostile input)"
1101            ),
1102        });
1103    }
1104    html2text::config::with_decorator(PlainContentDecorator)
1105        .string_from_read(html, 10_000)
1106        .map_err(|e| ExtractError::Parse {
1107            format: "html",
1108            message: e.to_string(),
1109        })
1110}
1111
1112/// The deepest block-element nesting `html_to_text` tolerates. No legitimate
1113/// document nests containers anywhere near this deep; the cap exists purely to
1114/// refuse the deeply-nested bomb that makes html2text's layout pass run for
1115/// minutes. Set with large headroom so it can only fire on pathological input.
1116const MAX_HTML_NESTING_DEPTH: usize = 4_096;
1117
1118/// HTML5 void elements — they have no closing tag, so they must NOT increment
1119/// the nesting depth (a document of many sibling `<br>`/`<img>` is flat, not
1120/// deep). Kept lowercase; the scan lowercases the tag name before matching.
1121const HTML_VOID_ELEMENTS: &[&str] = &[
1122    "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source",
1123    "track", "wbr",
1124];
1125
1126/// Scan an HTML byte stream once and return `Some(depth)` if open-tag nesting
1127/// ever exceeds `limit`, else `None`. This is a deliberately crude, allocation-
1128/// free tag scanner — NOT a parser. It tracks only nesting *depth* to bound
1129/// html2text's super-linear layout cost; correctness of the depth count past the
1130/// limit does not matter (we only care whether it is exceeded). Closing tags
1131/// decrement (saturating at 0), void/self-closing tags and comments/doctype/PI
1132/// are ignored, and a `<` not followed by a tag-ish character is treated as
1133/// literal text rather than a tag open (so `a < b` in prose does not inflate it).
1134fn html_block_nesting_exceeds(html: &[u8], limit: usize) -> Option<usize> {
1135    let mut depth: usize = 0;
1136    let mut i = 0usize;
1137    let n = html.len();
1138    while i < n {
1139        if html[i] != b'<' {
1140            i += 1;
1141            continue;
1142        }
1143        // Look at the byte after `<` to classify the tag.
1144        let Some(&c) = html.get(i + 1) else { break };
1145        if c == b'!' || c == b'?' {
1146            // Comment, doctype, CDATA, or processing instruction — skip to `>`.
1147            i = memchr_gt(html, i + 1);
1148            continue;
1149        }
1150        if c == b'/' {
1151            depth = depth.saturating_sub(1);
1152            i = memchr_gt(html, i + 1);
1153            continue;
1154        }
1155        if !c.is_ascii_alphabetic() {
1156            // A stray `<` in text (`a < b`) — not a tag open.
1157            i += 1;
1158            continue;
1159        }
1160        // Find the tag's end `>` and whether it self-closes (`... />`).
1161        // `memchr_gt` returns the index ONE PAST the `>`, so the `>` byte is at
1162        // `end - 1` and the self-closing `/` (`<div/>`, `<div />`) is at `end - 2`.
1163        // (Reading `end - 1` here always saw the `>`, so the check was dead and
1164        // every self-closing NON-void element was miscounted as an open tag —
1165        // tripping the depth cap on a flat, valid document.)
1166        let end = memchr_gt(html, i + 1);
1167        let self_closing = end >= 2 && html.get(end - 2) == Some(&b'/');
1168        // Extract the tag name (letters/digits after `<`).
1169        let name_end = (i + 1..end.min(n))
1170            .find(|&j| !html[j].is_ascii_alphanumeric())
1171            .unwrap_or(end.min(n));
1172        let name = html[i + 1..name_end].to_ascii_lowercase();
1173        let is_void = std::str::from_utf8(&name)
1174            .map(|s| HTML_VOID_ELEMENTS.contains(&s))
1175            .unwrap_or(false);
1176        if !self_closing && !is_void {
1177            depth += 1;
1178            if depth > limit {
1179                return Some(depth);
1180            }
1181        }
1182        i = end;
1183    }
1184    None
1185}
1186
1187/// Index just past the next `>` at or after `from` (or `len` if none). Small
1188/// helper so [`html_block_nesting_exceeds`] always makes forward progress.
1189fn memchr_gt(hay: &[u8], from: usize) -> usize {
1190    let mut j = from;
1191    while j < hay.len() {
1192        if hay[j] == b'>' {
1193            return j + 1;
1194        }
1195        j += 1;
1196    }
1197    hay.len()
1198}
1199
1200/// A `html2text` decorator that flattens HTML to plain text WITHOUT emitting the
1201/// markup that would otherwise have to be post-stripped: no `[`/`]` around link
1202/// text, no `#` heading prefix, no `^{…}` superscript braces. List-item markers
1203/// (`* ` for unordered, `N. ` for ordered) ARE emitted — they are content-
1204/// faithful and match the corpus convention. Quote prefixes are kept as in the
1205/// stock plain decorator. This is the fix for the literal-content corruption the
1206/// old `strip_markdown_decorations`/`unwrap_brackets` post-pass caused.
1207#[derive(Clone, Debug)]
1208struct PlainContentDecorator;
1209
1210impl html2text::render::TextDecorator for PlainContentDecorator {
1211    type Annotation = ();
1212
1213    fn decorate_link_start(&mut self, _url: &str) -> (String, Self::Annotation) {
1214        (String::new(), ())
1215    }
1216    fn decorate_link_end(&mut self) -> String {
1217        String::new()
1218    }
1219    fn decorate_em_start(&self) -> (String, Self::Annotation) {
1220        (String::new(), ())
1221    }
1222    fn decorate_em_end(&self) -> String {
1223        String::new()
1224    }
1225    fn decorate_strong_start(&self) -> (String, Self::Annotation) {
1226        (String::new(), ())
1227    }
1228    fn decorate_strong_end(&self) -> String {
1229        String::new()
1230    }
1231    fn decorate_strikeout_start(&self) -> (String, Self::Annotation) {
1232        (String::new(), ())
1233    }
1234    fn decorate_strikeout_end(&self) -> String {
1235        String::new()
1236    }
1237    fn decorate_code_start(&self) -> (String, Self::Annotation) {
1238        (String::new(), ())
1239    }
1240    fn decorate_code_end(&self) -> String {
1241        String::new()
1242    }
1243    fn decorate_preformat_first(&self) -> Self::Annotation {}
1244    fn decorate_preformat_cont(&self) -> Self::Annotation {}
1245    fn decorate_image(&mut self, _src: &str, title: &str) -> (String, Self::Annotation) {
1246        // Alt/title text only — no surrounding brackets (the stock plain
1247        // decorator wraps it in `[...]`, which would read as literal content).
1248        (title.to_string(), ())
1249    }
1250    fn header_prefix(&self, _level: usize) -> String {
1251        // No `#` heading marker — heading text reads as plain prose.
1252        String::new()
1253    }
1254    fn quote_prefix(&self) -> String {
1255        "> ".to_string()
1256    }
1257    fn unordered_item_prefix(&self) -> String {
1258        "* ".to_string()
1259    }
1260    fn ordered_item_prefix(&self, i: i64) -> String {
1261        format!("{i}. ")
1262    }
1263    fn decorate_superscript_start(&self) -> (String, Self::Annotation) {
1264        // Plain text: no `^{…}` braces (which would corrupt literal content).
1265        (String::new(), ())
1266    }
1267    fn decorate_superscript_end(&self) -> String {
1268        String::new()
1269    }
1270    fn make_subblock_decorator(&self) -> Self {
1271        PlainContentDecorator
1272    }
1273}
1274
1275/// Strip the residual markdown decorations `html2text`'s plain renderer emits:
1276/// leading run of `#` (ATX heading markers) at the start of a line, and `[...]`
1277/// brackets around link/anchor text (the reference-style `[n]` suffix is already
1278/// gone under `plain_no_decorate`). Bullet (`*`) and ordered (`N.`) markers are
1279/// left intact — they are content, not decoration.
1280///
1281/// No longer used by [`html_to_text`] (the [`PlainContentDecorator`] now removes
1282/// these decorations at the source so literal `[brackets]`/`#hashes` survive);
1283/// retained only for its unit test documenting the old renderer's behavior.
1284#[allow(dead_code)]
1285fn strip_markdown_decorations(text: &str) -> String {
1286    let mut out = String::with_capacity(text.len());
1287    for line in text.lines() {
1288        // Strip a leading "#"-run + the single space after it (ATX heading).
1289        let trimmed = line.trim_start();
1290        let after_hashes = trimmed.trim_start_matches('#');
1291        let line = if after_hashes.len() != trimmed.len() {
1292            // It was a heading line: keep indentation-free heading text.
1293            after_hashes.trim_start()
1294        } else {
1295            line
1296        };
1297        out.push_str(&unwrap_brackets(line));
1298        out.push('\n');
1299    }
1300    out
1301}
1302
1303/// Replace every `[inner]` with `inner` (one pass, non-nested). `html2text`'s
1304/// plain renderer wraps link/anchor text in single brackets; unwrapping yields
1305/// the bare text. Escaped or unmatched brackets are left as-is.
1306///
1307/// No longer used by [`html_to_text`] (see [`strip_markdown_decorations`]);
1308/// retained only for its unit test.
1309#[allow(dead_code)]
1310fn unwrap_brackets(line: &str) -> String {
1311    if !line.contains('[') {
1312        return line.to_string();
1313    }
1314    let mut out = String::with_capacity(line.len());
1315    let mut chars = line.chars().peekable();
1316    while let Some(c) = chars.next() {
1317        if c == '[' {
1318            // Collect until the matching ']'; if none, emit the '[' literally.
1319            let mut inner = String::new();
1320            let mut closed = false;
1321            for d in chars.by_ref() {
1322                if d == ']' {
1323                    closed = true;
1324                    break;
1325                }
1326                inner.push(d);
1327            }
1328            if closed {
1329                out.push_str(&inner);
1330            } else {
1331                out.push('[');
1332                out.push_str(&inner);
1333            }
1334        } else {
1335            out.push(c);
1336        }
1337    }
1338    out
1339}
1340
1341// ─────────────────────────────────────────────────────────────────────────────
1342// Shared zip helpers (docx + epub)
1343// ─────────────────────────────────────────────────────────────────────────────
1344
1345/// Open a zip archive from a reader, mapping any failure to a typed
1346/// [`ExtractError::Parse`] tagged with the calling format.
1347fn open_zip<R: Read + std::io::Seek>(
1348    reader: R,
1349    format: &'static str,
1350) -> Result<zip::ZipArchive<R>> {
1351    zip::ZipArchive::new(reader).map_err(|e| ExtractError::Parse {
1352        format,
1353        message: format!("not a valid zip container: {e}"),
1354    })
1355}
1356
1357/// Cap on a single decompressed zip entry. docx/epub members are XML text — a
1358/// member that inflates past this ceiling is a decompression bomb or corruption,
1359/// not real evidence. `sources/` is untrusted input, so bound the read rather
1360/// than let `read_to_end` follow a hostile DEFLATE stream until OOM.
1361const MAX_ZIP_ENTRY_BYTES: u64 = 256 * 1024 * 1024;
1362
1363/// Read a single zip entry to a UTF-8 string, bounded by [`MAX_ZIP_ENTRY_BYTES`]
1364/// so a zip-bomb member cannot exhaust memory. A missing entry, an over-cap
1365/// entry, or a read failure is a typed [`ExtractError::Parse`]; invalid UTF-8 is
1366/// lossily decoded (OOXML / XHTML are declared UTF-8, but we never panic on a
1367/// stray byte).
1368fn read_zip_entry<R: Read + std::io::Seek>(
1369    archive: &mut zip::ZipArchive<R>,
1370    name: &str,
1371    format: &'static str,
1372) -> Result<String> {
1373    let entry = archive.by_name(name).map_err(|e| ExtractError::Parse {
1374        format,
1375        message: format!("missing zip entry {name:?}: {e}"),
1376    })?;
1377    // Reject up front when the central directory declares an over-cap size...
1378    let declared = entry.size();
1379    if declared > MAX_ZIP_ENTRY_BYTES {
1380        return Err(ExtractError::Parse {
1381            format,
1382            message: format!(
1383                "zip entry {name:?} declares {declared} bytes, over the {MAX_ZIP_ENTRY_BYTES}-byte cap"
1384            ),
1385        });
1386    }
1387    // ...and bound the actual decompressed read so a lying header (a bomb that
1388    // understates its uncompressed size) still cannot allocate past the cap.
1389    let mut bytes = Vec::new();
1390    entry
1391        .take(MAX_ZIP_ENTRY_BYTES + 1)
1392        .read_to_end(&mut bytes)
1393        .map_err(|e| ExtractError::Parse {
1394            format,
1395            message: format!("reading {name:?}: {e}"),
1396        })?;
1397    if bytes.len() as u64 > MAX_ZIP_ENTRY_BYTES {
1398        return Err(ExtractError::Parse {
1399            format,
1400            message: format!(
1401                "zip entry {name:?} exceeds the {MAX_ZIP_ENTRY_BYTES}-byte cap (decompression bomb?)"
1402            ),
1403        });
1404    }
1405    Ok(String::from_utf8_lossy(&bytes).into_owned())
1406}
1407
1408/// Look up a start/empty element's attribute value by local name, returning it
1409/// unescaped as an owned `String`. Prefix-agnostic on the attribute key.
1410fn attr_value(elem: &quick_xml::events::BytesStart<'_>, key: &[u8]) -> Option<String> {
1411    elem.attributes().flatten().find_map(|attr| {
1412        if local_name(attr.key.as_ref()) == key {
1413            // `unescape_value` returns an XML-unescaped `Cow<str>` — exactly the
1414            // owned attribute text we want. It is soft-deprecated in quick-xml
1415            // 0.40 in favor of `normalized_value(XmlVersion)`, whose extra
1416            // version arg and byte-Cow return buy us nothing here; the simple
1417            // form is correct for the UTF-8 OOXML/OPF attributes we read.
1418            #[allow(deprecated)]
1419            attr.unescape_value().ok().map(|cow| cow.into_owned())
1420        } else {
1421            None
1422        }
1423    })
1424}
1425
1426#[cfg(test)]
1427mod tests {
1428    use super::*;
1429    use std::path::PathBuf;
1430
1431    /// Absolute path to a corpus-c-formats fixture under `sources/docs/`.
1432    fn fixture(name: &str) -> PathBuf {
1433        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1434            .join("../../tests/corpora/corpus-c-formats/sources/docs")
1435            .join(name)
1436    }
1437
1438    /// Read the known-good `.txt` sibling of a fixture.
1439    fn expected(name: &str) -> String {
1440        std::fs::read_to_string(fixture(&format!("{name}.txt"))).unwrap()
1441    }
1442
1443    /// Token-level normalization: collapse every run of whitespace (incl.
1444    /// newlines) to one space and trim. This is the corpus's recommended,
1445    /// layout-agnostic comparison ("same words, same order").
1446    fn tokens(s: &str) -> String {
1447        s.split_whitespace().collect::<Vec<_>>().join(" ")
1448    }
1449
1450    /// The sorted set of non-blank, token-normalized lines — order-agnostic
1451    /// content comparison (used where extractor reading-order legitimately
1452    /// differs, e.g. multi-column PDF).
1453    fn line_set(s: &str) -> Vec<String> {
1454        let mut v: Vec<String> = s.lines().map(tokens).filter(|l| !l.is_empty()).collect();
1455        v.sort();
1456        v
1457    }
1458
1459    // ── untrusted-input guards (adversarial review) ──────────────────────────
1460
1461    /// A crafted spreadsheet date cell carries an arbitrary f64 serial. An
1462    /// out-of-range serial must NOT panic (debug `attempt to add with overflow`)
1463    /// and must NOT fabricate a calendar date (release `1e308` → `1899-12-29`);
1464    /// it keeps the raw serial, exactly like the duration fallback.
1465    #[test]
1466    fn excel_datetime_out_of_range_serial_stays_raw_and_never_panics() {
1467        use calamine::{ExcelDateTime, ExcelDateTimeType};
1468        // In-range serial → a real calendar date (contains a `-`).
1469        let in_range = render_excel_datetime(&ExcelDateTime::new(
1470            46_188.0,
1471            ExcelDateTimeType::DateTime,
1472            false,
1473        ));
1474        assert!(
1475            in_range.contains('-'),
1476            "an in-range serial should render a calendar date, got {in_range}"
1477        );
1478        // Out-of-range / hostile serials keep the raw serial string, no panic.
1479        for serial in [1e308_f64, 3_000_000.0, 9e18, -5.0] {
1480            let out = render_excel_datetime(&ExcelDateTime::new(
1481                serial,
1482                ExcelDateTimeType::DateTime,
1483                false,
1484            ));
1485            assert_eq!(
1486                out,
1487                serial.to_string(),
1488                "out-of-range serial {serial} must stay raw, got {out}"
1489            );
1490        }
1491    }
1492
1493    /// The HTML adapter's block-nesting guard refuses a deeply-nested bomb (the
1494    /// O(depth^2) html2text blowup) while passing flat documents — including ones
1495    /// with tens of thousands of sibling VOID elements (which must not count as
1496    /// depth) and prose containing a literal `<`.
1497    #[test]
1498    fn html_nesting_guard_refuses_deep_bomb_passes_flat() {
1499        let deep = format!(
1500            "<html><body>{}x{}</body></html>",
1501            "<div>".repeat(8_000),
1502            "</div>".repeat(8_000)
1503        );
1504        assert!(
1505            html_block_nesting_exceeds(deep.as_bytes(), MAX_HTML_NESTING_DEPTH).is_some(),
1506            "an 8000-deep nest must trip the guard"
1507        );
1508        assert!(
1509            html_to_text(deep.as_bytes()).is_err(),
1510            "html_to_text must refuse the bomb (typed error), not hang"
1511        );
1512
1513        let flat = format!("<html><body>{}</body></html>", "<br>".repeat(50_000));
1514        assert!(
1515            html_block_nesting_exceeds(flat.as_bytes(), MAX_HTML_NESTING_DEPTH).is_none(),
1516            "50k sibling void <br> are flat, not deep — must pass"
1517        );
1518
1519        let normal =
1520            "<html><body><div><p>hi <a href=\"u\">link</a>; a < b in prose</p></div></body></html>";
1521        assert!(
1522            html_block_nesting_exceeds(normal.as_bytes(), MAX_HTML_NESTING_DEPTH).is_none(),
1523            "ordinary nesting (and a stray `<`) must pass"
1524        );
1525        assert!(
1526            html_to_text(normal.as_bytes()).is_ok(),
1527            "a normal document must still flatten fine"
1528        );
1529    }
1530
1531    #[test]
1532    fn regression_html_self_closing_non_void_is_flat_not_deep() {
1533        // Adversarial review #17: a self-closing NON-void element (`<div/>`,
1534        // `<section />`) is flat, not a nesting increment. The off-by-one read the
1535        // `>` byte (always present) instead of the `/` (at end-2), so the
1536        // self-closing check was dead and N such elements miscounted as depth N,
1537        // falsely tripping the cap on a valid, flat document (XHTML/EPUB chapters
1538        // commonly self-close).
1539        let flat = "<div/>".repeat(MAX_HTML_NESTING_DEPTH + 1000);
1540        assert!(
1541            html_block_nesting_exceeds(flat.as_bytes(), MAX_HTML_NESTING_DEPTH).is_none(),
1542            "a flat run of self-closing <div/> must not trip the nesting cap"
1543        );
1544        let spaced = "<section />".repeat(MAX_HTML_NESTING_DEPTH + 1000);
1545        assert!(
1546            html_block_nesting_exceeds(spaced.as_bytes(), MAX_HTML_NESTING_DEPTH).is_none(),
1547            "`<section />` (space before slash) is self-closing too"
1548        );
1549        // Defense intact: genuine deep nesting of the SAME tag still trips it.
1550        let deep = "<div>".repeat(MAX_HTML_NESTING_DEPTH + 1);
1551        assert!(
1552            html_block_nesting_exceeds(deep.as_bytes(), MAX_HTML_NESTING_DEPTH).is_some(),
1553            "real deep nesting must still trip the cap"
1554        );
1555    }
1556
1557    // ── format detection ────────────────────────────────────────────────────
1558
1559    #[test]
1560    fn detects_format_by_extension_case_insensitively() {
1561        assert_eq!(Format::from_path(Path::new("a.pdf")), Some(Format::Pdf));
1562        assert_eq!(Format::from_path(Path::new("a.PDF")), Some(Format::Pdf));
1563        assert_eq!(Format::from_path(Path::new("a.docx")), Some(Format::Docx));
1564        assert_eq!(
1565            Format::from_path(Path::new("a.xlsx")),
1566            Some(Format::Spreadsheet)
1567        );
1568        assert_eq!(
1569            Format::from_path(Path::new("a.ods")),
1570            Some(Format::Spreadsheet)
1571        );
1572        assert_eq!(Format::from_path(Path::new("a.epub")), Some(Format::Epub));
1573        assert_eq!(Format::from_path(Path::new("a.html")), Some(Format::Html));
1574        assert_eq!(Format::from_path(Path::new("a.htm")), Some(Format::Html));
1575        assert_eq!(Format::from_path(Path::new("a.txt")), None);
1576        assert_eq!(Format::from_path(Path::new("noext")), None);
1577    }
1578
1579    #[test]
1580    fn unsupported_extension_is_typed_error() {
1581        let err = extract(Path::new("/tmp/whatever.txt")).unwrap_err();
1582        assert!(matches!(err, ExtractError::UnsupportedFormat(ref e) if e == "txt"));
1583        assert_eq!(err.code(), "UNSUPPORTED_FORMAT");
1584    }
1585
1586    #[test]
1587    fn missing_extension_is_unsupported() {
1588        let err = extract(Path::new("/tmp/noext")).unwrap_err();
1589        assert!(matches!(err, ExtractError::UnsupportedFormat(ref e) if e.is_empty()));
1590    }
1591
1592    // ── normalization ─────────────────────────────────────────────────────────
1593
1594    #[test]
1595    fn normalize_collapses_blanks_and_trims() {
1596        let raw = "\r\n\r\nHeading\r\n\r\n\r\n\r\nBody line   \r\n\r\n";
1597        assert_eq!(normalize_text(raw), "Heading\n\nBody line\n");
1598    }
1599
1600    #[test]
1601    fn normalize_empty_stays_empty() {
1602        assert_eq!(normalize_text(""), "");
1603        assert_eq!(normalize_text("   \n\n  \n"), "");
1604    }
1605
1606    // ── per-format extraction against corpus-c fixtures ───────────────────────
1607
1608    #[test]
1609    fn extract_text_pdf_matches_known_good() {
1610        let got = extract(&fixture("text.pdf")).unwrap();
1611        assert_eq!(got.metadata["format"], MetaValue::Str("pdf".into()));
1612        assert_eq!(got.metadata["pages"], MetaValue::Num(1));
1613        assert_eq!(tokens(&got.text), tokens(&expected("text.pdf")));
1614    }
1615
1616    #[test]
1617    fn extract_weird_fonts_pdf_matches_known_good() {
1618        let got = extract(&fixture("weird-fonts.pdf")).unwrap();
1619        assert_eq!(tokens(&got.text), tokens(&expected("weird-fonts.pdf")));
1620    }
1621
1622    #[test]
1623    fn extract_multi_column_pdf_matches_content_order_agnostic() {
1624        // pdf-extract reads column-by-column; the known-good `.txt` captures the
1625        // interleaved (pdftotext) order. Both carry identical content — assert
1626        // the line SET, not the order. (README § multi-column.)
1627        let got = extract(&fixture("multi-column.pdf")).unwrap();
1628        assert_eq!(line_set(&got.text), line_set(&expected("multi-column.pdf")));
1629    }
1630
1631    #[test]
1632    fn extract_image_only_pdf_yields_empty() {
1633        // No text layer → empty out, never hallucinated text. OCR out of scope.
1634        let got = extract(&fixture("image-only.pdf")).unwrap();
1635        assert_eq!(got.text, "");
1636        assert!(expected("image-only.pdf").trim().is_empty());
1637    }
1638
1639    #[test]
1640    fn extract_encrypted_pdf_without_password_refuses_cleanly() {
1641        let err = extract(&fixture("encrypted.pdf")).unwrap_err();
1642        assert!(
1643            matches!(err, ExtractError::Encrypted(_)),
1644            "expected Encrypted, got {err:?}"
1645        );
1646        assert_eq!(err.code(), "DOCUMENT_ENCRYPTED");
1647    }
1648
1649    #[test]
1650    fn guard_pdf_panic_contains_unwind_as_parse_error() {
1651        // The "never panics" contract: an internal pdf-extract/lopdf panic must
1652        // surface as a typed ExtractError::Parse, not abort the process. (cargo
1653        // captures the unwind's stderr line for a passing test.)
1654        let contained: Result<()> = guard_pdf_panic(|| panic!("simulated pdf-extract abort"));
1655        assert!(
1656            matches!(contained, Err(ExtractError::Parse { format: "pdf", .. })),
1657            "panic must be contained as a pdf Parse error, got {contained:?}"
1658        );
1659        // The success path is transparent — the value passes straight through.
1660        let ok: Result<u32> = guard_pdf_panic(|| 42);
1661        assert_eq!(ok.unwrap(), 42);
1662    }
1663
1664    #[test]
1665    fn extract_docx_matches_known_good() {
1666        let got = extract(&fixture("sample.docx")).unwrap();
1667        assert_eq!(got.metadata["format"], MetaValue::Str("docx".into()));
1668        assert_eq!(tokens(&got.text), tokens(&expected("sample.docx")));
1669    }
1670
1671    #[test]
1672    fn extract_xlsx_matches_known_good() {
1673        let got = extract(&fixture("sample.xlsx")).unwrap();
1674        assert_eq!(got.metadata["format"], MetaValue::Str("spreadsheet".into()));
1675        assert_eq!(got.metadata["sheets"], MetaValue::Num(1));
1676        assert_eq!(
1677            got.metadata["sheet_names"],
1678            MetaValue::Str("Expenses".into())
1679        );
1680        // Tab-separated, integers without `.0` — exact match (no soft-wrap risk).
1681        assert_eq!(got.text.trim_end(), expected("sample.xlsx").trim_end());
1682    }
1683
1684    #[test]
1685    fn extract_epub_matches_known_good() {
1686        let got = extract(&fixture("sample.epub")).unwrap();
1687        assert_eq!(got.metadata["format"], MetaValue::Str("epub".into()));
1688        assert_eq!(got.metadata["chapters"], MetaValue::Num(1));
1689        assert_eq!(
1690            got.metadata["title"],
1691            MetaValue::Str("Operations Playbook".into())
1692        );
1693        assert_eq!(tokens(&got.text), tokens(&expected("sample.epub")));
1694    }
1695
1696    #[test]
1697    fn extract_html_matches_known_good() {
1698        let got = extract(&fixture("sample.html")).unwrap();
1699        assert_eq!(got.metadata["format"], MetaValue::Str("html".into()));
1700        assert_eq!(tokens(&got.text), tokens(&expected("sample.html")));
1701    }
1702
1703    // ── helper-level unit tests ───────────────────────────────────────────────
1704
1705    #[test]
1706    fn unwrap_brackets_flattens_link_text() {
1707        assert_eq!(
1708            unwrap_brackets("contact [ops@acme.example] or the [handbook]."),
1709            "contact ops@acme.example or the handbook."
1710        );
1711        // Unmatched '[' is preserved.
1712        assert_eq!(unwrap_brackets("a [b c"), "a [b c");
1713        // No brackets → untouched.
1714        assert_eq!(unwrap_brackets("plain text"), "plain text");
1715    }
1716
1717    #[test]
1718    fn strip_markdown_decorations_drops_heading_hashes() {
1719        let input = "# Title\n## Section\n* bullet\n1. ordered\nplain\n";
1720        let out = strip_markdown_decorations(input);
1721        assert_eq!(out, "Title\nSection\n* bullet\n1. ordered\nplain\n");
1722    }
1723
1724    #[test]
1725    fn local_name_strips_prefix() {
1726        assert_eq!(local_name(b"w:t"), b"t");
1727        assert_eq!(local_name(b"t"), b"t");
1728        assert_eq!(local_name(b"dc:title"), b"title");
1729    }
1730
1731    #[test]
1732    fn extracted_serializes_to_text_metadata_json() {
1733        let got = extract(&fixture("sample.xlsx")).unwrap();
1734        let json = serde_json::to_value(&got).unwrap();
1735        assert!(json.get("text").is_some());
1736        assert_eq!(json["metadata"]["format"], "spreadsheet");
1737        assert_eq!(json["metadata"]["sheets"], 1);
1738        // MetaValue::Num serializes as a bare JSON number, Str as a bare string.
1739        assert!(json["metadata"]["sheets"].is_number());
1740        assert!(json["metadata"]["format"].is_string());
1741    }
1742
1743    // ── regression: leading-blank normalization is linear (finding #13) ────────
1744
1745    /// `normalize_text` must trim leading blank lines in O(n), not O(n²). The
1746    /// pre-fix loop used `lines.remove(0)` per blank line — O(n) shift each, so a
1747    /// document dominated by leading blanks took O(n²) and hung extraction.
1748    ///
1749    /// 500_000 leading blank lines is ~2.5e11 element shifts under the old code
1750    /// (minutes-to-hours, effectively a hang) but instant under the index-and-
1751    /// slice path; the test reconstructs the finding's trigger (an adapter output
1752    /// that is mostly leading blanks then one line of text) and asserts the
1753    /// correct, fully-trimmed result. Against the pre-fix code this test does not
1754    /// complete in a reasonable time — encoding the quadratic regression.
1755    #[test]
1756    fn regression_normalize_text_leading_blanks_is_linear() {
1757        let blanks = "\n".repeat(500_000);
1758        let raw = format!("{blanks}only real line\n");
1759        // Leading blanks fully trimmed; single trailing newline; body intact.
1760        assert_eq!(normalize_text(&raw), "only real line\n");
1761
1762        // A wholly-blank giant input still collapses to empty (the other branch).
1763        assert_eq!(normalize_text(&"   \n".repeat(500_000)), "");
1764    }
1765
1766    // ── regression: spreadsheet dense-grid bomb is refused (finding #4) ────────
1767
1768    /// Build a VALID `.xlsx` whose single sheet declares two real cells at the
1769    /// opposite corners of Excel's grid (`A1` and `XFD1048576`). `calamine`
1770    /// materializes a sheet as a DENSE `Vec<Data>` sized from the MIN/MAX cell
1771    /// positions, so this two-cell sheet would force a ~1.7e10-element (~400 GB)
1772    /// allocation and abort the process. We reuse the corpus `sample.xlsx`
1773    /// container verbatim and swap ONLY `xl/worksheets/sheet1.xml`, so every
1774    /// other part (workbook, rels, content-types) is a real, openable workbook.
1775    fn write_dense_bomb_xlsx(dest: &Path) {
1776        use std::io::Write;
1777
1778        let base = std::fs::read(fixture("sample.xlsx")).expect("corpus sample.xlsx exists");
1779        let mut archive =
1780            zip::ZipArchive::new(std::io::Cursor::new(base)).expect("sample.xlsx is a valid zip");
1781
1782        let bomb_sheet = b"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\
1783<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">\
1784<sheetData>\
1785<row r=\"1\"><c r=\"A1\"><v>1</v></c></row>\
1786<row r=\"1048576\"><c r=\"XFD1048576\"><v>2</v></c></row>\
1787</sheetData></worksheet>";
1788
1789        let out = std::fs::File::create(dest).unwrap();
1790        let mut writer = zip::ZipWriter::new(out);
1791        let opts = zip::write::SimpleFileOptions::default()
1792            .compression_method(zip::CompressionMethod::Stored);
1793
1794        for i in 0..archive.len() {
1795            let entry = archive.by_index(i).unwrap();
1796            let name = entry.name().to_string();
1797            if name == "xl/worksheets/sheet1.xml" {
1798                writer.start_file(name, opts).unwrap();
1799                writer.write_all(bomb_sheet).unwrap();
1800            } else {
1801                // Copy every other entry's already-compressed bytes verbatim.
1802                writer.raw_copy_file(entry).unwrap();
1803            }
1804        }
1805        writer.finish().unwrap();
1806    }
1807
1808    /// A spreadsheet whose declared dense grid exceeds [`MAX_SPREADSHEET_CELLS`]
1809    /// is refused with a typed [`ExtractError::Parse`] BEFORE calamine allocates
1810    /// the dense matrix — never an OOM/abort. Pre-fix, `extract_spreadsheet`
1811    /// called `worksheet_range` directly and the process aborted on the
1812    /// allocation; this test would not return (it would kill the test runner),
1813    /// so it encodes the resource-exhaustion regression.
1814    #[test]
1815    fn regression_spreadsheet_dense_bomb_refused_not_oom() {
1816        let tmp = tempfile::TempDir::new().unwrap();
1817        let bomb = tmp.path().join("invoice.xlsx");
1818        write_dense_bomb_xlsx(&bomb);
1819
1820        // A few-hundred-byte file on disk — the whole point of the bomb.
1821        assert!(
1822            std::fs::metadata(&bomb).unwrap().len() < 10_000,
1823            "the bomb must be tiny on disk; the danger is the in-memory expansion"
1824        );
1825
1826        let err = extract(&bomb).unwrap_err();
1827        assert!(
1828            matches!(
1829                err,
1830                ExtractError::Parse {
1831                    format: "spreadsheet",
1832                    ..
1833                }
1834            ),
1835            "an over-cap dense grid must be a typed spreadsheet Parse refusal, got {err:?}"
1836        );
1837        assert_eq!(err.code(), "EXTRACT_PARSE_ERROR");
1838    }
1839
1840    /// The cap is a guard, not a wall: a normal spreadsheet still extracts. Locks
1841    /// down that the preflight bound does not regress the legitimate path (the
1842    /// corpus `sample.xlsx` is a 3×3 grid, far under the cap).
1843    #[test]
1844    fn regression_spreadsheet_cap_allows_real_workbook() {
1845        let got = extract(&fixture("sample.xlsx")).unwrap();
1846        assert_eq!(got.metadata["sheets"], MetaValue::Num(1));
1847        assert!(!got.text.is_empty());
1848    }
1849
1850    // ── regression: entity-ref / CDATA fidelity (findings #34, #1011) ──────────
1851
1852    /// Build a minimal valid `.docx` whose `word/document.xml` body is the given
1853    /// run XML, written to `dest`. Only the three OOXML members `extract_docx`
1854    /// touches need to be real; the rest of a Word package is optional for text
1855    /// extraction.
1856    fn write_docx(dest: &Path, body_runs: &str) {
1857        use std::io::Write;
1858        let document = format!(
1859            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\
1860<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">\
1861<w:body>{body_runs}</w:body></w:document>"
1862        );
1863        let file = std::fs::File::create(dest).unwrap();
1864        let mut writer = zip::ZipWriter::new(file);
1865        let opts = zip::write::SimpleFileOptions::default()
1866            .compression_method(zip::CompressionMethod::Stored);
1867        writer.start_file("word/document.xml", opts).unwrap();
1868        writer.write_all(document.as_bytes()).unwrap();
1869        writer.finish().unwrap();
1870    }
1871
1872    #[test]
1873    fn regression_docx_resolves_entity_refs() {
1874        // quick-xml 0.40 surfaces `&amp;`/`&lt;`/`&gt;`/`&#8212;` as separate
1875        // GeneralRef events; pre-fix they were routed to `_ => {}` and dropped,
1876        // corrupting `Smith & Co invoice <final> total — 100`.
1877        let tmp = tempfile::TempDir::new().unwrap();
1878        let f = tmp.path().join("entity.docx");
1879        write_docx(
1880            &f,
1881            "<w:p><w:r><w:t>Smith &amp; Co invoice &lt;final&gt; total &#8212; 100</w:t></w:r></w:p>",
1882        );
1883        let got = extract(&f).unwrap();
1884        assert_eq!(got.text, "Smith & Co invoice <final> total — 100\n");
1885    }
1886
1887    #[test]
1888    fn regression_docx_preserves_cdata_run_text() {
1889        // CDATA inside `<w:t>` is valid and literal; pre-fix it fell through the
1890        // wildcard arm and the payload vanished.
1891        let tmp = tempfile::TempDir::new().unwrap();
1892        let f = tmp.path().join("cdata.docx");
1893        write_docx(
1894            &f,
1895            "<w:p><w:r><w:t>Line A.</w:t></w:r></w:p>\
1896<w:p><w:r><w:t><![CDATA[IMPORTANT CDATA CONTENT]]></w:t></w:r></w:p>\
1897<w:p><w:r><w:t>Line C.</w:t></w:r></w:p>",
1898        );
1899        let got = extract(&f).unwrap();
1900        assert_eq!(got.text, "Line A.\nIMPORTANT CDATA CONTENT\nLine C.\n");
1901    }
1902
1903    #[test]
1904    fn resolve_entity_ref_maps_named_and_numeric() {
1905        use quick_xml::events::BytesRef;
1906        let r = |s: &'static str| resolve_entity_ref(&BytesRef::new(s));
1907        assert_eq!(r("amp"), "&");
1908        assert_eq!(r("lt"), "<");
1909        assert_eq!(r("gt"), ">");
1910        assert_eq!(r("quot"), "\"");
1911        assert_eq!(r("apos"), "'");
1912        assert_eq!(r("#8212"), "—");
1913        assert_eq!(r("#x2014"), "—");
1914        // Unknown named entity → bare name (best-effort, never a panic).
1915        assert_eq!(r("nbsp"), "nbsp");
1916    }
1917
1918    // ── regression: EPUB OPF parsing (findings #35, #37, #1012) ────────────────
1919
1920    /// Build a minimal valid EPUB at `dest`. `opf_metadata` is spliced verbatim
1921    /// inside `<metadata>`; `manifest_href` is the chapter item's href; the
1922    /// chapter XHTML is stored under the literal zip entry `chapter_entry`. The
1923    /// mimetype member is written first and stored (per the EPUB OCF spec).
1924    fn write_epub(dest: &Path, opf_metadata: &str, manifest_href: &str, chapter_entry: &str) {
1925        use std::io::Write;
1926        let container = "<?xml version=\"1.0\"?>\
1927<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\
1928<rootfiles><rootfile full-path=\"OEBPS/content.opf\" \
1929media-type=\"application/oebps-package+xml\"/></rootfiles></container>";
1930        let opf = format!(
1931            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
1932<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"id\">\
1933<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">{opf_metadata}</metadata>\
1934<manifest><item id=\"c1\" href=\"{manifest_href}\" media-type=\"application/xhtml+xml\"/></manifest>\
1935<spine><itemref idref=\"c1\"/></spine></package>"
1936        );
1937        let chapter = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
1938<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>\
1939<p>Hello world body text.</p></body></html>";
1940
1941        let file = std::fs::File::create(dest).unwrap();
1942        let mut writer = zip::ZipWriter::new(file);
1943        let stored = zip::write::SimpleFileOptions::default()
1944            .compression_method(zip::CompressionMethod::Stored);
1945        // mimetype must be the first member and stored uncompressed.
1946        writer.start_file("mimetype", stored).unwrap();
1947        writer.write_all(b"application/epub+zip").unwrap();
1948        writer.start_file("META-INF/container.xml", stored).unwrap();
1949        writer.write_all(container.as_bytes()).unwrap();
1950        writer.start_file("OEBPS/content.opf", stored).unwrap();
1951        writer.write_all(opf.as_bytes()).unwrap();
1952        writer.start_file(chapter_entry, stored).unwrap();
1953        writer.write_all(chapter.as_bytes()).unwrap();
1954        writer.finish().unwrap();
1955    }
1956
1957    #[test]
1958    fn regression_epub_title_accumulates_entities_and_nested_events() {
1959        // Pre-fix the title was cut at the first Text node, so an entity or a
1960        // comment inside `<dc:title>` truncated it.
1961        let tmp = tempfile::TempDir::new().unwrap();
1962
1963        let f1 = tmp.path().join("entity.epub");
1964        write_epub(
1965            &f1,
1966            "<dc:title>Smith &amp; Jones: A &lt;Tale&gt;</dc:title>",
1967            "chapter.xhtml",
1968            "OEBPS/chapter.xhtml",
1969        );
1970        let got = extract(&f1).unwrap();
1971        assert_eq!(
1972            got.metadata["title"],
1973            MetaValue::Str("Smith & Jones: A <Tale>".into())
1974        );
1975
1976        let f2 = tmp.path().join("comment.epub");
1977        write_epub(
1978            &f2,
1979            "<dc:title>Part One<!-- editorial --> and Part Two</dc:title>",
1980            "chapter.xhtml",
1981            "OEBPS/chapter.xhtml",
1982        );
1983        let got = extract(&f2).unwrap();
1984        assert_eq!(
1985            got.metadata["title"],
1986            MetaValue::Str("Part One and Part Two".into())
1987        );
1988    }
1989
1990    #[test]
1991    fn regression_epub_self_closing_title_does_not_capture_author() {
1992        // A self-closing `<dc:title/>` (an untitled book) must NOT latch the next
1993        // text node (the author) as the title.
1994        let tmp = tempfile::TempDir::new().unwrap();
1995        let f = tmp.path().join("empty-title.epub");
1996        write_epub(
1997            &f,
1998            "<dc:title/><dc:creator>John Doe</dc:creator>",
1999            "chapter.xhtml",
2000            "OEBPS/chapter.xhtml",
2001        );
2002        let got = extract(&f).unwrap();
2003        // No (or empty) title — never the author. `put_str` omits empty values.
2004        assert!(
2005            !got.metadata.contains_key("title"),
2006            "self-closing title must not capture the author, got {:?}",
2007            got.metadata.get("title")
2008        );
2009        // The chapter still extracts.
2010        assert_eq!(got.metadata["chapters"], MetaValue::Num(1));
2011    }
2012
2013    /// Build an `.epub` whose spine references the single chapter `spine_count`
2014    /// times — the spine-amplification shape.
2015    fn write_epub_with_spine(dest: &Path, spine_count: usize) {
2016        use std::io::Write;
2017        let container = "<?xml version=\"1.0\"?>\
2018<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\
2019<rootfiles><rootfile full-path=\"OEBPS/content.opf\" \
2020media-type=\"application/oebps-package+xml\"/></rootfiles></container>";
2021        let itemrefs = "<itemref idref=\"c1\"/>".repeat(spine_count);
2022        let opf = format!(
2023            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
2024<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"id\">\
2025<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:title>Bomb</dc:title></metadata>\
2026<manifest><item id=\"c1\" href=\"chapter.xhtml\" media-type=\"application/xhtml+xml\"/></manifest>\
2027<spine>{itemrefs}</spine></package>"
2028        );
2029        let chapter = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
2030<html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>Repeated chapter body.</p></body></html>";
2031        let file = std::fs::File::create(dest).unwrap();
2032        let mut writer = zip::ZipWriter::new(file);
2033        let stored = zip::write::SimpleFileOptions::default()
2034            .compression_method(zip::CompressionMethod::Stored);
2035        writer.start_file("mimetype", stored).unwrap();
2036        writer.write_all(b"application/epub+zip").unwrap();
2037        writer.start_file("META-INF/container.xml", stored).unwrap();
2038        writer.write_all(container.as_bytes()).unwrap();
2039        writer.start_file("OEBPS/content.opf", stored).unwrap();
2040        writer.write_all(opf.as_bytes()).unwrap();
2041        writer.start_file("OEBPS/chapter.xhtml", stored).unwrap();
2042        writer.write_all(chapter.as_bytes()).unwrap();
2043        writer.finish().unwrap();
2044    }
2045
2046    #[test]
2047    fn regression_epub_spine_amplification_is_bounded() {
2048        // Adversarial review #8: a tiny .epub whose spine references the same
2049        // chapter a huge number of times pegged a CPU core (re-decoding +
2050        // re-rendering the chapter each time) and ballooned output. The spine
2051        // length is now capped, so an over-cap spine is REFUSED — fast, never
2052        // hung.
2053        let tmp = tempfile::TempDir::new().unwrap();
2054        let bomb = tmp.path().join("bomb.epub");
2055        write_epub_with_spine(&bomb, MAX_EPUB_SPINE_ITEMS + 1);
2056        let err = extract(&bomb).unwrap_err();
2057        assert!(
2058            matches!(&err, ExtractError::Parse { message, .. } if message.contains("spine")),
2059            "an over-cap spine must be refused with a spine error; got {err:?}"
2060        );
2061
2062        // A legitimate small repeat-spine still extracts: memoization renders the
2063        // shared chapter once, but each reading-order reference is still counted.
2064        let ok = tmp.path().join("ok.epub");
2065        write_epub_with_spine(&ok, 5);
2066        let got = extract(&ok).unwrap();
2067        assert_eq!(got.metadata["chapters"], MetaValue::Num(5));
2068    }
2069
2070    #[test]
2071    fn regression_epub_percent_encoded_href_resolves() {
2072        // An href `my%20chapter.xhtml` must match the zip entry
2073        // `OEBPS/my chapter.xhtml`; pre-fix the lookup failed and the chapter was
2074        // silently dropped (empty text, 0 chapters).
2075        let tmp = tempfile::TempDir::new().unwrap();
2076        let f = tmp.path().join("spaced.epub");
2077        write_epub(
2078            &f,
2079            "<dc:title>Spaced</dc:title>",
2080            "my%20chapter.xhtml",
2081            "OEBPS/my chapter.xhtml",
2082        );
2083        let got = extract(&f).unwrap();
2084        assert_eq!(got.metadata["chapters"], MetaValue::Num(1));
2085        assert!(
2086            got.text.contains("Hello world body text."),
2087            "percent-encoded-href chapter must extract, got {:?}",
2088            got.text
2089        );
2090    }
2091
2092    #[test]
2093    fn percent_decode_handles_spaces_and_unicode_and_stray_percent() {
2094        assert_eq!(percent_decode("my%20chapter.xhtml"), "my chapter.xhtml");
2095        // `%C3%A9` is UTF-8 for `é`.
2096        assert_eq!(percent_decode("caf%C3%A9.xhtml"), "café.xhtml");
2097        // A stray `%` not followed by two hex digits is emitted verbatim.
2098        assert_eq!(percent_decode("100%done"), "100%done");
2099        assert_eq!(percent_decode("plain.xhtml"), "plain.xhtml");
2100    }
2101
2102    #[test]
2103    fn normalize_zip_path_resolves_dot_segments() {
2104        assert_eq!(
2105            normalize_zip_path("OEBPS/../text/ch1.xhtml"),
2106            "text/ch1.xhtml"
2107        );
2108        assert_eq!(normalize_zip_path("OEBPS/./ch1.xhtml"), "OEBPS/ch1.xhtml");
2109        assert_eq!(normalize_zip_path("OEBPS/ch1.xhtml"), "OEBPS/ch1.xhtml");
2110    }
2111
2112    // ── regression: spreadsheet date rendering (finding #1013) ─────────────────
2113
2114    #[test]
2115    fn render_excel_datetime_renders_iso_not_serial() {
2116        use calamine::{ExcelDateTime, ExcelDateTimeType};
2117        // 46188 → 2026-06-15 (date only, midnight → no time component).
2118        let date = ExcelDateTime::new(46188.0, ExcelDateTimeType::DateTime, false);
2119        assert_eq!(render_excel_datetime(&date), "2026-06-15");
2120        // 46143.5 → 2026-05-01 12:00:00 (has a time component).
2121        let dt = ExcelDateTime::new(46143.5, ExcelDateTimeType::DateTime, false);
2122        assert_eq!(render_excel_datetime(&dt), "2026-05-01 12:00:00");
2123        // A duration is elapsed time, not a calendar date → keep the serial form.
2124        let dur = ExcelDateTime::new(1.5, ExcelDateTimeType::TimeDelta, false);
2125        assert_eq!(render_excel_datetime(&dur), "1.5");
2126    }
2127
2128    #[test]
2129    fn render_cell_dates_are_iso() {
2130        use calamine::{Data, ExcelDateTime, ExcelDateTimeType};
2131        assert_eq!(
2132            render_cell(&Data::DateTime(ExcelDateTime::new(
2133                46188.0,
2134                ExcelDateTimeType::DateTime,
2135                false
2136            ))),
2137            "2026-06-15"
2138        );
2139        // The integer/float/string paths are unchanged by the date fix.
2140        assert_eq!(render_cell(&Data::Float(3450.0)), "3450");
2141        assert_eq!(render_cell(&Data::Int(7)), "7");
2142    }
2143
2144    // ── regression: HTML/EPUB literal-content fidelity (finding #36) ───────────
2145
2146    /// Render an HTML body string through the production extract path.
2147    fn html_text(body: &str) -> String {
2148        let tmp = tempfile::TempDir::new().unwrap();
2149        let f = tmp.path().join("doc.html");
2150        std::fs::write(&f, format!("<html><body>{body}</body></html>")).unwrap();
2151        extract(&f).unwrap().text
2152    }
2153
2154    #[test]
2155    fn regression_html_keeps_literal_brackets_and_hashes() {
2156        // Pre-fix every `[bracketed]` substring and every leading-`#` run was
2157        // stripped from real prose, fusing `total[net]` into `totalnet` and
2158        // deleting the `#` from `#1 in sales`.
2159        let out = html_text(
2160            "<p>#1 in sales this quarter</p>\
2161<p>see chart[3] for data, array[0] = total[net]</p>",
2162        );
2163        assert!(out.contains("#1 in sales this quarter"), "got {out:?}");
2164        assert!(
2165            out.contains("see chart[3] for data, array[0] = total[net]"),
2166            "got {out:?}"
2167        );
2168
2169        // Citation markers and subscripts survive intact.
2170        let out = html_text("<p>See note [1] and [sic] here.</p><p>x[i] + y[j]</p>");
2171        assert!(out.contains("See note [1] and [sic] here."), "got {out:?}");
2172        assert!(out.contains("x[i] + y[j]"), "got {out:?}");
2173    }
2174
2175    #[test]
2176    fn html_headings_render_as_plain_prose_no_hash() {
2177        // A real `<h1>` heading still renders WITHOUT a `#` marker (the renderer
2178        // emits no heading prefix now), so headings read as prose.
2179        let out = html_text("<h1>Launch Plan</h1><p>Body prose.</p>");
2180        assert!(out.contains("Launch Plan"), "got {out:?}");
2181        assert!(
2182            !out.contains('#'),
2183            "no heading marker expected, got {out:?}"
2184        );
2185    }
2186
2187    #[test]
2188    fn html_links_render_as_bare_text_no_brackets() {
2189        // Link display text renders bare; the surrounding `[...]` the stock plain
2190        // decorator would add is gone.
2191        let out = html_text("<p>See the <a href=\"https://x.example\">handbook</a>.</p>");
2192        assert!(out.contains("See the handbook."), "got {out:?}");
2193    }
2194}