accent-proust 0.11.0

A Rust implementation of the Markdoc language: parse, validate, transform, render, and format.
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
//! Upstream's `src/validator.test.ts`, ported.
//!
//! The conformance corpus grades 9 of its 105 cases on validation and 96 on a
//! rendered tree, so it measures the validator barely and by accident. This file
//! is the validator's real gate: it is the assertions upstream wrote about the
//! code being transliterated, which is the only thing that can tell a faithful
//! port from a plausible one.
//!
//! # Two upstream tests are deliberately absent
//!
//! - **"should allow async validators"** asserts that an `async validate()` on a
//!   schema is awaited. `DIVERGENCES.md` entry 3 declines async hooks, so the
//!   test asserts the thing this crate does not do.
//! - **"should validate partial file attributes"** needs the built-in `partial`
//!   tag, which is schema *content* and belongs to the transform stage. It
//!   lands with the built-in schemas, not here.
//!
//! # Where the assertions are stronger than upstream's
//!
//! Upstream mostly asserts with a `toDeepEqualSubset` matcher, which checks that
//! the reported errors contain the listed ones. These tests compare the full
//! sequence of `(id, message)` pairs instead. That is stricter on purpose: the
//! order errors are reported in is observable, and a port that produced the
//! right errors in the wrong order would pass a subset check.
//!
//! # The node schemas here are a stand-in
//!
//! Upstream's `Markdoc.validate` merges its built-in node schemas (`src/schema.ts`)
//! into the caller's config before validating, which is why its tests can pass a
//! config naming only tags. Those schemas are schema *content* and belong to the
//! transform stage; until they land, [`nodes`] declares the few node types these
//! tests actually reach, and only the fields validation reads -- no `render`, no
//! `transform`. Every declaration is copied from upstream's, so a test that
//! passes here passes for upstream's reason rather than a convenient one. When
//! the built-ins land, this function is deleted and they take its place.

use std::sync::Arc;

use indexmap::IndexMap;

use accent_proust::ast::{ErrorLevel, Node, NodeType, ValidationError, Value};
use accent_proust::parse::parse;
use accent_proust::validate::{
    AttributeType, Config, ConfigFunction, MapSchemaSource, RenderPolicy, Schema, SchemaAttribute,
    ValidationType, Variables, validate_tree,
};

/// The built-in node schemas these tests reach, standing in for upstream's.
///
/// See the module docs for why this exists and when it goes away. `children` is
/// left unrestricted rather than copying upstream's lists, because no test here
/// exercises a nesting rule and an unenforced list is easier to remove honestly
/// than a half-copied one.
fn nodes() -> IndexMap<NodeType, Schema> {
    let mut nodes = IndexMap::new();
    nodes.insert(NodeType::Document, Schema::new());
    nodes.insert(NodeType::Paragraph, Schema::new());
    nodes.insert(NodeType::Inline, Schema::new());
    nodes.insert(
        NodeType::Text,
        Schema::new().attribute("content", hidden(required(string()))),
    );
    nodes.insert(
        NodeType::Heading,
        Schema::new().attribute("level", hidden(required(number()))),
    );
    nodes.insert(
        NodeType::Fence,
        Schema::new()
            .attribute("content", hidden(required(string())))
            .attribute("language", string()),
    );
    nodes
}

/// A config with the node schemas above and nothing else.
fn config() -> Config<'static> {
    Config::new().with_schemas(Arc::new(schemas(vec![])))
}

fn string() -> SchemaAttribute {
    typed(ValidationType::String)
}

fn number() -> SchemaAttribute {
    typed(ValidationType::Number)
}

fn typed(attribute_type: ValidationType) -> SchemaAttribute {
    SchemaAttribute {
        attribute_type: Some(attribute_type),
        ..SchemaAttribute::default()
    }
}

fn required(mut attribute: SchemaAttribute) -> SchemaAttribute {
    attribute.required = true;
    attribute
}

fn hidden(mut attribute: SchemaAttribute) -> SchemaAttribute {
    attribute.render = RenderPolicy::Hidden;
    attribute
}

