halldyll-parser 0.1.0

HTML/CSS parsing and content extraction for halldyll scraper
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
//! Main HTML parser API for halldyll-parser
//!
//! This module provides the primary `HtmlParser` struct that orchestrates
//! all parsing operations and provides a clean, unified API.

use scraper::Html;
use std::time::Instant;
use url::Url;

use crate::content::{
    extract_headings, extract_paragraphs, extract_lists,
    extract_tables, extract_code_blocks, extract_quotes, extract_images,
};
use crate::links::extract_links;
use crate::metadata::{extract_metadata, extract_structured_data};
use crate::text::extract_text;
use crate::types::{
    ParsedContent, PageMetadata, TextContent, Heading, Link, Image,
    ListContent, TableContent, CodeBlock, Quote, StructuredData,
    ParseStats, ParserConfig, ParserResult,
};

// ============================================================================
// HTML PARSER
// ============================================================================

/// Main HTML parser
/// 
/// # Example
/// ```rust
/// use halldyll_parser::HtmlParser;
/// 
/// let html = r#"
///     <html>
///     <head><title>Test</title></head>
///     <body><p>Hello world</p></body>
///     </html>
/// "#;
/// 
/// let parser = HtmlParser::new();
/// let result = parser.parse(html).unwrap();
/// 
/// println!("Title: {:?}", result.metadata.title);
/// ```
#[derive(Debug, Clone)]
pub struct HtmlParser {
    config: ParserConfig,
}

impl HtmlParser {
    /// Create a new parser with default configuration
    pub fn new() -> Self {
        Self {
            config: ParserConfig::default(),
        }
    }

    /// Create a parser with custom configuration
    pub fn with_config(config: ParserConfig) -> Self {
        Self { config }
    }

    /// Create a parser with a base URL
    pub fn with_base_url(url: &str) -> ParserResult<Self> {
        let parsed_url = Url::parse(url)?;
        Ok(Self {
            config: ParserConfig {
                base_url: Some(parsed_url),
                ..Default::default()
            },
        })
    }

    /// Set the base URL for resolving relative URLs
    pub fn set_base_url(&mut self, url: &str) -> ParserResult<()> {
        self.config.base_url = Some(Url::parse(url)?);
        Ok(())
    }

    /// Get the current configuration
    pub fn config(&self) -> &ParserConfig {
        &self.config
    }

    /// Get mutable configuration
    pub fn config_mut(&mut self) -> &mut ParserConfig {
        &mut self.config
    }

    // ========================================================================
    // MAIN PARSE METHODS
    // ========================================================================

    /// Parse HTML and extract all content
    pub fn parse(&self, html: &str) -> ParserResult<ParsedContent> {
        let start = Instant::now();
        let html_size = html.len();
        
        // Parse HTML document
        let document = Html::parse_document(html);
        
        // Initialize stats
        let mut stats = ParseStats {
            html_size,
            ..Default::default()
        };

        // Count nodes
        stats.node_count = document.tree.nodes().count();
        
        // Extract all content
        let metadata = extract_metadata(&document, self.config.base_url.as_ref())?;
        let text = extract_text(&document, &self.config)?;
        let headings = extract_headings(&document)?;
        let paragraphs = extract_paragraphs(&document, &self.config)?;
        
        let links = if self.config.extract_links {
            extract_links(&document, &self.config)?
        } else {
            Vec::new()
        };
        
        let images = if self.config.extract_images {
            extract_images(&document, self.config.base_url.as_ref())?
        } else {
            Vec::new()
        };
        
        let lists = extract_lists(&document)?;
        
        let tables = if self.config.extract_tables {
            extract_tables(&document)?
        } else {
            Vec::new()
        };
        
        let code_blocks = if self.config.extract_code_blocks {
            extract_code_blocks(&document)?
        } else {
            Vec::new()
        };
        
        let quotes = extract_quotes(&document)?;
        
        let structured_data = if self.config.extract_structured_data {
            extract_structured_data(&document)
        } else {
            Vec::new()
        };
        
        // Finalize stats
        stats.parse_time_us = start.elapsed().as_micros() as u64;
        
        Ok(ParsedContent {
            metadata,
            text,
            headings,
            paragraphs,
            links,
            images,
            lists,
            tables,
            code_blocks,
            quotes,
            structured_data,
            stats,
        })
    }

