quillmark-core 0.52.0

Core types and functionality for Quillmark
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
//! # Error Handling
//!
//! Structured error handling with diagnostics and source location tracking.
//!
//! ## Overview
//!
//! The `error` module provides error types and diagnostic types for actionable
//! error reporting with source location tracking.
//!
//! ## Key Types
//!
//! - [`RenderError`]: Main error enum for rendering operations

//! - [`Diagnostic`]: Structured diagnostic information
//! - [`Location`]: Source file location (file, line, column)
//! - [`Severity`]: Error severity levels (Error, Warning, Note)
//! - [`RenderResult`]: Result type with artifacts and warnings
//!
//! ## Error Hierarchy
//!
//! ### RenderError Variants
//!
//! - [`RenderError::EngineCreation`]: Failed to create rendering engine
//! - [`RenderError::InvalidFrontmatter`]: Malformed YAML frontmatter
//! - [`RenderError::TemplateFailed`]: Template rendering error
//! - [`RenderError::CompilationFailed`]: Backend compilation errors
//! - [`RenderError::FormatNotSupported`]: Requested format not supported
//! - [`RenderError::UnsupportedBackend`]: Backend not registered
//! - [`RenderError::DynamicAssetCollision`]: Asset filename collision
//! - [`RenderError::DynamicFontCollision`]: Font filename collision
//! - [`RenderError::InputTooLarge`]: Input size limits exceeded
//! - [`RenderError::YamlTooLarge`]: YAML size exceeded maximum
//! - [`RenderError::NestingTooDeep`]: Nesting depth exceeded maximum
//!
//! ## Examples
//!
//! ### Error Handling
//!
//! ```no_run
//! use quillmark_core::{RenderError, error::print_errors};
//! # use quillmark_core::{RenderResult, OutputFormat};
//! # struct Workflow;
//! # impl Workflow {
//! #     fn render(&self, _: &str, _: Option<()>) -> Result<RenderResult, RenderError> {
//! #         Ok(RenderResult::new(vec![], OutputFormat::Pdf))
//! #     }
//! # }
//! # let workflow = Workflow;
//! # let markdown = "";
//!
//! match workflow.render(markdown, None) {
//!     Ok(result) => {
//!         // Process artifacts
//!         for artifact in result.artifacts {
//!             std::fs::write(
//!                 format!("output.{:?}", artifact.output_format),
//!                 &artifact.bytes
//!             )?;
//!         }
//!     }
//!     Err(e) => {
//!         // Print structured diagnostics
//!         print_errors(&e);
//!         
//!         // Match specific error types
//!         match e {
//!             RenderError::CompilationFailed { diags } => {
//!                 eprintln!("Compilation failed with {} errors:", diags.len());
//!                 for diag in diags {
//!                     eprintln!("{}", diag.fmt_pretty());
//!                 }
//!             }
//!             RenderError::InvalidFrontmatter { diag } => {
//!                 eprintln!("Frontmatter error: {}", diag.message);
//!             }
//!             _ => eprintln!("Error: {}", e),
//!         }
//!     }
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ### Creating Diagnostics
//!
//! ```
//! use quillmark_core::{Diagnostic, Location, Severity};
//!
//! let diag = Diagnostic::new(Severity::Error, "Undefined variable".to_string())
//!     .with_code("E001".to_string())
//!     .with_location(Location {
//!         file: "template.typ".to_string(),
//!         line: 10,
//!         col: 5,
//!     })
//!     .with_hint("Check variable spelling".to_string());
//!
//! println!("{}", diag.fmt_pretty());
//! ```
//!
//! Example output:
//! ```text
//! [ERROR] Undefined variable (E001) at template.typ:10:5
//!   hint: Check variable spelling
//! ```
//!
//! ### Result with Warnings
//!
//! ```no_run
//! # use quillmark_core::{RenderResult, Diagnostic, Severity, OutputFormat};
//! # let artifacts = vec![];
//! let result = RenderResult::new(artifacts, OutputFormat::Pdf)
//!     .with_warning(Diagnostic::new(
//!         Severity::Warning,
//!         "Deprecated field used".to_string(),
//!     ));
//! ```
//!
//! ## Pretty Printing
//!
//! The [`Diagnostic`] type provides [`Diagnostic::fmt_pretty()`] for human-readable output with error code, location, and hints.
//!
//! ## Machine-Readable Output
//!
//! All diagnostic types implement `serde::Serialize` for JSON export:
//!
//! ```no_run
//! # use quillmark_core::{Diagnostic, Severity};
//! # let diagnostic = Diagnostic::new(Severity::Error, "Test".to_string());
//! let json = serde_json::to_string(&diagnostic).unwrap();
//! ```