/// The node schemas above plus `pairs` as tags, as one source.
fn schemas(pairs: Vec<(&str, Schema)>) -> MapSchemaSource {
    let mut schemas = MapSchemaSource::new();
    schemas.nodes_mut().extend(nodes());
    for (name, schema) in pairs {
        schemas.insert_tag(name, schema);
    }
    schemas
}

fn functions(pairs: Vec<(&str, ConfigFunction)>) -> IndexMap<String, ConfigFunction> {
    pairs
        .into_iter()
        .map(|(name, function)| (name.to_string(), function))
        .collect()
}

fn parameters(pairs: Vec<(&str, SchemaAttribute)>) -> IndexMap<String, SchemaAttribute> {
    pairs
        .into_iter()
        .map(|(name, attribute)| (name.to_string(), attribute))
        .collect()
}

/// Every problem, as `(id, message)` in the order it was reported.
fn errors<'a>(document: &'a Node<'a>, config: &Config<'a>) -> Vec<(&'static str, String)> {
    validate_tree(document, config)
        .into_iter()
        .map(|found| (found.error.id, found.error.message))
        .collect()
}

/// Sugar for the expectation side, so a test reads as a list of pairs.
fn expected(pairs: &[(&'static str, &str)]) -> Vec<(&'static str, String)> {
    pairs
        .iter()
        .map(|(id, message)| (*id, (*message).to_string()))
        .collect()
}

// ---------------------------------------------------------------------------
// function validation
// ---------------------------------------------------------------------------

/// The config upstream's `return type checking` and `checks parameters` blocks
/// share, with function validation switched on.
fn function_config(functions: IndexMap<String, ConfigFunction>) -> Config<'static> {
    let mut config = config();
    config.validation.validate_functions = true;
    config.functions = Arc::new(functions);
    config.schemas = Arc::new(schemas(vec![
        ("foo", Schema::new().attribute("bar", string())),
        (
            "union-tag-1",
            Schema::new()
                .attribute("foo", string())
                .attribute("bar", number())
                .attribute("baz", typed(ValidationType::Boolean)),
        ),
    ]));
    config
}

fn returns(value_type: ValidationType) -> ConfigFunction {
    ConfigFunction {
        returns: Some(value_type),
        ..ConfigFunction::default()
    }
}

/// The `functions` block upstream declares once for its return-type tests.
fn return_type_functions() -> IndexMap<String, ConfigFunction> {
    functions(vec![
        ("baz", returns(ValidationType::String)),
        ("number", returns(ValidationType::Number)),
        (
            "nested",
            ConfigFunction {
                returns: Some(ValidationType::String),
                parameters: Some(parameters(vec![("0", string()), ("1", number())])),
                ..ConfigFunction::default()
            },
        ),
        (
            "withUnion",
            ConfigFunction {
                returns: Some(ValidationType::Union(vec![
                    ValidationType::String,
                    ValidationType::Number,
                ])),
                parameters: Some(IndexMap::new()),
                ..ConfigFunction::default()
            },
        ),
    ])
}

#[test]
fn ensures_that_function_exists() {
    let config = function_config(IndexMap::new());
    let document = parse("{% foo bar=baz() /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[("function-undefined", "Undefined function: 'baz'")])
    );
}

#[test]
fn correctly_handles_union_types() {
    let config = function_config(return_type_functions());

    let document = parse("{% union-tag-1 foo=withUnion() bar=withUnion() /%}");
    assert!(errors(&document, &config).is_empty());

    // `baz` is typed `Boolean`, which is not one of the union's members.
    let document = parse("{% union-tag-1 foo=withUnion() bar=withUnion() baz=withUnion() /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "attribute-type-invalid",
            "Attribute 'baz' must be type of 'Boolean'"
        )])
    );
}

#[test]
fn correctly_handles_return_types_for_nested_function_calls() {
    let config = function_config(return_type_functions());

    let document = parse("{% foo bar=nested(baz(), number()) /%}");
    assert!(errors(&document, &config).is_empty());

    let document = parse("{% foo bar=nested(number(), baz()) /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[
            (
                "parameter-type-invalid",
                "Parameter '0' of 'nested' must be type of 'String'"
            ),
            (
                "parameter-type-invalid",
                "Parameter '1' of 'nested' must be type of 'Number'"
            ),
        ])
    );
}