    /// Parse HTML fragment (not a full document)
    pub fn parse_fragment(&self, html: &str) -> ParserResult<ParsedContent> {
        let start = Instant::now();
        
        // Wrap in body for consistent parsing
        let wrapped = format!("<body>{}</body>", html);
        let document = Html::parse_fragment(&wrapped);
        
        let mut stats = ParseStats {
            html_size: html.len(),
            node_count: document.tree.nodes().count(),
            ..Default::default()
        };

        let text = extract_text(&document, &self.config)?;
        let headings = extract_headings(&document)?;
        let paragraphs = extract_paragraphs(&document, &self.config)?;
        let links = extract_links(&document, &self.config)?;
        let images = extract_images(&document, self.config.base_url.as_ref())?;
        let lists = extract_lists(&document)?;
        let tables = extract_tables(&document)?;
        let code_blocks = extract_code_blocks(&document)?;
        let quotes = extract_quotes(&document)?;
        
        stats.parse_time_us = start.elapsed().as_micros() as u64;
        
        Ok(ParsedContent {
            metadata: PageMetadata::default(),
            text,
            headings,
            paragraphs,
            links,
            images,
            lists,
            tables,
            code_blocks,
            quotes,
            structured_data: Vec::new(),
            stats,
        })
    }

    // ========================================================================
    // INDIVIDUAL EXTRACTION METHODS
    // ========================================================================

    /// Extract only metadata
    pub fn extract_metadata(&self, html: &str) -> ParserResult<PageMetadata> {
        let document = Html::parse_document(html);
        extract_metadata(&document, self.config.base_url.as_ref())
    }

    /// Extract only text content
    pub fn extract_text(&self, html: &str) -> ParserResult<TextContent> {
        let document = Html::parse_document(html);
        extract_text(&document, &self.config)
    }

    /// Extract only headings
    pub fn extract_headings(&self, html: &str) -> ParserResult<Vec<Heading>> {
        let document = Html::parse_document(html);
        extract_headings(&document)
    }

    /// Extract only links
    pub fn extract_links(&self, html: &str) -> ParserResult<Vec<Link>> {
        let document = Html::parse_document(html);
        extract_links(&document, &self.config)
    }

    /// Extract only images
    pub fn extract_images(&self, html: &str) -> ParserResult<Vec<Image>> {
        let document = Html::parse_document(html);
        extract_images(&document, self.config.base_url.as_ref())
    }

    /// Extract only lists
    pub fn extract_lists(&self, html: &str) -> ParserResult<Vec<ListContent>> {
        let document = Html::parse_document(html);
        extract_lists(&document)
    }

    /// Extract only tables
    pub fn extract_tables(&self, html: &str) -> ParserResult<Vec<TableContent>> {
        let document = Html::parse_document(html);
        extract_tables(&document)
    }

    /// Extract only code blocks
    pub fn extract_code_blocks(&self, html: &str) -> ParserResult<Vec<CodeBlock>> {
        let document = Html::parse_document(html);
        extract_code_blocks(&document)
    }

    /// Extract only quotes
    pub fn extract_quotes(&self, html: &str) -> ParserResult<Vec<Quote>> {
        let document = Html::parse_document(html);
        extract_quotes(&document)
    }

    /// Extract only structured data
    pub fn extract_structured_data(&self, html: &str) -> Vec<StructuredData> {
        let document = Html::parse_document(html);
        extract_structured_data(&document)
    }

    // ========================================================================
    // UTILITY METHODS
    // ========================================================================

    /// Resolve a relative URL to absolute using the parser's base URL
    pub fn resolve_url(&self, href: &str) -> Option<String> {
        let trimmed = href.trim();
        
        if trimmed.is_empty() {
            return None;
        }
        
        // Already absolute
        if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
            return Some(trimmed.to_string());
        }
        
        // Protocol-relative
        if trimmed.starts_with("//") {
            return Some(format!("https:{}", trimmed));
        }
        
