html_generator/
error.rs

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
// Copyright © 2025 HTML Generator. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Error types for HTML generation and processing.
//!
//! This module defines custom error types used throughout the HTML generation library.
//! It provides a centralized location for all error definitions, making it easier to manage and handle errors consistently across the codebase.

use std::io;
use thiserror::Error;

/// Enum to represent various errors that can occur during HTML generation, processing, or optimization.
#[derive(Error, Debug)]
pub enum HtmlError {
    /// Error that occurs when a regular expression fails to compile.
    ///
    /// This variant contains the underlying error from the `regex` crate.
    #[error("Failed to compile regex: {0}")]
    RegexCompilationError(#[from] regex::Error),

    /// Error indicating failure in extracting front matter from the input content.
    ///
    /// This variant is used when there is an issue parsing the front matter of a document.
    /// The associated string provides details about the error.
    #[error("Failed to extract front matter: {0}")]
    FrontMatterExtractionError(String),

    /// Error indicating a failure in formatting an HTML header.
    ///
    /// This variant is used when the header cannot be formatted correctly. The associated string provides more details.
    #[error("Failed to format header: {0}")]
    HeaderFormattingError(String),

    /// Error that occurs when parsing a selector fails.
    ///
    /// This variant is used when a CSS or HTML selector cannot be parsed.
    /// The first string is the selector, and the second string provides additional context.
    #[error("Failed to parse selector '{0}': {1}")]
    SelectorParseError(String, String),

    /// Error indicating failure to minify HTML content.
    ///
    /// This variant is used when there is an issue during the HTML minification process. The associated string provides details.
    #[error("Failed to minify HTML: {0}")]
    MinificationError(String),

    /// Error that occurs during the conversion of Markdown to HTML.
    ///
    /// This variant is used when the Markdown conversion process encounters an issue. The associated string provides more information.
    #[error("Failed to convert Markdown to HTML: {message}")]
    MarkdownConversion {
        /// The error message
        message: String,
        /// The source error, if available
        #[source]
        source: Option<io::Error>,
    },

    /// Errors that occur during HTML minification.
    #[error("HTML minification failed: {message}")]
    Minification {
        /// The error message
        message: String,
        /// The source error, if available
        size: Option<usize>,
        /// The source error, if available
        #[source]
        source: Option<io::Error>,
    },

    /// SEO-related errors.
    #[error("SEO optimization failed: {kind}: {message}")]
    Seo {
        /// The kind of SEO error
        kind: SeoErrorKind,
        /// The error message
        message: String,
        /// The problematic element, if available
        element: Option<String>,
    },

    /// Accessibility-related errors.
    #[error("Accessibility check failed: {kind}: {message}")]
    Accessibility {
        /// The kind of accessibility error
        kind: ErrorKind,
        /// The error message
        message: String,
        /// The relevant WCAG guideline, if available
        wcag_guideline: Option<String>,
    },

    /// Error indicating that a required HTML element is missing.
    ///
    /// This variant is used when a necessary HTML element (like a title tag) is not found.
    #[error("Missing required HTML element: {0}")]
    MissingHtmlElement(String),

    /// Error that occurs when structured data is invalid.
    ///
    /// This variant is used when JSON-LD or other structured data does not meet the expected format or requirements.
    #[error("Invalid structured data: {0}")]
    InvalidStructuredData(String),

    /// Input/Output errors
    ///
    /// This variant is used when an IO operation fails (e.g., reading or writing files).
    #[error("IO error: {0}")]
    Io(#[from] io::Error),

    /// Error indicating an invalid input.
    ///
    /// This variant is used when the input content is invalid or does not meet the expected criteria.
    #[error("Invalid input: {0}")]
    InvalidInput(String),

    /// Error indicating an invalid front matter format.
    ///
    /// This variant is used when the front matter of a document does not follow the expected format.
    #[error("Invalid front matter format: {0}")]
    InvalidFrontMatterFormat(String),

    /// Error indicating an input that is too large.
    ///
    /// This variant is used when the input content exceeds a certain size limit.
    #[error("Input too large: size {0} bytes")]
    InputTooLarge(usize),

    /// Error indicating an invalid header format.
    ///
    /// This variant is used when an HTML header does not conform to the expected format.
    #[error("Invalid header format: {0}")]
    InvalidHeaderFormat(String),

    /// Error that occurs when converting from UTF-8 fails.
    ///
    /// This variant wraps errors that occur when converting a byte sequence to a UTF-8 string.
    #[error("UTF-8 conversion error: {0}")]
    Utf8ConversionError(#[from] std::string::FromUtf8Error),

    /// Error indicating a failure during parsing.
    ///
    /// This variant is used for general parsing errors where the specific source of the issue isn't covered by other variants.
    #[error("Parsing error: {0}")]
    ParsingError(String),

    /// Errors that occur during template rendering.
    #[error("Template rendering failed: {message}")]
    TemplateRendering {
        /// The error message
        message: String,
        /// The source error, if available
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Error indicating a validation failure.
    ///
    /// This variant is used when a validation step fails, such as schema validation or data integrity checks.
    #[error("Validation error: {0}")]
    ValidationError(String),

    /// A catch-all error for unexpected failures.
    ///
    /// This variant is used for errors that do not fit into other categories.
    #[error("Unexpected error: {0}")]
    UnexpectedError(String),
}

/// Types of SEO-related errors
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SeoErrorKind {
    /// Missing required meta tags
    MissingMetaTags,
    /// Invalid input
    InvalidInput,
    /// Invalid structured data
    InvalidStructuredData,
    /// Missing title
    MissingTitle,
    /// Missing description
    MissingDescription,
    /// Other SEO-related errors
    Other,
}

/// Types of accessibility-related errors
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ErrorKind {
    /// Missing ARIA attributes
    MissingAriaAttributes,
    /// Invalid ARIA attribute values
    InvalidAriaValue,
    /// Missing alternative text
    MissingAltText,
    /// Incorrect heading structure
    HeadingStructure,
    /// Missing form labels
    MissingFormLabels,
    /// Other accessibility-related errors
    Other,
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorKind::MissingAriaAttributes => {
                write!(f, "Missing ARIA attributes")
            }
            ErrorKind::InvalidAriaValue => {
                write!(f, "Invalid ARIA attribute values")
            }
            ErrorKind::MissingAltText => {
                write!(f, "Missing alternative text")
            }
            ErrorKind::HeadingStructure => {
                write!(f, "Incorrect heading structure")
            }
            ErrorKind::MissingFormLabels => {
                write!(f, "Missing form labels")
            }
            ErrorKind::Other => {
                write!(f, "Other accessibility-related errors")
            }
        }
    }
}

impl std::fmt::Display for SeoErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SeoErrorKind::MissingMetaTags => {
                write!(f, "Missing required meta tags")
            }
            SeoErrorKind::InvalidStructuredData => {
                write!(f, "Invalid structured data")
            }
            SeoErrorKind::MissingTitle => write!(f, "Missing title"),
            SeoErrorKind::InvalidInput => write!(f, "Invalid input"),
            SeoErrorKind::MissingDescription => {
                write!(f, "Missing description")
            }
            SeoErrorKind::Other => {
                write!(f, "Other SEO-related errors")
            }
        }
    }
}