#[test]
fn accepts_a_correct_return_type() {
    let config = function_config(return_type_functions());
    let document = parse("{% foo bar=baz() /%}");
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn correctly_handles_no_return_type() {
    let config = function_config(functions(vec![("baz", ConfigFunction::default())]));
    let document = parse("{% foo bar=baz() /%}");
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn identifies_an_incorrect_return_type() {
    let config = function_config(functions(vec![("baz", returns(ValidationType::Number))]));
    let document = parse("{% foo bar=baz() /%}");
    assert_eq!(
        errors(&document, &config)
            .into_iter()
            .map(|(id, _)| id)
            .collect::<Vec<_>>(),
        ["attribute-type-invalid"]
    );
}

/// The `checks parameters` block's functions.
fn parameter_functions() -> IndexMap<String, ConfigFunction> {
    functions(vec![
        (
            "baz",
            ConfigFunction {
                returns: Some(ValidationType::String),
                parameters: Some(IndexMap::new()),
                ..ConfigFunction::default()
            },
        ),
        (
            "qux",
            ConfigFunction {
                returns: Some(ValidationType::String),
                parameters: Some(parameters(vec![("test", string())])),
                ..ConfigFunction::default()
            },
        ),
        ("noTyping", ConfigFunction::default()),
        (
            "requiredParam",
            ConfigFunction {
                returns: Some(ValidationType::String),
                parameters: Some(parameters(vec![
                    ("test", string()),
                    ("req", required(string())),
                ])),
                ..ConfigFunction::default()
            },
        ),
    ])
}

#[test]
fn with_a_missing_optional_parameter() {
    let config = function_config(parameter_functions());
    let document = parse("{% foo bar=qux() /%}");
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn with_a_missing_required_parameter() {
    let config = function_config(parameter_functions());
    let document = parse("{% foo bar=requiredParam() /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "parameter-missing-required",
            "Missing required parameter: 'req'"
        )])
    );
}

#[test]
fn accepts_defined_parameters_with_a_keyed_parameter() {
    let config = function_config(parameter_functions());
    let document = parse(r#"{% foo bar=qux(test="example") /%}"#);
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn ignores_parameters_when_there_is_no_typing() {
    let config = function_config(parameter_functions());
    let document = parse("{% foo bar=noTyping(foo=1) /%}");
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn rejects_undeclared_parameters_with_a_keyed_parameter() {
    let config = function_config(parameter_functions());
    let document = parse("{% foo bar=baz(foo=1) /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[("parameter-undefined", "Invalid parameter: 'foo'")])
    );
}

#[test]
fn rejects_undeclared_parameters_with_a_positional_parameter() {
    let config = function_config(parameter_functions());

    let document = parse("{% foo bar=baz(1) /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[("parameter-undefined", "Invalid parameter: '0'")])
    );

    // Upstream's subset assertion names only the positional one. Both are
    // reported, because `baz` declares no parameters at all.
    let document = parse("{% foo bar=baz(1, test=2) /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[
            ("parameter-undefined", "Invalid parameter: '0'"),
            ("parameter-undefined", "Invalid parameter: 'test'"),
        ])
    );
}

// ---------------------------------------------------------------------------
// inline rule
// ---------------------------------------------------------------------------

fn inline_config() -> Config<'static> {
    let mut config = config();
    config.schemas = Arc::new(schemas(vec![
        (
            "foo",
            Schema {
                inline: Some(true),
                ..Schema::new()
            },
        ),
        (
            "bar",
            Schema {
                inline: Some(false),
                ..Schema::new()
            },
        ),
        ("baz", Schema::new()),
    ]));
    config
}

