auditmysite 1.7.2

Resource-efficient WCAG 2.2 AA 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
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! Structured data (Schema.org) detection
//!
//! Detects JSON-LD, Microdata, and RDFa structured data.

use chromiumoxide::Page;
use serde::{Deserialize, Serialize};
use tracing::info;

use crate::error::{AuditError, Result};
use web_checks::structured_data::StructuralIssue;

/// Structured data analysis
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StructuredData {
    /// JSON-LD scripts found
    pub json_ld: Vec<JsonLdSchema>,
    /// Schema types detected
    pub types: Vec<SchemaType>,
    /// Has any structured data
    pub has_structured_data: bool,
    /// Detected schema types associated with rich-result features.
    /// Kept under its legacy field name for JSON compatibility.
    pub rich_snippets_potential: Vec<String>,
    /// Validation issues: missing required properties per schema block
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub schema_issues: Vec<SchemaIssue>,
    /// Feature-specific required/recommended property assessment per node.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rule_assessments: Vec<crate::seo::schema_rules::SchemaRuleAssessment>,
    /// Fit between visible page intent and the detected primary schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fit_assessment: Option<crate::seo::schema_fit::SchemaFitAssessment>,
    /// Conservative comparisons between visible content and JSON-LD values.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content_parity: Vec<crate::seo::schema_parity::ContentParityAssessment>,
    /// Collection-only input for page-type derivation; full visible values are
    /// intentionally not duplicated in the public JSON report.
    #[serde(skip)]
    pub(crate) visible_facts: crate::seo::schema_parity::VisibleSchemaFacts,
}

/// A required-property validation issue for a JSON-LD block
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaIssue {
    /// The @type of the affected schema block
    pub schema_type: String,
    /// Whether the missing property is required or recommended for rich-result quality
    pub severity: SchemaIssueSeverity,
    /// Machine-readable issue key
    pub issue_type: String,
    /// Canonical-English description for language-independent JSON output.
    /// PDF output re-derives localized text via [`schema_issue_text`].
    pub message: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SchemaIssueSeverity {
    Required,
    Recommended,
}

/// Localize a schema issue from its stable machine-readable key.
pub fn schema_issue_text(issue: &SchemaIssue, en: bool) -> String {
    let schema_type = if issue.schema_type.is_empty() {
        "JSON-LD"
    } else {
        issue.schema_type.as_str()
    };

    match issue.issue_type.as_str() {
        "jsonld_parse_error" => {
            if en {
                "The JSON-LD block contains invalid JSON and cannot be evaluated.".to_string()
            } else {
                "Der JSON-LD-Block enthält ungültiges JSON und kann nicht ausgewertet werden."
                    .to_string()
            }
        }
        "jsonld_invalid_root" => {
            if en {
                "The JSON-LD root must be an object or an array of objects.".to_string()
            } else {
                "Die JSON-LD-Wurzel muss ein Objekt oder eine Liste von Objekten sein.".to_string()
            }
        }
        "jsonld_missing_context" => {
            if en {
                "No schema.org @context was found; schema terms cannot be interpreted reliably."
                    .to_string()
            } else {
                "Kein schema.org-@context gefunden; die Schema-Begriffe sind nicht zuverlässig interpretierbar."
                    .to_string()
            }
        }
        "jsonld_missing_type" => {
            if en {
                "A JSON-LD node has no @type and cannot be assigned to a schema type.".to_string()
            } else {
                "Ein JSON-LD-Knoten hat keinen @type und kann keinem Schema-Typ zugeordnet werden."
                    .to_string()
            }
        }
        "jsonld_graph_not_array" => {
            if en {
                "The @graph value must be an array of JSON-LD nodes.".to_string()
            } else {
                "Der Wert von @graph muss eine Liste von JSON-LD-Knoten sein.".to_string()
            }
        }
        "jsonld_empty_document" => {
            if en {
                "The JSON-LD block contains no nodes.".to_string()
            } else {
                "Der JSON-LD-Block enthält keine Knoten.".to_string()
            }
        }
        issue_type => {
            if let Some(prop) = issue_type.strip_prefix("schema_recommended_missing_") {
                if en {
                    format!("{schema_type}: recommended property \"{prop}\" is missing")
                } else {
                    format!("{schema_type}: Empfohlenes Feld \"{prop}\" fehlt")
                }
            } else if let Some(prop) = issue_type.strip_prefix("schema_missing_") {
                if en {
                    format!("{schema_type}: required property \"{prop}\" is missing")
                } else {
                    format!("{schema_type}: Pflichtfeld \"{prop}\" fehlt")
                }
            } else {
                issue.message.clone()
            }
        }
    }
}

/// Short localized label for report tables.
pub fn schema_issue_label(issue: &SchemaIssue, en: bool) -> &'static str {
    match issue.issue_type.as_str() {
        "jsonld_parse_error" => {
            if en {
                "JSON syntax"
            } else {
                "JSON-Syntax"
            }
        }
        "jsonld_invalid_root" => {
            if en {
                "Root structure"
            } else {
                "Wurzelstruktur"
            }
        }
        "jsonld_missing_context" => {
            if en {
                "Schema context"
            } else {
                "Schema-Kontext"
            }
        }
        "jsonld_missing_type" => {
            if en {
                "Schema type"
            } else {
                "Schema-Typ"
            }
        }
        "jsonld_graph_not_array" => "@graph",
        "jsonld_empty_document" => {
            if en {
                "Empty block"
            } else {
                "Leerer Block"
            }
        }
        _ => "Schema.org",
    }
}

