1use crate::html::{Kid, Node, Tree, Visit, py_space, py_strip, unescape};
5use crate::settings::limit;
6use crate::tables::{COMBINING, FOLD, ND_ZEROS};
7use crate::{fetch::title_head, fetch::words_of, outline::sections_of};
8use indexmap::IndexMap;
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, ser::PrettyFormatter};
11use std::collections::{BTreeSet, HashMap, HashSet};
12use std::sync::LazyLock;
13
14pub const DOC_V: u32 = 18;
16pub const COMMENT: usize = 7;
18
19#[derive(Deserialize)]
21#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
22pub struct Lists {
23 block: Vec<&'static str>,
25 drop_always: Vec<&'static str>,
27 sectioning: Vec<&'static str>,
29 sectioning_roles: Vec<&'static str>,
30 row: Vec<&'static str>,
32 cell: Vec<&'static str>,
33 cookie: Vec<&'static str>,
35 skip_link: Vec<&'static str>,
37 magic: Vec<(String, &'static str)>,
39 pub text: Vec<&'static str>,
41 lazy_src: Vec<&'static str>,
46 filler: Vec<&'static str>,
47 image_ext: Vec<&'static str>,
48 picture_page: Vec<&'static str>,
49 not_content: Vec<&'static str>,
50 not_content_alt: Vec<&'static str>,
51 share_card: Vec<&'static str>,
52 share_host: Vec<&'static str>,
53 tracking: Vec<&'static str>,
54 ad_slot: Vec<&'static str>,
56 post_counts: Vec<(&'static str, Vec<&'static str>)>,
62 post_marker: Vec<&'static str>,
63 post_skip: Vec<&'static str>,
64 post_facts: Vec<(&'static str, Vec<&'static str>)>,
65 post_time: (&'static str, Vec<&'static str>, Vec<&'static str>),
66 info: Vec<(&'static str, Vec<&'static str>)>,
68 currency: Vec<&'static str>,
70}
71
72pub static LISTS: LazyLock<Lists> = LazyLock::new(|| crate::settings::table("clean"));
73
74#[derive(Serialize, Deserialize, Clone, Default)]
75pub struct Section {
76 pub level: usize,
77 pub title: String,
78 pub lines: Vec<String>,
79}
80
81#[derive(Serialize, Deserialize, Default)]
83pub struct Loss {
84 pub vs_light_lost: usize,
85 pub light_facts: usize,
86 pub pruned_chars: usize,
89 pub visible_chars: usize,
92 pub price_pruned: usize,
95}
96
97#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Debug)]
99pub struct Media {
100 pub src: String,
101 pub alt: String,
102 pub video: bool,
104 pub w: u32,
107 pub h: u32,
108 pub ty: String,
110 pub demoted: bool,
113 #[serde(skip)]
115 key: (String, u32),
116 #[serde(skip)]
118 linked: bool,
119}
120
121pub type Info = IndexMap<String, String>;
123
124#[derive(Serialize, Deserialize, Default)]
125pub struct Tokens {
126 pub clean: usize,
127}
128
129#[derive(Serialize, Deserialize, Default)]
131pub struct Doc {
132 pub v: u32,
133 pub chunk: usize,
135 pub url: String,
136 pub final_url: String,
137 pub title: String,
138 pub info: Info,
139 pub sections: Vec<Section>,
140 pub top: usize,
141 pub links: Vec<String>,
142 pub anchors: Vec<String>,
144 pub mode: String,
145 pub loss: Loss,
146 pub tokens: Tokens,
147 pub cut: usize,
149 pub islands: usize,
151 pub media: Vec<Media>,
153}
154
155impl Doc {
156 pub fn new(url: &str, final_url: &str, title: String, sections: Vec<Section>, mode: &str) -> Doc {
160 Doc {
161 v: DOC_V,
162 chunk: crate::settings::get().chunk.value,
163 url: url.into(),
164 final_url: final_url.into(),
165 title,
166 tokens: Tokens { clean: sections.iter().flat_map(|s| s.lines.iter()).map(|t| tok(t)).sum() },
167 sections,
168 top: 1,
169 mode: mode.into(),
170 ..Doc::default()
171 }
172 }
173
174 pub fn served(&self) -> usize {
176 self.sections.len().saturating_sub(self.islands)
177 }
178}
179
180pub fn tok(s: &str) -> usize {
185 weights(s).sum::<usize>().div_ceil(216)
186}
187
188pub fn tok_cut(s: &str, cap: usize) -> usize {
190 let mut w = 0;
191 s.char_indices().zip(weights(s)).find(|&(_, c)| (w += c, w > cap * 216).1).map_or(s.len(), |((i, _), _)| i)
192}
193
194fn weights(s: &str) -> impl Iterator<Item = usize> + '_ {
196 let mark = |c: char| c.is_ascii_punctuation();
197 s.chars().scan(' ', move |prev, c| {
198 let letter = c.is_ascii_alphabetic() || mark(*prev) && mark(c);
199 *prev = c;
200 Some(usize::from(!py_space(c)) * if letter { 80 } else { 270 })
201 })
202}
203
204pub fn collapse(s: &str) -> String {
206 s.split(py_space).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ")
207}
208
209fn combining(cp: u32) -> bool {
211 let at = COMBINING.partition_point(|&(_, hi)| hi < cp);
212 COMBINING.get(at).is_some_and(|&(lo, _)| lo <= cp)
213}
214
215pub fn fold(s: &str) -> String {
217 let mut out = String::with_capacity(s.len());
218 for c in s.chars() {
219 let cp = c as u32;
220 if cp < 0x80 {
221 out.push(c);
222 } else if (0xAC00..=0xD7A3).contains(&cp) {
223 let syl = cp - 0xAC00;
225 let jamo = [0x1100 + syl / 588, 0x1161 + (syl % 588) / 28, 0x11A7 + syl % 28];
226 let len = if syl.is_multiple_of(28) { 2 } else { 3 };
227 out.extend(jamo[..len].iter().filter_map(|&j| char::from_u32(j)));
228 } else if !combining(cp) {
229 let at = FOLD.binary_search_by_key(&cp, |&(k, _)| k);
230 if let Ok(at) = at { out.push_str(FOLD[at].1) } else { out.push(c) }
231 }
232 }
233 out.to_lowercase()
234}
235
236pub fn decode(raw: Vec<u8>, header: Option<&str>) -> (Vec<u8>, &'static str) {
240 use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1252, X_USER_DEFINED};
241 let meta = || match prescan(&raw[..raw.len().min(1024)]).and_then(Encoding::for_label) {
242 Some(e) if e == UTF_16BE || e == UTF_16LE => Some(UTF_8),
244 Some(e) if e == X_USER_DEFINED => Some(WINDOWS_1252),
245 e => e,
246 };
247 let bom = Encoding::for_bom(&raw).map(|b| b.0);
248 let sent = header.and_then(|h| Encoding::for_label(h.as_bytes()));
249 let enc = bom.or(sent).or_else(meta).unwrap_or(UTF_8);
250 let name = if enc == UTF_8 { "" } else { enc.name() };
251 if enc == UTF_8 && !raw.starts_with(b"\xEF\xBB\xBF") {
252 return (raw, name);
253 }
254 (enc.decode_with_bom_removal(&raw).0.into_owned().into_bytes(), name)
255}
256
257fn prescan(head: &[u8]) -> Option<&[u8]> {
259 let low = head.to_ascii_lowercase();
260 let mut at = 0;
261 while let Some(i) = find(&low[at..], b"<meta").map(|i| i + at) {
262 let end = find(&low[i..], b">").map_or(low.len(), |e| i + e);
263 at = end;
264 let Some(c) = find(&low[i..end], b"charset").map(|c| i + c + 7) else { continue };
265 let rest = head[c..end].trim_ascii_start().strip_prefix(b"=").map(<[u8]>::trim_ascii_start);
266 let Some(v) = rest.map(|r| r.strip_prefix(b"\"").or(r.strip_prefix(b"'")).unwrap_or(r)) else { continue };
267 let n = v.iter().position(|b| b" \"';/>\t\n\r".contains(b)).unwrap_or(v.len());
268 if n > 0 {
269 return Some(&v[..n]);
270 }
271 }
272 None
273}
274
275fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
276 hay.windows(needle.len()).position(|w| w == needle)
277}
278
279pub fn kind_of(ctype: &str, body: &[u8]) -> &'static str {
287 let ct = ctype.split(';').next().unwrap_or_default().trim().to_ascii_lowercase();
288 let head = body.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(body).trim_ascii_start();
289 let low = head[..head.len().min(1024)].to_ascii_lowercase();
290 let opens = |tags: &[&[u8]]| tags.iter().any(|t| low.starts_with(t));
291 let bare = ct.is_empty() || ct == "text/plain";
292 match () {
293 _ if let Some(k) = sniff(body) => k,
294 _ if ct.contains("application/pdf") => "pdf",
295 _ if ct.contains("application/zip") || ct.contains("officedocument") => "zip",
296 _ if ct.contains("html") || opens(&[b"<!doctype html"]) || find(&low, b"<html").is_some() => "html",
297 _ if ct.contains("json") => "json",
298 _ if bare && opens(&[b"{", b"["]) && serde_json::from_slice::<serde::de::IgnoredAny>(body).is_ok() => "json",
299 _ if ct.contains("xml") || bare && opens(&[b"<?xml", b"<rss", b"<feed", b"<urlset", b"<sitemapindex"]) => "xml",
300 _ if ct == "text/markdown" => "md",
301 _ if ct.starts_with("text/") => "text",
302 _ => "html",
303 }
304}
305
306pub fn sniff(raw: &[u8]) -> Option<&'static str> {
308 LISTS.magic.iter().find(|m| raw.starts_with(m.0.as_bytes())).map(|m| m.1)
309}
310
311pub fn is_digit(c: char) -> bool {
313 let u = c as u32;
314 c.is_ascii_digit() || (u >= 0x660 && ND_ZEROS.iter().any(|&z| u >= z && u < z + 10))
315}
316
317pub fn is_word(c: char) -> bool {
319 c.is_alphanumeric() || c == '_'
320}
321
322pub const CARD: &str = "▸ ";
324pub const PIECE: &str = " · ";
326pub static LREF: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(r"\[l[0-9]+\]").expect("a pattern"));
328
329#[derive(Clone)]
330pub enum Line {
331 H(usize, String),
332 T(String),
333}
334
335impl Line {
336 pub fn text(&self) -> &str {
337 match self {
338 Line::H(_, t) | Line::T(t) => t,
339 }
340 }
341}
342
343#[derive(PartialEq, Clone, Copy)]
344enum Mode {
345 Light,
346 Hard,
347 Clean,
348}
349
350struct Render<'a> {
351 tree: &'a Tree,
352 tlen: &'a [usize],
353 base_url: Option<url::Url>,
355 mode: Mode,
356 js: bool,
357 lines: Vec<Line>,
358 buf: String,
360 marks: Vec<usize>,
361 links: IndexMap<String, String>,
364 inline: usize,
365 media: Vec<usize>,
367 thread: HashMap<usize, usize>,
369 by: Option<(usize, usize)>,
371 worded: HashSet<String>,
373 owed: Vec<(usize, String, usize)>,
375}
376
377fn measure(t: &Tree, id: usize, tlen: &mut [usize]) -> usize {
380 let mut s = 0;
381 for k in &t.nodes[id].kids {
382 match k {
383 Kid::Text(x) => s += py_strip(x).chars().count(),
384 Kid::Node(c) if t.nodes[*c].tag == "template" => tlen[*c] = measure(t, c + 1, tlen),
385 Kid::Node(c) if !LISTS.drop_always.contains(&t.nodes[*c].tag.as_str()) => s += measure(t, *c, tlen),
386 Kid::Node(_) => {}
387 }
388 }
389 tlen[id] = s;
390 s
391}
392
393fn hidden(n: &Node, text: usize) -> bool {
396 if n.attr("hidden").is_some() || n.attr("aria-hidden") == Some("true") && text <= 1 {
397 return true;
398 }
399 let style = n.attr("style").unwrap_or("");
400 [("display", "none"), ("visibility", "hidden")].iter().any(|(k, v)| {
402 style.match_indices(k).any(|(i, _)| {
403 let r = style[i + k.len()..].trim_start_matches(py_space);
404 r.strip_prefix(':').is_some_and(|r| r.trim_start_matches(py_space).starts_with(v))
405 })
406 })
407}
408
409impl Render<'_> {
410 fn chrome(&self, id: usize, scoped: bool) -> bool {
411 let n = &self.tree.nodes[id];
412 if self.tlen[id] as f64 > 0.5 * self.tlen[0].max(1) as f64 {
413 return false;
414 }
415 let (role, tag) = (n.attr("role").unwrap_or("").to_lowercase(), n.tag.as_str());
416 let nav = matches!(role.as_str(), "navigation" | "banner" | "contentinfo");
417 if nav || matches!(tag, "nav" | "aside" | "form") || (!scoped && matches!(tag, "header" | "footer")) {
418 return true;
419 }
420 let cid = format!("{} {}", n.attr("id").unwrap_or(""), n.attr("class").unwrap_or("")).to_lowercase();
421 LISTS.cookie.iter().any(|w| cid.contains(w))
422 || self.mode == Mode::Clean && (tag == "dialog" || role.ends_with("dialog") || hidden(n, self.tlen[id]))
423 }
424
425 fn comments(&self) -> HashMap<usize, usize> {
432 let t = self.tree;
433 let block = |i: &usize| matches!(t.nodes[*i].tag.as_str(), "li" | "article") || t.nodes[*i].tag.contains('-');
434 let says = |i: &usize| t.nodes[*i].kids.iter().any(|k| matches!(k, Kid::Text(s) if paragraph(s)));
435 let said: HashSet<usize> = (0..t.nodes.len()).filter(says).filter_map(|i| up(t, i).find(block)).collect();
436 let pruned = |a: usize| self.mode != Mode::Light && self.chrome(a, true);
438 let served = |i: &usize| up(t, *i).last() == Some(0) && !up(t, *i).any(pruned);
439 let dated: Vec<usize> = (0..t.nodes.len()).filter(|i| t.nodes[*i].tag == "time" && served(i)).collect();
440 let tags = dated.iter().filter_map(|&i| up(t, i).find(|b| said.contains(b))).map(|b| t.nodes[b].tag.as_str());
441 let tag = commonest(tags.collect());
442 let item = |c: usize| t.nodes[c].parent.filter(|&p| t.nodes[p].tag == "li" && tag != Some("li")).unwrap_or(c);
443 let of = |i: &usize| up(t, *i).find(|&b| Some(t.nodes[b].tag.as_str()) == tag).map(item);
444 let comments: HashSet<usize> = dated.iter().filter_map(of).collect();
445 let mut depths: HashMap<usize, usize> =
446 comments.iter().map(|&c| (c, up(t, c).skip(1).filter(|a| comments.contains(a)).count())).collect();
447 let list = commonest(depths.iter().filter(|e| *e.1 == 0).map(|e| t.nodes[*e.0].parent).collect()).flatten();
449 depths.retain(|&c, d| *d > 0 || t.nodes[c].parent == list);
450 let width =
453 |n: &Node| n.attr("width").filter(|_| n.kids.is_empty() && n.attr("height") == Some("1"))?.parse().ok();
454 let in_row = |i: usize| up(t, i).find(|&r| t.nodes[r].tag == "tr");
455 let row = |i: usize| width(&t.nodes[i]).and_then(|w: usize| Some((in_row(i)?, w)));
456 let mut rows: Vec<(usize, usize)> = (0..t.nodes.len()).filter_map(row).filter(|r| served(&r.0)).collect();
457 rows.dedup_by_key(|r| r.0);
458 let steps: Vec<usize> = rows.iter().map(|r| r.1).collect::<BTreeSet<_>>().into_iter().collect();
459 let prose: HashSet<usize> = (0..t.nodes.len()).filter(says).filter_map(in_row).collect();
463 let head = |v: Visit| matches!(v, Visit::Node(n) if matches!(n.tag.as_bytes(), [b'h', b'1'..=b'6']));
464 let post = |r: &&(usize, usize)| prose.contains(&r.0) && !t.walk(r.0, &[]).any(head);
465 let talk = steps.first() == Some(&0) && rows.iter().filter(post).count() >= limit("thread_rows");
466 depths.extend(rows.iter().filter(|_| talk).map(|&(r, w)| (r, steps.partition_point(|&s| s < w))));
467 let tops = depths.values().filter(|&&d| d == 0).count();
469 if depths.len() >= limit("thread_rows") && (2..depths.len()).contains(&tops) { depths } else { HashMap::new() }
470 }
471
472 fn listed(&self, x: usize) -> bool {
475 self.tree.nodes[x].tag == "li" || self.chrome(x, true)
476 }
477
478 fn post(&self) -> Info {
484 let t = self.tree;
485 let counts = |i: usize| (i, t.nodes[i].attrs.iter().filter_map(count).collect::<Vec<_>>());
486 let placed = |c: &(usize, Vec<(String, String)>)| !c.1.is_empty() && !up(t, c.0).any(|a| self.listed(a));
487 let Some((i, found)) = (0..t.nodes.len()).map(counts).find(placed) else {
488 return Info::new();
489 };
490 let (key, when, unit) = &LISTS.post_time;
491 let named = |(k, v): &(String, String)| {
492 let name = bare(k);
493 let words: Vec<&str> = name.split(['-', '_', ':']).collect();
494 let has = |list: &[&str]| words.iter().any(|w| list.contains(w));
495 let fact = LISTS.post_facts.iter().find(|r| r.1.contains(&name.as_str())).map(|r| r.0);
496 let key = if has(when) && has(unit) { Some(*key) } else { fact };
497 Some((key?.to_string(), fact_value(v)?))
498 };
499 let mut info = Info::new();
500 for (k, v) in found.into_iter().chain(t.nodes[i].attrs.iter().filter_map(named)) {
501 info.entry(k).or_insert(v); }
503 info
504 }
505
506 fn declared(&self) -> Option<usize> {
511 let (t, path) = (self.tree, up(self.tree, *self.thread.keys().min()?).collect::<Vec<_>>());
512 let words = count_words("comments");
513 let said = |s: &str| match s.split_whitespace().collect::<Vec<_>>()[..] {
514 [n, w] if words.contains(&w.to_lowercase().as_str()) => n.replace(',', "").parse().ok(),
515 _ => None,
516 };
517 let attr = |(_, v): &(String, String)| said(v);
518 let text = |k: &Kid| if let Kid::Text(s) = k { said(s) } else { None };
519 let p = &path;
520 let shown = |i: &usize| !p.contains(i) && !up(t, *i).take_while(|a| !p.contains(a)).any(|a| self.listed(a));
521 let found = |i: usize| t.nodes[i].attrs.iter().filter_map(attr).chain(t.nodes[i].kids.iter().filter_map(text));
522 let mut near =
523 (0..path[0]).rev().filter(shown).flat_map(|i| found(i).map(move |n| (p.iter().find(|&&a| a <= i), n)));
524 let (at, n) = near.next()?;
525 near.take_while(|f| f.0 == at).all(|f| f.1 == n).then_some(n)
526 }
527
528 fn push(&mut self, s: &str) {
531 let gap = self.buf.ends_with(is_digit) && s.starts_with(is_digit);
532 self.buf.push_str(if gap { " " } else { "" });
533 self.marks.push(self.buf.len());
534 self.buf.push_str(s);
535 }
536
537 fn flush(&mut self) {
538 if self.inline > 0 {
539 self.push(" ");
540 return;
541 }
542 let t = collapse(&self.buf);
543 self.buf.clear();
544 self.marks.clear();
545 self.lines.extend((!t.is_empty() && t != "-" && t != "|" && t != "- |").then_some(Line::T(t)));
546 }
547
548 fn target(&self, href: &str) -> Option<String> {
550 let href = py_strip(href);
551 if href.is_empty() || ["#", "javascript:", "mailto:", "tel:", "data:"].iter().any(|p| href.starts_with(p)) {
552 return None;
553 }
554 let mut j = url::Url::options().base_url(self.base_url.as_ref()).parse(href).ok()?;
555 j.set_fragment(None);
556 let u = String::from(j);
557 let same = self.base_url.as_ref().is_some_and(|b| b.as_str() == u);
558 (u.starts_with("http") && !same && !skip_link(&u)).then_some(u)
559 }
560
561 fn worded_links(&self) -> HashSet<String> {
563 let t = self.tree;
564 let worded = |&a: &usize| t.nodes[a].tag == "a" && worded(&t.texts(a, &LISTS.drop_always).collect::<String>());
565 (0..t.nodes.len()).filter(worded).filter_map(|a| self.target(t.nodes[a].attr("href")?)).collect()
566 }
567
568 fn link(&mut self, href: &str, text: &str) -> Option<usize> {
569 let u = self.target(href)?;
570 let (i, a) = self.links.insert_full(u, collapse(text));
571 if let Some(a) = a.filter(|a| a.len() > text.len()) {
572 self.links[i] = a; }
574 Some(i + 1)
575 }
576
577 fn text_of(&mut self, id: usize, scoped: bool) -> String {
578 let save = (std::mem::take(&mut self.buf), std::mem::take(&mut self.marks));
579 self.inline += 1;
580 self.kids(id, scoped);
581 self.inline -= 1;
582 let t = collapse(&self.buf);
583 (self.buf, self.marks) = save;
584 t
585 }
586
587 fn kids(&mut self, id: usize, scoped: bool) {
588 let kids = &self.tree.nodes[id].kids;
589 let cards = if self.inline == 0 { self.groups(id) } else { HashSet::new() };
590 let mut spans = vec![];
591 for k in kids {
592 match k {
593 Kid::Text(s) => self.push(s),
594 Kid::Node(c) if cards.contains(c) => {
595 self.flush();
596 let l0 = self.lines.len();
597 self.walk(*c, scoped);
598 self.flush();
599 spans.push(l0..self.lines.len());
600 }
601 Kid::Node(c) => self.walk(*c, scoped),
602 }
603 }
604 self.cards(&spans);
605 }
606
607 fn groups(&self, id: usize) -> HashSet<usize> {
611 let t = self.tree;
612 let kids: Vec<usize> = t.nodes[id].kids.iter().filter_map(Kid::node).collect();
613 let mut shapes: IndexMap<(&str, &str), Vec<usize>> = IndexMap::new();
614 let tag = |c: usize| t.nodes[c].tag.as_str();
616 let boxed =
617 |c: usize| !part(&t.nodes[c], &LISTS.row) && (LISTS.block.contains(&tag(c)) || tag(c).contains('-'));
618 for &c in kids.iter().filter(|&&c| boxed(c)) {
619 shapes.entry(shape(&t.nodes[c])).or_default().push(c);
620 }
621 let own = |c: usize| held(t, c, &|n| shape(n) == shape(&t.nodes[c]) || n.tag == "pre" || n.tag == "table");
623 let card = |c: &&usize| !own(**c) && !byline(t, self.tlen, **c) && !self.thread.contains_key(*c);
624 let shown = kids.iter().filter(|&&c| boxed(c) && self.tlen[c] > 0).count();
626 let most = |v: &Vec<usize>| v.len() >= limit("card_repeats") && 5 * v.len() >= 3 * shown;
627 let cards = shapes.into_values().filter(|v| most(v) && 5 * v.iter().filter(card).count() >= 4 * v.len());
628 cards.flatten().collect()
629 }
630
631 fn cards(&mut self, spans: &[std::ops::Range<usize>]) {
638 let ids: Vec<Vec<(usize, usize)>> = spans.iter().map(|s| link_ids(&self.lines[s.clone()])).collect();
639 let mut uses: IndexMap<usize, usize> = IndexMap::new();
640 for i in ids.iter().flat_map(|v| v.iter().map(|i| i.1).collect::<HashSet<_>>()) {
641 *uses.entry(i).or_default() += 1;
642 }
643 let own = |v: Vec<(usize, usize)>| v.into_iter().filter(|i| 2 * uses[&i.1] < spans.len()).collect::<Vec<_>>();
644 let rows: Vec<_> = spans.iter().zip(ids).map(|(s, v)| self.card_row(&self.lines[s.clone()], &own(v))).collect();
645 let ok = 5 * rows.iter().flatten().filter(|r| r.1).count() >= 4 * rows.len();
646 for (s, (row, _)) in spans.iter().zip(rows).filter_map(|(s, r)| Some((s, r?))).filter(|_| ok) {
647 self.lines[s.start] = Line::T(row);
648 self.lines[s.start + 1..s.end].fill(Line::T(String::new()));
649 }
650 let tail: Vec<Line> = self.lines.drain(spans.first().map_or(self.lines.len(), |s| s.start)..).collect();
651 self.lines.extend(tail.into_iter().filter(|l| !matches!(l, Line::T(t) if t.is_empty())));
652 }
653
654 fn card_row(&self, lines: &[Line], ids: &[(usize, usize)]) -> Option<(String, bool)> {
662 if lines.len() < 2 || lines.iter().any(|l| l.text().starts_with(CARD)) {
663 return None;
664 }
665 let anchor = |i: usize| self.links.get_index(i - 1).map_or("", |(_, a)| a.as_str());
666 let head = lines.iter().position(|l| matches!(l, Line::H(..)));
667 let key = |i: &&(usize, usize)| (anchor(i.1).len(), lines[i.0].text().len()); let main = ids.iter().rev().filter(|i| head.is_none_or(|h| i.0 == h)).max_by_key(key);
670 let all: usize = ids.iter().map(|i| i.1).collect::<HashSet<_>>().into_iter().map(|i| anchor(i).len()).sum();
671 let titled = |m: usize| {
673 head.map_or(anchor(m).split_whitespace().nth(1).is_some(), |h| 2 * anchor(m).len() >= lines[h].text().len())
674 };
675 let article = lines.iter().filter(|l| matches!(l, Line::H(..))).nth(1).is_some();
677 let one = !article && main.is_some_and(|&(_, m)| titled(m) && 5 * anchor(m).len() >= 2 * all);
678 let mark = main.map_or(String::new(), |i| format!("[l{}]", i.1));
679 let mut ps: Vec<String> =
680 lines.iter().map(|l| collapse(&l.text().trim_start_matches("- ").replace(&mark, ""))).collect();
681 let title = ps.remove(head.or(main.map(|i| i.0)).unwrap_or(0));
682 ps.retain(|p| !p.is_empty() && *p != title); let title = collapse(&format!("{title} {mark}"));
684 Some((format!("{CARD}{}", [vec![title], ps].concat().join(PIECE)), one))
685 }
686
687 fn walk(&mut self, id: usize, scoped: bool) {
688 let tree = self.tree;
689 let n = &tree.nodes[id];
690 let tag = n.tag.as_str();
691 if LISTS.drop_always.contains(&tag) || (tag == "noscript" && self.js) {
692 return;
693 }
694 if self.mode != Mode::Light && self.chrome(id, scoped) {
695 return;
696 }
697 self.media.extend(matches!(tag, "img" | "video").then_some(id));
698 let role = n.attr("role").unwrap_or("").to_lowercase();
699 let scoped = scoped || LISTS.sectioning.contains(&tag) || LISTS.sectioning_roles.contains(&role.as_str());
700 let top = self.inline == 0;
701 if let Some(&depth) = self.thread.get(&id).filter(|_| top) {
703 self.flush();
704 self.lines.push(Line::H(COMMENT + depth.min(limit("thread_depth")), String::new()));
705 }
706 let quoted = || up(tree, id).any(|a| self.thread.contains_key(&a));
708 if tag == "time" && quoted() {
711 let short = |x: &usize| !self.thread.contains_key(x) && self.tlen[*x] <= limit("byline_chars");
712 let head = self.lines.iter().rposition(|l| matches!(l, Line::H(lv, _) if *lv >= COMMENT));
713 self.by = head.zip(up(tree, id).take_while(short).last());
714 }
715 match tag.as_bytes() {
716 [b'h', d @ b'1'..=b'6'] if top && !quoted() => self.heading(id, scoped, usize::from(d - b'0')),
717 b"pre" if top => self.pre(id),
718 _ if top && part(n, &LISTS.row) => self.row(id, scoped),
719 _ => self.inline_or_block(id, scoped, top),
720 }
721 if let Some((h, _)) = self.by.take_if(|b| b.1 == id).filter(|_| self.inline == 0) {
722 self.flush();
723 if self.lines[h + 1..].iter().all(|l| !paragraph(l.text())) && self.lines.len() > h + 2 {
724 let by: Vec<String> = self.lines.drain(h + 1..).map(|l| l.text().to_string()).collect();
725 self.lines.push(Line::T(by.join(" ")));
726 }
727 }
728 }
729
730 fn heading(&mut self, id: usize, scoped: bool, level: usize) {
731 self.flush();
732 let t = self.text_of(id, scoped);
733 self.lines.extend((!t.is_empty()).then_some(Line::H(level, t)));
734 }
735
736 fn row(&mut self, id: usize, scoped: bool) {
739 self.flush();
740 let tree = self.tree;
741 let td: Vec<usize> =
742 tree.nodes[id].kids.iter().filter_map(Kid::node).filter(|&c| part(&tree.nodes[c], &LISTS.cell)).collect();
743 if td.is_empty() || held(tree, id, &|n| n.tag == "table") {
744 return self.kids(id, scoped);
745 }
746 let cells: Vec<String> = td.into_iter().map(|c| self.text_of(c, scoped)).collect();
747 self.lines.extend(cells.iter().any(|c| !c.is_empty()).then(|| Line::T(format!("| {} |", cells.join(" | ")))));
748 }
749
750 fn pre(&mut self, id: usize) {
752 self.flush();
753 let t: String = self.tree.texts(id, &LISTS.drop_always).collect();
754 let text = t.replace("\r\n", "\n");
755 let kept = text.split(PY_NEWLINE).filter(|ln| !py_strip(ln).is_empty());
756 self.lines.extend(kept.map(|ln| Line::T(ln.trim_end_matches(py_space).to_string())));
757 }
758
759 fn anchor(&mut self, id: usize, scoped: bool) {
765 let blocks = self.inline == 0 && held(self.tree, id, &|n| LISTS.block.contains(&n.tag.as_str()));
766 if blocks {
767 self.flush();
768 }
769 let (b0, l0, m0) = (self.marks.len(), self.lines.len(), self.media.len());
770 self.kids(id, scoped);
771 if blocks {
772 self.flush();
773 }
774 let tail = self.marks.get(b0).map_or(String::new(), |&m| self.buf[m..].to_string());
775 let text = self.lines[l0..].iter().map(Line::text).chain([tail.as_str()]).collect::<Vec<_>>().join(" ");
776 let name = self.accname(id, m0, &text);
777 let name = if name.is_empty() || py_strip(&text).is_empty() { name } else { format!("{PIECE}{name}") };
778 if py_strip(&text).is_empty() && name.is_empty() {
779 return;
780 }
781 let Some(i) = self.link(self.tree.nodes[id].attr("href").unwrap_or(""), &format!("{text}{name}")) else {
782 return;
783 };
784 let near = |p| collapse(&self.tree.texts(p, &LISTS.drop_always).collect::<Vec<_>>().join(" "));
785 if py_strip(&text).is_empty() && self.tree.nodes[id].parent.is_some_and(|p| near(p).contains(&name)) {
786 return self.owed.push((self.lines.len(), name, i));
787 }
788 if !blocks {
789 return self.push(&format!(" {name} [l{i}] "));
790 }
791 if self.lines.len() == l0 {
792 self.lines.push(Line::T(String::new())); }
794 let ls = self.lines[l0..].iter().enumerate();
795 let title = ls.clone().filter(|l| !paragraph(l.1.text())).max_by_key(|l| l.1.text().chars().count());
796 let at = ls.clone().find(|l| matches!(l.1, Line::H(..))).or(title).map_or(0, |l| l.0);
797 let (Line::T(t) | Line::H(_, t)) = &mut self.lines[l0 + at];
798 *t = collapse(&format!("{t}{name} [l{i}]"));
799 }
800
801 fn pay(&mut self) {
804 for (l0, name, i) in std::mem::take(&mut self.owed) {
805 let line = self.lines.iter_mut().skip(l0).find(|l| l.text().contains(&name));
806 if let Some(Line::T(t) | Line::H(_, t)) = line {
807 t.push_str(&format!(" [l{i}]"));
808 }
809 }
810 }
811
812 fn accname(&self, id: usize, m0: usize, text: &str) -> String {
820 let t = self.tree;
821 let href = t.nodes[id].attr("href").and_then(|h| self.target(h));
822 if worded(text) || href.is_none_or(|h| self.worded.contains(&h)) {
823 return String::new();
824 }
825 let shown = self.media[m0..].iter().map(|&i| &t.nodes[i]).filter(|n| !decorative(n));
826 let mut alts: Vec<&str> = shown.filter_map(|n| n.attr("alt")).collect();
827 alts.dedup();
828 let alt = alts.join(" ");
829 let n = &t.nodes[id];
830 let names = [n.attr("aria-label"), Some(alt.as_str()), n.attr("title").filter(|_| py_strip(text).is_empty())];
831 let name = names.into_iter().flatten().map(collapse).find(|s| !s.is_empty()).unwrap_or_default();
832 if name.split_whitespace().count() >= limit("name_words") { name } else { String::new() }
833 }
834
835 fn inline_or_block(&mut self, id: usize, scoped: bool, top: bool) {
836 let tree = self.tree;
837 let n = &tree.nodes[id];
838 let tag = n.tag.as_str();
839 match tag {
840 "br" => self.flush(),
841 "sup" if let Some(t) = sup_digits(n) => self.push(&t),
843 "a" => self.anchor(id, scoped),
844 "dt" if top => {
845 self.flush();
846 let t = self.text_of(id, scoped);
847 if !t.is_empty() {
848 self.push(&format!("{t}: "));
849 }
850 }
851 "dd" | "li" if top => {
852 if tag == "li" {
853 self.flush();
854 self.push("- ");
855 }
856 self.kids(id, scoped);
857 self.flush();
858 }
859 _ => {
860 let block = LISTS.block.contains(&tag);
861 if block {
862 self.flush();
863 }
864 self.kids(id, scoped);
865 if block {
866 self.flush();
867 } else if (tag == "span" || tag == "label") && !top {
868 self.push(" ");
869 }
870 }
871 }
872 }
873}
874
875fn decorative(n: &Node) -> bool {
877 n.attr("aria-hidden") == Some("true") || matches!(n.attr("role"), Some("presentation" | "none"))
878}
879
880fn worded(text: &str) -> bool {
882 text.chars().zip(text.chars().skip(1)).any(|(a, b)| a.is_alphabetic() && b.is_alphabetic())
883}
884
885fn link_ids(lines: &[Line]) -> Vec<(usize, usize)> {
887 let id = |(k, m): (usize, regex::Match)| Some((k, m.as_str()[2..m.len() - 1].parse::<usize>().ok()?));
888 let ids = lines.iter().enumerate().flat_map(|(k, l)| LREF.find_iter(l.text()).map(move |m| (k, m)));
889 ids.filter_map(id).collect()
890}
891
892fn byline(t: &Tree, tlen: &[usize], id: usize) -> bool {
896 let block = |n: &Node| LISTS.block.contains(&n.tag.as_str());
897 let (line, time) = (|k: &usize| !held(t, *k, &block), |k: usize| held(t, k, &|n| n.tag == "time"));
898 let mut shown = t.nodes[id].kids.iter().filter_map(Kid::node).filter(|&k| tlen[k] > 0).peekable();
899 let first = shown.next_if(|&k| block(&t.nodes[k])).map(|k| vec![k]);
900 let first = first.unwrap_or_else(|| shown.take_while(|&k| !block(&t.nodes[k]) && line(&k)).collect());
901 let head = held(t, id, &|n| matches!(n.tag.as_bytes(), [b'h', b'1'..=b'6']));
902 !head && first.iter().all(line) && first.into_iter().any(|k| t.nodes[k].tag == "time" || time(k))
903}
904
905fn shape(n: &Node) -> (&str, &str) {
907 (n.tag.as_str(), n.attr("class").and_then(|c| c.split_whitespace().next()).unwrap_or(""))
908}
909
910fn part(n: &Node, of: &[&str]) -> bool {
913 of.contains(&n.tag.as_str()) || n.attr("role").is_some_and(|r| of.contains(&r.to_lowercase().as_str()))
914}
915
916fn held(t: &Tree, id: usize, f: &impl Fn(&Node) -> bool) -> bool {
918 t.walk(id, &LISTS.drop_always).skip(1).any(|v| matches!(v, Visit::Node(n) if f(n)))
919}
920
921fn sup_digits(n: &Node) -> Option<String> {
923 let t = n.kids.iter().map(|k| if let Kid::Text(s) = k { Some(s.as_str()) } else { None });
924 let t: String = t.collect::<Option<_>>()?;
925 const SUP: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
926 let sup = |c: char| SUP[c as usize - '0' as usize];
927 (!t.is_empty() && t.chars().all(|c| c.is_ascii_digit())).then(|| t.chars().map(sup).collect())
928}
929
930const PY_NEWLINE: [char; 10] = ['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\u{85}', '\u{2028}', '\u{2029}'];
932
933fn skip_link(u: &str) -> bool {
934 u.match_indices('/').any(|(i, _)| {
935 let r = &u[i + 1..];
936 LISTS.skip_link.iter().any(|w| {
937 r.len() >= w.len()
938 && r.as_bytes()[..w.len()].eq_ignore_ascii_case(w.as_bytes())
939 && r[w.len()..].chars().next().is_none_or(|c| !is_word(c))
940 })
941 })
942}
943
944pub fn host_of(url: &str) -> String {
946 let host = url::Url::parse(url).ok();
947 host.and_then(|u| u.host_str().map(|h| h.trim_matches(['[', ']']).to_lowercase())).unwrap_or_default()
948}
949
950pub fn facts(lines: &[Line], priced: bool) -> HashSet<String> {
955 let mut s = HashSet::new();
956 for ln in lines {
957 let cs: Vec<char> = LREF.replace_all(ln.text(), " ").chars().collect();
958 let digit = |k: usize| cs.get(k).is_some_and(|c| is_digit(*c));
959 let mut from = 0;
960 while let Some(st) = (from..cs.len()).find(|&k| digit(k)) {
961 let joins =
963 |k: usize| k > st && matches!(cs[k], '.' | ',' | ':' | '/' | '-') && digit(k - 1) && digit(k + 1);
964 let end = (st..cs.len()).find(|&k| !digit(k) && !joins(k)).unwrap_or(cs.len());
965 let (before, after): (String, String) =
966 (cs[st.saturating_sub(4)..st].iter().collect(), cs[end..].iter().take(4).collect());
967 let mark = |c: &&str| before.trim_end().ends_with(c) || after.trim_start().starts_with(c);
968 let digits = cs[st..end].iter().filter(|c| is_digit(**c)).count();
969 if digits >= 2 && (!priced || LISTS.currency.iter().any(mark)) {
970 s.insert(cs[st..end].iter().collect());
971 }
972 from = end.max(st + 1);
973 }
974 }
975 s
976}
977
978pub fn card(d: Doc) -> Doc {
981 let clean = tok(&d.title) + d.info.values().map(|v| tok(v)).sum::<usize>();
982 Doc { mode: "og".into(), sections: Vec::new(), tokens: Tokens { clean }, ..d }
983}
984
985pub fn esc(v: &str) -> String {
987 v.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">")
988}
989
990pub fn markdown(raw: &[u8], url: &str, fin: &str) -> Doc {
995 use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
996 let text = String::from_utf8_lossy(raw);
997 let front = text.strip_prefix("---").and_then(|r| r.split_once("\n---")).map_or("", |(f, _)| f);
998 let og =
999 front.lines().filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim(), v.trim().trim_matches(['"', '\''])));
1000 let og = og.filter(|(k, _)| matches!(*k, "title" | "description" | "image"));
1001 let h1 = text.lines().find_map(|l| l.strip_prefix("# ")).unwrap_or_default();
1003 let og: String = og.map(|(k, v)| format!("<meta property=\"og:{k}\" content=\"{}\">", esc(v))).collect();
1004 let mut html = format!("<title>{}</title>{og}", esc(h1));
1005 let opts = Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_TABLES;
1006 let mut ev: Vec<Event> = Parser::new_ext(&text, opts).collect();
1007 let ld = |w: &[Event]| matches!(w, [Event::Start(Tag::CodeBlock(_)), Event::Text(t), Event::End(TagEnd::CodeBlock)] if t.trim_start().starts_with("{\"@context\""));
1009 while let Some(i) = ev.windows(3).position(ld) {
1010 let Event::Text(t) = &ev[i + 1] else { break };
1011 let script = format!("<script type=\"application/ld+json\">{t}</script>");
1012 ev.splice(i..i + 3, [Event::Html(script.into())]);
1013 }
1014 pulldown_cmark::html::push_html(&mut html, ev.into_iter());
1015 Doc { mode: "md".into(), ..build_doc(&crate::html::parse(&html), url, fin, false) }
1016}
1017
1018fn pick<'a>(v: &'a Value, k: &str) -> Option<&'a Value> {
1020 match v.get(k).filter(|x| truthy(x))? {
1021 Value::Array(v) => v.first(),
1022 x => Some(x),
1023 }
1024}
1025
1026fn truthy(v: &Value) -> bool {
1028 match v {
1029 Value::Null => false,
1030 Value::Bool(b) => *b,
1031 Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
1032 Value::String(s) => !s.is_empty(),
1033 Value::Array(v) => !v.is_empty(),
1034 Value::Object(v) => !v.is_empty(),
1035 }
1036}
1037
1038fn py_str(v: &Value) -> String {
1041 match v {
1042 Value::Null => String::new(),
1043 Value::Bool(b) => if *b { "True" } else { "False" }.into(),
1044 Value::Number(n) => n.to_string(),
1045 Value::String(s) => s.clone(),
1046 Value::Array(v) => v.first().map(py_str).unwrap_or_default(),
1047 Value::Object(_) => v.get("name").map(py_str).unwrap_or_default(),
1048 }
1049}
1050
1051fn prose_chars(j: &Value) -> usize {
1054 match j {
1055 Value::String(s) if s.starts_with(['{', '[']) => serde_json::from_str(s).map_or(0, |inner| prose_chars(&inner)),
1056 Value::String(s) if py_strip(s).contains(' ') => s.chars().count(),
1057 Value::Array(v) => v.iter().map(prose_chars).sum(),
1058 Value::Object(v) => v.values().map(prose_chars).sum(),
1059 _ => 0,
1060 }
1061}
1062
1063fn inert_chars(t: &Tree, tlen: &[usize]) -> usize {
1066 let templates = (0..t.nodes.len()).filter(|&i| t.nodes[i].tag == "template").map(|i| tlen[i]);
1067 let json = t.json.iter().filter_map(|(_, j, _)| serde_json::from_str::<Value>(py_strip(j)).ok());
1068 templates.sum::<usize>() + json.map(|j| prose_chars(&j)).sum::<usize>()
1069}
1070
1071fn walk_ld<'a>(j: &'a Value, depth: usize, out: &mut Vec<&'a Value>) {
1072 if depth > 6 {
1073 return;
1074 }
1075 match j {
1076 Value::Object(v) => {
1077 out.push(j);
1078 v.values().for_each(|x| walk_ld(x, depth + 1, out));
1079 }
1080 Value::Array(v) => v.iter().for_each(|x| walk_ld(x, depth + 1, out)),
1081 _ => {}
1082 }
1083}
1084
1085fn page_info(t: &Tree, base: &str) -> (Info, Vec<Media>, usize) {
1088 let (mut info, mut media) = (meta_info(t), Vec::new());
1089 for key in ["og:image", "twitter:image", "og:video"] {
1090 let get = |k: &str| t.meta(&format!("{key}{k}")).unwrap_or_default();
1091 let src = ["", ":url", ":secure_url"].iter().map(|k| get(k)).find(|s| !s.is_empty()).unwrap_or_default();
1092 let (alt, w, h, ty) = (get(":alt").into(), px(get(":width")), px(get(":height")), get(":type").into());
1093 add(&mut media, base, Media { src: src.into(), alt, video: key == "og:video", w, h, ty, ..Media::default() });
1094 }
1095 let og = media.len();
1096 for (_, blob, _) in t.json.iter().filter(|j| j.2).take(20) {
1097 let Ok(json) = serde_json::from_str::<Value>(py_strip(blob)) else { continue };
1098 let mut objs = Vec::new();
1099 walk_ld(&json, 0, &mut objs);
1100 for obj in objs {
1101 ld_info(obj, &mut info);
1102 ld_media(obj, base, &mut media);
1103 }
1104 }
1105 let rel =
1106 |n: &&Node| n.attr("rel").is_some_and(|r| r.split_whitespace().any(|w| w.eq_ignore_ascii_case("image_src")));
1107 for n in t.nodes.iter().filter(|n| n.tag == "link").filter(rel) {
1108 add(&mut media, base, Media { src: n.attr("href").unwrap_or_default().into(), ..Media::default() });
1109 }
1110 info.extend(t.meta("og:site_name").map(|s| ("site".to_string(), s.to_string())));
1111 let info = info.into_iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| (k, collapse(&unescape(&v))));
1112 (info.collect(), media, og)
1113}
1114
1115fn px(v: &str) -> u32 {
1117 v.trim().trim_end_matches("px").parse().unwrap_or(0)
1118}
1119
1120fn ld_media<'a>(obj: &'a Value, base: &str, out: &mut Vec<Media>) {
1124 let text = |k: &str| obj.get(k).map(py_str).unwrap_or_default();
1125 let list = |v: &'a Value| if let Value::Array(v) = v { v.as_slice() } else { std::slice::from_ref(v) };
1126 let url_of = |u: &Value| if let Value::String(s) = u.get("url").unwrap_or(u) { s.clone() } else { String::new() };
1127 for (k, demoted) in [("logo", true), ("image", false), ("thumbnailUrl", false)] {
1128 for u in obj.get(k).into_iter().flat_map(list) {
1129 add(out, base, Media { src: url_of(u), demoted, ..Media::default() });
1130 }
1131 }
1132 if text("@type") == "ImageObject" {
1133 let src = if text("contentUrl").is_empty() { text("url") } else { text("contentUrl") };
1134 let (alt, w, h) = (text("caption"), px(&text("width")), px(&text("height")));
1135 add(out, base, Media { src, alt, w, h, ..Media::default() });
1136 }
1137}
1138
1139fn body_media(t: &Tree, id: usize, base: &str) -> Option<Media> {
1144 let (n, page) = (&t.nodes[id], url::Url::parse(base).ok()?);
1145 if decorative(n) {
1146 return None;
1147 }
1148 let attr = |k: &str| n.attr(k).unwrap_or_default();
1149 let (w, h, alt) = (px(attr("width")), px(attr("height")), collapse(attr("alt")));
1150 if n.tag == "video" {
1151 return Some(Media { src: n.attr("poster")?.into(), video: true, w, h, ..Media::default() });
1152 }
1153 let pic = n.parent.filter(|&p| t.nodes[p].tag == "picture").map(|p| &t.nodes[p].kids[..]).unwrap_or_default();
1154 let source = |k: &Kid| k.node().and_then(|c| t.nodes[c].attr("srcset"));
1155 let set: Vec<&str> = pic.iter().filter_map(source).chain(n.attr("srcset")).chain(n.attr("data-srcset")).collect();
1156 let named = |k: &str| k.strip_prefix("data-").is_some_and(|k| LISTS.lazy_src.iter().any(|w| k.contains(w)));
1157 let data = n.attrs.iter().find(|(k, v)| named(k) && v.starts_with(['/', 'h']) && !v.contains(' '));
1158 let src = largest(&set.join(", ")).map(String::from).or(data.map(|d| d.1.clone()));
1159 let url = page.join(py_strip(&src.or(n.attr("src").map(String::from))?)).ok()?;
1160 let (away, linked) = links(t, id, &page);
1161 let demoted = has_word(attr("class"), &LISTS.not_content) || away || ad_slot(t, id);
1162 Some(Media { src: url.into(), alt, w, h, demoted, linked, ..Media::default() })
1163}
1164
1165fn links(t: &Tree, id: usize, page: &url::Url) -> (bool, bool) {
1171 let above: Vec<usize> = up(t, id).skip(1).collect();
1172 let empty = |c: &usize| t.nodes[*c].tag == "a" && t.texts(*c, &[]).all(|s| s.trim().is_empty());
1173 let kids = above.iter().take(2).flat_map(|&p| &t.nodes[p].kids);
1174 let overlay = kids.filter_map(Kid::node).filter(empty);
1175 let below = |u: &url::Url| page.path().len() > 1 && u.path().starts_with(page.path());
1176 let href =
1177 |a: usize| page.join(t.nodes[a].attr("href")?).ok().filter(|u| u.scheme().starts_with("http") && !below(u));
1178 let own = |u: &url::Url| has_word(u.path(), &LISTS.image_ext) || has_word(u.path(), &LISTS.picture_page);
1179 let around: Vec<url::Url> = above.iter().filter(|&&p| t.nodes[p].tag == "a").filter_map(|&a| href(a)).collect();
1180 let away = around.iter().chain(&overlay.filter_map(href).collect::<Vec<_>>()).any(|u| !own(u));
1181 (away, around.iter().any(own))
1182}
1183
1184fn ad_slot(t: &Tree, id: usize) -> bool {
1189 let max: usize = limit("ad_slot_words");
1190 let name = |n: &Node| format!("{} {} {}", n.tag, n.attr("class").unwrap_or(""), n.attr("id").unwrap_or(""));
1191 let small = |p: usize| {
1192 let text = || t.texts(p, &LISTS.drop_always).flat_map(str::split_whitespace);
1193 let few = text().filter(|w| w.chars().any(char::is_alphanumeric)).nth(max.saturating_sub(1)).is_none();
1194 few && facts(&[Line::T(text().collect::<Vec<_>>().join(" "))], false).is_empty()
1195 };
1196 up(t, id).any(|p| has_word(&name(&t.nodes[p]), &LISTS.ad_slot) && small(p))
1197}
1198
1199fn largest(set: &str) -> Option<&str> {
1201 let size = |d: Option<&str>| d.and_then(|d| d.get(..d.len() - 1)?.parse::<f64>().ok()).unwrap_or(1.0);
1202 let all =
1203 set.split(", ").filter_map(|c| c.split_whitespace().next().map(|u| (u, size(c.split_whitespace().nth(1)))));
1204 all.max_by(|a, b| a.1.total_cmp(&b.1)).map(|c| c.0)
1205}
1206
1207fn has_word(text: &str, list: &[&str]) -> bool {
1210 words(text).iter().any(|w| list.contains(&w.strip_suffix('s').unwrap_or(w)))
1211}
1212
1213fn words(text: &str) -> Vec<String> {
1215 text.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(String::from).collect()
1216}
1217
1218static SIZE: LazyLock<regex::Regex> = LazyLock::new(|| {
1220 regex::Regex::new(r"\d{2,4}px-|(?:[-_]|\b)(\d{2,4})x(\d{2,4})|@[1-4]x|=s\d{2,4}|\b[wh]_\d{2,4}\b")
1221 .expect("a pattern")
1222});
1223
1224static NAME_END: LazyLock<regex::Regex> = LazyLock::new(|| {
1227 regex::Regex::new(&format!(r"\.(?:{})(?:[^a-z0-9]|$)|=", LISTS.image_ext.join("|"))).expect("a pattern")
1228});
1229
1230fn key_of(u: &url::Url) -> (String, u32) {
1237 let path = u.path().to_lowercase().replace("%2f", "/");
1238 let (dir, file) = path.rsplit_once('/').unwrap_or_default();
1239 let name = SIZE.replace_all(NAME_END.find(file).map_or(file, |m| &file[..m.start()]), "");
1240 let word = !name.contains(|c: char| c.is_ascii_digit() || !c.is_alphanumeric());
1241 let query: Vec<_> = u.query_pairs().map(|(_, v)| v).filter(|v| v.contains('/') && v.contains('.')).collect();
1242 let dir = if name.len() < 8 || word { SIZE.replace_all(dir, "") } else { "".into() };
1243 let key = format!("{dir}{name}?{}", query.join("&"));
1244 let words = SIZE.find_iter(&path).flat_map(|m| m.as_str().split(|c: char| !c.is_ascii_digit()).map(str::parse));
1245 let width = u.query_pairs().filter(|(k, _)| k == "w" || k == "width").map(|(_, v)| v.parse());
1246 (key, words.chain(width).filter_map(Result::ok).max().unwrap_or(0))
1247}
1248
1249fn add(out: &mut Vec<Media>, base: &str, m: Media) {
1257 let m = Media { alt: unjson(&m.alt), ..m };
1258 let url = url::Url::parse(base).and_then(|b| b.join(py_strip(&m.src))).ok().filter(|_| !m.src.trim().is_empty());
1259 let Some(mut url) = url.filter(|u| matches!(u.scheme(), "http" | "https" | "file")) else { return };
1260 let ext = url.path().rsplit_once('.').map(|e| e.1.to_ascii_lowercase()).filter(|e| (2..=4).contains(&e.len()));
1261 let ty = m.ty.rsplit('/').next().map(str::to_string).filter(|t| !t.is_empty()).or(ext).unwrap_or_default();
1262 let file = url.path_segments().and_then(|mut s| s.next_back()).unwrap_or_default();
1263 let filler = has_word(file, &["placeholder"]) || ty == "gif" && has_word(file, &LISTS.filler);
1264 let (host, last) = (url.host_str().and_then(|h| h.split('.').next()), file.to_lowercase().replace("%2f", "/"));
1266 let own = has_word(last.rsplit('/').next().unwrap_or_default(), &LISTS.share_card);
1267 let card = own || has_word(host.unwrap_or_default(), &LISTS.share_host);
1268 let side = |c: ®ex::Captures, i| c.get(i).and_then(|n| n.as_str().parse().ok());
1269 let named = SIZE.captures_iter(&file.to_lowercase()).find_map(|c| side(&c, 1).zip(side(&c, 2)));
1270 let (w, h) = if m.w == 0 && m.h == 0 { named.unwrap_or_default() } else { (m.w, m.h) };
1272 let (aspect, icon): (u32, u32) = (limit("strip_aspect"), limit("icon_px"));
1274 let strip = w.min(h) > 0 && w.max(h) >= aspect * w.min(h);
1275 if filler || strip || ty.starts_with("svg") || (1..icon).contains(&w) || (1..icon).contains(&h) {
1276 return;
1277 }
1278 let tracking = |kv: &&str| LISTS.tracking.iter().any(|t| kv.to_lowercase().starts_with(t));
1279 let kept: Vec<&str> = url.query().into_iter().flat_map(|q| q.split('&')).filter(|kv| !tracking(kv)).collect();
1280 url.set_query(Some(kept.join("&")).filter(|q| !q.is_empty()).as_deref());
1281 let (key, by_url) = key_of(&url);
1282 let m = Media { key: (key, w.max(h).max(by_url)), src: url.into(), ty, demoted: m.demoted || card, ..m };
1283 let Some(x) = out.iter_mut().find(|x| x.key.0 == m.key.0) else { return out.push(m) };
1284 let alt = if x.alt.is_empty() { m.alt.clone() } else { std::mem::take(&mut x.alt) };
1285 if m.key.1 > x.key.1 {
1286 *x = Media { demoted: x.demoted, ..m };
1287 }
1288 x.alt = alt;
1289}
1290
1291fn unjson(s: &str) -> String {
1294 let (mut out, mut rest) = (Vec::new(), s);
1295 while let Some(c) = rest.chars().next() {
1296 let hex = rest.strip_prefix("\\u").and_then(|r| r.get(..4)).filter(|h| !h.starts_with('+'));
1297 let (units, len) = match hex.map(|h| u16::from_str_radix(h, 16)) {
1298 Some(Ok(u)) => (vec![u], 6),
1299 _ if ["\\n", "\\t", "\\r"].iter().any(|e| rest.starts_with(e)) => (vec![32], 2),
1300 _ => (c.encode_utf16(&mut [0; 2]).to_vec(), c.len_utf8()),
1301 };
1302 out.extend(units);
1303 rest = &rest[len..];
1304 }
1305 collapse(&String::from_utf16_lossy(&out))
1306}
1307
1308fn rank(cards: (Vec<Media>, usize), t: &Tree, body: &[usize], base: &str, info: &Info) -> Vec<Media> {
1316 let (mut out, head) = cards;
1317 body.iter().filter_map(|&id| body_media(t, id, base)).for_each(|m| add(&mut out, base, m));
1318 out[head..].sort_by_key(|m| std::cmp::Reverse((m.alt.chars().count(), u64::from(m.w) * u64::from(m.h))));
1319 let named = |a: &str, keys: &[&str]| info.iter().any(|(k, v)| keys.contains(&k.as_str()) && v.to_lowercase() == a);
1320 let site = words(info.get("site").map_or("", String::as_str));
1322 let has_site = |a: &str| words(a).windows(site.len().max(1)).any(|w| w == site) && words(a).len() <= site.len() + 2;
1323 let avatar_px: u32 = limit("avatar_px");
1325 for m in &mut out {
1326 let (alt, (small, big)) = (m.alt.to_lowercase(), (m.w.min(m.h), m.w.max(m.h)));
1327 let words = alt.split_whitespace().count();
1328 let avatar = small > 0 && big <= avatar_px && 4 * big <= 5 * small && words < 4 && !m.linked;
1329 let handle = alt.starts_with('@') && !alt.contains(' ');
1330 let few = words <= 3 && (has_word(&alt, &LISTS.not_content) || has_word(&alt, &LISTS.not_content_alt));
1332 let named_by = few || has_word(&m.src, &LISTS.not_content) || has_site(&alt);
1333 m.demoted |= avatar || handle || named(&alt, &["author"]) || named_by;
1334 if named(&alt, &["title"]) || alt == collapse(&t.title).to_lowercase() {
1335 m.alt.clear();
1336 }
1337 }
1338 out.sort_by_key(|m| m.demoted);
1339 out
1340}
1341
1342fn meta_info(t: &Tree) -> Info {
1351 let mut info = IndexMap::new();
1352 let og = t.meta("og:title");
1353 let named = og.unwrap_or(&t.title);
1354 let site = og.is_none() && matches!(title_head(named), h if h.len() < named.len() && words_of(h).len() == 1);
1355 let text = |i| collapse(&t.texts(i, &["button", "input", "select"]).collect::<String>());
1356 let apart = |h: &str| site && words_of(named).iter().all(|w| !words_of(h).contains(w));
1357 let mine = |h: &String| !h.is_empty() && (apart(h) || qualified(title_head(named), h));
1358 let title = t.nodes.iter().position(|n| n.tag == "h1").map(text).filter(mine);
1359 info.insert("title".into(), title.unwrap_or_else(|| named.to_string()));
1360 for (key, names) in &LISTS.info {
1361 let named = |v: &&str| *key != "author" || !v.starts_with("http");
1363 let Some(v) = names.iter().find_map(|k| t.meta(k)).filter(named) else { continue };
1364 let cut = if *key == "description" { 300 } else { usize::MAX };
1365 info.insert(key.to_string(), v.chars().take(cut).collect());
1366 }
1367 if let Some(price) = t.meta("product:price:amount").or(t.meta("og:price:amount")) {
1368 let cur = t.meta("product:price:currency").or(t.meta("og:price:currency")).unwrap_or("");
1369 info.insert("price".into(), format!("{price} {cur}"));
1370 }
1371 info
1372}
1373
1374fn qualified(head: &str, name: &str) -> bool {
1376 let rest = head.strip_prefix(name).unwrap_or_default().trim_start();
1377 rest.strip_prefix('(').and_then(|q| q.strip_suffix(')')).is_some_and(|q| !q.contains(['(', ')']))
1378}
1379
1380fn ld_info(obj: &Value, info: &mut Info) {
1382 if !info.contains_key("author")
1383 && let Some(author @ (Value::Object(_) | Value::String(_))) = pick(obj, "author")
1384 && let Some(name) = author.get("name").or(Some(author).filter(|a| a.is_string()))
1385 && truthy(name)
1386 && !py_str(name).starts_with("http")
1387 {
1388 info.insert("author".into(), py_str(name));
1389 }
1390 for (key, ld) in [("published", "datePublished"), ("modified", "dateModified")] {
1391 if !info.contains_key(key)
1392 && let Some(date) = pick(obj, ld)
1393 {
1394 info.insert(key.into(), py_str(date));
1395 }
1396 }
1397 if !info.contains_key("price")
1398 && let Some(offer @ Value::Object(_)) = pick(obj, "offers")
1399 && let Some(price) = pick(offer, "price").or(pick(offer, "lowPrice"))
1400 {
1401 let cur = offer.get("priceCurrency").map(py_str).unwrap_or_default();
1402 info.insert("price".into(), py_strip(&format!("{} {cur}", py_str(price))).to_string());
1403 }
1404 if !info.contains_key("rating")
1405 && let Some(rating @ Value::Object(_)) = obj.get("aggregateRating")
1406 && let Some(value) = pick(rating, "ratingValue")
1407 {
1408 let count = pick(rating, "reviewCount").or(pick(rating, "ratingCount")).map_or("?".into(), py_str);
1409 info.insert("rating".into(), format!("{} ({count} reviews)", py_str(value)));
1410 }
1411}
1412
1413fn render<'a>(t: &'a Tree, tlen: &'a [usize], base: &str, mode: Mode, js: bool) -> Render<'a> {
1414 let mut r = Render {
1415 tree: t,
1416 tlen,
1417 base_url: url::Url::parse(base.split('#').next().unwrap_or(base)).ok(),
1418 mode,
1419 js,
1420 lines: Vec::new(),
1421 buf: String::new(),
1422 marks: Vec::new(),
1423 links: IndexMap::new(),
1424 inline: 0,
1425 media: Vec::new(),
1426 thread: HashMap::new(),
1427 by: None,
1428 worded: HashSet::new(),
1429 owed: Vec::new(),
1430 };
1431 r.thread = r.comments();
1432 r.worded = r.worded_links();
1433 r.kids(0, false);
1434 r.flush();
1435 r.pay();
1436 r
1437}
1438
1439pub fn pretty(v: &Value) -> String {
1441 let mut out = serde_json::Serializer::with_formatter(Vec::new(), PrettyFormatter::with_indent(b" "));
1442 v.serialize(&mut out).map_or_else(|_| v.to_string(), |()| String::from_utf8_lossy(&out.into_inner()).into())
1443}
1444
1445fn one_space(text: &str) -> Vec<u8> {
1447 let sorted = |mut v: Value| {
1448 v.sort_all_objects();
1449 pretty(&v).into_bytes()
1450 };
1451 serde_json::from_str::<Value>(text).map_or_else(|_| text.as_bytes().to_vec(), sorted)
1452}
1453
1454fn islands(tree: &Tree, r: &mut Render, url: &str) -> Vec<Section> {
1459 let sec = |label: String, bytes: usize, lines| Section {
1460 level: 0,
1461 title: format!("island {label} {} KB", bytes.div_ceil(1024)),
1462 lines,
1463 };
1464 let mut out = Vec::new();
1465 r.lines.clear();
1466 let (part, json): (usize, usize) = (limit("island_template_1_in"), limit("island_json_bytes"));
1468 let big = |i: &usize| tree.nodes[*i].tag == "template" && r.tlen[*i] > 0 && r.tlen[*i] * part >= r.tlen[0];
1469 for f in (0..tree.nodes.len()).filter(big).map(|i| i + 1).collect::<Vec<_>>() {
1470 r.kids(f, false);
1471 r.flush();
1472 r.pay();
1473 let lines = std::mem::take(&mut r.lines).into_iter().map(|l| match l {
1474 Line::H(lv, t) => format!("{} {t}", "#".repeat(lv)),
1475 Line::T(t) => t,
1476 });
1477 out.push(sec(tree.nodes[f - 1].label(), r.tlen[f - 1], lines.collect()));
1478 }
1479 for (label, text, _) in tree.json.iter().filter(|(_, t, _)| t.len() >= json) {
1480 let doc = crate::text::build(&one_space(text), "json", url, url);
1481 out.push(sec(label.clone(), text.len(), doc.sections.into_iter().flat_map(|s| s.lines).collect()));
1482 }
1483 out
1484}
1485
1486fn commonest<T: Ord + Copy>(mut v: Vec<T>) -> Option<T> {
1488 v.sort_unstable();
1489 v.chunk_by(|a, b| a == b).max_by_key(|g| g.len()).map(|g| g[0])
1490}
1491
1492fn count_words(key: &str) -> Vec<&'static str> {
1494 LISTS.post_counts.iter().filter(|r| r.0 == key).flat_map(|r| r.1.iter().copied()).collect()
1495}
1496
1497pub fn post_keys() -> impl Iterator<Item = &'static str> {
1499 LISTS.post_counts.iter().chain(&LISTS.post_facts).map(|r| r.0)
1500}
1501
1502fn bare(k: &str) -> String {
1504 let k = k.to_lowercase();
1505 match k.strip_prefix("data-") {
1506 Some(rest) => rest.to_string(),
1507 None => k,
1508 }
1509}
1510
1511fn count((k, v): &(String, String)) -> Option<(String, String)> {
1515 let k = bare(k);
1516 let words: Vec<&str> = k.split(['-', '_', ':']).collect();
1517 let has = |list: &[&str]| words.iter().any(|w| list.contains(w));
1518 if !has(&LISTS.post_marker) || has(&LISTS.post_skip) {
1519 return None;
1520 }
1521 let key = LISTS.post_counts.iter().find(|r| has(&r.1))?.0;
1522 Some((key.to_string(), whole(v)?.to_string()))
1523}
1524
1525fn whole(v: &str) -> Option<u64> {
1527 let v = v.trim().replace(',', "").to_lowercase();
1528 let suffix = [("k", 1e3), ("m", 1e6)].iter().find_map(|(s, m)| Some((v.strip_suffix(s)?, *m)));
1529 let (num, times) = suffix.unwrap_or((&v, 1.0));
1530 let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
1531 let fine = match num.split_once('.') {
1532 Some((a, b)) => times > 1.0 && digits(a) && digits(b),
1533 None => digits(num),
1534 };
1535 if !fine {
1536 return None;
1537 }
1538 Some((num.parse::<f64>().ok()? * times).round() as u64)
1539}
1540
1541fn fact_value(v: &str) -> Option<String> {
1544 let v = v.trim();
1545 let d = v.as_bytes();
1546 let date = d.len() >= 10
1547 && d[4] == b'-'
1548 && d[7] == b'-'
1549 && [0, 1, 2, 3, 5, 6, 8, 9].iter().all(|&i| d[i].is_ascii_digit());
1550 if date {
1551 return Some(v[..10].to_string());
1552 }
1553 let number = v.bytes().any(|b| b.is_ascii_digit()) && v.bytes().all(|b| b.is_ascii_digit() || b"+-.,".contains(&b));
1554 v.replace(',', "").parse::<f64>().ok().filter(|_| number).map(|_| v.to_string())
1555}
1556
1557fn up(t: &Tree, i: usize) -> impl Iterator<Item = usize> + '_ {
1559 std::iter::successors(Some(i), |&p| t.nodes[p].parent)
1560}
1561
1562pub fn build_doc(tree: &Tree, url: &str, final_url: &str, js: bool) -> Doc {
1565 let (mut info, cards, og) = page_info(tree, final_url);
1566 let mut tlen = vec![0; tree.nodes.len()];
1567 measure(tree, 0, &mut tlen);
1568 let light = render(tree, &tlen, final_url, Mode::Light, js);
1572 let (fl, priced) = (facts(&light.lines, false), facts(&light.lines, true));
1573 let lost = |lines: &[Line]| fl.difference(&facts(lines, false)).count();
1574 let loss_max: f64 = limit("loss_max");
1575 let keeps = |lines: &[Line]| lost(lines) as f64 <= loss_max * fl.len() as f64;
1576 let mut mode = "clean";
1577 let mut used = render(tree, &tlen, final_url, Mode::Clean, js);
1578 let media = rank((cards, og), tree, &std::mem::take(&mut used.media), final_url, &info);
1580 if !keeps(&used.lines) {
1581 (mode, used) = ("hard", render(tree, &tlen, final_url, Mode::Hard, js));
1582 }
1583 let title = info.get("title").cloned().unwrap_or_default();
1584 let chars = |secs: &[Section]| secs.iter().flat_map(|s| s.lines.iter()).map(|l| l.chars().count()).sum();
1585 let mut pruned_chars = None;
1586 if !keeps(&used.lines) {
1587 pruned_chars = Some(chars(§ions_of(&used.lines).0));
1588 (mode, used) = ("light", light);
1589 }
1590 let (sections, top) = sections_of(&used.lines);
1591 let pruned_chars = pruned_chars.unwrap_or_else(|| chars(§ions));
1592 let visible_chars = tlen[0] + inert_chars(tree, &tlen);
1593 let (vs_light_lost, price_pruned) = (lost(&used.lines), priced.difference(&facts(&used.lines, false)).count());
1594 let loss = Loss { vs_light_lost, light_facts: fl.len(), pruned_chars, visible_chars, price_pruned };
1595 let title = if title.is_empty() { crate::lang::short(final_url, 60) } else { title };
1596 let islands = islands(tree, &mut used, final_url);
1597 let post = used.post();
1599 let stated = used.declared().filter(|_| !post.contains_key("comments"));
1600 info.extend(post);
1601 info.extend(stated.map(|n| ("comments".into(), n.to_string())));
1602 let mut doc = Doc {
1603 info,
1604 top,
1605 links: used.links.keys().cloned().collect(),
1606 anchors: used.links.into_values().collect(),
1607 cut: tree.cut,
1608 loss,
1609 islands: islands.len(),
1610 media,
1611 ..Doc::new(url, final_url, title, sections, mode)
1612 };
1613 doc.sections.extend(islands);
1614 doc
1615}
1616
1617pub fn paragraph(t: &str) -> bool {
1619 t.split_whitespace().count() >= limit("paragraph_words")
1620}
1621
1622#[cfg(test)]
1623mod tests {
1624 use super::*;
1625 use crate::html::parse;
1626
1627 #[test]
1632 fn the_post_counts_come_from_its_own_element() {
1633 let info = |h: &str| {
1634 let i = build_doc(&parse(h), "https://a.example/", "https://a.example/", false).info;
1635 post_keys().filter_map(|k| Some(format!("{k} {}", i.get(k)?))).collect::<Vec<_>>().join(" · ")
1636 };
1637 let post_el = r#"<x-post id=t3_1 comment-count="296" score="26" upvote-ratio="0.9265"
1638 created-timestamp="2025-12-11T09:49:02.123000+0000"><h1>What finally pushed you</h1></x-post>"#;
1639 let comments = r#"<template><x-comment score="40" created-timestamp="2025-12-12T01:00:00"
1640 comment-count="3"><p>A reply</p></x-comment></template>"#;
1641 let reddit = format!("<body>{post_el}{comments}</body>");
1642 assert_eq!(info(&reddit), "comments 296 · score 26 · posted 2025-12-11");
1643 let text = "<p>The post itself, long enough to be the page's main text for the reader here.</p>";
1645 let nav = r#"<nav><a href="/hot" data-comment-count="812">Hot</a></nav>"#;
1646 let cards = r#"<ul><li data-comment-count="57"><a href="/r">Related</a></li></ul>"#;
1647 let post = format!(r#"<article data-comment-count="4" data-published-date="2024-05-01">{text}</article>"#);
1648 assert_eq!(info(&format!("<body>{nav}{cards}{post}</body>")), "comments 4 · posted 2024-05-01");
1649 assert_eq!(info(&format!("<body>{nav}{cards}{text}</body>")), "");
1650 let when = |a: &str| info(&format!(r#"<div data-comment-count="1" {a}="2024-03-01T10:00">x</div>"#));
1652 assert_eq!(when("data-posted-time"), "comments 1 · posted 2024-03-01");
1653 assert_eq!(when("created_date"), "comments 1 · posted 2024-03-01");
1654 assert_eq!(when("datetime"), "comments 1 · posted 2024-03-01");
1655 for other in ["data-created-by", "data-update-time", "data-date"] {
1656 assert_eq!(when(other), "comments 1", "{other}");
1657 }
1658 let linkedin =
1659 r#"<div class="feed"><article data-num-comments="3" data-num-likes="1,204"><p>Post</p></article>"#;
1660 assert_eq!(info(linkedin), "comments 3 · likes 1204");
1661 assert_eq!(
1662 info(r#"<div data-answer-count="2.1k" data-datetime="2024-03-01">Q</div>"#),
1663 "answers 2100 · posted 2024-03-01"
1664 );
1665 let stack = r#"<div data-score="2"><span data-remaining-comments-count="6"></span></div>"#;
1667 assert_eq!(info(stack), "");
1668 assert_eq!(info(r#"<li data-score="92">Staff</li><li data-score="96">Comfort</li>"#), "");
1669 assert_eq!(info(r#"<a data-comment-id="99999" data-comment-count="many" data-commentcount="5">x</a>"#), "");
1670 assert_eq!(info(r#"<p data-like-count="2.5" data-unread-count="4" data-total-comments="-1">x</p>"#), "");
1671 let later = r#"<p data-comment-count="40">40 comments</p><div data-score="7" data-comment-count="1"></div>"#;
1673 assert_eq!(info(later), "comments 40");
1674 }
1675
1676 #[test]
1679 fn a_site_name_title_yields_to_the_h1() {
1680 let title = |head: &str| {
1681 let h = format!("<head>{head}</head><h1>Visiting <b>Portugal</b> for a week</h1><h1>Other</h1>");
1682 page_info(&parse(&h), "https://a.example/").0.get("title").cloned().unwrap_or_default()
1683 };
1684 assert_eq!(title("<title>Reddit - The heart of the internet</title>"), "Visiting Portugal for a week");
1685 assert_eq!(title("<title>Reddit</title>"), "Reddit");
1686 assert_eq!(title("<title>Rust traits explained | Blog</title>"), "Rust traits explained | Blog");
1687 let held = "<title>Lisboa - Visiting Portugal for a week</title>";
1688 assert_eq!(title(held), "Lisboa - Visiting Portugal for a week");
1689 assert_eq!(title("<title>Site Maintenance</title>"), "Site Maintenance");
1690 let og = "<title>Reddit</title><meta property='og:title' content='From og'>";
1691 assert_eq!(title(og), "From og");
1692 let docs = |h1: &str| {
1694 let h = format!("<head><title>widget - Lang</title></head><h1>{h1}</h1>");
1695 page_info(&parse(&h), "https://a.example/").0.get("title").cloned().unwrap_or_default()
1696 };
1697 assert_eq!(docs("Crate widget <button>Copy item path</button>"), "widget - Lang");
1698 assert_eq!(docs("Module <span>Widget</span>"), "widget - Lang");
1699 assert_eq!(docs("<button>Copy item path</button>"), "widget - Lang");
1700 assert_eq!(docs("Gadget parts for sale"), "Gadget parts for sale");
1701 }
1702
1703 #[test]
1707 fn a_page_reads_one_title_whatever_the_render_timing() {
1708 let title = |head: &str, h1: &str| {
1709 let h = format!("<head>{head}</head><h1>{h1}</h1><p>Posts and replies</p>");
1710 page_info(&parse(&h), "https://a.example/@nasa").0.get("title").cloned().unwrap_or_default()
1711 };
1712 let early = "<title>Clipsite - Make Your Day</title>";
1713 let late = "<title>NASA (@nasa) | Clipsite</title><meta property='og:title' content='NASA (@nasa) | Clipsite'>";
1714 assert_eq!((title(early, "NASA"), title(late, "NASA")), ("NASA".into(), "NASA".into()));
1715 assert_eq!(title("<title>Cleo Abram (@cleoabram) | Clipsite</title>", "Cleo Abram"), "Cleo Abram");
1716 assert_eq!(title("<title>vitiral (u/vitiral) - Forum</title>", "vitiral"), "vitiral");
1717 let stays = ["Rytas - Žalgiris - League", "History of Rome - Wiki", "Dune (2021) (film) - Db"];
1718 for t in stays {
1719 let h1 = t.split(' ').next().unwrap_or_default();
1720 assert_eq!(title(&format!("<title>{t}</title>"), h1), t, "{t}");
1721 }
1722 }
1723
1724 #[test]
1728 fn json_marks_in_a_run_are_cheap() {
1729 let island = "l206 \"core_ux_fix\": {\nl207 \"vid\": \"v1\"\nl208 },\nl209 \"creator_center_connect\": {\nl210 \"vid\": \"v1\"\nl211 },\nl212 \"creator_center_connect_global\": {\nl213 \"vid\": \"v2\"\nl214 },\nl215 \"creator_center_global_comment_management\": {\nl216 \"vid\": \"v1\"\nl217 },\nl218 \"creator_center_global_post_management\": {\nl219 \"vid\": \"v1\"\nl220 },\nl221 \"creator_center_test\": {\nl222 \"vid\": \"v2\"\nl223 },\nl224 \"csp_merge_support\": {\nl225 \"vid\": \"v1\"";
1730 let t = tok(island);
1731 assert!((165..=275).contains(&t), "{t} vs 220 real");
1732 assert_eq!(tok_cut(island, t), island.len());
1733 assert!(tok(&island[..tok_cut(island, 40)]) <= 40);
1734 }
1735
1736 #[test]
1739 fn a_thread_states_its_size() {
1740 let text = "a reply that says one thing in a sentence long enough to be a paragraph here";
1741 let c = |i: usize, kids: &str| {
1742 format!("<li><article><b>user{i}</b> <time>Jan {i}</time><p>{text}</p></article>{kids}</li>")
1743 };
1744 let thread: String = (0..4).map(|i| c(i, &format!("<ol>{}</ol>", c(i + 10, "")))).collect();
1745 let at = |own: &str, between: &str, after: &str| {
1746 let html = format!(
1747 "<html><body><article><h1>A post</h1>{own}<p>{text}</p></article>{between}<div><h2>Discussion</h2>\
1748 <ol>{thread}</ol>{after}</div></body></html>"
1749 );
1750 build_doc(&parse(&html), "https://a.example/p", "https://a.example/p", false).info.get("comments").cloned()
1751 };
1752 let related = "<section><h3>Related</h3><ul><li><a href=/o>Another post</a> <span>450 comments</span></li></ul></section>";
1753 assert_eq!(at("", related, ""), None, "a related post's count");
1754 assert_eq!(at("", "<aside><p><a href=/hot>99 comments</a></p></aside>", ""), None, "a pruned sidebar's");
1755 assert_eq!(
1756 at("", r#"<nav><a href=/prev aria-label="88 comments">Previous</a></nav>"#, ""),
1757 None,
1758 "a nav label"
1759 );
1760 assert_eq!(at("", "", " 77 comments"), None, "after the thread");
1761 assert_eq!(at("<a href=#c>12 comments</a>", related, "").as_deref(), Some("12"), "the post's own");
1762 assert_eq!(at("<p>12 comments</p><p>14 comments</p>", "", ""), None, "a tie claims none");
1763 assert_eq!(at("<p>1,204 Comments</p>", "", "").as_deref(), Some("1204"));
1764 assert_eq!(at("", r#"<div data-comment-count="301"></div>"#, "").as_deref(), Some("301"), "a count attribute");
1765 assert_eq!(at(r#"<x data-comment-id="12345"></x><p>7 comment threads</p>"#, "", ""), None, "an id, a phrase");
1766 }
1767
1768 #[test]
1771 fn cards_beside_a_thread_keep_its_comments() {
1772 let text = "a reply that says one thing in a sentence long enough to be a paragraph here";
1773 let c = |i: usize, kids: &str| {
1774 format!("<li><article><b>user{i}</b> <time>Jan {i}</time><p>{text}</p></article>{kids}</li>")
1775 };
1776 let thread: String = (0..4).map(|i| c(i, &format!("<ol>{}</ol>", c(i + 10, "")))).collect();
1777 let card =
1778 |i: usize| format!("<div class=c><h3><a href=/p{i}>A related post {i}</a></h3><p>{i}2 votes</p></div>");
1779 let html = format!("<main><h1>Post</h1>{}<ol>{thread}</ol></main>", (1..=4).map(card).collect::<String>());
1780 let d = build_doc(&parse(&html), "https://a.example/p", "https://a.example/p", false);
1781 let cards = d.sections.iter().flat_map(|s| &s.lines).filter(|l| l.starts_with(CARD)).count();
1782 assert_eq!((cards, d.sections.iter().filter(|s| s.level >= COMMENT).count()), (4, 8));
1783 }
1784
1785 #[test]
1788 fn spacer_rows_are_comments() {
1789 let para = "this comment says one thing in a sentence long enough to be prose";
1790 let post = |(i, w): (usize, usize)| {
1792 let spacer = format!("<img height=1 width={w}><img height=1 width=14>");
1793 format!(
1794 "<tr><td><table><tr><td>{spacer}</td><td>user{i} 2 hours ago</td><td>{para} {i}</td></tr></table></td></tr>"
1795 )
1796 };
1797 let page = |rows: String| {
1798 let html =
1799 format!("<html><body><table><tr><td><b>Story</b><table>{rows}</table></td></tr></table></body></html>");
1800 build_doc(&parse(&html), "https://a.example/item", "https://a.example/item", false).sections
1801 };
1802 let tree = [0, 40, 80, 40, 0, 40, 0, 0].into_iter().enumerate().map(post).collect::<String>();
1803 let levels: Vec<usize> = page(tree).iter().map(|s| s.level).collect();
1804 assert_eq!(levels, [0, 7, 8, 9, 8, 7, 8, 7, 7], "the story, then a comment a row at 7 + its depth");
1805 let flat = [0; 8].into_iter().enumerate().map(post).collect::<String>();
1806 assert_eq!(page(flat).len(), 1, "flat posts are a feed, no thread");
1807 let short = [0, 40, 80, 40, 0, 40, 0].into_iter().enumerate().map(post).collect::<String>();
1808 assert_eq!(page(short).len(), 1, "7 comments: one block");
1809 let cell = |i: usize| format!("<tr><td>10.{i}</td><td>{para} {i}</td></tr>");
1811 let data = page((1..=8).map(cell).collect());
1812 assert_eq!((data.len(), data[0].lines.len()), (1, 9), "the story line, then a line a row: {:?}", data[0].lines);
1813 let story = |(i, w): (usize, usize)| {
1815 let photo = format!("<img src=p{i}.jpg width={w} height=200>");
1816 format!("<tr><td><table><tr><td width={w}>{photo}</td><td>{para} {i}</td></tr></table></td></tr>")
1817 };
1818 let news = [120, 300, 600, 300, 120, 300, 120, 120].into_iter().enumerate().map(story).collect::<String>();
1819 assert!(page(news).iter().all(|s| s.level < COMMENT), "photos and cell widths are no thread");
1820 let rows = |cell: &dyn Fn(usize, usize) -> String, ws: &[usize]| {
1822 let row = |(i, &w): (usize, &usize)| format!("<tr><td><img height=1 width={w}></td>{}</tr>", cell(i, w));
1823 page(ws.iter().enumerate().map(row).collect()).into_iter().filter(|s| s.level >= COMMENT).count()
1824 };
1825 let stair = [0, 20, 20, 0, 20, 40, 40, 0, 20, 20];
1826 let toc = |i: usize, _| format!("<td><a href=#s{i}>{i} Part {i}</a></td><td>{i}</td>");
1827 let files = |i: usize, _| format!("<td><a href=/f{i}.c>f{i}.c</a></td><td>r{i}</td><td>2004-03-0{i}</td>");
1828 let gov = |i: usize, _| format!("<td><b>News {i}</b><br>{para} {i}</td>");
1829 let letter = |i: usize, _| format!("<td><h3>Story {i}</h3><p>{para} {i}</p></td>");
1830 let found = [
1831 rows(&toc, &stair),
1832 rows(&files, &stair),
1833 rows(&gov, &[10, 1, 1, 10, 1, 1, 10, 1, 1, 10]),
1834 rows(&letter, &stair),
1835 ];
1836 assert_eq!(found, [0; 4], "a contents list, a file tree, a layout, a newsletter");
1837 let t0 = std::time::Instant::now();
1839 let chain = (0..4_000usize).map(|i| (i, if i.is_multiple_of(2) { 0 } else { i })).map(post).collect::<String>();
1840 let deepest = page(chain).iter().map(|s| s.level).max();
1841 assert_eq!(deepest, Some(COMMENT + limit::<usize>("thread_depth")));
1842 assert!(t0.elapsed().as_secs() < 20, "{:?}", t0.elapsed());
1843 }
1844
1845 #[test]
1848 fn a_pruned_thread_counts_nothing() {
1849 let para = "this comment says one thing in a sentence long enough to be prose";
1850 let li = |i: usize, kids: &str| format!("<li><time>{i}h ago</time><p>{para} {i}</p>{kids}</li>");
1851 let tree: String = (0..4).map(|i| li(i, &format!("<ol>{}</ol>", li(10 + i, "")))).collect();
1852 let body: String = (0..40).map(|i| format!("<p>{para} body {i}</p>")).collect();
1853 let html = format!("<html><body><main>{body}</main><aside><ol>{tree}</ol></aside></body></html>");
1854 let doc = build_doc(&parse(&html), "https://a.example/p", "https://a.example/p", false);
1855 assert_eq!(doc.mode, "clean");
1856 assert!(doc.sections.iter().all(|s| s.level < COMMENT), "{:?}", doc.sections.len());
1857 let post = |i: usize, w: &str| format!("<article><time>{w} {i}</time><p>{para} {w} {i}</p></article>");
1858 let (upd, side): (String, String) =
1859 ((0..9).map(|i| post(i, "update")).collect(), (0..2).map(|i| post(i, "side")).collect());
1860 let blog = format!(
1861 "<html><body><article><h1>Live</h1><time>now</time><p>{para}</p>{upd}</article><aside>{side}</aside></body></html>"
1862 );
1863 let doc = build_doc(&parse(&blog), "https://a.example/p", "https://a.example/p", false);
1864 assert!(doc.sections.iter().all(|s| s.level < COMMENT), "the sidebar's posts were its second top");
1865 }
1866
1867 #[test]
1871 fn markdown_is_a_page() {
1872 let md = "# Camera modules?\n\nIntro with [a link](/a) and enough words to keep.\n\n## Wiring\n\n```\n# not a \
1873 heading\n```\n\n\n\n## Code\n\nMore words.\n\n```json\n\
1874 {\"@context\":\"https://schema.org\",\"@type\":\"WebPage\",\"dateModified\":\"2026-10-08\"}\n```\n";
1875 let d = markdown(md.as_bytes(), "https://ex.com/t/1", "https://ex.com/t/1");
1876 let titles: Vec<&str> = d.sections.iter().map(|s| s.title.as_str()).collect();
1877 assert_eq!(
1878 (d.mode.as_str(), d.title.as_str(), titles),
1879 ("md", "Camera modules?", vec!["Camera modules?", "Wiring", "Code"])
1880 );
1881 assert_eq!(
1882 (d.media.len(), d.media[0].src.as_str(), d.media[0].alt.as_str()),
1883 (1, "https://ex.com/b.jpg", "The board")
1884 );
1885 assert_eq!(d.links.first().map(String::as_str), Some("https://ex.com/a"));
1886 let modified = d.info.get("modified").map(String::as_str);
1887 assert_eq!(modified, Some("2026-10-08"), "JSON-LD read as such: {:?}", d.info);
1888 assert!(!d.sections.iter().flat_map(|s| &s.lines).any(|l| l.contains("@context")), "never text");
1889 }
1890
1891 #[test]
1893 fn kind_of_bodies() {
1894 let cases: &[(&str, &[u8], &str)] = &[
1895 ("text/plain", b"%PDF-1.7", "pdf"),
1896 ("application/pdf", b"<html>", "pdf"),
1897 ("text/plain; charset=utf-8", b"local x = 1\n", "text"),
1898 ("text/csv", b"a,b\n1,2", "text"),
1899 ("text/markdown", b"# Title", "md"),
1900 ("text/plain", b"<!DOCTYPE html><title>x</title>", "html"),
1901 ("text/html", b"{\"a\":1}", "html"),
1902 ("application/json", b"not json", "json"),
1903 ("text/plain", b" [1, 2]", "json"),
1904 ("text/plain", b"[section]\nkey=1", "text"),
1905 ("", b"{\"a\": [1]}", "json"),
1906 ("", b"{ broken", "html"),
1907 ("application/rss+xml", b"<rss>", "xml"),
1908 ("", b"<?xml version=\"1.0\"?><urlset/>", "xml"),
1909 ("", b"<?xml version=\"1.0\"?><html xmlns=\"x\">", "html"),
1910 ("application/xhtml+xml", b"<?xml?><html>", "html"),
1911 ("", b"<p>local notes</p>", "html"),
1912 ("application/octet-stream", b"plain words", "html"),
1913 ];
1914 for (ct, body, want) in cases {
1915 assert_eq!(kind_of(ct, body), *want, "{ct} {}", String::from_utf8_lossy(body));
1916 }
1917 }
1918
1919 #[test]
1920 fn charset_order() {
1921 let cz = b"<meta charset=\"windows-1250\"><p>\x8Elu\x9D cena 120 \x80</p>".to_vec();
1922 let d = |b: &[u8], h| {
1923 let (t, n) = decode(b.to_vec(), h);
1924 (String::from_utf8(t).unwrap_or_default(), n)
1925 };
1926 assert!(d(&cz, None).0.contains("Žluť cena 120 €") && d(&cz, None).1 == "windows-1250");
1927 let eq = b"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-2'><p>\xAE</p>";
1928 assert_eq!(
1929 d(eq, None),
1930 ("<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-2'><p>Ž</p>".into(), "ISO-8859-2")
1931 );
1932 assert_eq!(d(&cz, Some("utf-8")).1, "", "the header wins over the page");
1933 assert_eq!(
1934 d(b"\xEF\xBB\xBF<meta charset=windows-1250>\xC5\xBD", Some("iso-8859-1")).0,
1935 "<meta charset=windows-1250>Ž"
1936 );
1937 assert_eq!(d(b"<meta charset=utf-16><p>x</p>", None).1, "", "utf-16 from ASCII bytes = UTF-8");
1938 assert_eq!(d(b"<p>plain \xC5\xBD</p>", None), ("<p>plain Ž</p>".into(), ""));
1939 assert_eq!(d(b"<meta name=x><meta charset=bogus>", None).1, "", "an unknown label is ignored");
1940 }
1941
1942 #[test]
1943 fn facts_and_fold() {
1944 let line = [Line::T("Preis 1 299,99 € · 2026-10-11 · 7 · m² 45 · EUR 12 · $30 · 40 USD · 50% off".into())];
1945 let f = facts(&line, false);
1946 assert!(f.contains("299,99") && f.contains("2026-10-11") && f.contains("45") && !f.contains("7"));
1947 let priced: BTreeSet<String> = facts(&line, true).into_iter().collect();
1948 assert_eq!(priced.into_iter().collect::<Vec<_>>(), ["12", "299,99", "30", "40"], "next to € EUR $ USD");
1949 assert_eq!(fold("Žluťoučký ĚŠ Café"), "zlutoucky es cafe");
1950 assert_eq!(fold("Brand™ ½ Full fi"), "brandtm 1⁄2 full fi");
1951 assert_eq!(fold("한").chars().count(), 3);
1952 assert_eq!(collapse(" a \u{a0}\n b "), "a b");
1953 let ours = [Line::T("Home [l10] · Shop [l11] · 12 items [l12]".into())];
1954 assert_eq!(facts(&ours, false).into_iter().collect::<Vec<_>>(), ["12"], "[lN] ids are ours");
1955 }
1956
1957 #[test]
1960 fn link_ids_are_not_page_numbers() {
1961 let nav: String = (0..40).map(|i| format!("<a href='/p{i}'>page</a> ")).collect();
1962 let h = format!("<nav>{nav}</nav><h1>Words</h1><p>Only words here, no digits at all.</p>");
1963 let d = build_doc(&parse(&h), "https://ex.com/", "https://ex.com/", false);
1964 assert_eq!((d.mode.as_str(), d.loss.light_facts, d.loss.vs_light_lost), ("clean", 0, 0));
1965 }
1966
1967 #[test]
1970 fn pre_lines_and_combining_edges() {
1971 let h = "<pre>a\r\nb\x0cc\u{2028}d\r\r\ne \n\n</pre>";
1972 let d = build_doc(&parse(h), "https://x.io/", "https://x.io/", false);
1973 assert_eq!(d.sections[0].lines, ["a", "b", "c", "d", "e"]);
1974 let (lo, hi) = COMBINING[0];
1975 let (last_lo, last_hi) = COMBINING[COMBINING.len() - 1];
1976 let f = |cp: u32| fold(&format!("x{}", char::from_u32(cp).expect("a char")));
1977 assert_eq!((f(lo), f(hi), f(last_lo), f(last_hi)), ("x".into(), "x".into(), "x".into(), "x".into()));
1978 assert_eq!(f(lo - 1).chars().count(), 2);
1979 assert_eq!(f(0x2FF).chars().count(), 2, "just below U+0300");
1980 }
1981
1982 #[test]
1983 fn clean_prunes_chrome_and_keeps_links() {
1984 let h = "<html><head><title>T</title></head><body><nav><a href='/x'>menu</a></nav>\
1985 <h1>One</h1><p>Price <a href='/p'>12 EUR</a></p><h2>Two</h2><p>b 24 36 48</p>\
1986 <footer>foot 2026</footer></body></html>";
1987 let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
1988 assert_eq!(d.links, vec!["https://ex.com/p".to_string()]);
1989 assert_eq!(d.sections[0].lines, vec!["Price 12 EUR [l1]".to_string()]);
1990 assert_eq!((d.mode.as_str(), d.loss.vs_light_lost), ("clean", 1)); }
1992
1993 #[test]
1998 fn a_picture_link_reads_its_accessible_name() {
1999 let h = "<h1>Videos</h1><div><a href='/v/1'><div><img alt='Crew-13 reaches the ISS this week'></div>\
2000 <div><strong>1.7M</strong></div></a></div>\
2001 <p>See <a href='/v/2' aria-label='The full launch video in HD'><img alt=''></a></p>\
2002 <div><a href='/p/3'><img alt='Red wool winter coat for women'></a><a href='/p/3'>Red coat</a></div>\
2003 <div><a href='/share'><img alt='Share this page'></a><a href='/v/5'><img role=presentation alt='a b c d'></a></div>\
2004 <p><a href='/docs'><img alt='a small book icon here'> Read the docs</a></p>\
2005 <p><a href='/x25' title='The X.25 protocol for packet networks'>X.25</a></p>\
2006 <div><a href='/n/7' aria-label='Storm closes the harbour for two days'></a><img alt='Waves'>\
2007 <h3>Weather</h3><p>Storm closes the harbour for two days</p></div>";
2008 let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2009 let want = [
2010 "1.7M · Crew-13 reaches the ISS this week [l1]",
2011 "See The full launch video in HD [l2]",
2012 "Red coat [l3]",
2013 "Read the docs [l4]",
2014 "X.25 [l5]",
2015 "Storm closes the harbour for two days [l6]",
2016 ];
2017 assert_eq!(d.sections.iter().flat_map(|s| &s.lines).collect::<Vec<_>>(), want);
2018 }
2019
2020 #[test]
2023 fn button_text_is_page_text() {
2024 let h = "<h1>Hotels in Seville</h1><p>Two hotels found for your dates in the old town.</p>\
2025 <div><button><span>9.1</span> Excellent (17k ratings) Seville, 0.5 miles to City center</button></div>\
2026 <form><input name=q><button>Search 2.0</button></form>";
2027 let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2028 assert!(has(&d, "9.1 Excellent (17k ratings) Seville, 0.5 miles") && !has(&d, "Search 2.0"));
2029 }
2030
2031 #[test]
2034 fn aria_hidden_text_is_on_screen() {
2035 let h = "<h1>Earbuds</h1><p>Wireless earbuds with a case and three tip sizes in the box.</p>\
2036 <p><span aria-hidden=true>4.6 out of 5 stars</span> <span aria-hidden=true>16,544</span>\
2037 <i aria-hidden=true>★</i> ratings</p>";
2038 let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2039 assert_eq!(d.mode, "clean");
2040 assert!(has(&d, "4.6 out of 5 stars 16,544 ratings"));
2041 }
2042
2043 #[test]
2046 fn digits_at_an_element_boundary_get_a_space() {
2047 let h = "<h1>Coins</h1><p>Prices of the day for the top coins on the market.</p>\
2048 <p><span>$109.72</span><span>0.24%</span> · <span>4,336</span><span>3</span> gold · 419<sup>00</sup> €</p>";
2049 let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2050 assert!(has(&d, "$109.72 0.24% · 4,336 3 gold · 419⁰⁰ €"));
2051 }
2052
2053 fn has(d: &Doc, needle: &str) -> bool {
2054 d.sections.iter().flat_map(|s| s.lines.iter()).any(|l| l.contains(needle))
2055 }
2056
2057 #[test]
2059 fn aria_rows_are_table_rows() {
2060 let h = include_str!("../tests/fixtures/table-aria.html");
2061 let d = build_doc(&parse(h), "https://docs.example/limits", "https://docs.example/limits", false);
2062 let rows: Vec<&String> =
2063 d.sections.iter().flat_map(|s| s.lines.iter()).filter(|l| l.starts_with('|')).collect();
2064 assert_eq!(rows.len(), 9, "{rows:?}");
2065 assert_eq!(rows[0], "| Plan | Traffic, GB | Total req/s | Render req/s |");
2066 assert_eq!(rows[1], "| Free trial | 1 | 10 | 3 |");
2067 assert_eq!(rows[8], "| Custom + | Custom | Custom | Custom |");
2068 }
2069
2070 #[test]
2071 fn loss_guard_measures_against_light() {
2072 let h = include_str!("../tests/fixtures/price-rows.html");
2074 let d = build_doc(&parse(h), "https://store.example/p/x", "https://store.example/p/x", false);
2075 assert_eq!((d.mode.as_str(), d.loss.vs_light_lost), ("light", 0));
2076 assert!(has(&d, "Regular price") && has(&d, "13,50 €"));
2077 }
2078
2079 #[test]
2082 fn ld_keeps_document_order_and_number_spelling() {
2083 let ld = |j: &str| {
2084 let v: Value = serde_json::from_str(j).expect("json");
2085 let mut objs = Vec::new();
2086 walk_ld(&v, 0, &mut objs);
2087 let mut info = IndexMap::new();
2088 objs.iter().for_each(|o| ld_info(o, &mut info));
2089 info.into_iter().collect::<Vec<_>>()
2090 };
2091 let i = ld(
2092 r#"{"offers":{"price":330,"priceCurrency":"EUR"},"aggregateRating":{"ratingValue":4.5,"ratingCount":12}}"#,
2093 );
2094 assert_eq!(i, [("price".into(), "330 EUR".into()), ("rating".into(), "4.5 (12 reviews)".into())]);
2095 assert_eq!(ld(r#"{"offers":{"price":12.0}}"#)[0].1, "12.0");
2096 let dup = ld(r#"{"offers":{"price":"1","priceCurrency":"EUR","price":"2"}}"#);
2097 assert_eq!(dup[0].1, "2 EUR", "last value, first place");
2098 let first = ld(r#"{"a":{"datePublished":"2026-01-01"},"b":{"datePublished":"2026-02-02"}}"#);
2099 assert_eq!(first[0], ("published".into(), "2026-01-01".into()), "document order, not sorted keys");
2100 let v: Value = serde_json::from_str(r#"{"b":1,"a":2}"#).expect("json");
2101 assert!(matches!(&v, Value::Object(kv) if kv.keys().eq(["b", "a"])));
2102 assert_eq!(one_space(r#"{"r":1.4984391259105099}"#), b"{\n \"r\": 1.4984391259105099\n}");
2105 }
2106
2107 #[test]
2111 fn og_card_and_body_media() {
2112 let h = include_str!("../tests/fixtures/og-card.html");
2113 let d = build_doc(&parse(h), "https://social.example/a/status/1", "https://social.example/a/status/1", false);
2114 let src: Vec<&str> = d.media.iter().map(|m| m.src.as_str()).collect();
2115 assert_eq!(
2116 src,
2117 [
2118 "https://img.example/media/galaxy?format=webp&name=large",
2119 "https://social.example/media/arm-1600.jpg",
2120 "https://social.example/profile/other.jpg",
2122 "https://social.example/profile/agency_normal.jpg",
2123 "https://social.example/static/share.png",
2124 ]
2125 );
2126 let og = &d.media[0];
2127 assert_eq!((og.w, og.h, og.ty.as_str(), og.video), (5955, 3969, "webp", false));
2128 assert!(og.alt.starts_with("A starfield filled with thousands of stars"), "{og:?}");
2129 assert!(og.alt.ends_with(" dust. The Milky Way’s bar, seen edge-on 🌌."), "{og:?}");
2130 assert_eq!(d.media[1].alt, "The bar of stars");
2131 assert_eq!(d.media.iter().map(|m| m.demoted).collect::<Vec<_>>(), [false, false, true, true, true]);
2132 assert_eq!(
2133 unjson(r"a\u00e9 \ud83c b\x \u12"),
2134 "aé \u{fffd} b\\x \\u12",
2135 "a lone half is U+FFFD; the rest is kept"
2136 );
2137 }
2138
2139 #[test]
2145 fn media_is_counted_honestly() {
2146 let h = include_str!("../tests/fixtures/media-honest.html");
2147 let d = build_doc(&parse(h), "https://news.example/a/river", "https://news.example/a/river", false);
2148 let base = |s: &str| s.trim_start_matches("https://news.example").to_string();
2149 let pick = |demoted: bool| d.media.iter().filter(|m| m.demoted == demoted).map(|m| base(&m.src)).collect();
2150 let counted: Vec<String> = pick(false);
2151 assert_eq!(
2152 counted,
2153 [
2154 "/img/2026/2511401-685193-1287x836.jpg?v=2",
2155 "/img/reply-box-3301.jpg",
2156 "/img/2026/crowd-5512-150x84.jpg",
2157 "/img/lantern-4410.jpg",
2158 "/img/hero-77001-1500.jpg",
2159 "/thumb/250px-Old_bridge_at_dusk.jpg",
2160 ]
2161 );
2162 assert_eq!(d.media[0].alt, "Boats on the river");
2163 let mut demoted: Vec<String> = pick(true);
2164 demoted.sort();
2165 let want = ["/b/build.png", "/brand/site_logo.jpg", "/img/2026/feed-8801-150x84.jpg"];
2166 let more = ["/img/2026/other-9901-393x221.jpg", "/people/editor.jpg", "/static/poster-1024x576.png"];
2167 assert_eq!(demoted, [want, more].concat());
2168 let size = |u: &str| key_of(&url::Url::parse(u).expect("url"));
2169 assert_eq!(size("https://x.io/a/1280px-Big_bridge.jpg").0, size("https://x.io/b/Big_bridge@2x.jpg").0);
2170 assert_eq!(size("https://x.io/p/AbC123=s1600").1, 1600);
2171 assert_eq!(size("https://x.io/p/photo_640x480.jpg?w=1200").1, 1200);
2172 }
2173
2174 #[test]
2180 fn media_keys_galleries_and_cards() {
2181 let key = |u: &str| key_of(&url::Url::parse(u).expect("url")).0;
2182 let wiki = "https://up.wiki/c/thumb/a/ab/Gate_of_Dawn.jpg/250px-Gate_of_Dawn.jpg";
2183 assert_eq!(key(wiki), key("https://up.wiki/c/a/ab/Gate_of_Dawn.jpg"));
2184 let cdn = "https://cdn.io/fetch/w_1456,c_limit/https%3A%2F%2Fs3.io%2Fimages%2F";
2185 assert_ne!(key(&format!("{cdn}acafbb9a-17a6_389x557.png")), key(&format!("{cdn}46d227b9-ef48_943x796.png")));
2186 assert_eq!(
2187 key(&format!("{cdn}acafbb9a-17a6_389x557.png")),
2188 key("https://cdn.io/w_40/acafbb9a-17a6_389x557.png")
2189 );
2190 assert_ne!(
2191 key("https://x.io/_next/image?url=%2Fa%2Fp1.jpg&w=750"),
2192 key("https://x.io/_next/image?url=%2Fa%2Fp2.jpg")
2193 );
2194 assert_ne!(key("https://x.io/img/IMG_2026.10.11.jpg"), key("https://x.io/img/IMG_2026.10.12.jpg"));
2195 assert_ne!(key("https://up.wiki/c/History._The_warrior.jpg"), key("https://up.wiki/c/History._A_helmet.jpg"));
2197 assert_eq!(key("https://ae.io/kf/S5501ck.jpg_960x960q75.jpg_.avif"), key("https://ae.io/kf/S5501ck.jpg"));
2198 let thumbs: String = (1..=3)
2199 .map(|i| {
2200 format!("<div><a href='/photos/{i}'><img src='/img/p{i}-thumb.jpg' width=120 height=120></a></div>")
2201 })
2202 .collect();
2203 let h = format!(
2204 "<meta property='og:site_name' content='Jane Photo'><main><p>My portfolio</p>{thumbs}\
2205 <div><a href='/blog/next-post'><img src='/img/next.jpg' alt='Next post'></a></div>\
2206 <p><img src='/img/1500x40whitespace.jpg'><img src='/img/jane.png' alt='Jane Photo logo'>\
2207 <img src='https://opengraph.example/abc/jane/portfolio'><img src='/tile.png' alt='Map'></p></main>"
2208 );
2209 let d = build_doc(&parse(&h), "https://jane.example/portfolio", "https://jane.example/portfolio", false);
2210 let rows: Vec<(&str, bool)> =
2211 d.media.iter().map(|m| (m.src.rsplit('/').next().unwrap_or_default(), m.demoted)).collect();
2212 let (gallery, rest) = rows.split_at(3);
2213 assert!(gallery.iter().all(|r| !r.1) && rest.iter().all(|r| r.1), "{rows:?}");
2214 assert_eq!(rest.iter().map(|r| r.0).collect::<Vec<_>>(), ["jane.png", "next.jpg", "tile.png", "portfolio"]);
2215 }
2216
2217 #[test]
2221 fn share_cards_by_whole_words() {
2222 let card = |src: &str| {
2223 let h = format!(
2224 "<main><p>{}</p><img src='{src}' alt='a photo of the ridge at dawn'></main>",
2225 "Text. ".repeat(9)
2226 );
2227 build_doc(&parse(&h), "https://ex.io/p", "https://ex.io/p", false)
2228 .media
2229 .iter()
2230 .map(|m| m.demoted)
2231 .collect::<Vec<_>>()
2232 };
2233 let host = ["https://mastodon.social/a.png", "https://social.ex.io/m/a.png", "https://cards.ex.io/x/1.jpg"];
2234 for src in [&["/product-card-image/1.jpg", "/img/discard.jpg", "/i/blog.png"][..], &host].concat() {
2235 assert_eq!(card(src), [false], "{src}");
2236 }
2237 let proxied = "https://cdn.io/fetch/w_1200/https%3A%2F%2Fs3.io%2Fp%2Fog-image.png";
2238 let og = ["https://opengraph.gh.io/x/repo", "https://og-image.ex.app/a.png", proxied];
2239 for src in [&["/static/og-image.png", "/a/share_card.jpg", "/s/social-preview.jpg"][..], &og].concat() {
2240 assert_eq!(card(src), [true], "{src}");
2241 }
2242 }
2243
2244 #[test]
2246 fn size_in_name_is_not_declared() {
2247 let imgs = "<img src='/a/boats-1287x836.jpg' alt='Boats'><img src='/a/rule-1500x40.jpg' alt='a rule'>\
2248 <img src='/a/dot-12x12.png' alt='a dot'><img src='/a/x.jpg' width=640 height=480 alt='X'>";
2249 let h = format!("<main><p>{}</p>{imgs}</main>", "Text. ".repeat(9));
2250 let d = build_doc(&parse(&h), "https://ex.io/p", "https://ex.io/p", false);
2251 let rows: Vec<(&str, u32, u32)> = d.media.iter().map(|m| (m.alt.as_str(), m.w, m.h)).collect();
2252 assert_eq!(rows, [("Boats", 0, 0), ("X", 640, 480)]);
2253 }
2254
2255 #[test]
2258 fn site_name_by_whole_words() {
2259 let demoted = |site: &str, alt: &str| {
2260 let h = format!(
2261 "<meta property='og:site_name' content='{site}'><main><p>Post</p>\
2262 <img src='/a/p.jpg' alt='{alt}' width=800 height=600></main>"
2263 );
2264 let d = build_doc(&parse(&h), "https://s.example/p", "https://s.example/p", false);
2265 d.media.iter().map(|m| m.demoted).collect::<Vec<_>>()
2266 };
2267 assert_eq!(demoted("X", "Red fox"), [false]);
2268 assert_eq!(demoted("X", "X"), [true]);
2269 assert_eq!(demoted("Jane Photo", "Jane Photo logo"), [true]);
2270 assert_eq!(demoted("Jane Photo", "Jane Photo"), [true]);
2271 assert_eq!(demoted("Jane Photo", "Jane at the photo fair"), [false]);
2272 }
2273
2274 #[test]
2275 fn digit_sup_is_superscript() {
2276 let h = include_str!("../tests/fixtures/price-sup-digits.html");
2278 let d = build_doc(&parse(h), "https://shop.example/p", "https://shop.example/p", false);
2279 assert!(
2280 has(&d, "Regular price 419⁰⁰ €") && has(&d, "17⁹⁹ €") && has(&d, "12 m², "),
2281 "{:?}",
2282 d.sections.iter().map(|s| &s.lines).collect::<Vec<_>>()
2283 );
2284 assert!(!has(&d, "41900"));
2285 }
2286
2287 #[test]
2291 fn cards_and_what_stays_lines() {
2292 let lines = |body: &str| {
2293 let d = build_doc(&parse(body), "https://ex.com/", "https://ex.com/", false);
2294 d.sections.into_iter().flat_map(|s| s.lines).collect::<Vec<_>>()
2295 };
2296 let reply = |n: usize, inner: &str| {
2297 format!("<div class=c><a href=/u{n}>user{n}</a><div>{n}h ago</div><div>Reply text {n}</div>{inner}</div>")
2298 };
2299 let thread: String = (1..=4).map(|n| reply(n, &reply(n + 10, ""))).collect();
2300 assert!(!lines(&thread).iter().any(|l| l.starts_with(CARD)), "{:?}", lines(&thread));
2301 let flat = (1..=5).map(|n| {
2303 format!("<div class=c><a href=/u{n}>John Smith{n}</a> <time>{n}h ago</time><p>I think option {n} wins.</p><p>Also see version 0.{n} notes.</p></div>")
2304 });
2305 let flat = lines(&flat.collect::<String>());
2306 assert!(!flat.iter().any(|l| l.starts_with(CARD)) && flat[0] == "John Smith1 [l1] 1h ago", "{flat:?}");
2307 let dated = (1..=5)
2309 .map(|n| format!("<div class=d><time>May {n}</time><h3><a href=/p{n}>Post title {n} here</a></h3></div>"));
2310 let wrapped = (1..=5).map(|n| {
2311 format!("<div class=w><a href=/r{n}><div>Release notes {n}</div><div><time>May {n}</time></div></a></div>")
2312 });
2313 for page in [dated.collect::<String>(), wrapped.collect()] {
2314 assert_eq!(lines(&page).iter().filter(|l| l.starts_with(CARD)).count(), 5, "{:?}", lines(&page));
2315 }
2316 let menu: String = (1..=5).map(|n| format!("<li class=m><a href=/r{n}>Region {n}</a> 3{n}</li>")).collect();
2317 assert!(!lines(&format!("<ul>{menu}</ul>")).iter().any(|l| l.starts_with(CARD)));
2318 let code: String = (1..=4)
2319 .map(|n| format!("<div class=k><a href=/f{n}>fn f{n}</a><p>Since {n}.0</p><pre>f{n}()</pre></div>"))
2320 .collect();
2321 assert!(!lines(&code).iter().any(|l| l.starts_with(CARD)), "{:?}", lines(&code));
2322 }
2323
2324 #[test]
2329 fn cards_are_whole_groups_of_titled_items() {
2330 let doc = |body: &str| build_doc(&parse(body), "https://ex.com/", "https://ex.com/", false);
2331 let rows = |d: &Doc| {
2332 d.sections.iter().flat_map(|s| s.lines.clone()).filter(|l| l.starts_with(CARD)).collect::<Vec<_>>()
2333 };
2334 let story = |n: usize| {
2335 format!(
2336 "<div class=t><a href=/a{n}><h3>Story number {n} today</h3><p>Teaser {n}</p><span>{n} hrs ago</span></a></div>"
2337 )
2338 };
2339 let d = doc(&format!("<h1>News</h1>{}", (1..=4).map(story).collect::<String>()));
2340 assert_eq!(
2341 rows(&d).get(1).map(String::as_str),
2342 Some("▸ Story number 2 today [l2] · Teaser 2 · 2 hrs ago"),
2343 "{:?}",
2344 d.sections.iter().map(|s| (&s.title, &s.lines)).collect::<Vec<_>>()
2345 );
2346 assert_eq!(d.links[1], "https://ex.com/a2");
2347 let job = |n: usize| {
2348 format!(
2349 "<li class=j><a href=/co{n}>View Company Profile</a><a href=/job{n}><div>New</div><div>Senior engineer {n}</div><div>Acme Ltd</div><div>$100,000 USD</div></a></li>"
2350 )
2351 };
2352 let d = doc(&format!("<ul>{}</ul>", (1..=4).map(job).collect::<String>()));
2353 assert_eq!(rows(&d)[0], "▸ Senior engineer 1 [l2] · View Company Profile [l1] · New · Acme Ltd · $100,000 USD");
2354 let wiki = |n: usize| {
2355 format!(
2356 "<section class=s><h2>Topic {n}</h2><div class=hat>Main article: <a href=/t{n}>Topic {n}</a></div><p>In 19{n}0 the <a href=/w{n}>thing {n}</a> grew.</p></section>"
2357 )
2358 };
2359 let d = doc(&format!("<h1>History</h1>{}", (1..=5).map(wiki).collect::<String>()));
2360 assert!(rows(&d).is_empty() && d.sections.len() == 6, "{:?}", rows(&d));
2361 let method = |n: usize| {
2362 format!(
2363 "<div class=m><h3 id=f{n}><a href=#f{n}>fn set_{n}(x: u{n}) -> Self</a></h3><a href=/src{n}>source</a><p>Sets {n}.</p></div>"
2364 )
2365 };
2366 assert!(rows(&doc(&(1..=5).map(method).collect::<String>())).is_empty());
2367 let auto = |n: usize| {
2368 format!("<section class=impl><a href=#i{n}>§</a><h3>impl !Send{n} for <a href=/T.html>T</a></h3></section>")
2369 };
2370 assert!(rows(&doc(&(1..=5).map(auto).collect::<String>())).is_empty());
2371 let post = |n: usize| {
2372 format!(
2373 "<div class=p><a href=/u/user{n}>user{n}</a><span>Oct {n}, 2025</span><p>My reply number {n}.</p></div>"
2374 )
2375 };
2376 assert!(rows(&doc(&(1..=5).map(post).collect::<String>())).is_empty());
2377 let odd = "<div class=t><h3>Our sponsor of 2026</h3><p>Ad copy</p><a href=/ad>more</a></div>";
2379 let d = doc(&format!("<h1>News</h1>{}{odd}", (1..=4).map(story).collect::<String>()));
2380 assert!(rows(&d).len() == 5 && d.sections.len() == 1, "{:?}", rows(&d));
2381 let d = doc(&format!("<h1>News</h1>{}{odd}{odd}{odd}", (1..=2).map(story).collect::<String>()));
2382 assert!(rows(&d).is_empty(), "{:?}", rows(&d));
2383 }
2384
2385 #[test]
2389 fn card_pieces_keep_order_and_articles_stay_sections() {
2390 let doc = |body: &str| build_doc(&parse(body), "https://ex.com/", "https://ex.com/", false);
2391 let rows = |d: &Doc| {
2392 d.sections.iter().flat_map(|s| s.lines.clone()).filter(|l| l.starts_with(CARD)).collect::<Vec<_>>()
2393 };
2394 let note = |n: usize| {
2395 format!(
2396 "<div class=r><a href=/v{n}><h3>Release {n} notes</h3></a><img alt='Release {n} notes'><p>This release brings many small fixes to the parser and the cache layer.</p><li>Bump dependencies</li><li>Fix the docs</li><li>Bump dependencies</li></div>"
2397 )
2398 };
2399 let d = doc(&(1..=4).map(note).collect::<String>());
2400 let want = "▸ Release 1 notes [l1] · This release brings many small fixes to the parser and the cache layer. · Bump dependencies · Fix the docs · Bump dependencies";
2401 assert_eq!(rows(&d).first().map(String::as_str), Some(want), "{:?}", rows(&d));
2402 let post = |n: usize| {
2403 format!(
2404 "<article class=post><h2><a href=/p{n}>Post title number {n}</a></h2><time>Oct {n}</time><p>Intro {n}.</p><h3>Background {n}</h3><p>More {n}.</p></article>"
2405 )
2406 };
2407 let d = doc(&format!("<h1>Blog</h1>{}", (1..=4).map(post).collect::<String>()));
2408 assert!(rows(&d).is_empty() && d.sections.len() == 9, "{:?}", rows(&d));
2409 let app = |n: usize| {
2411 format!(
2412 "<div class=a><div><a href=/help>Learn more about results and reviews.</a></div><div><a href=/app{n}>Markdown tool {n}</a></div><div>4.{n}</div></div>"
2413 )
2414 };
2415 let d = doc(&(1..=4).map(app).collect::<String>());
2416 let want = "▸ Markdown tool 2 [l3] · Learn more about results and reviews. [l1] · 4.2";
2417 assert_eq!(rows(&d).get(1).map(String::as_str), Some(want), "{:?}", rows(&d));
2418 }
2419
2420 #[test]
2423 fn many_siblings_are_linear() {
2424 let run = |n: usize| {
2425 let body = format!("<ul>{}</ul>", (0..n).map(|k| format!("<li>{k}</li>")).collect::<String>());
2426 let t = std::time::Instant::now();
2427 let d = build_doc(&parse(&body), "https://ex.com/", "https://ex.com/", false);
2428 assert_eq!(d.sections.iter().map(|s| s.lines.len()).sum::<usize>(), n);
2429 t.elapsed().as_secs_f64()
2430 };
2431 let (small, big) = (run(4_000), run(40_000));
2432 assert!(big < 40.0 * small + 0.5, "{small:.3} s → {big:.3} s");
2433 }
2434}