fastapi-output 0.3.0

Agent-aware rich console output for fastapi_rust
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
//! Error formatting component.
//!
//! Provides formatted error display for validation errors, HTTP errors,
//! and internal errors with location path display.

use crate::mode::OutputMode;
use crate::themes::FastApiTheme;
use std::fmt::Write;

const ANSI_RESET: &str = "\x1b[0m";
const ANSI_BOLD: &str = "\x1b[1m";

/// Location item for error paths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LocItem {
    /// Field name.
    Field(String),
    /// Array index.
    Index(usize),
}

impl LocItem {
    /// Create a field location item.
    #[must_use]
    pub fn field(name: impl Into<String>) -> Self {
        Self::Field(name.into())
    }

    /// Create an index location item.
    #[must_use]
    pub const fn index(idx: usize) -> Self {
        Self::Index(idx)
    }

    /// Format the location item.
    #[must_use]
    pub fn format(&self) -> String {
        match self {
            Self::Field(name) => name.clone(),
            Self::Index(idx) => format!("[{idx}]"),
        }
    }
}

/// A single validation error.
#[derive(Debug, Clone)]
pub struct ValidationErrorDetail {
    /// Location path (e.g., ["body", "user", "email"]).
    pub loc: Vec<LocItem>,
    /// Error message.
    pub msg: String,
    /// Error type (e.g., "value_error", "type_error").
    pub error_type: String,
    /// The actual input value that caused the error.
    pub input: Option<String>,
    /// Expected value or constraint (e.g., "integer", "min: 1", "email format").
    pub expected: Option<String>,
    /// Context information (e.g., constraint values).
    pub ctx: Option<ValidationContext>,
}

/// Context information for validation errors.
#[derive(Debug, Clone, Default)]
pub struct ValidationContext {
    /// Minimum constraint value.
    pub min: Option<String>,
    /// Maximum constraint value.
    pub max: Option<String>,
    /// Pattern that was expected.
    pub pattern: Option<String>,
    /// Expected type name.
    pub expected_type: Option<String>,
    /// Additional context key-value pairs.
    pub extra: Vec<(String, String)>,
}

impl ValidationContext {
    /// Create a new empty context.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set minimum constraint.
    #[must_use]
    pub fn min(mut self, min: impl Into<String>) -> Self {
        self.min = Some(min.into());
        self
    }

    /// Set maximum constraint.
    #[must_use]
    pub fn max(mut self, max: impl Into<String>) -> Self {
        self.max = Some(max.into());
        self
    }

    /// Set pattern constraint.
    #[must_use]
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }

    /// Set expected type.
    #[must_use]
    pub fn expected_type(mut self, expected: impl Into<String>) -> Self {
        self.expected_type = Some(expected.into());
        self
    }

    /// Add extra context.
    #[must_use]
    pub fn extra(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((key.into(), value.into()));
        self
    }

    /// Check if context has any values.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.min.is_none()
            && self.max.is_none()
            && self.pattern.is_none()
            && self.expected_type.is_none()
            && self.extra.is_empty()
    }

    /// Format context as a string.
    #[must_use]
    pub fn format(&self) -> String {
        let mut parts = Vec::new();
        if let Some(min) = &self.min {
            parts.push(format!("min={min}"));
        }
        if let Some(max) = &self.max {
            parts.push(format!("max={max}"));
        }
        if let Some(pattern) = &self.pattern {
            parts.push(format!("pattern={pattern}"));
        }
        if let Some(expected) = &self.expected_type {
            parts.push(format!("expected={expected}"));
        }
        for (k, v) in &self.extra {
            parts.push(format!("{k}={v}"));
        }
        parts.join(", ")
    }
}

impl ValidationErrorDetail {
    /// Create a new validation error.
    #[must_use]
    pub fn new(loc: Vec<LocItem>, msg: impl Into<String>, error_type: impl Into<String>) -> Self {
        Self {
            loc,
            msg: msg.into(),
            error_type: error_type.into(),
            input: None,
            expected: None,
            ctx: None,
        }
    }

    /// Set the input value that caused the error.
    #[must_use]
    pub fn input(mut self, input: impl Into<String>) -> Self {
        self.input = Some(input.into());
        self
    }

    /// Set the expected value or constraint.
    #[must_use]
    pub fn expected(mut self, expected: impl Into<String>) -> Self {
        self.expected = Some(expected.into());
        self
    }

    /// Set the validation context.
    #[must_use]
    pub fn ctx(mut self, ctx: ValidationContext) -> Self {
        self.ctx = Some(ctx);
        self
    }