/// JSON-LD schema data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonLdSchema {
    /// Schema @type
    pub schema_type: String,
    /// All schema @type values found on the root object
    #[serde(default)]
    pub schema_types: Vec<String>,
    /// Raw JSON content
    pub content: serde_json::Value,
    /// Is valid JSON-LD
    pub is_valid: bool,
}

/// Known schema types
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SchemaType {
    Organization,
    LocalBusiness,
    Person,
    Article,
    BlogPosting,
    NewsArticle,
    Product,
    Offer,
    Event,
    Recipe,
    VideoObject,
    CollectionPage,
    ItemList,
    ProfilePage,
    JobPosting,
    SoftwareApplication,
    WebApplication,
    MobileApplication,
    WebPage,
    WebSite,
    BreadcrumbList,
    FAQPage,
    HowTo,
    Review,
    AggregateRating,
    Other(String),
}

impl std::str::FromStr for SchemaType {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(match s {
            "Organization" => SchemaType::Organization,
            "LocalBusiness" => SchemaType::LocalBusiness,
            "Person" => SchemaType::Person,
            "Article" => SchemaType::Article,
            "BlogPosting" => SchemaType::BlogPosting,
            "NewsArticle" => SchemaType::NewsArticle,
            "Product" => SchemaType::Product,
            "Offer" => SchemaType::Offer,
            "Event" => SchemaType::Event,
            "Recipe" => SchemaType::Recipe,
            "VideoObject" => SchemaType::VideoObject,
            "CollectionPage" => SchemaType::CollectionPage,
            "ItemList" => SchemaType::ItemList,
            "ProfilePage" => SchemaType::ProfilePage,
            "JobPosting" => SchemaType::JobPosting,
            "SoftwareApplication" => SchemaType::SoftwareApplication,
            "WebApplication" => SchemaType::WebApplication,
            "MobileApplication" => SchemaType::MobileApplication,
            "WebPage" => SchemaType::WebPage,
            "WebSite" => SchemaType::WebSite,
            "BreadcrumbList" => SchemaType::BreadcrumbList,
            "FAQPage" => SchemaType::FAQPage,
            "HowTo" => SchemaType::HowTo,
            "Review" => SchemaType::Review,
            "AggregateRating" => SchemaType::AggregateRating,
            other => SchemaType::Other(other.to_string()),
        })
    }
}

