trafilatura 0.3.0

Extract readable content, comments, and metadata from web pages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
// Port of go-trafilatura/core.go

//! Web content extraction library.
//!
//! `trafilatura` extracts the main text, comments, and metadata from web pages,
//! stripping boilerplate (navigation, ads, footers) while preserving the
//! article body. It is a faithful Rust port of
//! [go-trafilatura](https://github.com/markusmobius/go-trafilatura).
//!
//! # Quick start
//!
//! ```rust
//! use trafilatura::{extract, Options};
//!
//! let html = r#"<html><body>
//!   <nav>Menu items</nav>
//!   <article><p>This is the main article content.</p></article>
//!   <footer>Copyright 2024</footer>
//! </body></html>"#;
//!
//! let result = extract(html, &Options::default()).unwrap();
//! assert!(result.content_text.contains("main article content"));
//! ```
//!
//! # Features
//!
//! - **Content extraction** — identifies and extracts the main body text using
//!   CSS selector rules, paragraph scoring, and heuristic filters.
//! - **Comment extraction** — separately extracts user comments (optional).
//! - **Metadata** — extracts title, author, date, description, categories, tags,
//!   license, and more from meta tags, OpenGraph, and JSON-LD.
//! - **Fallback strategies** — when primary extraction yields too little content,
//!   falls back to readability-based or baseline extraction.
//! - **Language filtering** — optionally reject documents that don't match a
//!   target language (detected via `whatlang`).
//! - **Deduplication** — LRU-based detection of duplicate content across multiple
//!   extractions.
//!
//! # Builder-style options
//!
//! ```rust
//! use trafilatura::{extract, Options, ExtractionFocus};
//!
//! let html = "<html><body><article><p>Hello world</p></article></body></html>";
//! let opts = Options::default()
//!     .with_fallback(true)
//!     .with_links(true)
//!     .with_focus(ExtractionFocus::FavorRecall);
//! let result = extract(html, &opts).unwrap();
//! assert_eq!(result.content_text, "Hello world");
//! ```
//!
//! # Markdown output (requires `markdown` feature)
//!
//! ```rust,ignore
//! use trafilatura::{extract, create_markdown_document, Options};
//!
//! let result = extract(html, &Options::default()).unwrap();
//!
//! // Just the content as markdown:
//! let md = result.content_markdown();
//!
//! // Full document with YAML front matter + content + comments:
//! let doc = create_markdown_document(&result);
//! ```
//!
//! # Related crates
//!
//! - [`libreadability`](https://crates.io/crates/libreadability) — Mozilla Readability
//!   port for extracting a clean article DOM subtree.
//! - [`justext`](https://crates.io/crates/justext) — paragraph-level boilerplate
//!   removal using stopword density.
//! - [`html2markdown`](https://crates.io/crates/html2markdown) — converts HTML to
//!   Markdown via an intermediate AST.

pub mod dom;
pub mod error;
pub(crate) mod extraction;
pub mod metadata;
pub mod options;
pub mod result;
pub(crate) mod selector;
pub(crate) mod settings;
pub mod utils;

// Convenience re-exports for library users and the CLI binary.
pub use error::TrafilaturaError;
pub use options::{Config, ExtractionFocus, FallbackCandidates, HtmlDateMode, Options};
pub use result::{ExtractResult, Metadata};

#[cfg(feature = "markdown")]
pub use html2markdown::Options as MarkdownOptions;

use crate::dom::Document;
use crate::extraction::{
    baseline::baseline,
    external::compare_external_extraction,
    html_processing::{convert_tags, doc_cleaning, post_cleaning, prune_unwanted_nodes},
    {extract_comments, extract_content},
};
use crate::settings::FORMAT_TAG_CATALOG;
use crate::utils::{
    language::{check_html_language, language_classifier},
    lru::LruCache,
    text::duplicate_test,
};