    /// Format the location path as a string.
    #[must_use]
    pub fn format_loc(&self) -> String {
        if self.loc.is_empty() {
            return String::new();
        }

        let mut result = String::new();
        for (i, item) in self.loc.iter().enumerate() {
            match item {
                LocItem::Field(name) => {
                    if i > 0 {
                        result.push('.');
                    }
                    result.push_str(name);
                }
                LocItem::Index(idx) => {
                    let _ = write!(result, "[{idx}]");
                }
            }
        }
        result
    }
}

/// HTTP error information.
#[derive(Debug, Clone)]
pub struct HttpErrorInfo {
    /// HTTP status code.
    pub status: u16,
    /// Error detail message.
    pub detail: String,
    /// Optional error code.
    pub code: Option<String>,
    /// Request path (for context).
    pub path: Option<String>,
    /// Request method (for context).
    pub method: Option<String>,
}

impl HttpErrorInfo {
    /// Create a new HTTP error.
    #[must_use]
    pub fn new(status: u16, detail: impl Into<String>) -> Self {
        Self {
            status,
            detail: detail.into(),
            code: None,
            path: None,
            method: None,
        }
    }

    /// Set the error code.
    #[must_use]
    pub fn code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());
        self
    }

    /// Set the request path.
    #[must_use]
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Set the request method.
    #[must_use]
    pub fn method(mut self, method: impl Into<String>) -> Self {
        self.method = Some(method.into());
        self
    }

    /// Get the status category name.
    #[must_use]
    pub fn status_category(&self) -> &'static str {
        match self.status {
            400 => "Bad Request",
            401 => "Unauthorized",
            403 => "Forbidden",
            404 => "Not Found",
            405 => "Method Not Allowed",
            409 => "Conflict",
            422 => "Unprocessable Entity",
            429 => "Too Many Requests",
            500 => "Internal Server Error",
            502 => "Bad Gateway",
            503 => "Service Unavailable",
            504 => "Gateway Timeout",
            _ if self.status >= 400 && self.status < 500 => "Client Error",
            _ if self.status >= 500 => "Server Error",
            _ => "Error",
        }
    }
}

/// Formatted error output.
#[derive(Debug, Clone)]
pub struct FormattedError {
    /// Plain text version.
    pub plain: String,
    /// ANSI-formatted version.
    pub rich: String,
}

/// Error formatter.
#[derive(Debug, Clone)]
pub struct ErrorFormatter {
    mode: OutputMode,
    theme: FastApiTheme,
    /// Whether to show error codes.
    pub show_codes: bool,
    /// Whether to show request context.
    pub show_context: bool,
}

impl ErrorFormatter {
    /// Create a new error formatter.
    #[must_use]
    pub fn new(mode: OutputMode) -> Self {
        Self {
            mode,
            theme: FastApiTheme::default(),
            show_codes: true,
            show_context: true,
        }
    }

    /// Set the theme.
    #[must_use]
    pub fn theme(mut self, theme: FastApiTheme) -> Self {
        self.theme = theme;
        self
    }

    /// Format a list of validation errors.
    #[must_use]
    pub fn format_validation_errors(&self, errors: &[ValidationErrorDetail]) -> FormattedError {
        match self.mode {
            OutputMode::Plain => {
                let plain = self.format_validation_plain(errors);
                FormattedError {
                    plain: plain.clone(),
                    rich: plain,
                }
            }
            OutputMode::Minimal | OutputMode::Rich => {
                let plain = self.format_validation_plain(errors);
                let rich = self.format_validation_rich(errors);
                FormattedError { plain, rich }
            }
        }
    }

    fn format_validation_plain(&self, errors: &[ValidationErrorDetail]) -> String {
        let mut lines = Vec::new();

        lines.push(format!(
            "Validation Error ({count} error(s)):",
            count = errors.len()
        ));
        lines.push(String::new());

        for error in errors {
            let loc = error.format_loc();
            if loc.is_empty() {
                lines.push(format!("  - {msg}", msg = error.msg));
            } else {
                lines.push(format!("  - {loc}: {msg}", msg = error.msg));
            }

            // Show input value if present
            if let Some(input) = &error.input {
                lines.push(format!("    Input: {input}"));
            }

            // Show expected value if present
            if let Some(expected) = &error.expected {
                lines.push(format!("    Expected: {expected}"));
            }

            // Show context if present
            if let Some(ctx) = &error.ctx {
                if !ctx.is_empty() {
                    lines.push(format!("    Context: {}", ctx.format()));
                }
            }

            if self.show_codes {
                lines.push(format!(
                    "    [type: {error_type}]",
                    error_type = error.error_type
                ));
            }
        }

        lines.join("\n")
    }