        // Resolve relative
        self.config.base_url.as_ref()
            .and_then(|base| base.join(trimmed).ok())
            .map(|u| u.to_string())
    }

    /// Check if the parser has a base URL configured
    pub fn has_base_url(&self) -> bool {
        self.config.base_url.is_some()
    }

    /// Get the base URL if configured
    pub fn base_url(&self) -> Option<&Url> {
        self.config.base_url.as_ref()
    }
}

impl Default for HtmlParser {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// CONVENIENCE FUNCTIONS
// ============================================================================

/// Parse HTML with default settings (convenience function)
pub fn parse(html: &str) -> ParserResult<ParsedContent> {
    HtmlParser::new().parse(html)
}

/// Parse HTML with a base URL (convenience function)
pub fn parse_with_url(html: &str, base_url: &str) -> ParserResult<ParsedContent> {
    HtmlParser::with_base_url(base_url)?.parse(html)
}

/// Quick metadata extraction (convenience function)
pub fn get_metadata(html: &str) -> ParserResult<PageMetadata> {
    HtmlParser::new().extract_metadata(html)
}

/// Quick text extraction (convenience function)
pub fn get_text(html: &str) -> ParserResult<TextContent> {
    HtmlParser::new().extract_text(html)
}

/// Quick link extraction (convenience function)
pub fn get_links(html: &str) -> ParserResult<Vec<Link>> {
    HtmlParser::new().extract_links(html)
}

// ============================================================================
// TESTS
// ============================================================================

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

    const SAMPLE_HTML: &str = r#"
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Test Page</title>
            <meta name="description" content="A test page for parsing">
            <meta property="og:title" content="OG Test Page">
            <link rel="canonical" href="https://example.com/test">
        </head>
        <body>
            <header><nav>Navigation</nav></header>
            <main>
                <article>
                    <h1>Main Title</h1>
                    <p>This is the first paragraph of the article content.</p>
                    <h2>Section One</h2>
                    <p>Another paragraph with more detailed information.</p>
                    <ul>
                        <li>Item 1</li>
                        <li>Item 2</li>
                    </ul>
                    <a href="/internal">Internal Link</a>
                    <a href="https://external.com" rel="nofollow">External Link</a>
                    <img src="/image.jpg" alt="Test Image">
                    <pre><code class="language-rust">fn main() {}</code></pre>
                </article>
            </main>
            <footer>Footer content</footer>
        </body>
        </html>
    "#;

    #[test]
    fn test_parser_new() {
        let parser = HtmlParser::new();
        assert!(!parser.has_base_url());
    }

    #[test]
    fn test_parser_with_base_url() {
        let parser = HtmlParser::with_base_url("https://example.com").unwrap();
        assert!(parser.has_base_url());
        assert_eq!(parser.base_url().unwrap().host_str(), Some("example.com"));
    }

    #[test]
    fn test_parser_set_base_url() {
        let mut parser = HtmlParser::new();
        parser.set_base_url("https://example.com").unwrap();
        assert!(parser.has_base_url());
    }

    #[test]
    fn test_full_parse() {
        let parser = HtmlParser::with_base_url("https://example.com").unwrap();
        let result = parser.parse(SAMPLE_HTML).unwrap();
        
        // Metadata
        assert_eq!(result.metadata.title, Some("Test Page".to_string()));
        assert_eq!(result.metadata.description, Some("A test page for parsing".to_string()));
        assert!(result.metadata.opengraph.is_present());
        
        // Content
        assert!(!result.headings.is_empty());
        assert!(!result.paragraphs.is_empty());
        assert!(!result.lists.is_empty());
        assert!(!result.links.is_empty());
        assert!(!result.images.is_empty());
        assert!(!result.code_blocks.is_empty());
        
        // Stats
        assert!(result.stats.html_size > 0);
        assert!(result.stats.parse_time_us > 0);
    }

    #[test]
    fn test_extract_metadata_only() {
        let parser = HtmlParser::new();
        let metadata = parser.extract_metadata(SAMPLE_HTML).unwrap();
        
        assert_eq!(metadata.title, Some("Test Page".to_string()));
        assert_eq!(metadata.language, Some("en".to_string()));
    }