impl SchemaType {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Organization => "Organization",
            Self::LocalBusiness => "LocalBusiness",
            Self::Person => "Person",
            Self::Article => "Article",
            Self::BlogPosting => "BlogPosting",
            Self::NewsArticle => "NewsArticle",
            Self::Product => "Product",
            Self::Offer => "Offer",
            Self::Event => "Event",
            Self::Recipe => "Recipe",
            Self::VideoObject => "VideoObject",
            Self::CollectionPage => "CollectionPage",
            Self::ItemList => "ItemList",
            Self::ProfilePage => "ProfilePage",
            Self::JobPosting => "JobPosting",
            Self::SoftwareApplication => "SoftwareApplication",
            Self::WebApplication => "WebApplication",
            Self::MobileApplication => "MobileApplication",
            Self::WebPage => "WebPage",
            Self::WebSite => "WebSite",
            Self::BreadcrumbList => "BreadcrumbList",
            Self::FAQPage => "FAQPage",
            Self::HowTo => "HowTo",
            Self::Review => "Review",
            Self::AggregateRating => "AggregateRating",
            Self::Other(s) => s,
        }
    }

    pub fn is_organization_like(&self) -> bool {
        matches!(self, Self::Organization | Self::LocalBusiness)
            || matches!(
                self.as_str(),
                "Airline"
                    | "Consortium"
                    | "Corporation"
                    | "EducationalOrganization"
                    | "FundingScheme"
                    | "GovernmentOrganization"
                    | "LibrarySystem"
                    | "LocalBusiness"
                    | "MedicalOrganization"
                    | "NGO"
                    | "NewsMediaOrganization"
                    | "OnlineBusiness"
                    | "PerformingGroup"
                    | "Project"
                    | "ResearchOrganization"
                    | "SearchRescueOrganization"
                    | "SportsOrganization"
                    | "WorkersUnion"
                    | "LegalService"
                    | "ProfessionalService"
            )
    }

    /// The schema type behind a possible search feature — the bare type name,
    /// never a promise about the result it might produce. Detecting `FAQPage`
    /// says the markup is present, not that Google renders an FAQ rich result
    /// for it, so the label no longer carries "Rich Snippet". Language-neutral;
    /// stored in the JSON report verbatim.
    pub fn rich_snippet_type(&self) -> Option<&'static str> {
        match self {
            SchemaType::Article | SchemaType::BlogPosting | SchemaType::NewsArticle => {
                Some("Article")
            }
            SchemaType::Product => Some("Product"),
            SchemaType::Recipe => Some("Recipe"),
            SchemaType::Event => Some("Event"),
            SchemaType::FAQPage => Some("FAQPage"),
            // Google removed HowTo rich results; keep the schema in the
            // inventory without presenting it as a current search feature.
            SchemaType::HowTo => None,
            SchemaType::Review | SchemaType::AggregateRating => Some("Review"),
            SchemaType::BreadcrumbList => Some("BreadcrumbList"),
            SchemaType::VideoObject => Some("VideoObject"),
            SchemaType::ProfilePage => Some("ProfilePage"),
            SchemaType::JobPosting => Some("JobPosting"),
            SchemaType::SoftwareApplication
            | SchemaType::WebApplication
            | SchemaType::MobileApplication => Some("SoftwareApplication"),
            SchemaType::LocalBusiness => Some("LocalBusiness"),
            _ => None,
        }
    }
}

