auditmysite 0.9.27

Resource-efficient WCAG 2.1 Accessibility Checker in 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
//! JSON Output Formatter
//!
//! Generates machine-readable JSON reports from the NormalizedReport model.
//! Uses the same score source as PDF output — no more inconsistencies.

use chrono::{DateTime, Utc};
use serde::Serialize;

use crate::audit::normalized::NormalizedReport;
use crate::audit::{AuditReport, BatchReport};
use crate::error::Result;
use crate::output::builder::build_batch_presentation;
use crate::output::builder::build_view_model;
use crate::output::explanations::get_explanation;
use crate::output::module::ReportModule as _;
use crate::output::report_model::{ReportConfig, UrlMatrixRow};

/// Generate JSON output from a normalized report
pub fn format_json_normalized(
    normalized: &NormalizedReport,
    report: &AuditReport,
    pretty: bool,
) -> Result<String> {
    let json_report = JsonReport::from_normalized(normalized, report);
    let output = if pretty {
        serde_json::to_string_pretty(&json_report)
    } else {
        serde_json::to_string(&json_report)
    };

    output.map_err(|e| crate::error::AuditError::OutputError {
        reason: format!("JSON serialization failed: {}", e),
    })
}

/// Generate JSON output from cached normalized data only.
pub fn format_json_cached(normalized: &NormalizedReport, pretty: bool) -> Result<String> {
    #[derive(Debug, Serialize)]
    struct CachedJsonReport<'a> {
        metadata: ReportMetadata,
        report: &'a NormalizedReport,
    }

    let payload = CachedJsonReport {
        metadata: ReportMetadata {
            tool: format!("auditmysite v{}", env!("CARGO_PKG_VERSION")),
            timestamp: normalized.timestamp,
            wcag_level: normalized.wcag_level.to_string(),
            execution_time_ms: normalized.duration_ms,
        },
        report: normalized,
    };

    let output = if pretty {
        serde_json::to_string_pretty(&payload)
    } else {
        serde_json::to_string(&payload)
    };

    output.map_err(|e| crate::error::AuditError::OutputError {
        reason: format!("JSON serialization failed: {}", e),
    })
}

/// Generate deterministic JSON output for batch reports.
pub fn format_json_batch(batch_report: &BatchReport, pretty: bool) -> Result<String> {
    let normalized_reports: Vec<NormalizedReport> = batch_report
        .reports
        .iter()
        .map(crate::audit::normalize)
        .collect();

    let presentation = build_batch_presentation(batch_report);

    let payload = BatchJsonReport {
        metadata: ReportMetadata {
            tool: format!("auditmysite v{}", env!("CARGO_PKG_VERSION")),
            timestamp: batch_report_timestamp(batch_report),
            wcag_level: normalized_reports
                .first()
                .map(|report| report.wcag_level.to_string())
                .unwrap_or_else(|| "mixed".to_string()),
            execution_time_ms: batch_report.total_duration_ms,
        },
        summary: &batch_report.summary,
        crawl_diagnostics: batch_report.crawl_diagnostics.as_ref(),
        errors: &batch_report.errors,
        url_matrix: presentation.url_matrix,
        reports: normalized_reports,
    };

    let output = if pretty {
        serde_json::to_string_pretty(&payload)
    } else {
        serde_json::to_string(&payload)
    };

    output.map_err(|e| crate::error::AuditError::OutputError {
        reason: format!("JSON serialization failed: {}", e),
    })
}

/// Extended JSON report with metadata + normalized data + module details
#[derive(Debug, Serialize)]
pub struct JsonReport {
    /// Report metadata
    pub metadata: ReportMetadata,
    /// Normalized audit results (score, grade, certificate, findings with taxonomy)
    pub report: NormalizedReport,
    /// AI/LLM fix guidance — one entry per finding group with problem description,
    /// user impact, root cause, recommendation, and code examples
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub fix_guidance: Vec<FixGuidance>,
    /// Module detail data (performance, SEO, security, mobile)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub performance: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seo: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mobile: Option<serde_json::Value>,
    /// UX analysis (CTA clarity, visual hierarchy, trust signals, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ux: Option<serde_json::Value>,
    /// Journey analysis (entry clarity, orientation, navigation, interaction, conversion)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub journey: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub confidence_summary: Vec<OutputConfidenceSignal>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<OutputCapabilitySignal>,
    /// Dark mode support analysis
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dark_mode: Option<serde_json::Value>,
    /// Source quality analysis (Substanz / Konsistenz / Autorität)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_quality: Option<serde_json::Value>,
    /// AI visibility analysis (LLM-Readability, Citation, Chunks, Knowledge Graph, Policy)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ai_visibility: Option<serde_json::Value>,
    /// Historical timeline for this URL (score trend, deltas, recent snapshots)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub history: Option<serde_json::Value>,
}

