Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(markdown): preserve inline code breaks and nested emphasis
ldm0ae10292ea40f
diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rsindex d6839c404..af25d4488 100644--- a/moli-html2md/src/machine.rs+++ b/moli-html2md/src/machine.rs@@ -11,7 +11,7 @@ enum Task<'a, Id> {EndHeading(usize),EndList(usize),EndItem(String),- RawChildren(Option<Id>, usize),+ RawChildren(Option<Id>, usize, bool),EndCode,EndPre(Option<&'a str>),}@@ -59,7 +59,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {.push(Task::Children(self.dom.next_sibling(node), depth));self.tasks.push(Task::Visit(node, depth));}- Task::Children(None, _) | Task::RawChildren(None, _) => {}+ Task::Children(None, _) | Task::RawChildren(None, _, _) => {}Task::Boundary => self.writer().boundary(2),Task::PopStyle => self.writer().pop_style(),Task::EndLink(serial) => self.writer().end_link(serial),@@ -123,7 +123,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {list.loose |= loose;self.writer().block(&item, separation, separation);}- Task::RawChildren(Some(node), depth) => self.raw_node(node, depth),+ Task::RawChildren(Some(node), depth, inline) => self.raw_node(node, depth, inline),Task::EndCode => {let text = std::mem::take(&mut self.raw);let preformatted = self.options.preformatted_code;@@ -232,8 +232,11 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {};self.tasks.push(end);if depth + 1 < self.options.max_depth {- self.tasks- .push(Task::RawChildren(self.dom.first_child(node), depth + 1));+ self.tasks.push(Task::RawChildren(+ self.dom.first_child(node),+ depth + 1,+ tag == "code",+ ));}return;}@@ -318,17 +321,26 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {.or(self.options.default_code_language.as_deref())}- fn raw_node(&mut self, node: D::NodeId, depth: usize) {- self.tasks- .push(Task::RawChildren(self.dom.next_sibling(node), depth));+ fn raw_node(&mut self, node: D::NodeId, depth: usize, inline: bool) {+ self.tasks.push(Task::RawChildren(+ self.dom.next_sibling(node),+ depth,+ inline,+ ));if depth >= self.options.max_depth {return;}match self.dom.node_kind(node) {NodeKind::Text(text) => self.raw.push_str(text),+ // Inline code normalizes line endings to spaces. Keep explicit+ // breaks without converting descendant formatting into Markdown.+ NodeKind::Element("br") if inline => self.raw.push('\n'),NodeKind::Document | NodeKind::Element(_) if depth + 1 < self.options.max_depth => {- self.tasks- .push(Task::RawChildren(self.dom.first_child(node), depth + 1));+ self.tasks.push(Task::RawChildren(+ self.dom.first_child(node),+ depth + 1,+ inline,+ ));}_ => {}}diff --git a/moli-html2md/src/writer.rs b/moli-html2md/src/writer.rsindex 3ee7c0f92..fcb3da3b8 100644--- a/moli-html2md/src/writer.rs+++ b/moli-html2md/src/writer.rs@@ -17,6 +17,7 @@ struct OpenStyle<'a> {style: Style<'a>,start: usize,html: bool,+ has_closed_child: bool,}#[derive(Default)]@@ -306,7 +307,12 @@ impl<'a> Writer<'a> {self.output.push('[');}}- self.emitted.push(OpenStyle { style, start, html });+ self.emitted.push(OpenStyle {+ style,+ start,+ html,+ has_closed_child: false,+ });}}@@ -331,10 +337,10 @@ impl<'a> Writer<'a> {}fn close_to(&mut self, count: usize, next: Option<char>) {+ let mut closing_run = None;+ let closed_child = self.emitted.len() > count;while self.emitted.len() > count {let opened = self.emitted.pop().expect("nonempty style stack");- let closing_needs_html = next.is_some_and(char::is_alphanumeric)- && self.output.chars().next_back().is_some_and(is_punctuation);let delimiters = match opened.style {Style::Strong => Some(("**", "<strong>", "</strong>")),Style::Emphasis => Some(("*", "<em>", "</em>")),@@ -343,23 +349,50 @@ impl<'a> Writer<'a> {self.output.push_str("](");destination(&mut self.output, href, title, self.single_line_attributes);self.output.push(')');+ closing_run = None;None}};if let Some((marker, open, close)) = delimiters {- if opened.html {- self.output.push_str(close);- } else if closing_needs_html {- // Only the converter's output changes. Remaining open- // ancestors precede this offset, so their offsets stay valid.- self.output- .replace_range(opened.start..opened.start + marker.len(), open);+ // Nested strong/emphasis closes with a single run of '*'. Its+ // left edge is the character before the run, not a delimiter+ // just emitted for the inner style. Links, HTML and a different+ // marker end that run and retain their own punctuation edge.+ let marker_byte = marker.as_bytes()[0];+ let preceding = match closing_run {+ Some((previous, preceding))+ if previous == marker_byte && !opened.has_closed_child =>+ {+ preceding+ }+ _ => self.output.chars().next_back(),+ };+ let closing_needs_html = next.is_some_and(char::is_alphanumeric)+ && preceding.is_some_and(is_punctuation);+ if opened.html || closing_needs_html {+ if !opened.html {+ // Only the converter's output changes. Remaining open+ // ancestors precede this offset, so their offsets stay valid.+ self.output+ .replace_range(opened.start..opened.start + marker.len(), open);+ }self.output.push_str(close);+ closing_run = None;} else {self.output.push_str(marker);+ closing_run = Some((marker_byte, preceding));}}}+ if closed_child {+ // Earlier child delimiters can pair with a later sibling before+ // the parent's closer is reached: ***a**b**c***d loses emphasis.+ // A child rewritten as HTML can also change the opening edge.+ // Keep the conservative edge check for those interrupted spans.+ for opened in &mut self.emitted {+ opened.has_closed_child = true;+ }+ }}fn flush_breaks(&mut self) {diff --git a/moli-html2md/tests/inline_boundaries.rs b/moli-html2md/tests/inline_boundaries.rsnew file mode 100644index 000000000..fd5b475ff--- /dev/null+++ b/moli-html2md/tests/inline_boundaries.rs@@ -0,0 +1,203 @@+mod support;++use moli_html2md::{Converter, Options};+use support::{Tree, rendered_html};++fn markdown_with(html: &str, options: Options) -> String {+ let dom = Tree::parse(html);+ let before = dom.clone();+ let result = Converter::new(options).convert(&dom, dom.root);+ assert_eq!(dom, before);+ result+}++fn markdown(html: &str) -> String {+ markdown_with(html, Options::default())+}++#[test]+fn inline_code_breaks_separate_words_without_formatting_markers() {+ for html in [+ "<code>git<br>status</code>",+ "<code><strong>git<br></strong><em>status</em></code>",+ "<code><a href='/'>git</a><span><br></span><b>status</b></code>",+ ] {+ for preformatted_code in [false, true] {+ let result = markdown_with(+ html,+ Options {+ preformatted_code,+ ..Options::default()+ },+ );+ assert_eq!(result, "`git status`", "{html}");+ assert_eq!(+ rendered_html(&result),+ "<p><code>git status</code></p>\n",+ "{html}"+ );+ }+ }+}++#[test]+fn inline_code_breaks_follow_the_selected_whitespace_mode() {+ let html = "<code>git<br><br> status</code>";+ assert_eq!(markdown(html), "`git status`");+ let result = markdown_with(+ html,+ Options {+ preformatted_code: true,+ ..Options::default()+ },+ );+ assert_eq!(result, "`git status`");+ assert_eq!(+ rendered_html(&result),+ "<p><code>git status</code></p>\n"+ );+}++#[test]+fn inline_code_breaks_keep_separation_at_code_span_edges() {+ for (html, expected) in [+ (+ "before<code>git<br></code><code>status</code>after",+ "before`git` `status`after",+ ),+ ("before<code><br>git<br></code>after", "before `git` after"),+ ] {+ assert_eq!(markdown(html), expected, "{html}");+ }+ let result = markdown_with(+ "before<code>git<br></code><code>status</code>after",+ Options {+ preformatted_code: true,+ ..Options::default()+ },+ );+ assert_eq!(result, "before`git status`after");+}++#[test]+fn inline_code_breaks_obey_the_depth_limit() {+ let html = "<code>git<span><br></span>status</code>";+ for (max_depth, expected) in [(3, "`gitstatus`"), (4, "`git status`")] {+ assert_eq!(+ markdown_with(+ html,+ Options {+ max_depth,+ ..Options::default()+ },+ ),+ expected+ );+ }+}++#[test]+fn pre_keeps_raw_text_and_line_endings() {+ let result = markdown("<pre><code><b>git</b>\n <em>status</em></code></pre>");+ assert_eq!(result, "```\ngit\n status\n```");+ assert_eq!(+ rendered_html(&result),+ "<pre><code>git\n status\n</code></pre>\n"+ );+}++#[test]+fn nested_emphasis_closes_with_markdown_before_a_word() {+ for (html, expected, expected_html) in [+ (+ "<em><strong>x</strong></em>y",+ "***x***y",+ "<p><em><strong>x</strong></em>y</p>\n",+ ),+ (+ "<strong><em>x</em></strong>y",+ "***x***y",+ "<p><em><strong>x</strong></em>y</p>\n",+ ),+ (+ "a<strong>b<em>c</em></strong>d",+ "a**b*c***d",+ "<p>a<strong>b<em>c</em></strong>d</p>\n",+ ),+ (+ "a<em>b<strong>c</strong></em>d",+ "a*b**c***d",+ "<p>a<em>b<strong>c</strong></em>d</p>\n",+ ),+ (+ "<strong><em>x</em>y</strong>z",+ "***x*y**z",+ "<p><strong><em>x</em>y</strong>z</p>\n",+ ),+ (+ "<em><strong>x</strong>y</em>z",+ "***x**y*z",+ "<p><em><strong>x</strong>y</em>z</p>\n",+ ),+ ] {+ let result = markdown(html);+ assert_eq!(result, expected, "{html}");+ assert_eq!(rendered_html(&result), expected_html, "{html}");+ }+}++#[test]+fn nested_emphasis_still_uses_html_after_literal_punctuation() {+ for text in ["word!", "word*", "word`", "word)", "日本語。"] {+ for (outer, inner) in [("em", "strong"), ("strong", "em")] {+ let html = format!("<{outer}><{inner}>{text}</{inner}></{outer}>after");+ let result = markdown(&html);+ assert!(result.contains(&format!("<{outer}>")), "{result}");+ assert_eq!(rendered_html(&result), format!("<p>{html}</p>\n"));+ }+ }+}++#[test]+fn closing_runs_stop_at_links_code_images_and_other_markers() {+ for (html, expected_html) in [+ (+ "<em><strong><a href='/'>x</a></strong></em>y",+ "<p><em><strong><a href=\"/\">x</a></strong></em>y</p>\n",+ ),+ (+ "<em><strong><code>x</code></strong></em>y",+ "<p><em><strong><code>x</code></strong></em>y</p>\n",+ ),+ (+ "<em><strong><img src='/x' alt='x'></strong></em>y",+ "<p><em><strong><img src=\"/x\" alt=\"x\" /></strong></em>y</p>\n",+ ),+ ("<em><del>x</del></em>y", "<p><em><del>x</del></em>y</p>\n"),+ ("<del><em>x</em></del>y", "<p><del><em>x</em></del>y</p>\n"),+ ] {+ assert_eq!(rendered_html(&markdown(html)), expected_html, "{html}");+ }+}++#[test]+fn separate_nested_spans_keep_html_when_delimiters_are_ambiguous() {+ let result = markdown("<em><strong>a</strong>b<strong>c</strong></em>d");+ assert_eq!(result, "<em>**a**b**c**</em>d");+ assert_eq!(+ rendered_html(&result),+ "<p><em><strong>a</strong>b<strong>c</strong></em>d</p>\n"+ );+ for text in ["x", "x!", "x*"] {+ for (outer, inner) in [("em", "strong"), ("strong", "em")] {+ let html = format!(+ "before<{outer}><{inner}>{text}</{inner}>b<{inner}>c</{inner}></{outer}>after"+ );+ assert_eq!(+ rendered_html(&markdown(&html)),+ format!("<p>{html}</p>\n"),+ "{html}"+ );+ }+ }+}diff --git a/moli-html2md/tests/tracking.rs b/moli-html2md/tests/tracking.rsnew file mode 100644index 000000000..903e9ca15--- /dev/null+++ b/moli-html2md/tests/tracking.rs@@ -0,0 +1,113 @@+//! Open review findings, separate from regressions asserting desired behavior.+//! These tests run normally and fail if the recorded behavior changes. When a+//! gap is fixed, replace its current-output assertion with the desired result+//! and update turndown/README.md; do not refresh the snapshot automatically.++mod support;++use moli_html2md::convert;+use support::{Tree, rendered_html};++fn markdown(html: &str) -> String {+ let dom = Tree::parse(html);+ let before = dom.clone();+ let result = convert(&dom, dom.root);+ assert_eq!(dom, before);+ result+}++fn track_list_spacing(html: &str) {+ let result = markdown(html);+ assert_eq!(result, "- before\n - inner\n- after");+ assert_eq!(+ rendered_html(&result),+ "<ul>\n<li>before\n<ul>\n<li>inner</li>\n</ul>\n</li>\n<li>after</li>\n</ul>\n"+ );+ // Output from the pinned Turndown 7.2.4 reference. Whether these wrappers+ // should make the outer list loose remains a compatibility decision.+ let turndown = "- before\n \n - inner\n \n- after";+ assert_eq!(+ rendered_html(turndown),+ "<ul>\n<li>\n<p>before</p>\n<ul>\n<li>inner</li>\n</ul>\n</li>\n<li>\n<p>after</p>\n</li>\n</ul>\n"+ );+ assert_ne!(rendered_html(&result), rendered_html(turndown));+}++#[test]+fn track_nested_list_spacing_through_a_transparent_wrapper() {+ track_list_spacing("<ul><li>before<ins><ul><li>inner</li></ul></ins></li><li>after</li></ul>");+}++#[test]+fn track_nested_list_spacing_before_a_trailing_empty_element() {+ track_list_spacing(+ "<ul><li>before<ul><li>inner</li></ul><span></span></li><li>after</li></ul>",+ );+}++#[test]+fn track_multiline_image_alt_becoming_a_heading() {+ let result = markdown("<img src='/x' alt='first\n# heading'>");+ // Turndown emits the same Markdown. Matching it does not preserve the image.+ assert_eq!(result, "");+ let actual_html = rendered_html(&result);+ assert_eq!(actual_html, "<p></h1>\n");+ let desired_html = "<p><img src=\"/x\" alt=\"first # heading\" /></p>\n";+ assert_ne!(+ actual_html, desired_html,+ "review the resolved image-alt gap"+ );+}++#[test]+fn track_multiline_link_title_becoming_a_heading() {+ let result = markdown("<a href='/' title='first\n# heading'>link</a>");+ // Turndown has this loss too; the link and its title must survive rendering.+ assert_eq!(result, "[link](/ \"first\n# heading\")");+ let actual_html = rendered_html(&result);+ assert_eq!(+ actual_html,+ "<p>[link](/ \"first</p>\n<h1>heading\")</h1>\n"+ );+ let desired_html = "<p><a href=\"/\" title=\"first\n# heading\">link</a></p>\n";+ assert_ne!(+ actual_html, desired_html,+ "review the resolved link-title gap"+ );+}++#[test]+fn track_multiple_nested_spans_at_the_end_of_a_paragraph() {+ // This predates the closing-edge fix: with no following character there+ // is no punctuation fallback, but sibling delimiters can still mispair.+ let result = markdown("<em><strong>x</strong>b<strong>c</strong></em>");+ assert_eq!(result, "***x**b**c***");+ let actual_html = rendered_html(&result);+ assert_eq!(+ actual_html,+ "<p><em><strong>x</strong>b</em><em>c</em>**</p>\n"+ );+ let desired_html = "<p><em><strong>x</strong>b<strong>c</strong></em></p>\n";+ assert_ne!(+ actual_html, desired_html,+ "review the resolved sibling-span gap"+ );+}++#[test]+fn track_mixed_emphasis_markers_at_an_intraword_opening() {+ // The opening check sees the text 'x', although the nested styles emit+ // punctuation first. This is separate from closing a same-marker run.+ let result = markdown("before<em><del><strong>x</strong></del></em>");+ assert_eq!(result, "before*~~**x**~~*");+ let actual_html = rendered_html(&result);+ assert_eq!(+ actual_html,+ "<p>before*<del><strong>x</strong></del>*</p>\n"+ );+ let desired_html = "<p>before<em><del><strong>x</strong></del></em></p>\n";+ assert_ne!(+ actual_html, desired_html,+ "review the resolved mixed-marker gap"+ );+}diff --git a/moli-html2md/tests/turndown/README.md b/moli-html2md/tests/turndown/README.mdindex a9292b338..3e9dd8595 100644--- a/moli-html2md/tests/turndown/README.md+++ b/moli-html2md/tests/turndown/README.md@@ -32,6 +32,29 @@ case is skipped. A reference change that makes a difference obsolete also failsthe test. Separate converter tests cover table expansion using Turndown core'sordinary block behavior and strikethrough as a Moli extension.+## Findings tracked outside the reference corpus++The 12 exceptions above describe this corpus, not every design difference or+every correctness issue. [tracking.rs](../tracking.rs) records these open review+findings with active assertions of both Markdown and rendered HTML:++| Tests | Status | Current behavior and comparison |+| --- | --- | --- |+| `track_nested_list_spacing_through_a_transparent_wrapper`, `track_nested_list_spacing_before_a_trailing_empty_element` | Open compatibility decision | Moli keeps the outer list tight when an `ins` wraps the nested list or an empty `span` follows it. Turndown makes it loose. Both preserve the list items. |+| `track_multiline_image_alt_becoming_a_heading` | Open bug, also present in Turndown | An image alt containing `first\n# heading` breaks the image into text and a heading. The desired HTML retains the image and its full label. |+| `track_multiline_link_title_becoming_a_heading` | Open bug, also present in Turndown | A link title containing `first\n# heading` breaks the link into text and a heading. The desired HTML retains the link and its multiline title. |+| `track_multiple_nested_spans_at_the_end_of_a_paragraph` | Open bug, also present in Turndown | `<em><strong>x</strong>b<strong>c</strong></em>` produces ambiguous star delimiters at paragraph end, losing the second strong span and exposing literal stars. |+| `track_mixed_emphasis_markers_at_an_intraword_opening` | Open bug in Moli's emphasis/strikethrough extension | `before<em><del><strong>x</strong></del></em>` loses outer emphasis because its opener precedes generated punctuation. |++These tests are not ignored or expected to panic. A change to a recorded output+requires review; when fixing a bug, replace the current-output assertion with a+regression asserting the desired semantics and remove its open entry here.++The inline-code `br` separator and nested-emphasis closing-delimiter fixes have+independent semantic regressions in [inline_boundaries.rs](../inline_boundaries.rs).+Inline-code breaks follow Moli's whitespace mode (one space after collapsing),+without copying the extra spaces from Turndown's Markdown hard-break syntax.+## RegenerationNormal Rust tests use the checked-in data and require neither Node nor network