    #[test]
    fn test_extract_text_only() {
        let parser = HtmlParser::new();
        let text = parser.extract_text(SAMPLE_HTML).unwrap();
        
        assert!(text.word_count > 0);
        assert!(text.cleaned_text.contains("Main Title"));
    }

    #[test]
    fn test_extract_links_only() {
        let parser = HtmlParser::with_base_url("https://example.com").unwrap();
        let links = parser.extract_links(SAMPLE_HTML).unwrap();
        
        assert_eq!(links.len(), 2);
        
        // Check internal link
        let internal = links.iter().find(|l| l.href == "/internal").unwrap();
        assert_eq!(internal.url, Some("https://example.com/internal".to_string()));
        
        // Check external link
        let external = links.iter().find(|l| l.href == "https://external.com").unwrap();
        assert!(external.is_nofollow);
    }

    #[test]
    fn test_extract_images_only() {
        let parser = HtmlParser::with_base_url("https://example.com").unwrap();
        let images = parser.extract_images(SAMPLE_HTML).unwrap();
        
        assert_eq!(images.len(), 1);
        assert_eq!(images[0].alt, "Test Image");
        assert_eq!(images[0].url, Some("https://example.com/image.jpg".to_string()));
    }

    #[test]
    fn test_parse_fragment() {
        let parser = HtmlParser::new();
        let result = parser.parse_fragment("<p>Hello <strong>world</strong></p>").unwrap();
        
        // Fragment parsing - just verify it parses without error
        // Text extraction may be empty for fragments without body
        let _ = result.paragraphs; // Use result to validate parsing works
    }

    #[test]
    fn test_resolve_url() {
        let parser = HtmlParser::with_base_url("https://example.com/dir/").unwrap();
        
        assert_eq!(
            parser.resolve_url("page.html"),
            Some("https://example.com/dir/page.html".to_string())
        );
        
        assert_eq!(
            parser.resolve_url("/absolute"),
            Some("https://example.com/absolute".to_string())
        );
        
        assert_eq!(
            parser.resolve_url("https://other.com"),
            Some("https://other.com".to_string())
        );
    }

    #[test]
    fn test_convenience_parse() {
        let result = parse(SAMPLE_HTML).unwrap();
        assert!(result.metadata.title.is_some());
    }

    #[test]
    fn test_convenience_parse_with_url() {
        let result = parse_with_url(SAMPLE_HTML, "https://example.com").unwrap();
        assert!(result.metadata.title.is_some());
    }

    #[test]
    fn test_convenience_get_metadata() {
        let metadata = get_metadata(SAMPLE_HTML).unwrap();
        assert_eq!(metadata.title, Some("Test Page".to_string()));
    }

    #[test]
    fn test_convenience_get_text() {
        let text = get_text(SAMPLE_HTML).unwrap();
        assert!(text.word_count > 0);
    }

    #[test]
    fn test_convenience_get_links() {
        let links = get_links(SAMPLE_HTML).unwrap();
        assert!(!links.is_empty());
    }

    #[test]
    fn test_parser_with_minimal_config() {
        let config = ParserConfig::minimal();
        let parser = HtmlParser::with_config(config);
        let result = parser.parse(SAMPLE_HTML).unwrap();
        
        // Should still extract metadata and text
        assert!(result.metadata.title.is_some());
        assert!(result.text.word_count > 0);
        
        // But not images/tables/etc
        assert!(result.images.is_empty());
        assert!(result.tables.is_empty());
    }

    #[test]
    fn test_malformed_html() {
        let parser = HtmlParser::new();
        let result = parser.parse("<p>Unclosed paragraph <div>Mixed</p></div>");
        
        // Should still parse without error
        assert!(result.is_ok());
    }

    #[test]
    fn test_empty_html() {
        let parser = HtmlParser::new();
        let result = parser.parse("").unwrap();
        
        assert!(result.metadata.title.is_none());
        assert!(result.text.is_empty());
    }

    #[test]
    fn test_parser_default() {
        let parser = HtmlParser::default();
        assert!(!parser.has_base_url());
    }

    #[test]
    fn test_config_mutation() {
        let mut parser = HtmlParser::new();
        parser.config_mut().extract_images = false;
        
        let result = parser.parse(SAMPLE_HTML).unwrap();
        assert!(result.images.is_empty());
    }
}