/// AI-oriented fix guidance for a single finding group
#[derive(Debug, Serialize)]
pub struct FixGuidance {
    pub rule_id: String,
    pub title: String,
    pub wcag_criterion: String,
    pub severity: String,
    pub occurrence_count: usize,
    pub problem: String,
    pub user_impact: String,
    pub typical_cause: String,
    pub recommendation: String,
    pub technical_note: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_example: Option<CodeExample>,
    pub affected_selectors: Vec<String>,
}

/// Bad/good code example pair
#[derive(Debug, Serialize)]
pub struct CodeExample {
    pub bad: String,
    pub good: String,
}

#[derive(Debug, Serialize)]
pub struct OutputConfidenceSignal {
    pub signal: String,
    pub assessment: String,
}

#[derive(Debug, Serialize)]
pub struct OutputCapabilitySignal {
    pub signal: String,
    pub source: String,
    pub confidence: String,
    pub surfaces: Vec<String>,
    pub note: String,
}

/// Report metadata for JSON output
#[derive(Debug, Serialize)]
pub struct ReportMetadata {
    /// Tool name and version
    pub tool: String,
    /// Timestamp when report was generated
    pub timestamp: DateTime<Utc>,
    /// WCAG conformance level checked
    pub wcag_level: String,
    /// Total execution time in milliseconds
    pub execution_time_ms: u64,
}

#[derive(Debug, Serialize)]
struct BatchJsonReport<'a> {
    pub metadata: ReportMetadata,
    pub summary: &'a crate::audit::BatchSummary,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crawl_diagnostics: Option<&'a crate::audit::CrawlDiagnostics>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: &'a Vec<crate::audit::BatchError>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub url_matrix: Vec<UrlMatrixRow>,
    pub reports: Vec<NormalizedReport>,
}

impl JsonReport {
    /// Create a JSON report from normalized data + raw module data
    pub fn from_normalized(normalized: &NormalizedReport, raw: &AuditReport) -> Self {
        // Build AI fix guidance from explanations + finding data
        let fix_guidance = Self::build_fix_guidance(normalized);
        let vm = build_view_model(normalized, &ReportConfig::default());

        Self {
            metadata: ReportMetadata {
                tool: format!("auditmysite v{}", env!("CARGO_PKG_VERSION")),
                timestamp: raw.timestamp,
                wcag_level: normalized.wcag_level.to_string(),
                execution_time_ms: normalized.duration_ms,
            },
            report: normalized.clone(),
            fix_guidance,
            performance: raw.performance.as_ref().map(|m| m.to_json()),
            seo: raw.seo.as_ref().map(|m| m.to_json()),
            security: raw.security.as_ref().map(|m| m.to_json()),
            mobile: raw.mobile.as_ref().map(|m| m.to_json()),
            ux: raw.ux.as_ref().map(|m| m.to_json()),
            journey: raw.journey.as_ref().map(|m| m.to_json()),
            dark_mode: raw.dark_mode.as_ref().map(|m| m.to_json()),
            source_quality: raw.source_quality.as_ref().map(|m| m.to_json()),
            ai_visibility: raw.ai_visibility.as_ref().map(|m| m.to_json()),
            confidence_summary: vm
                .methodology
                .confidence_summary
                .iter()
                .map(|(signal, assessment)| OutputConfidenceSignal {
                    signal: signal.clone(),
                    assessment: assessment.clone(),
                })
                .collect(),
            capabilities: vm
                .methodology
                .capabilities
                .iter()
                .map(|cap| OutputCapabilitySignal {
                    signal: cap.signal.clone(),
                    source: cap.source.clone(),
                    confidence: cap.confidence.clone(),
                    surfaces: cap.surfaces.clone(),
                    note: cap.note.clone(),
                })
                .collect(),
            history: None,
        }
    }