    fn format_validation_rich(&self, errors: &[ValidationErrorDetail]) -> String {
        let mut lines = Vec::new();
        let error_color = self.theme.error.to_ansi_fg();
        let muted = self.theme.muted.to_ansi_fg();
        let accent = self.theme.accent.to_ansi_fg();
        let warning = self.theme.warning.to_ansi_fg();
        let info = self.theme.info.to_ansi_fg();

        // Header
        lines.push(format!(
            "{error_color}{ANSI_BOLD}✗ Validation Error{ANSI_RESET} {muted}({count} error(s)){ANSI_RESET}",
            count = errors.len()
        ));
        lines.push(String::new());

        for error in errors {
            let loc = error.format_loc();

            // Error line with location
            if loc.is_empty() {
                lines.push(format!("  {warning}{ANSI_RESET} {msg}", msg = error.msg));
            } else {
                lines.push(format!(
                    "  {warning}{ANSI_RESET} {accent}{loc}{ANSI_RESET}: {msg}",
                    msg = error.msg
                ));
            }

            // Show input vs expected comparison
            if error.input.is_some() || error.expected.is_some() {
                if let Some(input) = &error.input {
                    lines.push(format!(
                        "    {muted}Got:{ANSI_RESET}      {error_color}{input}{ANSI_RESET}"
                    ));
                }
                if let Some(expected) = &error.expected {
                    lines.push(format!(
                        "    {muted}Expected:{ANSI_RESET} {info}{expected}{ANSI_RESET}"
                    ));
                }
            }

            // Show context if present
            if let Some(ctx) = &error.ctx {
                if !ctx.is_empty() {
                    lines.push(format!(
                        "    {muted}Constraints: {}{ANSI_RESET}",
                        ctx.format()
                    ));
                }
            }

            // Error type
            if self.show_codes {
                lines.push(format!(
                    "    {muted}[type: {error_type}]{ANSI_RESET}",
                    error_type = error.error_type
                ));
            }
        }

        lines.join("\n")
    }

    /// Format an HTTP error.
    #[must_use]
    pub fn format_http_error(&self, error: &HttpErrorInfo) -> FormattedError {
        match self.mode {
            OutputMode::Plain => {
                let plain = self.format_http_plain(error);
                FormattedError {
                    plain: plain.clone(),
                    rich: plain,
                }
            }
            OutputMode::Minimal | OutputMode::Rich => {
                let plain = self.format_http_plain(error);
                let rich = self.format_http_rich(error);
                FormattedError { plain, rich }
            }
        }
    }

    fn format_http_plain(&self, error: &HttpErrorInfo) -> String {
        let mut lines = Vec::new();

        // Status line
        lines.push(format!(
            "HTTP {status} {category}",
            status = error.status,
            category = error.status_category()
        ));

        // Detail
        lines.push(format!("Detail: {detail}", detail = error.detail));

        // Code
        if self.show_codes {
            if let Some(code) = &error.code {
                lines.push(format!("Code: {code}"));
            }
        }

        // Context
        if self.show_context {
            if let (Some(method), Some(path)) = (&error.method, &error.path) {
                lines.push(format!("Request: {method} {path}"));
            }
        }

        lines.join("\n")
    }

    fn format_http_rich(&self, error: &HttpErrorInfo) -> String {
        let mut lines = Vec::new();
        let status_color = self.status_color(error.status).to_ansi_fg();
        let muted = self.theme.muted.to_ansi_fg();
        let accent = self.theme.accent.to_ansi_fg();

        // Status line with color
        let icon = if error.status >= 500 { "" } else { "" };
        lines.push(format!(
            "{status_color}{ANSI_BOLD}{icon} HTTP {status}{ANSI_RESET} {muted}{category}{ANSI_RESET}",
            status = error.status,
            category = error.status_category()
        ));

        // Detail
        lines.push(format!("  {detail}", detail = error.detail));

        // Code
        if self.show_codes {
            if let Some(code) = &error.code {
                lines.push(format!("  {muted}Code: {accent}{code}{ANSI_RESET}"));
            }
        }

        // Context
        if self.show_context {
            if let (Some(method), Some(path)) = (&error.method, &error.path) {
                lines.push(format!(
                    "  {muted}Request: {accent}{method} {path}{ANSI_RESET}"
                ));
            }
        }

        lines.join("\n")
    }

    fn status_color(&self, status: u16) -> crate::themes::Color {
        match status {
            400..=499 => self.theme.status_4xx,
            500..=599 => self.theme.status_5xx,
            _ => self.theme.muted,
        }
    }