impl HtmlError {
    /// Creates a new InvalidInput error
    pub fn invalid_input(
        message: impl Into<String>,
        _input: Option<String>,
    ) -> Self {
        Self::InvalidInput(message.into())
    }

    /// Creates a new InputTooLarge error
    pub fn input_too_large(size: usize) -> Self {
        Self::InputTooLarge(size)
    }

    /// Creates a new Seo error
    pub fn seo(
        kind: SeoErrorKind,
        message: impl Into<String>,
        element: Option<String>,
    ) -> Self {
        Self::Seo {
            kind,
            message: message.into(),
            element,
        }
    }

    /// Creates a new Accessibility error
    pub fn accessibility(
        kind: ErrorKind,
        message: impl Into<String>,
        wcag_guideline: Option<String>,
    ) -> Self {
        Self::Accessibility {
            kind,
            message: message.into(),
            wcag_guideline,
        }
    }

    /// Creates a new MarkdownConversion error
    pub fn markdown_conversion(
        message: impl Into<String>,
        source: Option<io::Error>,
    ) -> Self {
        Self::MarkdownConversion {
            message: message.into(),
            source,
        }
    }
}

/// Type alias for a result using the `HtmlError` error type.
///
/// This type alias makes it more convenient to work with Results throughout the library,
/// reducing boilerplate and improving readability.
pub type Result<T> = std::result::Result<T, HtmlError>;

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

    // Basic Error Creation Tests
    mod basic_errors {
        use super::*;

        #[test]
        fn test_regex_compilation_error() {
            let regex_error =
                regex::Error::Syntax("invalid regex".to_string());
            let error: HtmlError = regex_error.into();
            assert!(matches!(
                error,
                HtmlError::RegexCompilationError(_)
            ));
            assert!(error
                .to_string()
                .contains("Failed to compile regex"));
        }

        #[test]
        fn test_front_matter_extraction_error() {
            let error = HtmlError::FrontMatterExtractionError(
                "Missing delimiter".to_string(),
            );
            assert_eq!(
                error.to_string(),
                "Failed to extract front matter: Missing delimiter"
            );
        }

        #[test]
        fn test_header_formatting_error() {
            let error = HtmlError::HeaderFormattingError(
                "Invalid header level".to_string(),
            );
            assert_eq!(
                error.to_string(),
                "Failed to format header: Invalid header level"
            );
        }

        #[test]
        fn test_selector_parse_error() {
            let error = HtmlError::SelectorParseError(
                "div>".to_string(),
                "Unexpected end".to_string(),
            );
            assert_eq!(
                error.to_string(),
                "Failed to parse selector 'div>': Unexpected end"
            );
        }

        #[test]
        fn test_minification_error() {
            let error = HtmlError::MinificationError(
                "Syntax error".to_string(),
            );
            assert_eq!(
                error.to_string(),
                "Failed to minify HTML: Syntax error"
            );
        }
    }

    // Structured Error Tests
    mod structured_errors {
        use super::*;

        #[test]
        fn test_markdown_conversion_with_source() {
            let source =
                io::Error::new(io::ErrorKind::Other, "source error");
            let error = HtmlError::markdown_conversion(
                "Conversion failed",
                Some(source),
            );
            assert!(error
                .to_string()
                .contains("Failed to convert Markdown to HTML"));
        }

        #[test]
        fn test_markdown_conversion_without_source() {
            let error = HtmlError::markdown_conversion(
                "Conversion failed",
                None,
            );
            assert!(error.to_string().contains("Conversion failed"));
        }

        #[test]
        fn test_minification_with_size_and_source() {
            let error = HtmlError::Minification {
                message: "Too large".to_string(),
                size: Some(1024),
                source: Some(io::Error::new(
                    io::ErrorKind::Other,
                    "IO error",
                )),
            };
            assert!(error
                .to_string()
                .contains("HTML minification failed"));
        }
    }

    // SEO Error Tests
    mod seo_errors {
        use super::*;

        #[test]
        fn test_seo_error_missing_meta_tags() {
            let error = HtmlError::seo(
                SeoErrorKind::MissingMetaTags,
                "Required meta tags missing",
                Some("head".to_string()),
            );
            assert!(error
                .to_string()
                .contains("Missing required meta tags"));
        }

        #[test]
        fn test_seo_error_without_element() {
            let error = HtmlError::seo(
                SeoErrorKind::MissingTitle,
                "Title not found",
                None,
            );
            assert!(error.to_string().contains("Missing title"));
        }

        #[test]
        fn test_all_seo_error_kinds() {
            let kinds = [
                SeoErrorKind::MissingMetaTags,
                SeoErrorKind::InvalidStructuredData,
                SeoErrorKind::MissingTitle,
                SeoErrorKind::MissingDescription,
                SeoErrorKind::Other,
            ];
            for kind in kinds {
                assert!(!kind.to_string().is_empty());
            }
        }
    }

    // Accessibility Error Tests
    mod accessibility_errors {
        use super::*;

        #[test]
        fn test_accessibility_error_with_guideline() {
            let error = HtmlError::accessibility(
                ErrorKind::MissingAltText,
                "Images must have alt text",
                Some("WCAG 1.1.1".to_string()),
            );
            assert!(error
                .to_string()
                .contains("Missing alternative text"));
        }

        #[test]
        fn test_accessibility_error_without_guideline() {
            let error = HtmlError::accessibility(
                ErrorKind::InvalidAriaValue,
                "Invalid ARIA value",
                None,
            );
            assert!(error
                .to_string()
                .contains("Invalid ARIA attribute values"));
        }

        #[test]
        fn test_all_accessibility_error_kinds() {
            let kinds = [
                ErrorKind::MissingAriaAttributes,
                ErrorKind::InvalidAriaValue,
                ErrorKind::MissingAltText,
                ErrorKind::HeadingStructure,
                ErrorKind::MissingFormLabels,
                ErrorKind::Other,
            ];
            for kind in kinds {
                assert!(!kind.to_string().is_empty());
            }
        }
    }

    // Input/Output Error Tests
    mod io_errors {
        use super::*;

        #[test]
        fn test_io_error_kinds() {
            let error_kinds = [
                io::ErrorKind::NotFound,
                io::ErrorKind::PermissionDenied,
                io::ErrorKind::ConnectionRefused,
                io::ErrorKind::ConnectionReset,
                io::ErrorKind::ConnectionAborted,
                io::ErrorKind::NotConnected,
                io::ErrorKind::AddrInUse,
                io::ErrorKind::AddrNotAvailable,
                io::ErrorKind::BrokenPipe,
                io::ErrorKind::AlreadyExists,
                io::ErrorKind::WouldBlock,
                io::ErrorKind::InvalidInput,
                io::ErrorKind::InvalidData,
                io::ErrorKind::TimedOut,
                io::ErrorKind::WriteZero,
                io::ErrorKind::Interrupted,
                io::ErrorKind::Unsupported,
                io::ErrorKind::UnexpectedEof,
                io::ErrorKind::OutOfMemory,
                io::ErrorKind::Other,
            ];

            for kind in error_kinds {
                let io_error = io::Error::new(kind, "test error");
                let html_error: HtmlError = io_error.into();
                assert!(matches!(html_error, HtmlError::Io(_)));
            }
        }
    }

    // Helper Method Tests
    mod helper_methods {
        use super::*;

        #[test]
        fn test_invalid_input_with_content() {
            let error = HtmlError::invalid_input(
                "Bad input",
                Some("problematic content".to_string()),
            );
            assert!(error.to_string().contains("Invalid input"));
        }

        #[test]
        fn test_input_too_large() {
            let error = HtmlError::input_too_large(1024);
            assert!(error.to_string().contains("1024 bytes"));
        }

        #[test]
        fn test_template_rendering_error() {
            let source_error = Box::new(io::Error::new(
                io::ErrorKind::Other,
                "render failed",
            ));
            let error = HtmlError::TemplateRendering {
                message: "Template error".to_string(),
                source: source_error,
            };
            assert!(error
                .to_string()
                .contains("Template rendering failed"));
        }
    }

    // Miscellaneous Error Tests
    mod misc_errors {
        use super::*;

        #[test]
        fn test_missing_html_element() {
            let error =
                HtmlError::MissingHtmlElement("title".to_string());
            assert!(error
                .to_string()
                .contains("Missing required HTML element"));
        }

        #[test]
        fn test_invalid_structured_data() {
            let error = HtmlError::InvalidStructuredData(
                "Invalid JSON-LD".to_string(),
            );
            assert!(error
                .to_string()
                .contains("Invalid structured data"));
        }

        #[test]
        fn test_invalid_front_matter_format() {
            let error = HtmlError::InvalidFrontMatterFormat(
                "Missing closing delimiter".to_string(),
            );
            assert!(error
                .to_string()
                .contains("Invalid front matter format"));
        }

        #[test]
        fn test_parsing_error() {
            let error =
                HtmlError::ParsingError("Unexpected token".to_string());
            assert!(error.to_string().contains("Parsing error"));
        }

        #[test]
        fn test_validation_error() {
            let error = HtmlError::ValidationError(
                "Schema validation failed".to_string(),
            );
            assert!(error.to_string().contains("Validation error"));
        }

        #[test]
        fn test_unexpected_error() {
            let error = HtmlError::UnexpectedError(
                "Something went wrong".to_string(),
            );
            assert!(error.to_string().contains("Unexpected error"));
        }
    }
}