use scraper::{Html, Selector};
use std::sync::LazyLock;
fn min_text_chars() -> usize {
std::env::var("MIN_TEXT_CHARS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120)
}
#[derive(Debug, Clone, Default)]
pub struct Extracted {
pub title: String,
pub text: String,
pub published: Option<chrono::DateTime<chrono::Utc>>,
pub language: Option<String>,
pub byline: Option<String>,
pub site_name: Option<String>,
pub page_type: Option<String>,
pub confidence: f64,
pub source: &'static str,
}
fn parse_datetime_utc(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
let s = raw.trim();
if s.is_empty() {
return None;
}
if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
return Some(dt.with_timezone(&chrono::Utc));
}
if let Ok(dt) = chrono::DateTime::parse_from_rfc2822(s) {
return Some(dt.with_timezone(&chrono::Utc));
}
for fmt in [
"%Y-%m-%dT%H:%M:%S%z",
"%Y-%m-%dT%H:%M%z",
"%Y-%m-%d %H:%M:%S%z",
] {
if let Ok(dt) = chrono::DateTime::parse_from_str(s, fmt) {
return Some(dt.with_timezone(&chrono::Utc));
}
}
for fmt in [
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M:%S",
] {
if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
return Some(ndt.and_utc());
}
}
let date_prefix = s.get(..10)?;
let nd = chrono::NaiveDate::parse_from_str(date_prefix, "%Y-%m-%d").ok()?;
Some(nd.and_hms_opt(0, 0, 0)?.and_utc())
}
fn normalize_lang(raw: &str) -> Option<String> {
let primary = raw
.trim()
.split(['-', '_'])
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
(!primary.is_empty()).then_some(primary)
}
fn clean_opt_str(opt: Option<String>) -> Option<String> {
opt.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
}
fn word_count(s: &str) -> usize {
s.split_whitespace().count()
}
fn readability_extract(html: &str, url: &str) -> Option<Extracted> {
let cfg = dom_smoothie::Config {
text_mode: dom_smoothie::TextMode::Formatted,
..Default::default()
};
let mut r = dom_smoothie::Readability::new(html, Some(url), Some(cfg)).ok()?;
let article = r.parse().ok()?;
let text = article.text_content.to_string();
if text.trim().is_empty() {
return None;
}
let chars = crate::util::char_len(&text);
let confidence = if chars >= 600 {
0.90
} else if chars >= min_text_chars() {
0.82
} else {
0.65
};
let mut title = article.title;
let mut published = article
.published_time
.as_deref()
.and_then(parse_datetime_utc)
.or_else(|| {
article
.modified_time
.as_deref()
.and_then(parse_datetime_utc)
});
let language = article.lang.as_deref().and_then(normalize_lang);
let mut byline = clean_opt_str(article.byline);
let mut site_name = clean_opt_str(article.site_name);
if (byline.is_none() || site_name.is_none() || published.is_none() || html.contains("@graph"))
&& html.contains("ld+json")
{
if let Some(meta) = json_ld_metadata(html) {
if let Some(h) = meta.headline {
if html.contains("@graph") || title.trim().is_empty() {
title = h;
}
}
byline = byline.or(meta.byline);
site_name = site_name.or(meta.site_name);
published = published.or(meta.published);
}
}
if published.is_none() {
published = meta_datetime_fallback(html);
}
Some(Extracted {
title,
text,
published,
language,
byline,
site_name,
page_type: None,
confidence,
source: "readability",
})
}
fn trafilatura_extract(html: &str, url: &str) -> Option<Extracted> {
let opts = rs_trafilatura::Options {
url: Some(url.to_string()),
include_tables: true,
include_links: false,
include_comments: false,
..Default::default()
};
let r = rs_trafilatura::extract_with_options(html, &opts).ok()?;
Some(Extracted {
title: r.metadata.title.clone().unwrap_or_default(),
text: r.content_text,
published: r.metadata.date,
language: r.metadata.language.as_deref().and_then(normalize_lang),
byline: clean_opt_str(r.metadata.author.clone()),
site_name: clean_opt_str(r.metadata.sitename.clone()),
page_type: r.metadata.page_type.clone(),
confidence: r.extraction_quality.clamp(0.0, 1.0),
source: "trafilatura",
})
}
fn wants_second_opinion(primary: &Extracted, html_len: usize) -> bool {
let chars = crate::util::char_len(&primary.text);
if chars < 600 {
return true;
}
if primary.confidence < 0.80 {
return true;
}
let ratio = chars as f64 / html_len.max(1) as f64;
ratio < 0.035
}
pub fn extract(html: &str, url: &str) -> Extracted {
let unwrapped = crate::deep_reader::unwrap_shadow_templates(html);
let html = unwrapped.as_deref().unwrap_or(html);
let de_sandpacked = crate::deep_reader::strip_sandpack_placeholders(html);
let html = de_sandpacked.as_deref().unwrap_or(html);
let noscript_unwrapped = crate::deep_reader::unwrap_noscript_fallbacks(html);
let html = noscript_unwrapped.as_deref().unwrap_or(html);
let mut best = readability_extract(html, url).unwrap_or_default();
if wants_second_opinion(&best, html.len()) {
if let Some(alt) = trafilatura_extract(html, url) {
if word_count(&alt.text) > word_count(&best.text) {
best.text = alt.text;
best.source = "trafilatura";
best.confidence = best.confidence.max(alt.confidence);
}
if best.title.trim().is_empty() && !alt.title.trim().is_empty() {
best.title = alt.title;
}
best.published = best.published.or(alt.published);
best.language = best.language.or(alt.language);
best.byline = best.byline.or(alt.byline);
best.site_name = best.site_name.or(alt.site_name);
best.page_type = best.page_type.or(alt.page_type);
}
}
if best.title.trim().is_empty() {
best.title = extract_title_from_html(html);
}
let dom_chars = crate::util::char_len(&best.text);
let min = min_text_chars();
let adopt =
|best: &mut Extracted, text: String, source: &'static str, confidence: f64, factor: f64| {
let n = crate::util::char_len(&text);
let current = crate::util::char_len(&best.text);
if n >= min && n as f64 >= current as f64 * factor {
best.text = text;
best.source = source;
best.confidence = best.confidence.max(confidence);
}
};
if html.contains("articleBody") {
if let Some(body) = json_ld_article_body(html) {
adopt(&mut best, body, "json-ld", 0.85, 1.3);
}
}
if dom_chars < 2_000 {
if let Some(text) = crate::deep_reader::hydration_text(html) {
adopt(&mut best, text, "hydration", 0.7, 2.0);
}
}
best.text = normalize_whitespace(&best.text);
best
}
#[allow(dead_code)]
pub fn extract_title_and_text(html: &str) -> (String, String) {
let e = extract(html, "https://example.invalid/");
(e.title, e.text)
}
#[allow(dead_code)]
pub fn extract_article_text(html: &str) -> String {
extract(html, "https://example.invalid/").text
}
pub fn is_usable(e: &Extracted) -> bool {
crate::util::char_len(&e.text) >= min_text_chars()
}
static SEL_OG_TITLE: LazyLock<Option<Selector>> =
LazyLock::new(|| Selector::parse(r#"meta[property="og:title"]"#).ok());
static SEL_TITLE: LazyLock<Option<Selector>> = LazyLock::new(|| Selector::parse("title").ok());
static SEL_H1: LazyLock<Option<Selector>> = LazyLock::new(|| Selector::parse("h1").ok());
static SEL_META_DESC: LazyLock<Option<Selector>> =
LazyLock::new(|| Selector::parse("meta[name='description']").ok());
static SEL_META_ANY: LazyLock<Option<Selector>> =
LazyLock::new(|| Selector::parse("meta[content]").ok());
static SEL_JSON_LD: LazyLock<Option<Selector>> =
LazyLock::new(|| Selector::parse("script[type='application/ld+json']").ok());
pub fn extract_title_from_html(html: &str) -> String {
let doc = Html::parse_document(html);
extract_title_from_doc(&doc)
}
pub fn extract_title_from_doc(doc: &Html) -> String {
if let Some(sel) = SEL_OG_TITLE.as_ref() {
if let Some(m) = doc.select(sel).next() {
if let Some(c) = m.value().attr("content") {
let t = c.trim();
if !t.is_empty() {
return t.to_string();
}
}
}
}
if let Some(sel) = SEL_TITLE.as_ref() {
if let Some(t) = doc.select(sel).next() {
let raw = t.text().collect::<String>().trim().to_string();
if !raw.is_empty() {
return strip_site_suffix(&raw);
}
}
}
if let Some(sel) = SEL_H1.as_ref() {
if let Some(h) = doc.select(sel).next() {
return h.text().collect::<String>().trim().to_string();
}
}
String::new()
}
fn strip_site_suffix(title: &str) -> String {
for sep in [" | ", " - ", " — ", " – ", " :: ", " » "] {
if let Some(idx) = title.rfind(sep) {
let head = title[..idx].trim();
if crate::util::char_len(head) >= 15 {
return head.to_string();
}
}
}
title.to_string()
}
pub fn extract_title_from_doc_pub(doc: &Html) -> String {
extract_title_from_doc(doc)
}
pub fn extract_youtube_meta(doc: &Html) -> Option<String> {
let sel = SEL_META_DESC.as_ref()?;
let m = doc.select(sel).next()?;
let c = m.value().attr("content")?.trim();
if crate::util::char_len(c) > 30 {
Some(c.to_string())
} else {
None
}
}
pub fn json_ld_article_body(html: &str) -> Option<String> {
let doc = Html::parse_document(html);
let sel = SEL_JSON_LD.as_ref()?;
let mut nodes = Vec::new();
for script in doc.select(sel) {
let raw = script.text().collect::<String>();
if let Ok(v) = serde_json::from_str::<serde_json::Value>(raw.trim()) {
flatten_ld(&v, &mut nodes);
}
}
let mut best: Option<String> = None;
for n in &nodes {
let Some(body) = n.get("articleBody").and_then(|v| v.as_str()) else {
continue;
};
let body = strip_tags(body.trim());
if crate::util::char_len(&body) < 100 {
continue;
}
if best
.as_ref()
.is_none_or(|b| crate::util::char_len(&body) > crate::util::char_len(b))
{
best = Some(body);
}
}
best
}
#[derive(Default)]
struct JsonLdMeta {
headline: Option<String>,
byline: Option<String>,
site_name: Option<String>,
published: Option<chrono::DateTime<chrono::Utc>>,
}
fn ld_person_name(v: &serde_json::Value) -> Option<String> {
match v {
serde_json::Value::String(s) => clean_opt_str(Some(s.clone())),
serde_json::Value::Object(o) => {
clean_opt_str(o.get("name").and_then(|n| n.as_str()).map(str::to_string))
}
serde_json::Value::Array(arr) => {
let names: Vec<String> = arr.iter().filter_map(ld_person_name).collect();
(!names.is_empty()).then(|| names.join(", "))
}
_ => None,
}
}
fn json_ld_metadata(html: &str) -> Option<JsonLdMeta> {
let doc = Html::parse_document(html);
let sel = SEL_JSON_LD.as_ref()?;
let mut nodes = Vec::new();
for script in doc.select(sel) {
let raw = script.text().collect::<String>();
if let Ok(v) = serde_json::from_str::<serde_json::Value>(raw.trim()) {
flatten_ld(&v, &mut nodes);
}
}
let is_article = |n: &serde_json::Value| {
ld_types(n).iter().any(|t| {
matches!(
t.as_str(),
"Article"
| "NewsArticle"
| "TechArticle"
| "BlogPosting"
| "ScholarlyArticle"
| "Report"
| "OpinionNewsArticle"
| "AnalysisNewsArticle"
| "LiveBlogPosting"
)
})
};
let mut meta = JsonLdMeta::default();
for n in nodes.iter().filter(|n| is_article(n)) {
if meta.headline.is_none() {
meta.headline = clean_opt_str(
n.get("headline")
.or_else(|| n.get("name"))
.and_then(|v| v.as_str())
.map(str::to_string),
);
}
if meta.byline.is_none() {
meta.byline = n.get("author").and_then(ld_person_name);
}
if meta.site_name.is_none() {
meta.site_name = n.get("publisher").and_then(ld_person_name);
}
if meta.published.is_none() {
meta.published = n
.get("datePublished")
.or_else(|| n.get("dateCreated"))
.or_else(|| n.get("dateModified"))
.and_then(|v| v.as_str())
.and_then(parse_datetime_utc);
}
}
(meta.headline.is_some()
|| meta.byline.is_some()
|| meta.site_name.is_some()
|| meta.published.is_some())
.then_some(meta)
}
fn meta_datetime_fallback(html: &str) -> Option<chrono::DateTime<chrono::Utc>> {
let doc = Html::parse_document(html);
let sel = SEL_META_ANY.as_ref()?;
let mut modified: Option<chrono::DateTime<chrono::Utc>> = None;
for el in doc.select(sel) {
let Some(content) = el.value().attr("content") else {
continue;
};
let key = el
.value()
.attr("property")
.or_else(|| el.value().attr("name"))
.unwrap_or("")
.trim()
.to_ascii_lowercase();
if key.is_empty() {
continue;
}
let is_pub = matches!(
key.as_str(),
"article:published_time"
| "og:published_time"
| "published_time"
| "pubdate"
| "publishdate"
| "datepublished"
| "parsely-pub-date"
| "dcterms.created"
| "dcterms:created"
| "dcterms.issued"
| "dcterms:issued"
| "dcterms.available"
| "dcterms:available"
| "dc.date.issued"
| "dc.date.created"
);
if is_pub {
if let Some(dt) = parse_datetime_utc(content) {
return Some(dt);
}
}
let is_mod = matches!(
key.as_str(),
"article:modified_time"
| "og:updated_time"
| "modified_time"
| "datemodified"
| "last-modified"
| "dcterms.modified"
| "dcterms:modified"
| "dc.date.modified"
);
if is_mod && modified.is_none() {
modified = parse_datetime_utc(content);
}
}
modified
}
fn flatten_ld(v: &serde_json::Value, out: &mut Vec<serde_json::Value>) {
match v {
serde_json::Value::Array(a) => {
for x in a {
flatten_ld(x, out);
}
}
serde_json::Value::Object(o) => {
if let Some(g) = o.get("@graph") {
flatten_ld(g, out);
}
out.push(v.clone());
for key in ["mainEntityOfPage", "mainContentOfPage", "hasPart"] {
if let Some(x) = o.get(key) {
if x.is_object() || x.is_array() {
flatten_ld(x, out);
}
}
}
}
_ => {}
}
}
pub fn ld_types(n: &serde_json::Value) -> Vec<String> {
match n.get("@type") {
Some(serde_json::Value::String(s)) => vec![s.clone()],
Some(serde_json::Value::Array(a)) => a
.iter()
.filter_map(|x| x.as_str().map(str::to_string))
.collect(),
_ => Vec::new(),
}
}
fn strip_tags(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut depth = 0usize;
for c in s.chars() {
match c {
'<' => depth += 1,
'>' => depth = depth.saturating_sub(1),
_ if depth == 0 => out.push(c),
_ => {}
}
}
out
}
fn normalize_whitespace(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut blank_run = 0usize;
for line in s.lines() {
let t = line.trim();
if t.is_empty() {
blank_run += 1;
continue;
}
if !out.is_empty() {
out.push_str(if blank_run > 0 { "\n\n" } else { "\n" });
}
blank_run = 0;
let collapsed: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
out.push_str(&collapsed);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const AMARUJALA: &str = include_str!("../tests/fixtures/articles/amarujala_hi.html");
#[test]
fn amarujala_hindi_article_extracts_full_body_not_the_meta_description() {
let got = extract(
AMARUJALA,
"https://www.amarujala.com/cricket/cricket-news/odi-world-cup-2026-india-vs-pakistan-match-venue-date-time-all-you-need-to-know-2026-10-01",
);
let chars = crate::util::char_len(&got.text);
assert!(
chars > 4_000,
"expected >4000 chars, got {chars} (v7.0 returned 180). source={} text={:?}",
got.source,
got.text.chars().take(120).collect::<String>()
);
assert!(
got.text.contains('\u{0915}') || got.text.contains('\u{092E}'),
"extracted text does not look like Devanagari"
);
}
#[test]
fn amarujala_yields_publication_date_and_language() {
let got = extract(
AMARUJALA,
"https://www.amarujala.com/cricket/cricket-news/x",
);
assert!(got.published.is_some(), "datePublished must be extracted");
assert_eq!(
got.language.as_deref(),
Some("hi"),
"language should be Hindi"
);
assert!(
got.confidence > 0.5,
"confidence {} too low",
got.confidence
);
}
#[test]
fn json_ld_prefers_longest_articlebody_over_any_description() {
let html = r#"<html><head>
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"WebPage",
"description":"A short page blurb that v7.0 returned instead of the article, padded out past the hundred character gate so it would win."}
</script>
<script type="application/ld+json">
{"@context":"https://schema.org","@type":["Article","NewsArticle"],
"articleBody":"THE REAL BODY. Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua enim ad minim veniam quis nostrud exercitation ullamco."}
</script>
</head><body></body></html>"#;
let body = json_ld_article_body(html).expect("should find articleBody");
assert!(body.starts_with("THE REAL BODY"), "got {body:?}");
}
#[test]
fn json_ld_walks_graph_nodes() {
let html = r#"<html><head><script type="application/ld+json">
{"@context":"https://schema.org","@graph":[
{"@type":"WebSite","name":"Site"},
{"@type":"NewsArticle","articleBody":"Graph nested body text that is comfortably longer than the one hundred character minimum so the extractor accepts it as real content."}
]}
</script></head><body></body></html>"#;
let body = json_ld_article_body(html).expect("must find body inside @graph");
assert!(body.starts_with("Graph nested body"), "got {body:?}");
}
#[test]
fn ld_types_handles_string_and_array() {
let s: serde_json::Value = serde_json::json!({"@type":"NewsArticle"});
let a: serde_json::Value = serde_json::json!({"@type":["Article","NewsArticle"]});
assert_eq!(ld_types(&s), vec!["NewsArticle"]);
assert_eq!(ld_types(&a), vec!["Article", "NewsArticle"]);
assert!(ld_types(&serde_json::json!({})).is_empty());
}
#[test]
fn normalize_whitespace_produces_real_paragraph_breaks() {
let messy = "\nFirst para\n \n\nSecond para\n\n\n\nThird\n";
let out = normalize_whitespace(messy);
assert_eq!(out.split("\n\n").count(), 3, "got {out:?}");
assert!(!out.contains(" "), "whitespace not collapsed: {out:?}");
}
#[test]
fn strip_site_suffix_keeps_substantial_titles() {
assert_eq!(
strip_site_suffix("India vs Pakistan World Cup Match Date | Amar Ujala"),
"India vs Pakistan World Cup Match Date"
);
assert_eq!(strip_site_suffix("Short | X"), "Short | X");
}
#[test]
fn second_opinion_triggers_on_thin_relative_output() {
let thin = Extracted {
text: "x".repeat(700),
confidence: 0.95,
..Default::default()
};
assert!(wants_second_opinion(&thin, 100_000));
assert!(!wants_second_opinion(&thin, 10_000));
let unsure = Extracted {
text: "x".repeat(5000),
confidence: 0.4,
..Default::default()
};
assert!(wants_second_opinion(&unsure, 10_000));
let tiny = Extracted {
text: "x".repeat(100),
confidence: 1.0,
..Default::default()
};
assert!(wants_second_opinion(&tiny, 1_000));
}
#[test]
fn strip_tags_removes_markup() {
assert_eq!(strip_tags("a <b>bold</b> word"), "a bold word");
assert_eq!(strip_tags("<p>only</p>"), "only");
}
#[test]
fn handles_empty_and_garbage_input_without_panicking() {
for input in ["", "<html></html>", "not html at all", "<<<>>>"] {
let e = extract(input, "https://x.test/");
assert!(!is_usable(&e) || crate::util::char_len(&e.text) >= min_text_chars());
}
}
#[test]
fn min_text_gate_is_character_based() {
let hindi = "क".repeat(50);
assert_eq!(crate::util::char_len(&hindi), 50);
assert_eq!(hindi.len(), 150);
let e = Extracted {
text: hindi,
..Default::default()
};
assert!(!is_usable(&e), "50 chars must not pass a 120-char gate");
}
fn prose(tag: &str, n: usize) -> String {
(0..n)
.map(|i| format!("{tag} paragraph {i}: The reactor cooling loop transfers heat from the core to the steam generators, and engineers monitor its pressure continuously."))
.collect::<Vec<_>>()
.join(" ")
}
#[test]
fn reads_declarative_shadow_dom() {
let html = format!(
"<html><head><title>S</title></head><body><main><div><template shadowrootmode=\"open\"><p>{}</p><p>{}</p></template></div></main></body></html>",
prose("SHADOW", 3),
prose("ROOT", 3)
);
let e = extract(&html, "https://example.org/s");
assert!(
e.text.contains("SHADOW paragraph 2") && e.text.contains("ROOT paragraph 0"),
"{}",
e.text
);
}
#[test]
fn reads_next_js_shells() {
let pages = format!(
r#"<html><head><title>N</title></head><body><div id="__next"></div><script id="__NEXT_DATA__" type="application/json">{{"props":{{"pageProps":{{"post":{{"body":"{}"}}}}}}}}</script></body></html>"#,
prose("NEXT", 5)
);
let e = extract(&pages, "https://example.org/n");
assert_eq!(e.source, "hydration");
assert!(e.text.contains("NEXT paragraph 4"));
let flight = serde_json::to_string(&format!(
r#"5:["$","p",null,{{"children":"{}"}}]"#,
prose("RSC", 4)
))
.unwrap();
let app = format!(
r#"<html><head><title>R</title></head><body><div></div><script>self.__next_f.push([1,{flight}])</script></body></html>"#
);
let e = extract(&app, "https://example.org/r");
assert!(e.text.contains("RSC paragraph 3"), "{}", e.text);
}
#[test]
fn json_ld_full_body_beats_a_dom_teaser() {
let body = prose("FULL", 8);
let html = format!(
r#"<html><head><title>P</title><script type="application/ld+json">{{"@type":"NewsArticle","headline":"P","articleBody":"{body}"}}</script></head>
<body><article><p>{}</p><div class="paywall">Subscribe to read more</div></article></body></html>"#,
prose("TEASER", 1)
);
let e = extract(&html, "https://example.org/p");
assert!(
e.text.contains("FULL paragraph 7"),
"via {}: {}",
e.source,
e.text
);
}
#[test]
fn ordinary_articles_are_not_replaced_by_hydration_noise() {
let html = format!(
r#"<html><head><title>A</title></head><body><article><p>{}</p><p>{}</p></article>
<script>window.__INITIAL_STATE__ = {{"related":"{}"}};</script></body></html>"#,
prose("REAL", 6),
prose("ALSO", 6),
prose("RELATED", 1)
);
let e = extract(&html, "https://example.org/a");
assert_ne!(e.source, "hydration");
assert!(e.text.contains("REAL paragraph 5"));
}
#[test]
fn wires_modified_time_fallback_and_extended_metadata() {
let html = format!(
r#"<!DOCTYPE html><html lang="en-US"><head>
<title>Microservices Guide</title>
<meta name="dcterms.modified" content="2026-02-20">
<script type="application/ld+json">
{{
"@context": "https://schema.org",
"@graph": [
{{
"@type": ["Article", "TechArticle"],
"headline": "Microservices Architecture Guide",
"author": {{ "@type": "Person", "name": "Martin Fowler" }},
"publisher": {{ "@type": "Organization", "name": "martinfowler.com" }}
}}
]
}}
</script>
</head><body><article><p>{}</p><p>{}</p></article></body></html>"#,
prose("ARCH", 4),
prose("DESIGN", 4)
);
let got = extract(
&html,
"https://martinfowler.com/articles/microservices.html",
);
assert_eq!(got.source, "readability");
assert_eq!(got.title, "Microservices Architecture Guide");
assert_eq!(got.language.as_deref(), Some("en"));
assert_eq!(got.byline.as_deref(), Some("Martin Fowler"));
assert_eq!(got.site_name.as_deref(), Some("martinfowler.com"));
assert!(
got.published.is_some(),
"modified_time fallback must populate published"
);
}
#[test]
fn unwraps_noscript_fallback_on_spa_shell() {
let html = format!(
r#"<!DOCTYPE html><html lang="en"><head>
<title>PEP 703 Thread</title>
<meta property="og:site_name" content="Discussions on Python.org">
<meta property="article:published_time" content="2023-07-28T20:44:43+00:00">
</head><body>
<div id="spa-root"></div>
<noscript><div id="main-outlet" role="main"><article><h1>PEP 703</h1><p>{}</p><p>{}</p></article></div></noscript>
</body></html>"#,
prose("GIL", 4),
prose("THREAD", 4)
);
let got = extract(&html, "https://discuss.python.org/t/pep-703/123");
assert!(
got.text.contains("GIL paragraph 3"),
"noscript content missing: {}",
got.text
);
assert_eq!(got.site_name.as_deref(), Some("Discussions on Python.org"));
assert!(got.published.is_some());
}
}