#[test]
fn allows_inline_or_block_when_undefined() {
    let config = inline_config();

    let document = parse("this is inline {% baz %}bar{% /baz %}");
    assert!(errors(&document, &config).is_empty());

    let document = parse("\n{% baz %}\nbar\n{% /baz %}\n      ");
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn validates_inline_tag() {
    let config = inline_config();

    let document = parse("this is inline {% foo %}bar{% /foo %}");
    assert!(errors(&document, &config).is_empty());

    let document = parse("\n{% foo %}\nbar\n{% /foo %}\n      ");
    let found = errors(&document, &config);
    assert_eq!(
        found.first().map(|(id, _)| *id),
        Some("tag-placement-invalid")
    );
    assert!(found[0].1.contains("should be inline"), "{found:?}");
}

#[test]
fn validates_block_tag() {
    let config = inline_config();

    let document = parse("\n{% bar %}\nbar\n{% /bar %}\n");
    assert!(errors(&document, &config).is_empty());

    let document = parse("this is inline {% bar %}bar{% /bar %}");
    let found = errors(&document, &config);
    assert_eq!(
        found.first().map(|(id, _)| *id),
        Some("tag-placement-invalid")
    );
    assert!(found[0].1.contains("should be block"), "{found:?}");
}

// ---------------------------------------------------------------------------
// attribute validation
// ---------------------------------------------------------------------------

#[test]
fn an_attribute_validate_hook_using_a_simple_conditional() {
    let mut config = config();
    config.schemas = Arc::new(schemas(vec![(
        "foo",
        Schema::new().attribute(
            "bar",
            SchemaAttribute {
                attribute_type: Some(ValidationType::Number),
                validate: Some(Arc::new(
                    |value: &Value, _config: &Config<'_>, _key: &str| {
                        let greater = matches!(value, Value::Number(n) if *n > 10.0);
                        if greater {
                            return Vec::new();
                        }
                        vec![ValidationError::new(
                            "attribute-should-be-greater-than-ten",
                            ErrorLevel::Error,
                            r#"Attribute "bar" must have value greater than 10."#,
                        )]
                    },
                )),
                ..SchemaAttribute::default()
            },
        ),
    )]));

    let document = parse("{% foo bar=20 /%}");
    assert!(errors(&document, &config).is_empty());

    let document = parse("{% foo bar=5 /%}");
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "attribute-should-be-greater-than-ten",
            r#"Attribute "bar" must have value greater than 10."#
        )])
    );
}

fn matches_config(allowed: Vec<&str>) -> Config<'static> {
    use accent_proust::validate::SchemaMatches;

    let mut config = config();
    config.schemas = Arc::new(schemas(vec![(
        "foo",
        Schema::new().attribute(
            "jawn",
            SchemaAttribute {
                attribute_type: Some(ValidationType::String),
                matches: Some(SchemaMatches::Values(
                    allowed.into_iter().map(str::to_string).collect(),
                )),
                ..SchemaAttribute::default()
            },
        ),
    )]));
    config
}

#[test]
fn should_return_error_on_failure_to_match_array() {
    let config = matches_config(vec!["bar", "baz", "bat"]);
    let document = parse(r#"{% foo jawn="cat" /%}"#);
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "attribute-value-invalid",
            r#"Attribute 'jawn' must match one of ["bar","baz","bat"]. Got 'cat' instead."#
        )])
    );
}

#[test]
fn elides_excess_values_in_matches_check() {
    // Upstream's `Array.from('foobarbazqux')`: twelve single-character values,
    // four more than the eight the message shows.
    let config = matches_config("foobarbazqux".split("").filter(|s| !s.is_empty()).collect());

    let document = parse(r#"{% foo jawn="cat" /%}"#);
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "attribute-value-invalid",
            r#"Attribute 'jawn' must match one of ["f","o","o","b","a","r","b","a", ... 4 more]. Got 'cat' instead."#
        )])
    );
}

#[test]
fn properly_validates_ids() {
    let config = config();

    let document = parse("# foo {% #bar %}");
    assert!(errors(&document, &config).is_empty());

    let document = parse("# foo {% #1bar %}");
    assert_eq!(
        errors(&document, &config).first().map(|(id, _)| *id),
        Some("attribute-value-invalid")
    );

    let document = parse(r##"# foo {% id="#bar" %}"##);
    assert_eq!(
        errors(&document, &config).first().map(|(id, _)| *id),
        Some("attribute-value-invalid")
    );
}

// ---------------------------------------------------------------------------
// custom type registration
// ---------------------------------------------------------------------------

/// Upstream registers a `Link` class with a `validate` method. Here it is an
/// `AttributeType`, which is the same object with the optionality of its methods
/// made explicit.
struct Link;

impl AttributeType for Link {
    fn name(&self) -> &'static str {
        "Link"
    }

    fn validate<'a>(
        &self,
        value: &Value,
        _config: &Config<'a>,
        _name: &str,
    ) -> Option<Vec<ValidationError<'a>>> {
        if matches!(value, Value::String(text) if text.starts_with("http")) {
            return Some(Vec::new());
        }
        Some(vec![ValidationError::new(
            "attribute-type-invalid",
            ErrorLevel::Error,
            "Attribute 'href' must be type of 'Link'",
        )])
    }
}