use crate::OutputFormat;

/// Maximum input size for markdown (10 MB)
pub const MAX_INPUT_SIZE: usize = 10 * 1024 * 1024;

/// Maximum YAML size (1 MB)
pub const MAX_YAML_SIZE: usize = 1024 * 1024;

/// Maximum nesting depth for markdown structures (100 levels)
pub const MAX_NESTING_DEPTH: usize = 100;

/// Maximum YAML nesting depth (100 levels)
/// Prevents stack overflow from deeply nested YAML structures
pub const MAX_YAML_DEPTH: usize = 100;

/// Maximum number of CARD blocks allowed per document
/// Prevents memory exhaustion from documents with excessive card blocks
pub const MAX_CARD_COUNT: usize = 1000;

/// Maximum number of fields allowed per document
/// Prevents memory exhaustion from documents with excessive fields
pub const MAX_FIELD_COUNT: usize = 1000;

/// Error severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Severity {
    /// Fatal error that prevents completion
    Error,
    /// Non-fatal issue that may need attention
    Warning,
    /// Informational message
    Note,
}

/// Location information for diagnostics
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Location {
    /// Source file name (e.g., "plate.typ", "template.typ", "input.md")
    pub file: String,
    /// Line number (1-indexed)
    pub line: u32,
    /// Column number (1-indexed)
    pub col: u32,
}

/// Structured diagnostic information
#[derive(Debug, serde::Serialize)]
pub struct Diagnostic {
    /// Error severity level
    pub severity: Severity,
    /// Optional error code (e.g., "E001", "typst::syntax")
    pub code: Option<String>,
    /// Human-readable error message
    pub message: String,
    /// Primary source location
    pub primary: Option<Location>,
    /// Optional hint for fixing the error
    pub hint: Option<String>,
    /// Source error that caused this diagnostic (for error chaining)
    /// Note: This field is excluded from serialization as Error trait
    /// objects cannot be serialized
    #[serde(skip)]
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl Diagnostic {
    /// Create a new diagnostic
    pub fn new(severity: Severity, message: String) -> Self {
        Self {
            severity,
            code: None,
            message,
            primary: None,
            hint: None,
            source: None,
        }
    }

    /// Set the error code
    pub fn with_code(mut self, code: String) -> Self {
        self.code = Some(code);
        self
    }

    /// Set the primary location
    pub fn with_location(mut self, location: Location) -> Self {
        self.primary = Some(location);
        self
    }

    /// Set a hint
    pub fn with_hint(mut self, hint: String) -> Self {
        self.hint = Some(hint);
        self
    }

    /// Set error source (chainable)
    pub fn with_source(mut self, source: Box<dyn std::error::Error + Send + Sync>) -> Self {
        self.source = Some(source);
        self
    }

    /// Get the source chain as a list of error messages
    pub fn source_chain(&self) -> Vec<String> {
        let mut chain = Vec::new();
        let mut current_source = self
            .source
            .as_ref()
            .map(|b| b.as_ref() as &dyn std::error::Error);
        while let Some(err) = current_source {
            chain.push(err.to_string());
            current_source = err.source();
        }
        chain
    }

    /// Format diagnostic for pretty printing
    pub fn fmt_pretty(&self) -> String {
        let mut result = format!(
            "[{}] {}",
            match self.severity {
                Severity::Error => "ERROR",
                Severity::Warning => "WARN",
                Severity::Note => "NOTE",
            },
            self.message
        );

        if let Some(ref code) = self.code {
            result.push_str(&format!(" ({})", code));
        }

        if let Some(ref loc) = self.primary {
            result.push_str(&format!("\n  --> {}:{}:{}", loc.file, loc.line, loc.col));
        }

        if let Some(ref hint) = self.hint {
            result.push_str(&format!("\n  hint: {}", hint));
        }

        result
    }

    /// Format diagnostic with source chain for debugging
    pub fn fmt_pretty_with_source(&self) -> String {
        let mut result = self.fmt_pretty();

        for (i, cause) in self.source_chain().iter().enumerate() {
            result.push_str(&format!("\n  cause {}: {}", i + 1, cause));
        }

        result
    }
}

impl std::fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// Serializable diagnostic for cross-language boundaries
///
/// This type is used when diagnostics need to be serialized and sent across
/// FFI boundaries (e.g., Python, WASM). Unlike `Diagnostic`, it does not
/// contain the non-serializable `source` field, but instead includes a
/// flattened `source_chain` for display purposes.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SerializableDiagnostic {
    /// Error severity level
    pub severity: Severity,
    /// Optional error code (e.g., "E001", "typst::syntax")
    pub code: Option<String>,
    /// Human-readable error message
    pub message: String,
    /// Primary source location
    pub primary: Option<Location>,
    /// Optional hint for fixing the error
    pub hint: Option<String>,
    /// Source chain as list of strings (for display purposes)
    pub source_chain: Vec<String>,
}