/// Parse an HTML string and extract its main readable content.
///
/// This is the primary entry point. It parses the HTML, extracts metadata,
/// identifies the main content and (optionally) comments, and returns
/// everything as both plain text and cleaned HTML.
///
/// # Errors
///
/// Returns [`TrafilaturaError`] if:
/// - The target language doesn't match (`LanguageMismatch`)
/// - Required metadata is missing when `has_essential_metadata` is set
/// - Extracted content is too short (`InsufficientContent`)
/// - The document is a duplicate (`DuplicateContent`)
///
/// # Example
///
/// ```rust
/// use trafilatura::{extract, Options};
///
/// let html = "<html><body><article><p>Hello world</p></article></body></html>";
/// let result = extract(html, &Options::default()).unwrap();
/// assert_eq!(result.content_text, "Hello world");
/// ```
pub fn extract(html: &str, opts: &Options) -> Result<ExtractResult, TrafilaturaError> {
    let doc = Document::parse(html);
    extract_document(doc, opts)
}

/// Extract readable content from an already-parsed [`Document`](dom::Document).
///
/// Use this when you have a pre-parsed DOM (e.g., from [`dom::Document::parse`])
/// and want to avoid re-parsing. The extraction pipeline is the same as [`extract`].
///
/// Port of `ExtractDocument`.
pub fn extract_document(doc: Document, opts: &Options) -> Result<ExtractResult, TrafilaturaError> {
    // Clone opts so we can mutate original_url if needed.
    let mut opts = opts.clone();

    // Prepare LRU cache for duplicate detection.
    let mut cache = LruCache::new(opts.config.cache_size);

    // HTML language check (fast early-exit before expensive extraction).
    if opts.target_language.is_some() && !check_html_language(&doc, &opts, false) {
        return Err(TrafilaturaError::LanguageMismatch {
            expected: opts.target_language.clone().unwrap_or_default(),
            got: String::new(),
        });
    }

    // Extract metadata (happens before content extraction in the Go pipeline).
    let mut meta = metadata::extract_metadata(&doc, &opts);

    // Check essential metadata requirements.
    if opts.has_essential_metadata {
        if meta.title.is_empty() {
            return Err(TrafilaturaError::MissingMetadata("title".into()));
        }
        if meta.url.is_empty() {
            return Err(TrafilaturaError::MissingMetadata("url".into()));
        }
        if meta.date.is_none() {
            return Err(TrafilaturaError::MissingMetadata("date".into()));
        }
    }

    // If OriginalURL was not provided, try to use the one found in metadata.
    if opts.original_url.is_none() && !meta.url.is_empty() {
        if let Ok(parsed) = url::Url::parse(&meta.url) {
            // Mirror Go's nurl.ParseRequestURI: only accept absolute URLs with a scheme.
            if matches!(parsed.scheme(), "http" | "https") {
                opts.original_url = Some(parsed);
            }
        }
    }

    // Apply user-specified prune selector (no backup — this is under full user control).
    let mut doc = doc;
    if let Some(sel) = &opts.prune_selector {
        let root = doc.root();
        let to_remove = doc.query_selector_all(root, sel);
        for id in to_remove.into_iter().rev() {
            doc.remove(id, false);
        }
    }

    // Clone the document before destructive cleaning for fallback strategies.
    let doc_backup1 = doc.clone_document();
    let mut doc_backup2 = doc.clone_document();

    // Clean and normalise tags on the main work document.
    doc_cleaning(&mut doc, &opts);
    convert_tags(&mut doc, &opts);

    // Extract comments first (comments sections are removed from `doc` as a side-effect).
    let (comments_doc, tmp_comments) = if !opts.exclude_comments {
        extract_comments(&mut doc, &mut cache, &opts)
    } else {
        if opts.focus == ExtractionFocus::FavorPrecision {
            doc = prune_unwanted_nodes(&doc, selector::discard::REMOVED_COMMENTS, false);
        }
        (None, String::new())
    };
    let len_comments = tmp_comments.chars().count();

    // Main content extraction.
    let (mut content_doc, mut tmp_body_text) = extract_content(&doc, &mut cache, &opts);

    // External fallback comparison (readability / domdistiller).
    if opts.enable_fallback {
        (content_doc, tmp_body_text) =
            compare_external_extraction(&doc_backup1, content_doc, &opts);
    }

    // Rescue with baseline if text is still too short and we are not in precision mode.
    let len_text = tmp_body_text.chars().count();
    if len_text < opts.config.min_extracted_size && opts.focus != ExtractionFocus::FavorPrecision {
        (content_doc, tmp_body_text) = baseline(&mut doc_backup2);
    }

    // Tree size sanity check.
    if let Some(max_tree) = opts.max_tree_size {
        let content_body = content_doc.body().unwrap_or_else(|| content_doc.root());
        if content_doc.children(content_body).len() > max_tree {
            // Strip formatting tags to reduce tree size.
            let fmt_tags: Vec<&str> = FORMAT_TAG_CATALOG.iter().copied().collect();
            content_doc.strip_tags(content_body, &fmt_tags);

            let n_children = content_doc.children(content_body).len();
            if n_children > max_tree {
                return Err(TrafilaturaError::TreeTooLarge(n_children));
            }
        }
    }

    // Size checks — both must be below their minimums. If either meets its
    // threshold the document is considered valid.
    let len_text = tmp_body_text.chars().count();
    if len_text < opts.config.min_output_size && len_comments < opts.config.min_output_comment_size
    {
        return Err(TrafilaturaError::InsufficientContent {
            text_len: len_text,
            comment_len: len_comments,
            min_output_size: opts.config.min_output_size,
            min_output_comment_size: opts.config.min_output_comment_size,
        });
    }

    // Duplicate check at body level.
    if opts.deduplicate {
        let content_body = content_doc.body().unwrap_or_else(|| content_doc.root());
        if duplicate_test(&content_doc, content_body, &mut cache, &opts) {
            return Err(TrafilaturaError::DuplicateContent);
        }
    }

    // Language classification and validation.
    let lang = language_classifier(&tmp_body_text, &tmp_comments);
    if let Some(ref target) = opts.target_language {
        // Match Go's strict semantics: reject even when lang is "" (unknown).
        // Go's `lang != opts.TargetLanguage` rejects undetected language when a target is set.
        if &lang != target {
            return Err(TrafilaturaError::LanguageMismatch {
                expected: target.clone(),
                got: lang.clone(),
            });
        }
    }
    if !lang.is_empty() {
        meta.language = lang;
    }

    // Post-cleaning of content and comments trees.
    post_cleaning(&mut content_doc);
    let mut comments_doc = comments_doc;
    if let Some(ref mut cd) = comments_doc {
        post_cleaning(cd);
    }

    // Serialise to HTML strings for the result.
    let content_body = content_doc.body().unwrap_or_else(|| content_doc.root());
    let content_html = content_doc.inner_html(content_body);

    let comments_html = if let Some(ref cd) = comments_doc {
        let comments_body = cd.body().unwrap_or_else(|| cd.root());
        cd.inner_html(comments_body)
    } else {
        String::new()
    };

    Ok(ExtractResult {
        content_text: tmp_body_text,
        comments_text: tmp_comments,
        content_html,
        comments_html,
        metadata: meta,
    })
}