#[test]
fn a_custom_type_returns_error_on_failure() {
    let mut config = config();
    config.schemas = Arc::new(schemas(vec![(
        "link",
        Schema::new()
            .render("a")
            .attribute("href", typed(ValidationType::Custom(Arc::new(Link)))),
    )]));

    let document = parse(r#"{% link href="/relative-link"  /%}"#);
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "attribute-type-invalid",
            "Attribute 'href' must be type of 'Link'"
        )])
    );
}

#[test]
fn a_custom_type_returns_no_errors_when_valid() {
    let mut config = config();
    config.schemas = Arc::new(schemas(vec![(
        "link",
        Schema {
            self_closing: true,
            ..Schema::new()
                .render("a")
                .attribute("href", typed(ValidationType::Custom(Arc::new(Link))))
        },
    )]));

    let document = parse(r#"{% link href="http://google.com"  /%}"#);
    assert!(errors(&document, &config).is_empty());
}

// ---------------------------------------------------------------------------
// variable validation
// ---------------------------------------------------------------------------

#[test]
fn should_only_validate_if_the_variables_config_is_passed() {
    let config = config();
    let document = parse("{% $valid.variable %}");
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn should_warn_against_missing_variables() {
    let mut config = config();
    config.variables = Some(Variables::new());

    let document = parse("{% $undefinedVariable %}");
    assert_eq!(
        errors(&document, &config),
        expected(&[(
            "variable-undefined",
            "Undefined variable: 'undefinedVariable'"
        )])
    );
    // Upstream also asserts the node the error is attached to.
    assert_eq!(
        validate_tree(&document, &config)
            .first()
            .map(|found| found.node_type),
        Some(NodeType::Text)
    );
}

#[test]
fn should_not_warn_if_variable_exists() {
    let mut config = config();
    let mut valid = IndexMap::new();
    valid.insert("variable".to_string(), Value::Boolean(false));
    let mut variables = Variables::new();
    variables.insert("valid".to_string(), Value::Hash(valid));
    config.variables = Some(variables);

    let document = parse("{% $valid.variable %}");
    assert!(errors(&document, &config).is_empty());
}

// ---------------------------------------------------------------------------
// indented code
// ---------------------------------------------------------------------------

#[test]
fn should_not_error_for_missing_support_for_code_block() {
    // Upstream disables markdown-it's `code` rule, so its parse of this document
    // is a heading followed by a paragraph; here the indented line is a
    // CommonMark indented code block, which is `DIVERGENCES.md` entry 11. The
    // assertion is unaffected -- neither shape produces a validation error --
    // and it is worth keeping for exactly that reason: the difference is in the
    // tree, not in what the validator says about it.
    let config = config();
    let document = parse(
        "   # https://spec.commonmark.org/0.30/#indented-code-block\n    4-space indented code",
    );
    assert!(errors(&document, &config).is_empty());
}

// ---------------------------------------------------------------------------
// attribute validation key
// ---------------------------------------------------------------------------

/// The message both `attribute validation key` tests assert, which is the point
/// of the block: the attribute's *name* reaches the check, so one function can
/// serve several attributes and still say which one it is talking about.
fn less_than_five<'a>(value: &Value, name: &str) -> Vec<ValidationError<'a>> {
    let small = match value {
        Value::Hash(entries) => matches!(entries.get("baz"), Some(Value::Number(n)) if *n < 5.0),
        _ => false,
    };
    if !small {
        return Vec::new();
    }
    vec![ValidationError::new(
        "invalid-foo-bar",
        ErrorLevel::Error,
        format!("The value of '{name}.baz' must be less than five"),
    )]
}

#[test]
fn an_attribute_validate_hook_receives_the_attribute_name() {
    let mut config = config();
    let attribute = || SchemaAttribute {
        attribute_type: Some(ValidationType::Object),
        validate: Some(Arc::new(
            |value: &Value, _config: &Config<'_>, name: &str| less_than_five(value, name),
        )),
        ..SchemaAttribute::default()
    };
    config.schemas = Arc::new(schemas(vec![(
        "foo",
        Schema::new()
            .attribute("bar", attribute())
            .attribute("blah", attribute()),
    )]));

    let document = parse("{% foo bar={baz: 3} /%}");
    assert_eq!(
        errors(&document, &config)
            .first()
            .map(|(_, message)| message.clone()),
        Some("The value of 'bar.baz' must be less than five".to_string())
    );
}

#[test]
fn a_custom_attribute_type_receives_the_attribute_name() {
    struct CustomType;
    impl AttributeType for CustomType {
        fn name(&self) -> &'static str {
            "CustomType"
        }

        fn validate<'a>(
            &self,
            value: &Value,
            _config: &Config<'a>,
            name: &str,
        ) -> Option<Vec<ValidationError<'a>>> {
            Some(less_than_five(value, name))
        }
    }

    let mut config = config();
    let custom = ValidationType::Custom(Arc::new(CustomType));
    config.schemas = Arc::new(schemas(vec![(
        "foo",
        Schema::new()
            .attribute("bar", typed(custom.clone()))
            .attribute("blah", typed(custom)),
    )]));

    let document = parse("{% foo bar={baz: 3} /%}");
    assert_eq!(
        errors(&document, &config)
            .first()
            .map(|(_, message)| message.clone()),
        Some("The value of 'bar.baz' must be less than five".to_string())
    );
}