impl From<Diagnostic> for SerializableDiagnostic {
    fn from(diag: Diagnostic) -> Self {
        let source_chain = diag.source_chain();
        Self {
            severity: diag.severity,
            code: diag.code,
            message: diag.message,
            primary: diag.primary,
            hint: diag.hint,
            source_chain,
        }
    }
}

impl From<&Diagnostic> for SerializableDiagnostic {
    fn from(diag: &Diagnostic) -> Self {
        Self {
            severity: diag.severity,
            code: diag.code.clone(),
            message: diag.message.clone(),
            primary: diag.primary.clone(),
            hint: diag.hint.clone(),
            source_chain: diag.source_chain(),
        }
    }
}

/// Error type for parsing operations
#[derive(thiserror::Error, Debug)]
pub enum ParseError {
    /// Input too large
    #[error("Input too large: {size} bytes (max: {max} bytes)")]
    InputTooLarge {
        /// Actual size
        size: usize,
        /// Maximum allowed size
        max: usize,
    },

    /// YAML parsing error
    #[error("YAML parsing error: {0}")]
    YamlError(#[from] serde_saphyr::Error),

    /// JSON parsing/conversion error
    #[error("JSON error: {0}")]
    JsonError(#[from] serde_json::Error),

    /// Invalid YAML structure
    #[error("Invalid YAML structure: {0}")]
    InvalidStructure(String),

    /// Missing CARD directive in inline metadata block
    #[error("{}", .diag.message)]
    MissingCardDirective {
        /// Diagnostic information with hint
        diag: Box<Diagnostic>,
    },

    /// YAML parsing error with location context
    #[error("YAML error at line {line}: {message}")]
    YamlErrorWithLocation {
        /// Error message
        message: String,
        /// Line number in the source document (1-indexed)
        line: usize,
        /// Index of the metadata block (0-indexed)
        block_index: usize,
    },

    /// Other parsing errors
    #[error("{0}")]
    Other(String),
}

impl ParseError {
    /// Create a MissingCardDirective error with helpful hint
    pub fn missing_card_directive() -> Self {
        let diag = Diagnostic::new(
            Severity::Error,
            "Inline metadata block missing CARD directive".to_string(),
        )
        .with_code("parse::missing_card".to_string())
        .with_hint(
            "Add 'CARD: <card_type>' to specify which card this block belongs to. \
            Example:\n---\nCARD: my_card_type\nfield: value\n---"
                .to_string(),
        );
        ParseError::MissingCardDirective {
            diag: Box::new(diag),
        }
    }

    /// Convert the parse error into a structured diagnostic
    pub fn to_diagnostic(&self) -> Diagnostic {
        match self {
            ParseError::MissingCardDirective { diag } => Diagnostic {
                severity: diag.severity,
                code: diag.code.clone(),
                message: diag.message.clone(),
                primary: diag.primary.clone(),
                hint: diag.hint.clone(),
                source: None, // Cannot clone trait object, but it's empty in this case usually
            },
            ParseError::InputTooLarge { size, max } => Diagnostic::new(
                Severity::Error,
                format!("Input too large: {} bytes (max: {} bytes)", size, max),
            )
            .with_code("parse::input_too_large".to_string()),
            ParseError::YamlError(e) => {
                Diagnostic::new(Severity::Error, format!("YAML parsing error: {}", e))
                    .with_code("parse::yaml_error".to_string())
            } // serde_saphyr::Error implements Error+Clone? No, usually Error is not Clone.
            ParseError::JsonError(e) => {
                Diagnostic::new(Severity::Error, format!("JSON conversion error: {}", e))
                    .with_code("parse::json_error".to_string())
            }
            ParseError::InvalidStructure(msg) => Diagnostic::new(Severity::Error, msg.clone())
                .with_code("parse::invalid_structure".to_string()),
            ParseError::YamlErrorWithLocation {
                message,
                line,
                block_index,
            } => Diagnostic::new(
                Severity::Error,
                format!(
                    "YAML error at line {} (block {}): {}",
                    line, block_index, message
                ),
            )
            .with_code("parse::yaml_error_with_location".to_string()),
            ParseError::Other(msg) => Diagnostic::new(Severity::Error, msg.clone()),
        }
    }
}

impl From<Box<dyn std::error::Error + Send + Sync>> for ParseError {
    fn from(err: Box<dyn std::error::Error + Send + Sync>) -> Self {
        ParseError::Other(err.to_string())
    }
}

impl From<String> for ParseError {
    fn from(msg: String) -> Self {
        ParseError::Other(msg)
    }
}

impl From<&str> for ParseError {
    fn from(msg: &str) -> Self {
        ParseError::Other(msg.to_string())
    }
}

/// Main error type for rendering operations
#[derive(thiserror::Error, Debug)]
pub enum RenderError {
    /// Failed to create rendering engine
    #[error("{diag}")]
    EngineCreation {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Invalid YAML frontmatter in markdown document
    #[error("{diag}")]
    InvalidFrontmatter {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Template rendering failed
    #[error("{diag}")]
    TemplateFailed {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Backend compilation failed with one or more errors
    #[error("Backend compilation failed with {} error(s)", diags.len())]
    CompilationFailed {
        /// List of diagnostics
        diags: Vec<Diagnostic>,
    },

    /// Requested output format not supported by backend
    #[error("{diag}")]
    FormatNotSupported {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Backend not registered with engine
    #[error("{diag}")]
    UnsupportedBackend {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Dynamic asset filename collision
    #[error("{diag}")]
    DynamicAssetCollision {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Dynamic font filename collision
    #[error("{diag}")]
    DynamicFontCollision {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Input size limits exceeded
    #[error("{diag}")]
    InputTooLarge {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// YAML size exceeded maximum allowed
    #[error("{diag}")]
    YamlTooLarge {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Nesting depth exceeded maximum allowed
    #[error("{diag}")]
    NestingTooDeep {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Validation failed for parsed document
    #[error("{diag}")]
    ValidationFailed {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Invalid schema definition
    #[error("{diag}")]
    InvalidSchema {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Quill configuration error
    #[error("{diag}")]
    QuillConfig {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Version not found
    #[error("{diag}")]
    VersionNotFound {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Quill not found (name doesn't exist)
    #[error("{diag}")]
    QuillNotFound {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },

    /// Invalid version format
    #[error("{diag}")]
    InvalidVersion {
        /// Diagnostic information
        diag: Box<Diagnostic>,
    },
}

impl RenderError {
    /// Extract all diagnostics from this error
    pub fn diagnostics(&self) -> Vec<&Diagnostic> {
        match self {
            RenderError::CompilationFailed { diags } => diags.iter().collect(),
            RenderError::EngineCreation { diag }
            | RenderError::InvalidFrontmatter { diag }
            | RenderError::TemplateFailed { diag }
            | RenderError::FormatNotSupported { diag }
            | RenderError::UnsupportedBackend { diag }
            | RenderError::DynamicAssetCollision { diag }
            | RenderError::DynamicFontCollision { diag }
            | RenderError::InputTooLarge { diag }
            | RenderError::YamlTooLarge { diag }
            | RenderError::NestingTooDeep { diag }
            | RenderError::ValidationFailed { diag }
            | RenderError::InvalidSchema { diag }
            | RenderError::QuillConfig { diag }
            | RenderError::VersionNotFound { diag }
            | RenderError::QuillNotFound { diag }
            | RenderError::InvalidVersion { diag } => vec![diag.as_ref()],
        }
    }
}

/// Convert ParseError to RenderError
impl From<ParseError> for RenderError {
    fn from(err: ParseError) -> Self {
        RenderError::InvalidFrontmatter {
            diag: Box::new(
                Diagnostic::new(Severity::Error, err.to_string())
                    .with_code("parse::error".to_string()),
            ),
        }
    }
}

/// Result type containing artifacts and warnings
#[derive(Debug)]
pub struct RenderResult {
    /// Generated output artifacts
    pub artifacts: Vec<crate::Artifact>,
    /// Non-fatal diagnostic messages
    pub warnings: Vec<Diagnostic>,
    /// Output format that was produced
    pub output_format: OutputFormat,
}

impl RenderResult {
    /// Create a new result with artifacts and output format
    pub fn new(artifacts: Vec<crate::Artifact>, output_format: OutputFormat) -> Self {
        Self {
            artifacts,
            warnings: Vec::new(),
            output_format,
        }
    }

    /// Add a warning to the result
    pub fn with_warning(mut self, warning: Diagnostic) -> Self {
        self.warnings.push(warning);
        self
    }
}

/// Helper to print structured errors
pub fn print_errors(err: &RenderError) {
    match err {
        RenderError::CompilationFailed { diags } => {
            for d in diags {
                eprintln!("{}", d.fmt_pretty());
            }
        }
        RenderError::TemplateFailed { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::InvalidFrontmatter { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::EngineCreation { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::FormatNotSupported { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::UnsupportedBackend { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::DynamicAssetCollision { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::DynamicFontCollision { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::InputTooLarge { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::YamlTooLarge { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::NestingTooDeep { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::ValidationFailed { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::InvalidSchema { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::QuillConfig { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::VersionNotFound { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::QuillNotFound { diag } => eprintln!("{}", diag.fmt_pretty()),
        RenderError::InvalidVersion { diag } => eprintln!("{}", diag.fmt_pretty()),
    }
}

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

    #[test]
    fn test_diagnostic_with_source_chain() {
        let root_err = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
        let diag = Diagnostic::new(Severity::Error, "Rendering failed".to_string())
            .with_source(Box::new(root_err));

        let chain = diag.source_chain();
        assert_eq!(chain.len(), 1);
        assert!(chain[0].contains("File not found"));
    }

    #[test]
    fn test_diagnostic_serialization() {
        let diag = Diagnostic::new(Severity::Error, "Test error".to_string())
            .with_code("E001".to_string())
            .with_location(Location {
                file: "test.typ".to_string(),
                line: 10,
                col: 5,
            });

        let serializable: SerializableDiagnostic = diag.into();
        let json = serde_json::to_string(&serializable).unwrap();
        assert!(json.contains("Test error"));
        assert!(json.contains("E001"));
    }

    #[test]
    fn test_render_error_diagnostics_extraction() {
        let diag1 = Diagnostic::new(Severity::Error, "Error 1".to_string());
        let diag2 = Diagnostic::new(Severity::Error, "Error 2".to_string());

        let err = RenderError::CompilationFailed {
            diags: vec![diag1, diag2],
        };

        let diags = err.diagnostics();
        assert_eq!(diags.len(), 2);
    }

    #[test]
    fn test_diagnostic_fmt_pretty() {
        let diag = Diagnostic::new(Severity::Warning, "Deprecated field used".to_string())
            .with_code("W001".to_string())
            .with_location(Location {
                file: "input.md".to_string(),
                line: 5,
                col: 10,
            })
            .with_hint("Use the new field name instead".to_string());

        let output = diag.fmt_pretty();
        assert!(output.contains("[WARN]"));
        assert!(output.contains("Deprecated field used"));
        assert!(output.contains("W001"));
        assert!(output.contains("input.md:5:10"));
        assert!(output.contains("hint:"));
    }

    #[test]
    fn test_diagnostic_fmt_pretty_with_source() {
        let root_err = std::io::Error::other("Underlying error");
        let diag = Diagnostic::new(Severity::Error, "Top-level error".to_string())
            .with_code("E002".to_string())
            .with_source(Box::new(root_err));

        let output = diag.fmt_pretty_with_source();
        assert!(output.contains("[ERROR]"));
        assert!(output.contains("Top-level error"));
        assert!(output.contains("cause 1:"));
        assert!(output.contains("Underlying error"));
    }

    #[test]
    fn test_render_result_with_warnings() {
        let artifacts = vec![];
        let warning = Diagnostic::new(Severity::Warning, "Test warning".to_string());

        let result = RenderResult::new(artifacts, OutputFormat::Pdf).with_warning(warning);

        assert_eq!(result.warnings.len(), 1);
        assert_eq!(result.warnings[0].message, "Test warning");
    }
}