    /// Format a simple error message.
    #[must_use]
    pub fn format_simple(&self, message: &str) -> FormattedError {
        let plain = format!("Error: {message}");

        let rich = match self.mode {
            OutputMode::Plain => plain.clone(),
            OutputMode::Minimal | OutputMode::Rich => {
                let error_color = self.theme.error.to_ansi_fg();
                format!("{error_color}{ANSI_BOLD}✗ Error:{ANSI_RESET} {message}")
            }
        };

        FormattedError { plain, rich }
    }
}

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

    #[test]
    fn test_loc_item_format() {
        assert_eq!(LocItem::field("name").format(), "name");
        assert_eq!(LocItem::index(0).format(), "[0]");
    }

    #[test]
    fn test_validation_error_format_loc() {
        let error = ValidationErrorDetail::new(
            vec![
                LocItem::field("body"),
                LocItem::field("users"),
                LocItem::index(0),
                LocItem::field("email"),
            ],
            "invalid email",
            "value_error",
        );

        assert_eq!(error.format_loc(), "body.users[0].email");
    }

    #[test]
    fn test_validation_error_empty_loc() {
        let error = ValidationErrorDetail::new(vec![], "missing field", "value_error");
        assert_eq!(error.format_loc(), "");
    }

    #[test]
    fn test_http_error_builder() {
        let error = HttpErrorInfo::new(404, "Resource not found")
            .code("NOT_FOUND")
            .path("/api/users/123")
            .method("GET");

        assert_eq!(error.status, 404);
        assert_eq!(error.detail, "Resource not found");
        assert_eq!(error.code, Some("NOT_FOUND".to_string()));
        assert_eq!(error.path, Some("/api/users/123".to_string()));
    }

    #[test]
    fn test_http_error_status_category() {
        assert_eq!(HttpErrorInfo::new(400, "").status_category(), "Bad Request");
        assert_eq!(HttpErrorInfo::new(404, "").status_category(), "Not Found");
        assert_eq!(
            HttpErrorInfo::new(500, "").status_category(),
            "Internal Server Error"
        );
        assert_eq!(
            HttpErrorInfo::new(418, "").status_category(),
            "Client Error"
        );
    }

    #[test]
    fn test_formatter_validation_plain() {
        let formatter = ErrorFormatter::new(OutputMode::Plain);
        let errors = vec![
            ValidationErrorDetail::new(
                vec![LocItem::field("body"), LocItem::field("email")],
                "invalid email format",
                "value_error.email",
            ),
            ValidationErrorDetail::new(
                vec![LocItem::field("body"), LocItem::field("age")],
                "must be positive",
                "value_error.number",
            ),
        ];

        let result = formatter.format_validation_errors(&errors);

        assert!(result.plain.contains("Validation Error"));
        assert!(result.plain.contains("2 error(s)"));
        assert!(result.plain.contains("body.email"));
        assert!(result.plain.contains("invalid email format"));
        assert!(result.plain.contains("body.age"));
        assert!(!result.plain.contains("\x1b["));
    }

    #[test]
    fn test_formatter_validation_rich_has_ansi() {
        let formatter = ErrorFormatter::new(OutputMode::Rich);
        let errors = vec![ValidationErrorDetail::new(
            vec![LocItem::field("name")],
            "required",
            "value_error",
        )];

        let result = formatter.format_validation_errors(&errors);

        assert!(result.rich.contains("\x1b["));
    }

    #[test]
    fn test_formatter_http_plain() {
        let formatter = ErrorFormatter::new(OutputMode::Plain);
        let error = HttpErrorInfo::new(404, "User not found")
            .code("USER_NOT_FOUND")
            .path("/api/users/123")
            .method("GET");

        let result = formatter.format_http_error(&error);

        assert!(result.plain.contains("HTTP 404"));
        assert!(result.plain.contains("Not Found"));
        assert!(result.plain.contains("User not found"));
        assert!(result.plain.contains("USER_NOT_FOUND"));
        assert!(result.plain.contains("GET /api/users/123"));
    }

    #[test]
    fn test_formatter_simple() {
        let formatter = ErrorFormatter::new(OutputMode::Plain);
        let result = formatter.format_simple("Something went wrong");

        assert!(result.plain.contains("Error:"));
        assert!(result.plain.contains("Something went wrong"));
    }

    #[test]
    fn test_formatter_no_codes() {
        let mut formatter = ErrorFormatter::new(OutputMode::Plain);
        formatter.show_codes = false;

        let errors = vec![ValidationErrorDetail::new(
            vec![LocItem::field("field")],
            "error",
            "error_type",
        )];

        let result = formatter.format_validation_errors(&errors);

        assert!(!result.plain.contains("error_type"));
    }
}