// ---------------------------------------------------------------------------
// Readable document builder
// ---------------------------------------------------------------------------

/// Creates a complete, self-contained HTML document from an [`ExtractResult`].
///
/// The output has metadata encoded as `<meta>` tags in `<head>`, article
/// content in `<div id="content-body">`, and comments (if any) in
/// `<div id="comments-body">`.
///
/// Port of `CreateReadableDocument`.
pub fn create_readable_document(result: &ExtractResult) -> String {
    let m = &result.metadata;

    let escape = |s: &str| {
        s.replace('&', "&amp;")
            .replace('"', "&quot;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
    };

    let date_str = match m.date {
        Some(d) => d.format("%Y-%m-%d").to_string(),
        None => String::new(),
    };

    let categories = m.categories.join(", ");
    let tags = m.tags.join("; ");

    let mut html = String::with_capacity(1024);
    html.push_str("<html><head>");

    for (name, value) in &[
        ("title", m.title.as_str()),
        ("author", m.author.as_str()),
        ("url", m.url.as_str()),
        ("hostname", m.hostname.as_str()),
        ("description", m.description.as_str()),
        ("sitename", m.sitename.as_str()),
        ("date", date_str.as_str()),
        ("categories", categories.as_str()),
        ("tags", tags.as_str()),
        ("license", m.license.as_str()),
    ] {
        html.push_str(r#"<meta name=""#);
        html.push_str(name);
        html.push_str(r#"" content=""#);
        html.push_str(&escape(value));
        html.push_str(r#""/>"#);
    }

    html.push_str("</head><body>");

    if !result.content_html.is_empty() {
        html.push_str(r#"<div id="content-body">"#);
        html.push_str(&result.content_html);
        html.push_str("</div>");
    }

    if !result.comments_html.is_empty() {
        html.push_str(r#"<div id="comments-body">"#);
        html.push_str(&result.comments_html);
        html.push_str("</div>");
    }

    html.push_str("</body></html>");
    html
}

// ---------------------------------------------------------------------------
// Markdown document builder
// ---------------------------------------------------------------------------

/// Creates a complete Markdown document from an [`ExtractResult`], with
/// metadata encoded as YAML front matter.
///
/// The output has the form:
///
/// ```text
/// ---
/// title: "Article Title"
/// author: "Jane Doe"
/// date: "2025-03-07"
/// ---
///
/// Article content in Markdown...
///
/// ## Comments
///
/// Comments in Markdown...
/// ```
///
/// All string values in front matter are double-quoted for safety. Empty
/// metadata fields are omitted. This is the Markdown counterpart of
/// [`create_readable_document`].
#[cfg(feature = "markdown")]
pub fn create_markdown_document(result: &ExtractResult) -> String {
    create_markdown_document_with(result, &MarkdownOptions::default())
}

/// Creates a complete Markdown document with custom [`MarkdownOptions`].
///
/// See [`create_markdown_document`] for details on the output format.
#[cfg(feature = "markdown")]
pub fn create_markdown_document_with(
    result: &ExtractResult,
    options: &MarkdownOptions,
) -> String {
    let mut out = String::with_capacity(1024);

    // Front matter
    write_front_matter(&mut out, &result.metadata);

    // Content
    let content = result.content_markdown_with(options);
    out.push_str(&content);

    // Comments — only emit the heading when there's content to separate from.
    let comments = result.comments_markdown_with(options);
    if !comments.is_empty() {
        // Ensure exactly one blank line before the heading.
        if !out.ends_with("\n\n") {
            if !out.ends_with('\n') {
                out.push('\n');
            }
            out.push('\n');
        }
        out.push_str("## Comments\n\n");
        out.push_str(&comments);
    }

    out
}

/// Escape a string for use as a YAML double-quoted scalar.
///
/// Handles backslash, double-quote, common whitespace escapes, and all
/// ASCII control characters (per YAML 1.2 §7.3.1).
#[cfg(feature = "markdown")]
fn yaml_escape(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len() + 2);
    escaped.push('"');
    for ch in s.chars() {
        match ch {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            '\0' => escaped.push_str("\\0"),
            // Remaining ASCII control characters and DEL.
            ch if (ch as u32) < 0x20 || ch == '\x7f' => {
                escaped.push_str(&format!("\\u{:04X}", ch as u32));
            }
            _ => escaped.push(ch),
        }
    }
    escaped.push('"');
    escaped
}

/// Write YAML front matter for the given metadata.
#[cfg(feature = "markdown")]
fn write_front_matter(out: &mut String, m: &Metadata) {
    out.push_str("---\n");

    let date_str = m.date.map(|d| d.format("%Y-%m-%d").to_string());

    for (key, value) in [
        ("title", Some(m.title.as_str())),
        ("author", Some(m.author.as_str())),
        ("url", Some(m.url.as_str())),
        ("hostname", Some(m.hostname.as_str())),
        ("description", Some(m.description.as_str())),
        ("sitename", Some(m.sitename.as_str())),
        ("date", date_str.as_deref()),
        ("license", Some(m.license.as_str())),
        ("language", Some(m.language.as_str())),
        ("image", Some(m.image.as_str())),
    ] {
        if let Some(v) = value {
            if !v.is_empty() {
                out.push_str(key);
                out.push_str(": ");
                out.push_str(&yaml_escape(v));
                out.push('\n');
            }
        }
    }

    if !m.categories.is_empty() {
        out.push_str("categories:\n");
        for cat in &m.categories {
            out.push_str("  - ");
            out.push_str(&yaml_escape(cat));
            out.push('\n');
        }
    }

    if !m.tags.is_empty() {
        out.push_str("tags:\n");
        for tag in &m.tags {
            out.push_str("  - ");
            out.push_str(&yaml_escape(tag));
            out.push('\n');
        }
    }

    out.push_str("---\n\n");
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn simple_article(body: &str) -> String {
        format!("<html><head><title>Test</title></head><body>{body}</body></html>")
    }

    #[test]
    fn test_extract_basic_article() {
        let html = simple_article(
            "<article><p>This is the main content of the article. It has enough text to pass \
             the minimum size threshold for extraction and should appear in the result.</p></article>",
        );
        let result = extract(&html, &Options::default()).unwrap();
        assert!(
            !result.content_text.is_empty(),
            "should extract content text"
        );
        assert!(
            result.content_text.contains("main content"),
            "content should contain article text"
        );
    }

    #[test]
    fn test_extract_strips_scripts_and_nav() {
        let html = simple_article(
            "<nav>Navigation</nav>\
             <script>alert('x')</script>\
             <article><p>Real content here that is long enough to be extracted without \
             any issues from the minimum size requirements.</p></article>",
        );
        let result = extract(&html, &Options::default()).unwrap();
        assert!(
            !result.content_text.contains("Navigation"),
            "nav should be stripped"
        );
        assert!(
            !result.content_text.contains("alert"),
            "script should be stripped"
        );
    }

    #[test]
    fn test_extract_empty_html_returns_error() {
        let result = extract("", &Options::default());
        assert!(result.is_err(), "empty HTML should return an error");
    }

    #[test]
    fn test_extract_exclude_comments() {
        let html = simple_article(
            "<article><p>Article content that is long enough to pass the threshold for \
             minimum extracted size in the extractor pipeline.</p></article>\
             <div id=\"comments\"><p>User comment here</p></div>",
        );
        let opts = Options::default().with_exclude_comments(true);
        let result = extract(&html, &opts).unwrap();
        assert!(
            result.comments_text.is_empty(),
            "comments should be excluded"
        );
    }

    #[test]
    fn test_extract_missing_essential_metadata_title() {
        let html = "<html><body><p>Content that is long enough to pass the minimum size \
                    threshold for the extraction algorithm to work properly.</p></body></html>";
        let opts = Options::default().with_essential_metadata(true);
        let result = extract(html, &opts);
        // No <title> in this document → should fail with MissingMetadata
        assert!(
            matches!(result, Err(TrafilaturaError::MissingMetadata(_))),
            "should fail with missing metadata"
        );
    }

    #[test]
    fn test_extract_favor_recall_option() {
        let html = simple_article(
            "<div class='content'><p>Some content in a div that recall mode should pick up \
             even without a standard article tag structure.</p></div>",
        );
        let opts = Options::default().with_focus(ExtractionFocus::FavorRecall);
        // Should not error; recall mode is more permissive
        let _ = extract(&html, &opts); // result may or may not have content; just check no panic
    }

    #[test]
    fn test_extract_document_returns_metadata() {
        let html = r#"<html>
            <head>
                <title>My Article Title</title>
                <meta name="author" content="Jane Doe" />
            </head>
            <body>
                <article>
                    <p>Article content that is long enough to pass the minimum size threshold
                    for the extraction algorithm to return a valid result without errors.</p>
                </article>
            </body>
        </html>"#;
        let result = extract(html, &Options::default()).unwrap();
        assert!(!result.metadata.title.is_empty(), "should extract title");
    }

    #[test]
    fn test_extract_content_html_populated() {
        let html = simple_article(
            "<article><p>Content text that is long enough to pass all minimum size checks \
             and produce a non-empty HTML output in the result struct.</p></article>",
        );
        let result = extract(&html, &Options::default()).unwrap();
        assert!(
            !result.content_html.is_empty(),
            "content_html should be populated"
        );
    }

    #[test]
    fn test_extract_missing_essential_metadata_url() {
        // Document has title and enough content but no canonical URL → MissingMetadata("url")
        let html = "<html><head><title>My Title</title></head>\
                    <body><article><p>Content that is long enough to pass the minimum \
                    size threshold for the extraction algorithm.</p></article></body></html>";
        let opts = Options::default().with_essential_metadata(true);
        let result = extract(html, &opts);
        assert!(
            matches!(result, Err(TrafilaturaError::MissingMetadata(_))),
            "should fail: no URL in metadata"
        );
    }

    #[test]
    fn test_extract_missing_essential_metadata_date() {
        // Provide title + canonical URL but no date → MissingMetadata("date")
        let html = r#"<html>
            <head>
                <title>My Title</title>
                <link rel="canonical" href="https://example.com/article" />
            </head>
            <body><article><p>Content that is long enough to pass the minimum size
            threshold for the extraction algorithm to work correctly.</p></article></body>
        </html>"#;
        let opts = Options::default().with_essential_metadata(true);
        let result = extract(html, &opts);
        assert!(
            matches!(result, Err(TrafilaturaError::MissingMetadata(_))),
            "should fail: no date in metadata"
        );
    }

    #[test]
    fn test_extract_prune_selector() {
        // The prune_selector should remove matched elements before any extraction.
        let html = simple_article(
            "<article><p>Keep this content that is definitely long enough to \
             pass the minimum size threshold.</p></article>\
             <div class=\"sidebar\"><p>Remove this sidebar text.</p></div>",
        );
        let opts = Options::default().with_prune_selector(".sidebar");
        let result = extract(&html, &opts).unwrap();
        assert!(
            !result.content_text.contains("Remove this sidebar"),
            "pruned element should not appear in output"
        );
        assert!(
            result.content_text.contains("Keep this content"),
            "non-pruned content should survive"
        );
    }

    #[test]
    fn test_extract_max_tree_size_error() {
        // Build a body with many direct children to trigger TreeTooLarge.
        let many_ps: String = (0..200)
            .map(|i| format!("<p>Paragraph number {i} with enough text.</p>"))
            .collect();
        let html = simple_article(&many_ps);
        let opts = Options::default().with_max_tree_size(10);
        let result = extract(&html, &opts);
        assert!(
            matches!(result, Err(TrafilaturaError::TreeTooLarge(_))),
            "should return TreeTooLarge when tree exceeds max_tree_size"
        );
    }

    #[test]
    fn test_extract_target_language_rejects_unknown() {
        // When whatlang cannot detect the language (short/ambiguous text) and a target
        // language is set, Go rejects the content. Rust should do the same.
        // Use a very short snippet that whatlang cannot classify reliably.
        let html = simple_article(
            "<article><p>Short text that is just barely long enough to pass the minimum \
             size threshold but may not be long enough to detect a language reliably.</p></article>",
        );
        let opts = Options::default().with_target_language("zh");
        let result = extract(&html, &opts);
        // Either the language was detected (and mismatched) or empty (and mismatched with "zh").
        // Either way, the result must be an error.
        assert!(
            matches!(result, Err(TrafilaturaError::LanguageMismatch { .. })),
            "should reject content when detected language != target language"
        );
    }

    // ---------------------------------------------------------------------------
    // create_readable_document
    // ---------------------------------------------------------------------------

    #[test]
    fn test_create_readable_document_structure() {
        let result = ExtractResult {
            content_text: "Hello world".into(),
            comments_text: String::new(),
            content_html: "<p>Hello world</p>".into(),
            comments_html: String::new(),
            metadata: crate::result::Metadata {
                title: "My Title".into(),
                author: "Jane Doe".into(),
                url: "https://example.com/article".into(),
                hostname: "example.com".into(),
                description: "A description".into(),
                sitename: "Example".into(),
                date: chrono::NaiveDate::from_ymd_opt(2023, 4, 5),
                categories: vec!["Tech".into(), "News".into()],
                tags: vec!["rust".into(), "web".into()],
                license: "CC BY 4.0".into(),
                ..Default::default()
            },
        };

        let html = create_readable_document(&result);

        // Should have proper HTML shell.
        assert!(
            html.starts_with("<html><head>"),
            "should start with html/head"
        );
        assert!(
            html.ends_with("</body></html>"),
            "should end with /body/html"
        );

        // Meta tags.
        assert!(html.contains(r#"name="title" content="My Title""#));
        assert!(html.contains(r#"name="author" content="Jane Doe""#));
        assert!(html.contains(r#"name="url" content="https://example.com/article""#));
        assert!(html.contains(r#"name="hostname" content="example.com""#));
        assert!(html.contains(r#"name="description" content="A description""#));
        assert!(html.contains(r#"name="sitename" content="Example""#));
        assert!(html.contains(r#"name="date" content="2023-04-05""#));
        assert!(html.contains(r#"name="categories" content="Tech, News""#));
        assert!(html.contains(r#"name="tags" content="rust; web""#));
        assert!(html.contains(r#"name="license" content="CC BY 4.0""#));

        // Content div.
        assert!(html.contains(r#"<div id="content-body">"#));
        assert!(html.contains("<p>Hello world</p>"));

        // No empty comments div when comments_html is empty.
        assert!(!html.contains(r#"id="comments-body""#));
    }

    #[test]
    fn test_create_readable_document_with_comments() {
        let result = ExtractResult {
            content_html: "<p>Article</p>".into(),
            comments_html: "<p>A comment</p>".into(),
            ..Default::default()
        };

        let html = create_readable_document(&result);
        assert!(html.contains(r#"<div id="comments-body">"#));
        assert!(html.contains("<p>A comment</p>"));
    }

    #[test]
    fn test_create_readable_document_no_date() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            ..Default::default()
        };

        let html = create_readable_document(&result);
        // Date meta tag should exist but have empty content.
        assert!(html.contains(r#"name="date" content="""#));
    }

    #[test]
    fn test_create_readable_document_escapes_special_chars() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            metadata: crate::result::Metadata {
                title: r#"Title with "quotes" & <tags>"#.into(),
                ..Default::default()
            },
            ..Default::default()
        };

        let html = create_readable_document(&result);
        // The title value in the attribute should be escaped.
        assert!(html.contains("&quot;quotes&quot;"));
        assert!(html.contains("&amp;"));
        assert!(html.contains("&lt;tags&gt;"));
    }

    // ---------------------------------------------------------------------------
    // create_markdown_document
    // ---------------------------------------------------------------------------

    #[cfg(feature = "markdown")]
    #[test]
    fn test_create_markdown_document_front_matter() {
        let result = ExtractResult {
            content_text: "Hello world".into(),
            content_html: "<p>Hello world</p>".into(),
            comments_html: String::new(),
            metadata: crate::result::Metadata {
                title: "My Title".into(),
                author: "Jane Doe".into(),
                url: "https://example.com/article".into(),
                hostname: "example.com".into(),
                description: "A description".into(),
                sitename: "Example".into(),
                date: chrono::NaiveDate::from_ymd_opt(2023, 4, 5),
                categories: vec!["Tech".into(), "News".into()],
                tags: vec!["rust".into(), "web".into()],
                license: "CC BY 4.0".into(),
                ..Default::default()
            },
            ..Default::default()
        };

        let md = create_markdown_document(&result);

        // Front matter delimiters.
        assert!(md.starts_with("---\n"), "should start with front matter");
        assert!(md.contains("\n---\n\n"), "should close front matter");

        // Metadata fields — all values are always double-quoted.
        assert!(md.contains("title: \"My Title\"\n"));
        assert!(md.contains("author: \"Jane Doe\"\n"));
        assert!(md.contains("url: \"https://example.com/article\"\n"));
        assert!(md.contains("hostname: \"example.com\"\n"));
        assert!(md.contains("description: \"A description\"\n"));
        assert!(md.contains("sitename: \"Example\"\n"));
        assert!(md.contains("date: \"2023-04-05\"\n"));
        assert!(md.contains("categories:\n  - \"Tech\"\n  - \"News\"\n"));
        assert!(md.contains("tags:\n  - \"rust\"\n  - \"web\"\n"));

        // Content.
        assert!(md.contains("Hello world"));
    }

    #[cfg(feature = "markdown")]
    #[test]
    fn test_create_markdown_document_omits_empty_fields() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            metadata: crate::result::Metadata {
                title: "Only Title".into(),
                ..Default::default()
            },
            ..Default::default()
        };

        let md = create_markdown_document(&result);
        assert!(md.contains("title: \"Only Title\"\n"));
        assert!(!md.contains("author:"));
        assert!(!md.contains("url:"));
        assert!(!md.contains("date:"));
        assert!(!md.contains("categories:"));
        assert!(!md.contains("tags:"));
    }

    #[cfg(feature = "markdown")]
    #[test]
    fn test_create_markdown_document_with_comments() {
        let result = ExtractResult {
            content_html: "<p>Article</p>".into(),
            comments_html: "<p>A comment</p>".into(),
            ..Default::default()
        };

        let md = create_markdown_document(&result);
        assert!(md.contains("Article"));
        assert!(md.contains("\n## Comments\n\n"));
        assert!(md.contains("A comment"));
    }

    #[cfg(feature = "markdown")]
    #[test]
    fn test_create_markdown_document_escapes_yaml_special_chars() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            metadata: crate::result::Metadata {
                title: "Title: with colon".into(),
                ..Default::default()
            },
            ..Default::default()
        };

        let md = create_markdown_document(&result);
        assert!(
            md.contains(r#"title: "Title: with colon""#),
            "colons should be quoted"
        );
    }

    #[cfg(feature = "markdown")]
    #[test]
    fn test_yaml_escape_backslashes_and_quotes() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            metadata: crate::result::Metadata {
                title: r#"C:\Users & "quotes""#.into(),
                ..Default::default()
            },
            ..Default::default()
        };

        let md = create_markdown_document(&result);
        assert!(
            md.contains(r#"title: "C:\\Users & \"quotes\"""#),
            "backslashes and quotes should be escaped, got: {}",
            md
        );
    }

    #[cfg(feature = "markdown")]
    #[test]
    fn test_yaml_escape_newlines() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            metadata: crate::result::Metadata {
                title: "Line one\nLine two".into(),
                ..Default::default()
            },
            ..Default::default()
        };

        let md = create_markdown_document(&result);
        assert!(
            md.contains(r#"title: "Line one\nLine two""#),
            "newlines should be escaped"
        );
    }

    #[cfg(feature = "markdown")]
    #[test]
    fn test_yaml_escape_categories_and_tags() {
        let result = ExtractResult {
            content_html: "<p>Content</p>".into(),
            metadata: crate::result::Metadata {
                categories: vec!["Science: Physics".into(), "*Breaking*".into()],
                tags: vec!["C:\\path".into()],
                ..Default::default()
            },
            ..Default::default()
        };

        let md = create_markdown_document(&result);
        assert!(md.contains(r#"  - "Science: Physics""#));
        assert!(md.contains(r#"  - "*Breaking*""#));
        assert!(md.contains(r#"  - "C:\\path""#));
    }
}