    /// Build fix guidance entries from normalized findings + explanation database
    fn build_fix_guidance(normalized: &NormalizedReport) -> Vec<FixGuidance> {
        normalized
            .findings
            .iter()
            .map(|finding| {
                let expl = get_explanation(&finding.rule_id);

                // Collect unique selectors from occurrences
                let mut seen = std::collections::HashSet::new();
                let affected_selectors: Vec<String> = finding
                    .occurrences
                    .iter()
                    .filter_map(|o| o.selector.clone())
                    .filter(|s| {
                        (s.contains('.')
                            || s.contains('#')
                            || s.contains('[')
                            || s.contains('>')
                            || s.contains(' '))
                            && seen.insert(s.clone())
                    })
                    .take(10)
                    .collect();

                let code_example = expl.and_then(|e| match (e.example_bad, e.example_good) {
                    (Some(bad), Some(good)) => Some(CodeExample {
                        bad: bad.to_string(),
                        good: good.to_string(),
                    }),
                    _ => None,
                });

                FixGuidance {
                    rule_id: finding.rule_id.clone(),
                    title: expl
                        .map(|e| e.customer_title.to_string())
                        .unwrap_or_else(|| finding.title.clone()),
                    wcag_criterion: finding.wcag_criterion.clone(),
                    severity: format!("{:?}", finding.severity).to_lowercase(),
                    occurrence_count: finding.occurrence_count,
                    problem: expl
                        .map(|e| e.customer_description.to_string())
                        .unwrap_or_else(|| finding.description.clone()),
                    user_impact: expl
                        .map(|e| e.user_impact.to_string())
                        .unwrap_or_else(|| finding.user_impact.clone()),
                    typical_cause: expl
                        .map(|e| e.typical_cause.to_string())
                        .unwrap_or_default(),
                    recommendation: expl
                        .map(|e| e.recommendation.to_string())
                        .unwrap_or_default(),
                    technical_note: expl
                        .map(|e| e.technical_note.to_string())
                        .unwrap_or_default(),
                    code_example,
                    affected_selectors,
                }
            })
            .collect()
    }

    /// Serialize to JSON string
    pub fn to_json(&self, pretty: bool) -> Result<String> {
        let output = if pretty {
            serde_json::to_string_pretty(self)
        } else {
            serde_json::to_string(self)
        };

        output.map_err(|e| crate::error::AuditError::OutputError {
            reason: format!("JSON serialization failed: {}", e),
        })
    }
}