// ---------------------------------------------------------------------------
// parent validation
// ---------------------------------------------------------------------------

#[test]
fn parent_validation_for_deep_nesting() {
    let mut config = config();
    let mut schemas = schemas(vec![
        ("foo", Schema::new()),
        ("bar", Schema::new()),
        ("baz", Schema::new()),
    ]);
    let heading = Schema {
        validate: Some(Arc::new(|_node: &Node<'_>, config: &Config<'_>| {
            if config
                .validation
                .parents
                .iter()
                .any(|parent| parent.tag.as_deref() == Some("foo"))
            {
                return vec![ValidationError::new(
                    "heading-in-foo",
                    ErrorLevel::Error,
                    "Can't nest a heading in tag 'foo'",
                )];
            }
            Vec::new()
        })),
        ..Schema::new().attribute("level", hidden(required(number())))
    };
    schemas.insert_node(NodeType::Heading, heading);
    config.schemas = Arc::new(schemas);

    let document =
        parse("\n{% foo %}\n{% bar %}\n{% baz %}\n# testing\n{% /baz %}\n{% /bar %}\n{% /foo %}\n");
    let found = errors(&document, &config);
    assert_eq!(found.len(), 1, "{found:?}");
    assert_eq!(found[0].0, "heading-in-foo");

    let document = parse(
        "\n{% foo %}\n{% bar %}\n{% /bar %}\n{% /foo %}\n\n{% bar %}\n{% baz %}\n# testing\n{% /baz %}\n{% /bar %}\n",
    );
    assert!(errors(&document, &config).is_empty());
}

#[test]
fn parent_validation_with_function_validation_enabled() {
    let mut config = config();
    config.validation.validate_functions = true;
    config.schemas = Arc::new(schemas(vec![
        ("foo", Schema::new()),
        (
            "bar",
            Schema {
                validate: Some(Arc::new(|_node: &Node<'_>, config: &Config<'_>| {
                    let parents: Vec<NodeType> = config
                        .validation
                        .parents
                        .iter()
                        .map(|parent| parent.node_type)
                        .collect();
                    assert_eq!(
                        parents,
                        [
                            NodeType::Document,
                            NodeType::Paragraph,
                            NodeType::Inline,
                            NodeType::Tag
                        ]
                    );
                    Vec::new()
                })),
                ..Schema::new()
            },
        ),
    ]));

    let document = parse("{% foo %}{% bar %}this is a test{% /bar %}{% /foo %}");
    assert!(errors(&document, &config).is_empty());
}