/// Detect structured data on a page
pub async fn detect_structured_data(page: &Page) -> Result<StructuredData> {
    info!("Detecting structured data...");

    let js_code = r#"
    (() => {
        const result = { jsonLd: [], microdata: false, rdfa: false };

        // Return raw script contents. Rust owns parsing and normalization so
        // top-level arrays, @graph and parse failures share one testable path.
        document.querySelectorAll('script[type="application/ld+json"]').forEach(script => {
            result.jsonLd.push(script.textContent || '');
        });

        // Check for microdata
        result.microdata = document.querySelectorAll('[itemscope]').length > 0;

        // Check for RDFa
        result.rdfa = document.querySelectorAll('[typeof], [property]').length > 0;

        return JSON.stringify(result);
    })()
    "#;

    let js_result = page
        .evaluate(js_code)
        .await
        .map_err(|e| AuditError::CdpError(format!("Structured data detection failed: {}", e)))?;

    let json_str = js_result.value().and_then(|v| v.as_str()).unwrap_or("{}");

    let parsed: serde_json::Value = serde_json::from_str(json_str).unwrap_or_default();
    let scripts: Vec<String> = parsed["jsonLd"]
        .as_array()
        .map(|values| {
            values
                .iter()
                .filter_map(|value| value.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    let mut structured_data = analyze_structured_data_payloads(
        &scripts,
        parsed["microdata"].as_bool().unwrap_or(false),
        parsed["rdfa"].as_bool().unwrap_or(false),
    );
    structured_data.visible_facts =
        crate::seo::schema_parity::extract_visible_schema_facts(page).await?;
    structured_data.content_parity = crate::seo::schema_parity::assess_content_parity(
        &structured_data.json_ld,
        &structured_data.visible_facts,
    );

    info!(
        "Structured data: {} JSON-LD schemas, {} types, {} rich snippet opportunities",
        structured_data
            .json_ld
            .iter()
            .filter(|schema| schema.is_valid && !schema.schema_types.is_empty())
            .count(),
        structured_data.types.len(),
        structured_data.rich_snippets_potential.len()
    );

    Ok(structured_data)
}

pub(crate) fn analyze_structured_data_payloads(
    scripts: &[String],
    has_microdata: bool,
    has_rdfa: bool,
) -> StructuredData {
    let mut json_ld = Vec::new();
    let mut schema_issues = Vec::new();

    for (block_index, (raw, block)) in scripts
        .iter()
        .zip(web_checks::structured_data::parse_blocks(scripts))
        .enumerate()
    {
        if block.json_error.is_some() || block.issues.contains(&StructuralIssue::EmptyScript) {
            json_ld.push(JsonLdSchema {
                schema_type: String::new(),
                schema_types: Vec::new(),
                content: serde_json::json!({
                    "raw": raw.chars().take(200).collect::<String>()
                }),
                is_valid: false,
            });
        }
        for issue in &block.issues {
            schema_issues.push(structural_issue(*issue, block_index, &block));
        }
        json_ld.extend(block.nodes.into_iter().map(|node| JsonLdSchema {
            schema_type: node.types.first().cloned().unwrap_or_default(),
            schema_types: node.types,
            content: node.content,
            is_valid: true,
        }));
    }

    let mut types = Vec::new();
    let mut rich_snippets_potential = Vec::new();
    for schema in json_ld.iter().filter(|schema| schema.is_valid) {
        for type_str in &schema.schema_types {
            let schema_type: SchemaType = type_str
                .parse()
                .unwrap_or(SchemaType::Other(type_str.to_string()));
            if let Some(rich_snippet) = schema_type.rich_snippet_type() {
                if !rich_snippets_potential
                    .iter()
                    .any(|item| item == rich_snippet)
                {
                    rich_snippets_potential.push(rich_snippet.to_string());
                }
            }
            if !types.contains(&schema_type) {
                types.push(schema_type);
            }
        }
    }

    let rule_assessments = build_rule_assessments(
        &json_ld,
        crate::seo::schema_rules::ProductRuleContext::Indeterminate,
    );
    schema_issues.extend(rule_assessments.iter().flat_map(rule_assessment_issues));

    StructuredData {
        json_ld,
        types,
        has_structured_data: !scripts.is_empty() || has_microdata || has_rdfa,
        rich_snippets_potential,
        schema_issues,
        rule_assessments,
        fit_assessment: None,
        content_parity: Vec::new(),
        visible_facts: crate::seo::schema_parity::VisibleSchemaFacts::default(),
    }
}

pub(crate) fn refresh_rule_assessments(
    structured_data: &mut StructuredData,
    product_context: crate::seo::schema_rules::ProductRuleContext,
) {
    structured_data
        .schema_issues
        .retain(|issue| !issue.issue_type.starts_with("schema_rule_"));
    structured_data.rule_assessments =
        build_rule_assessments(&structured_data.json_ld, product_context);
    structured_data.schema_issues.extend(
        structured_data
            .rule_assessments
            .iter()
            .flat_map(rule_assessment_issues),
    );
}

fn build_rule_assessments(
    schemas: &[JsonLdSchema],
    product_context: crate::seo::schema_rules::ProductRuleContext,
) -> Vec<crate::seo::schema_rules::SchemaRuleAssessment> {
    schemas
        .iter()
        .enumerate()
        .filter(|(_, schema)| schema.is_valid)
        .flat_map(|(node_index, schema)| {
            schema.schema_types.iter().flat_map(move |schema_type| {
                crate::seo::schema_rules::assess_node(
                    node_index,
                    schema_type,
                    &schema.content,
                    product_context,
                )
            })
        })
        .collect()
}

fn rule_assessment_issues(
    assessment: &crate::seo::schema_rules::SchemaRuleAssessment,
) -> Vec<SchemaIssue> {
    if assessment.requirement_status
        != crate::seo::schema_rules::SchemaRequirementStatus::MissingRequiredProperties
    {
        return Vec::new();
    }

    assessment
        .missing_required
        .iter()
        .map(|property| SchemaIssue {
            schema_type: assessment.schema_type.clone(),
            severity: SchemaIssueSeverity::Required,
            issue_type: format!(
                "schema_rule_missing_{}_{}",
                assessment.feature.key(),
                property
                    .chars()
                    .map(|character| {
                        if character.is_ascii_alphanumeric() {
                            character
                        } else {
                            '_'
                        }
                    })
                    .collect::<String>()
                    .trim_matches('_')
            ),
            message: format!(
                "{}: required property condition \"{}\" is not met for {}",
                assessment.schema_type,
                property,
                crate::seo::schema_rules::feature_label(assessment.feature, true)
            ),
        })
        .collect()
}

/// A structural problem from `web_checks::structured_data` as a stored
/// schema issue: stable key for the report, canonical English message (#406).
fn structural_issue(
    issue: StructuralIssue,
    block_index: usize,
    block: &web_checks::structured_data::Block,
) -> SchemaIssue {
    let block_no = block_index + 1;
    let (issue_type, message) = match issue {
        StructuralIssue::InvalidJson | StructuralIssue::EmptyScript => (
            "jsonld_parse_error",
            format!(
                "JSON-LD block {block_no} contains invalid JSON: {}",
                block
                    .json_error
                    .as_deref()
                    .unwrap_or("EOF while parsing a value at line 1 column 0")
            ),
        ),
        StructuralIssue::InvalidRoot => (
            "jsonld_invalid_root",
            format!("JSON-LD block {block_no} has a root or array entry that is not an object"),
        ),
        StructuralIssue::EmptyDocument => (
            "jsonld_empty_document",
            format!("JSON-LD block {block_no} contains no nodes"),
        ),
        StructuralIssue::GraphNotArray => (
            "jsonld_graph_not_array",
            "JSON-LD @graph value is not an array".to_string(),
        ),
        // Not schema.org, no context at all, or a @graph container without
        // one: the report treats all three as a missing schema.org context.
        StructuralIssue::MissingContext
        | StructuralIssue::NonSchemaOrgContext
        | StructuralIssue::GraphWithoutContext => (
            "jsonld_missing_context",
            "No schema.org @context found for JSON-LD node".to_string(),
        ),
        StructuralIssue::MissingType => (
            "jsonld_missing_type",
            "JSON-LD node has no @type".to_string(),
        ),
    };
    SchemaIssue {
        schema_type: "JSON-LD".to_string(),
        severity: SchemaIssueSeverity::Required,
        issue_type: issue_type.to_string(),
        message,
    }
}

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

    #[test]
    fn astro_structured_data_exports_work_inline_and_as_graph_without_runtime_dependency() {
        let fixture: serde_json::Value = serde_json::from_str(include_str!(
            "../../tests/fixtures/astro_structured_data_components.json"
        ))
        .unwrap();
        let components = fixture["components"].as_array().unwrap();
        let inline = fixture["inline"].as_array().unwrap();
        assert_eq!(components.len(), 18);
        assert_eq!(inline.len(), 17); // SchemaGraph is the graph container.

        for item in inline {
            let payload = item["payload"].to_string();
            let data = analyze_structured_data_payloads(&[payload], false, false);
            assert!(
                !data.json_ld.is_empty(),
                "{} inline fixture",
                item["component"]
            );
            assert!(!data
                .schema_issues
                .iter()
                .any(|issue| issue.issue_type.starts_with("jsonld_")));
        }

        let graph = fixture["useGraph"].to_string();
        let data = analyze_structured_data_payloads(&[graph], false, false);
        assert_eq!(data.json_ld.len(), inline.len());
        assert!(!data
            .schema_issues
            .iter()
            .any(|issue| issue.issue_type.starts_with("jsonld_")));
    }

    #[test]
    fn test_schema_type_from_str() {
        assert_eq!(
            "Article".parse::<SchemaType>().unwrap(),
            SchemaType::Article
        );
        assert_eq!(
            "Product".parse::<SchemaType>().unwrap(),
            SchemaType::Product
        );
        assert!(matches!(
            "CustomType".parse::<SchemaType>().unwrap(),
            SchemaType::Other(_)
        ));
    }

    #[test]
    fn test_rich_snippet_type() {
        assert_eq!(SchemaType::Article.rich_snippet_type(), Some("Article"));
        assert_eq!(SchemaType::Product.rich_snippet_type(), Some("Product"));
        assert_eq!(SchemaType::Organization.rich_snippet_type(), None);
        assert_eq!(SchemaType::HowTo.rich_snippet_type(), None);
    }

    #[test]
    fn organization_like_accepts_schema_subtypes() {
        assert!(SchemaType::Organization.is_organization_like());
        assert!(SchemaType::LocalBusiness.is_organization_like());
        assert!(SchemaType::Other("LegalService".into()).is_organization_like());
        assert!(SchemaType::Other("MedicalOrganization".into()).is_organization_like());
        assert!(!SchemaType::Person.is_organization_like());
        assert!(!SchemaType::WebSite.is_organization_like());
    }

    #[test]
    fn product_schema_accepts_review_instead_of_offer() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!({
                "@context": "https://schema.org",
                "@type": "Product",
                "name": "Audit",
                "review": {"@type": "Review", "author": {"@type": "Person", "name": "Ada"}}
            })
            .to_string()],
            false,
            false,
        );

        assert!(!data.schema_issues.iter().any(|issue| issue
            .issue_type
            .starts_with("schema_rule_missing_product_snippet")));
    }

    #[test]
    fn article_schema_reports_recommended_properties_separately() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!({
                "@context": "https://schema.org",
                "@type": "Article",
                "headline": "Accessibility audit",
                "image": "https://example.com/article.png",
                "author": { "@type": "Person", "name": "Ada" },
                "datePublished": "2026-01-01"
            })
            .to_string()],
            false,
            false,
        );

        assert!(!data
            .schema_issues
            .iter()
            .any(|issue| issue.severity == SchemaIssueSeverity::Required));
        assert!(data.rule_assessments[0]
            .missing_recommended
            .contains(&"dateModified".to_string()));
    }

    #[test]
    fn empty_schema_properties_count_as_missing() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!({
                "@context": "https://schema.org",
                "@type": "BreadcrumbList",
                "itemListElement": []
            })
            .to_string()],
            false,
            false,
        );

        assert!(data.schema_issues.iter().any(|issue| {
            issue.severity == SchemaIssueSeverity::Required
                && issue
                    .issue_type
                    .starts_with("schema_rule_missing_breadcrumb_itemListElement")
        }));
    }

    #[test]
    fn graph_nodes_are_normalized_once_without_container_false_positives() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!({
                "@context": "https://schema.org",
                "@graph": [
                    {
                        "@type": "Product",
                        "name": "Gadget",
                        "image": "https://example.com/gadget.jpg",
                        "offers": {"@type": "Offer", "price": "29.99", "priceCurrency": "EUR"}
                    },
                    {
                        "@type": "BreadcrumbList",
                        "itemListElement": [
                            {"@type": "ListItem", "position": 1, "name": "Home", "item": "https://example.com"},
                            {"@type": "ListItem", "position": 2, "name": "Products"}
                        ]
                    }
                ]
            })
            .to_string()],
            false,
            false,
        );

        assert_eq!(data.json_ld.len(), 2);
        assert_eq!(data.json_ld[0].schema_type, "Product");
        assert_eq!(data.json_ld[1].schema_type, "BreadcrumbList");
        assert!(!data
            .schema_issues
            .iter()
            .any(|issue| issue.severity == SchemaIssueSeverity::Required));
    }

    #[test]
    fn top_level_array_is_expanded_into_individual_nodes() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!([
                {
                    "@context": "https://schema.org",
                    "@type": "WebSite",
                    "name": "Example",
                    "url": "https://example.com"
                },
                {
                    "@context": "https://schema.org",
                    "@type": "WebPage",
                    "name": "About",
                    "url": "https://example.com/about"
                }
            ])
            .to_string()],
            false,
            false,
        );

        assert_eq!(data.json_ld.len(), 2);
        assert_eq!(data.types, vec![SchemaType::WebSite, SchemaType::WebPage]);
    }

    #[test]
    fn invalid_json_is_preserved_as_a_visible_structural_issue() {
        let data = analyze_structured_data_payloads(
            &[r#"{"@context":"https://schema.org","@type":"Product""#.to_string()],
            false,
            false,
        );

        assert!(data.has_structured_data);
        assert_eq!(data.json_ld.len(), 1);
        assert!(!data.json_ld[0].is_valid);
        assert!(data
            .schema_issues
            .iter()
            .any(|issue| issue.issue_type == "jsonld_parse_error"));
        assert!(data.schema_issues[0].message.starts_with("JSON-LD block 1"));
    }

    #[test]
    fn stored_schema_issue_messages_remain_canonical_english() {
        let data = analyze_structured_data_payloads(
            &[
                serde_json::json!({
                    "@context": "https://schema.org",
                    "@type": "Product",
                    "name": "Incomplete product"
                })
                .to_string(),
                r#"{"@type":"Product""#.to_string(),
            ],
            false,
            false,
        );

        assert!(data
            .schema_issues
            .iter()
            .all(|issue| !issue.message.contains("Pflichtfeld")
                && !issue.message.contains("Empfohlenes Feld")
                && !issue.message.contains("ungültig")));
    }

    #[test]
    fn full_schema_type_iri_is_normalized_to_known_type() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!({
                "@context": "https://schema.org",
                "@type": "https://schema.org/Product",
                "name": "Gadget",
                "image": "https://example.com/gadget.jpg",
                "offers": {"@type": "Offer", "price": "29.99", "priceCurrency": "EUR"}
            })
            .to_string()],
            false,
            false,
        );

        assert_eq!(data.json_ld[0].schema_type, "Product");
        assert_eq!(data.types, vec![SchemaType::Product]);
    }

    #[test]
    fn missing_context_and_type_are_reported_separately() {
        let data = analyze_structured_data_payloads(
            &[serde_json::json!({"name": "Untyped node"}).to_string()],
            false,
            false,
        );

        let issue_types: Vec<_> = data
            .schema_issues
            .iter()
            .map(|issue| issue.issue_type.as_str())
            .collect();
        assert!(issue_types.contains(&"jsonld_missing_context"));
        assert!(issue_types.contains(&"jsonld_missing_type"));
    }
}