fn batch_report_timestamp(batch_report: &BatchReport) -> DateTime<Utc> {
    batch_report
        .reports
        .iter()
        .map(|report| report.timestamp)
        .max()
        .unwrap_or(DateTime::<Utc>::UNIX_EPOCH)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::normalized::normalize;
    use crate::cli::WcagLevel;
    use crate::wcag::WcagResults;

    #[test]
    fn test_json_report_normalized() {
        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            WcagResults::new(),
            500,
        );
        let normalized = normalize(&report);
        let output = format_json_normalized(&normalized, &report, true).unwrap();

        assert!(output.contains("example.com"));
        assert!(output.contains("\"score\": 100"));
        assert!(output.contains("\"grade\": \"A\""));
        assert!(output.contains("\"certificate\": \"SEHR GUT\""));
        assert!(output.contains("\"severity_counts\""));
    }

    #[test]
    fn test_json_has_taxonomy_fields() {
        use crate::taxonomy::Severity;
        use crate::wcag::Violation;

        let mut results = WcagResults::new();
        results.add_violation(Violation::new(
            "1.1.1",
            "Non-text Content",
            WcagLevel::A,
            Severity::High,
            "Missing alt",
            "n1",
        ));

        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            500,
        );
        let normalized = normalize(&report);
        let output = format_json_normalized(&normalized, &report, true).unwrap();

        assert!(output.contains("\"dimension\""));
        assert!(output.contains("\"subcategory\""));
        assert!(output.contains("\"issue_class\""));
        assert!(output.contains("\"aggregation_key\""));
        assert!(output.contains("\"user_impact\""));
    }

    #[test]
    fn test_json_score_matches_normalized() {
        use crate::taxonomy::Severity;
        use crate::wcag::Violation;

        let mut results = WcagResults::new();
        results.add_violation(Violation::new(
            "1.1.1",
            "Alt",
            WcagLevel::A,
            Severity::High,
            "Missing",
            "n1",
        ));

        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            500,
        );
        let normalized = normalize(&report);
        let json_report = JsonReport::from_normalized(&normalized, &report);

        // JSON score must equal normalized score
        assert_eq!(json_report.report.score, normalized.score);
        assert_eq!(json_report.report.grade, normalized.grade);
        assert_eq!(json_report.report.certificate, normalized.certificate);
    }

    #[test]
    fn test_json_violations_match_severity_counts() {
        use crate::taxonomy::Severity;
        use crate::wcag::Violation;

        let mut results = WcagResults::new();
        // Three violations across two rules
        for node in ["n1", "n2", "n3"] {
            results.add_violation(Violation::new(
                "1.1.1",
                "Alt",
                WcagLevel::A,
                Severity::High,
                "Missing alt",
                node,
            ));
        }
        results.add_violation(Violation::new(
            "1.4.3",
            "Contrast",
            WcagLevel::AA,
            Severity::High,
            "Low contrast",
            "n4",
        ));

        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            500,
        );
        let normalized = normalize(&report);
        let json_report = JsonReport::from_normalized(&normalized, &report);

        // severity_counts.total must equal the sum of occurrences across all findings
        let occurrence_total: usize = json_report
            .report
            .findings
            .iter()
            .map(|f| f.occurrences.len())
            .sum();
        assert_eq!(
            json_report.report.severity_counts.total, occurrence_total,
            "severity_counts.total ({}) must equal sum of finding occurrences ({})",
            json_report.report.severity_counts.total, occurrence_total,
        );

        // Every finding must have at least one occurrence
        for finding in &json_report.report.findings {
            assert!(
                !finding.occurrences.is_empty(),
                "Finding {} has no occurrences",
                finding.rule_id
            );
        }

        // severity_counts breakdown must be consistent
        let high_from_findings: usize = json_report
            .report
            .findings
            .iter()
            .filter(|f| f.severity == crate::wcag::Severity::High)
            .map(|f| f.occurrences.len())
            .sum();
        assert_eq!(json_report.report.severity_counts.high, high_from_findings);
    }

    #[test]
    fn test_all_active_modules_present_in_json() {
        use crate::output::module::active_modules;
        use crate::performance::{PerformanceGrade, PerformanceScore, WebVitals};

        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            WcagResults::new(),
            500,
        )
        .with_performance(crate::audit::PerformanceResults {
            vitals: WebVitals::default(),
            score: PerformanceScore {
                overall: 80,
                grade: PerformanceGrade::Gold,
                lcp_score: Some(20),
                fcp_score: Some(20),
                cls_score: Some(20),
                interactivity_score: Some(20),
                metrics_available: 4,
            },
            render_blocking: None,
            content_weight: None,
        })
        .with_seo(crate::seo::SeoAnalysis::default())
        .with_security(crate::security::SecurityAnalysis {
            score: 90,
            grade: "A".to_string(),
            headers: Default::default(),
            ssl: Default::default(),
            issues: vec![],
            recommendations: vec![],
        })
        .with_ux(crate::ux::analyze_ux(&crate::AXTree::new()))
        .with_journey(crate::journey::analyze_journey(&crate::AXTree::new()));

        let active_keys: Vec<&'static str> = active_modules(&report)
            .into_iter()
            .map(|(key, _)| key)
            .collect();

        let normalized = normalize(&report);
        let json_report = JsonReport::from_normalized(&normalized, &report);
        let json_str = json_report.to_json(true).unwrap();
        let json_value: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        for key in &active_keys {
            assert!(
                json_value.get(key).is_some(),
                "Module '{}' is active but missing from JSON output — add it to JsonReport",
                key
            );
        }
    }
}