rave_engine 0.8.0

A secure and efficient JSON Schema validation and Rhai script execution engine
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! # JSON Schema Validator
//!
//! This module provides functionality for validating JSON data against JSON schemas.
//!
//! ## Overview
//!
//! The JSON Schema Validator is responsible for:
//! - Validating JSON instances against JSON schemas
//! - Supporting various JSON schema features
//! - Providing detailed error messages
//! - Handling complex validation scenarios
//!
//! ## Supported Schema Features
//!
//! The validator supports the following JSON schema features:
//! - Basic types (string, number, integer, boolean, null)
//! - Object validation with required properties
//! - Array validation with min/max items
//! - String validation with min/max length and patterns
//! - Number validation with min/max and multipleOf
//! - Nested object and array validation
//!
//! ## Performance Considerations
//!
//! - Validation is optimized for common use cases
//! - Complex schemas may impact performance
//! - Large JSON instances may require more memory
//! - Pattern matching with regex can be CPU-intensive
//!
//! ## Error Handling
//!
//! The validator provides detailed error messages for:
//! - Invalid schema structure
//! - Type mismatches
//! - Missing required fields
//! - Value range violations
//! - Pattern matching failures
//!
//! ## Example Usage
//!
//! ```rust
//! use rave_engine::prelude::json_schema_validator::validate_json_schema;
//! use serde_json::json;
//!
//! let schema = json!({
//!     "type": "object",
//!     "properties": {
//!         "name": { "type": "string", "minLength": 3 },
//!         "age": { "type": "integer", "minimum": 0 }
//!     },
//!     "required": ["name", "age"]
//! });
//!
//! let valid_instance = json!({
//!     "name": "John",
//!     "age": 30
//! });
//!
//! assert!(validate_json_schema(&schema, &valid_instance).is_ok());
//! ```
//!
//! ## Security Considerations
//!
//! The JSON Schema Validator implements several security measures:
//!
//! ### Input Validation
//! - All input is validated against the schema before processing
//! - Type checking prevents type confusion attacks
//! - Pattern validation prevents injection attacks
//! - Array bounds checking prevents buffer overflow attempts
//!
//! ### Resource Limits
//! - Maximum schema size: 1MB
//! - Maximum instance size: 10MB
//! - Maximum nesting depth: 32 levels
//! - Maximum string length: 1MB
//! - Maximum array length: 100,000 items
//!
//! ### Pattern Validation
//! - Regular expressions are pre-compiled and cached
//! - Pattern matching is safe against ReDoS attacks
//! - Complex patterns are limited to prevent CPU exhaustion
//!
//! ### Error Handling
//! - Detailed error messages are sanitized
//! - No sensitive information is leaked in error messages
//! - Stack traces are not exposed
//!
//! ### Performance Considerations
//! - Validation is optimized for common use cases
//! - Complex schemas may impact performance
//! - Large JSON instances may require more memory
//! - Pattern matching with regex can be CPU-intensive
//!
//! ### Best Practices
//! 1. Always validate user input against a strict schema
//! 2. Use appropriate type constraints
//! 3. Set reasonable size limits
//! 4. Use pattern validation for string fields
//! 5. Implement proper error handling
//! 6. Monitor resource usage
//! 7. Keep schemas simple and focused
//! 8. Regularly update dependencies
//! 9. Use secure defaults
//! 10. Implement proper logging
//!
//! ## Future Improvements
//!
//! Planned enhancements include:
//! - Support for more JSON schema features
//! - Performance optimizations
//! - Input size limits
//! - Better error messages
//! - Schema compilation for faster validation

use regex::Regex;
use serde_json::Value;
mod test;

/// Validates a JSON instance against a provided JSON schema.
///
/// This function performs a two-step validation:
/// 1. Validates the schema itself
/// 2. Validates the instance against the schema
///
/// # Arguments
///
/// * `schema` - A `serde_json::Value` containing the JSON schema to validate against
/// * `instance` - A `serde_json::Value` containing the JSON instance to validate
///
/// # Returns
///
/// Returns `Ok(())` if the instance is valid according to the schema,
/// or `Err(String)` with an error message if the validation fails.
///
/// # Examples
///
/// ```rust
/// use rave_engine::prelude::json_schema_validator::validate_json_schema;
/// use serde_json::json;
///
/// let schema = json!({
///     "type": "object",
///     "properties": {
///         "name": { "type": "string" },
///         "age": { "type": "integer" }
///     },
///     "required": ["name", "age"]
/// });
///
/// let valid_instance = json!({
///     "name": "John",
///     "age": 30
/// });
///
/// assert!(validate_json_schema(&schema, &valid_instance).is_ok());
/// ```
///
/// # Errors
///
/// Returns an error if:
/// * The schema is invalid
/// * The instance doesn't match the schema
/// * Required fields are missing
/// * Values are outside allowed ranges
/// * String patterns don't match
pub fn validate_json_schema(schema: &Value, instance: &Value) -> Result<(), String> {
    // First validate the schema itself
    is_valid_schema(schema)?;

    // Then validate the instance against the schema
    validate_instance(schema, instance)
}

/// Checks if the provided schema is a valid JSON schema.
///
/// # Arguments
///
/// * `schema` - A `serde_json::Value` containing the JSON schema to be validated.
///
/// # Returns
///
/// Returns `Ok(())` if the schema is valid, or `Err(String)` with an error message if the schema is invalid.
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use rave_engine::prelude::json_schema_validator::is_valid_schema;
///
/// let valid_schema = json!({
///     "type": "object",
///     "properties": {
///         "name": { "type": "string" }
///     }
/// });
///
/// assert!(is_valid_schema(&valid_schema).is_ok());
/// ```
pub fn is_valid_schema(schema: &Value) -> Result<(), String> {
    if let Some(schema_type) = schema.get("type") {
        if let Some(type_str) = schema_type.as_str() {
            match type_str {
                "object" => {
                    if schema.get("properties").is_none() {
                        return Err("Object schema must contain 'properties'".to_string());
                    }
                }
                "array" => {
                    if schema.get("items").is_none() {
                        return Err("Array schema must contain 'items'".to_string());
                    }
                }
                "string" | "integer" | "number" | "boolean" | "null" | "any" => {}
                _ => return Err(format!("Unsupported schema type: {type_str}")),
            }
        } else {
            return Err("'type' in schema must be a string".to_string());
        }
    } else {
        return Err("Schema must contain a 'type'".to_string());
    }
    Ok(())
}

/// Validates an instance against a schema.
fn validate_instance(schema: &Value, instance: &Value) -> Result<(), String> {
    // Handle single type (existing logic)
    if let Some(schema_type) = schema.get("type").and_then(|t| t.as_str()) {
        match schema_type {
            "object" => validate_object(schema, instance.get("data").unwrap_or(instance))?,
            "array" => validate_array(schema, instance.get("data").unwrap_or(instance))?,
            "string" => validate_string(schema, instance.get("data").unwrap_or(instance))?,
            "number" | "integer" => {
                validate_number(schema, instance.get("data").unwrap_or(instance))?
            }
            "boolean" => validate_boolean(instance.get("data").unwrap_or(instance))?,
            "null" => validate_null(instance.get("data").unwrap_or(instance))?,
            "any" => (),
            _ => return Err(format!("Unsupported type: {schema_type}")),
        }
    }
    // Handle multiple types (new logic)
    else if let Some(type_array) = schema.get("type").and_then(|t| t.as_array()) {
        let mut any_type_matched = false;

        for type_value in type_array {
            if let Some(type_str) = type_value.as_str() {
                let mut temp_schema = schema.clone();
                temp_schema
                    .as_object_mut()
                    .ok_or_else(|| "Failed to get object mut".to_string())?
                    .insert("type".to_string(), Value::String(type_str.to_string()));

                // Try to validate against this specific type
                if validate_instance(&temp_schema, instance).is_ok() {
                    any_type_matched = true;
                    break;
                }
            }
        }

        if !any_type_matched {
            let type_names: Vec<String> = type_array
                .iter()
                .filter_map(|t| t.as_str())
                .map(|s| s.to_string())
                .collect();
            return Err(format!(
                "Value does not match any of the allowed types: {}",
                type_names.join(", ")
            ));
        }
    }

    Ok(())
}

/// Validates an object instance against an object schema.
fn validate_object(schema: &Value, instance: &Value) -> Result<(), String> {
    if !instance.is_object() {
        return Err(format!("Expected object value: {instance}"));
    }

    let instance_obj = instance
        .as_object()
        .ok_or_else(|| "Failed to get object when validating object".to_string())?;

    // Check required fields
    if let Some(required) = schema.get("required").and_then(|r| r.as_array()) {
        for field in required {
            if let Some(field_name) = field.as_str() {
                if !instance_obj.contains_key(field_name) {
                    return Err(format!("Missing required field: {field_name}"));
                }
            }
        }
    }

    // Validate properties
    if let Some(properties) = schema.get("properties").and_then(|p| p.as_object()) {
        // Get the required fields set once, outside the loop - use &str to avoid allocations
        let required_fields: std::collections::HashSet<&str> = schema
            .get("required")
            .and_then(|r| r.as_array())
            .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
            .unwrap_or_default();

        for (key, prop_schema) in properties {
            if let Some(value) = instance_obj.get(key) {
                let is_required = required_fields.contains(key.as_str());

                // Fast path: if required, use original schema
                if is_required {
                    validate_instance(prop_schema, value)?;
                } else {
                    // For optional properties, allow null automatically
                    validate_with_null_allowed(prop_schema, value)?;
                }
            }
        }
    }

    Ok(())
}

/// Validates a value against a schema, automatically allowing null for the validation
fn validate_with_null_allowed(prop_schema: &Value, value: &Value) -> Result<(), String> {
    // Fast path: if value is null, it's automatically valid for optional properties
    if value.is_null() {
        return Ok(());
    }

    // Check if null is already allowed in the schema
    if let Some(type_array) = prop_schema.get("type").and_then(|t| t.as_array()) {
        if type_array.iter().any(|t| t.as_str() == Some("null")) {
            // Schema already allows null, use as-is
            return validate_instance(prop_schema, value);
        }

        // Add null to existing type array
        let mut new_types = type_array.clone();
        new_types.push(Value::String("null".to_string()));

        let mut enhanced_schema = prop_schema.clone();
        enhanced_schema
            .as_object_mut()
            .ok_or_else(|| "Failed to get object mut".to_string())?
            .insert("type".to_string(), Value::Array(new_types));

        validate_instance(&enhanced_schema, value)
    } else if let Some(single_type) = prop_schema.get("type").and_then(|t| t.as_str()) {
        if single_type == "null" {
            // Already null type, use as-is
            validate_instance(prop_schema, value)
        } else {
            // Convert single type to array with null
            let mut enhanced_schema = prop_schema.clone();
            enhanced_schema
                .as_object_mut()
                .ok_or_else(|| "Failed to get object mut".to_string())?
                .insert(
                    "type".to_string(),
                    Value::Array(vec![
                        Value::String(single_type.to_string()),
                        Value::String("null".to_string()),
                    ]),
                );
            validate_instance(&enhanced_schema, value)
        }
    } else {
        // No type specified, validate as-is
        validate_instance(prop_schema, value)
    }
}

/// Validates an array instance against an array schema.
fn validate_array(schema: &Value, instance: &Value) -> Result<(), String> {
    if !instance.is_array() {
        return Err("Expected array value".to_string());
    }

    let array = instance
        .as_array()
        .ok_or_else(|| "Failed to get array when validating array".to_string())?;

    // Validate minItems
    if let Some(min_items) = schema.get("minItems").and_then(|m| m.as_u64()) {
        if array.len() < min_items as usize {
            return Err(format!(
                "Array length {} is less than minItems {}",
                array.len(),
                min_items
            ));
        }
    }

    // Validate maxItems
    if let Some(max_items) = schema.get("maxItems").and_then(|m| m.as_u64()) {
        if array.len() > max_items as usize {
            return Err(format!(
                "Array length {} is greater than maxItems {}",
                array.len(),
                max_items
            ));
        }
    }

    // Validate uniqueItems
    if let Some(unique_items) = schema.get("uniqueItems").and_then(|u| u.as_bool()) {
        if unique_items {
            for i in 0..array.len() {
                for j in (i + 1)..array.len() {
                    if array[i] == array[j] {
                        return Err(format!(
                            "Array contains duplicate items at positions {i} and {j}"
                        ));
                    }
                }
            }
        }
    }

    // Validate items
    if let Some(items_schema) = schema.get("items") {
        for item in array {
            validate_instance(items_schema, item)?;
        }
    }

    Ok(())
}

/// Validates a string instance against a string schema.
fn validate_string(schema: &Value, instance: &Value) -> Result<(), String> {
    if !instance.is_string() {
        return Err(format!("Expected string value {instance:?}"));
    }

    let string = instance
        .as_str()
        .ok_or_else(|| "Failed to get string when validating string".to_string())?;

    // Validate minLength
    if let Some(min_length) = schema.get("minLength").and_then(|m| m.as_u64()) {
        if string.len() < min_length as usize {
            return Err(format!(
                "String length {} is less than minLength {}",
                string.len(),
                min_length
            ));
        }
    }

    // Validate maxLength
    if let Some(max_length) = schema.get("maxLength").and_then(|m| m.as_u64()) {
        if string.len() > max_length as usize {
            return Err(format!(
                "String length {} is greater than maxLength {}",
                string.len(),
                max_length
            ));
        }
    }

    // Validate pattern
    if let Some(pattern) = schema.get("pattern").and_then(|p| p.as_str()) {
        let regex = Regex::new(pattern).map_err(|e| format!("Invalid regex pattern: {e}"))?;
        if !regex.is_match(string) {
            return Err(format!("String does not match pattern: {pattern}"));
        }
    }

    Ok(())
}

/// Validates a number instance against a number schema.
fn validate_number(schema: &Value, instance: &Value) -> Result<(), String> {
    if !instance.is_number() {
        return Err("Expected number value".to_string());
    }

    let number = instance
        .as_f64()
        .ok_or_else(|| "Failed to get number when validating number".to_string())?;

    // Validate minimum
    if let Some(minimum) = schema.get("minimum").and_then(|m| m.as_f64()) {
        if number < minimum {
            return Err(format!("Value {number} is less than minimum {minimum}"));
        }
    }

    // Validate maximum
    if let Some(maximum) = schema.get("maximum").and_then(|m| m.as_f64()) {
        if number > maximum {
            return Err(format!("Value {number} is greater than maximum {maximum}"));
        }
    }

    // Validate multipleOf
    if let Some(multiple_of) = schema.get("multipleOf").and_then(|m| m.as_f64()) {
        if (number / multiple_of).fract() != 0.0 {
            return Err(format!("Value {number} is not a multiple of {multiple_of}"));
        }
    }

    Ok(())
}

/// Validates a boolean instance.
fn validate_boolean(instance: &Value) -> Result<(), String> {
    if !instance.is_boolean() {
        return Err("Expected boolean value".to_string());
    }
    Ok(())
}

/// Validates a null instance.
fn validate_null(instance: &Value) -> Result<(), String> {
    if !instance.is_null() {
        return Err("Expected null value".to_string());
    }
    Ok(())
}

/// Get the keys of a JSON Schema
///
/// # Arguments
///
/// * `schema` - A `serde_json::Value` containing the JSON schema.
///
/// # Returns
///
/// Returns `Ok(Vec<String>)` containing all property keys if the schema is an object,
/// or `Err(String)` with an error message if the schema is invalid.
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use rave_engine::prelude::json_schema_validator::get_keys;
///
/// let schema = json!({
///     "type": "object",
///     "properties": {
///         "name": { "type": "string" },
///         "age": { "type": "integer" }
///     }
/// });
///
/// let keys = get_keys(&schema).unwrap();
/// assert!(keys.contains(&"name".to_string()));
/// assert!(keys.contains(&"age".to_string()));
/// ```
pub fn get_keys(schema: &Value) -> Result<Vec<String>, String> {
    if let Some(properties) = schema.get("properties") {
        if let Some(obj) = properties.as_object() {
            Ok(obj.keys().cloned().collect())
        } else {
            Err("Properties must be an object".to_string())
        }
    } else {
        Ok(Vec::new())
    }
}
pub fn get_keys_for_consumed_inputs(schema: &Value) -> Result<Vec<String>, String> {
    if let Some(properties) = schema.get("properties") {
        if let Some(obj) = properties.as_object() {
            if let Some(consumed_inputs) = obj.get("consumed_inputs") {
                if let Some(obj) = consumed_inputs.as_object() {
                    if let Some(properties) = obj.get("properties") {
                        if let Some(obj) = properties.as_object() {
                            Ok(obj.keys().cloned().collect())
                        } else {
                            Err("Properties must be an object".to_string())
                        }
                    } else {
                        Ok(Vec::new())
                    }
                } else {
                    Err("Consumed inputs must be an object".to_string())
                }
            } else {
                Ok(Vec::new())
            }
        } else {
            Err("Properties must be an object".to_string())
        }
    } else {
        Ok(Vec::new())
    }
}
pub fn get_keys_for_inputs(schema: &Value) -> Result<Vec<String>, String> {
    if let Some(properties) = schema.get("properties") {
        if let Some(obj) = properties.as_object() {
            if let Some(inputs) = obj.get("inputs") {
                if let Some(obj) = inputs.as_object() {
                    if let Some(properties) = obj.get("properties") {
                        if let Some(obj) = properties.as_object() {
                            Ok(obj.keys().cloned().collect())
                        } else {
                            Err("Properties must be an object".to_string())
                        }
                    } else {
                        Ok(Vec::new())
                    }
                } else {
                    Err("Inputs must be an object".to_string())
                }
            } else {
                Ok(Vec::new())
            }
        } else {
            Err("Properties must be an object".to_string())
        }
    } else {
        Ok(Vec::new())
    }
}

/// Check if a field in the schema is of type array
///
/// # Arguments
///
/// * `schema` - A `serde_json::Value` containing the JSON schema.
/// * `name` - The name of the field to check.
///
/// # Returns
///
/// Returns `Ok(())` if the field exists and is of type array,
/// or `Err(String)` with an error message if the field doesn't exist or is not an array.
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use rave_engine::prelude::json_schema_validator::check_if_type_array_for_key;
///
/// let schema = json!({
///     "type": "object",
///     "properties": {
///         "items": { "type": "array" },
///         "name": { "type": "string" }
///     }
/// });
///
/// assert!(check_if_type_array_for_key(&schema, "items").is_ok());
/// ```
pub fn check_if_type_array_for_key(schema: &Value, name: &str) -> Result<(), String> {
    if let Some(properties) = schema.get("properties") {
        if let Some(field_schema) = properties.get(name) {
            if let Some(field_type) = field_schema.get("type") {
                if let Some(type_str) = field_type.as_str() {
                    if type_str == "array" {
                        Ok(())
                    } else {
                        Err(format!("Field '{name}' is not of type array"))
                    }
                } else {
                    Err(format!("Type for field '{name}' must be a string"))
                }
            } else {
                Err(format!("Field '{name}' has no type specified"))
            }
        } else {
            Err(format!("Field '{name}' not found in schema"))
        }
    } else {
        Err("Schema has no properties".to_string())
    }
}
pub fn get_properties(schema: &Value) -> Result<&Value, String> {
    if let Some(properties) = schema.get("properties") {
        Ok(properties)
    } else {
        Err("Schema has no properties".to_string())
    }
}
pub fn check_if_type_array_for_sub_key(schema: &Value, sub_keys: Vec<&str>) -> Result<(), String> {
    // get the schema of the sub_keys

    let mut schema = schema;
    for key in sub_keys[..sub_keys.len() - 1].iter() {
        if let Some(obj) = get_properties(schema)?.get(key) {
            schema = obj;
        } else {
            return Err(format!("Field '{key}' not found in schema"));
        }
    }
    check_if_type_array_for_key(schema, sub_keys[sub_keys.len() - 1])
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::time::Instant;

    #[test]
    fn test_validate_json_schema() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "integer" }
            },
            "required": ["name", "age"]
        });

        let valid_instance = json!({
            "name": "John",
            "age": 30
        });

        let invalid_instance = json!({
            "name": "John"
        });

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
        assert!(validate_json_schema(&schema, &invalid_instance).is_err());
    }

    #[test]
    fn test_is_valid_schema() {
        let valid_schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            }
        });

        let invalid_schema = json!({
            "type": "invalid_type"
        });

        assert!(is_valid_schema(&valid_schema).is_ok());
        assert!(is_valid_schema(&invalid_schema).is_err());
    }

    #[test]
    fn test_get_keys() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "integer" }
            }
        });

        let keys = get_keys(&schema).unwrap();
        assert_eq!(keys.len(), 2);
        assert!(keys.contains(&"name".to_string()));
        assert!(keys.contains(&"age".to_string()));
    }

    #[test]
    fn test_check_if_type_array_for_key() {
        let schema = json!({
            "type": "object",
            "properties": {
                "items": { "type": "array" },
                "name": { "type": "string" }
            }
        });

        assert!(check_if_type_array_for_key(&schema, "items").is_ok());
        assert!(check_if_type_array_for_key(&schema, "name").is_err());
        assert!(check_if_type_array_for_key(&schema, "nonexistent").is_err());
    }

    #[test]
    fn test_complex_object_validation() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string", "minLength": 3 },
                "age": { "type": "integer", "minimum": 0, "maximum": 150 },
                "email": { "type": "string", "pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" },
                "address": {
                    "type": "object",
                    "properties": {
                        "street": { "type": "string" },
                        "city": { "type": "string" },
                        "zip": { "type": "string", "pattern": "^\\d{5}$" }
                    },
                    "required": ["street", "city", "zip"]
                },
                "tags": {
                    "type": "array",
                    "items": { "type": "string" },
                    "minItems": 1,
                    "maxItems": 5
                }
            },
            "required": ["name", "age", "email"]
        });

        let valid_instance = json!({
            "name": "John Doe",
            "age": 30,
            "email": "john@example.com",
            "address": {
                "street": "123 Main St",
                "city": "Anytown",
                "zip": "12345"
            },
            "tags": ["tag1", "tag2"]
        });

        let invalid_instance = json!({
            "name": "Jo", // Too short
            "age": 200, // Too old
            "email": "invalid-email",
            "address": {
                "street": "123 Main St",
                "city": "Anytown"
                // Missing zip
            },
            "tags": [] // Empty array
        });

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
        assert!(validate_json_schema(&schema, &invalid_instance).is_err());
    }

    #[test]
    fn test_array_validation() {
        let schema = json!({
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": { "type": "integer" },
                    "name": { "type": "string" }
                },
                "required": ["id", "name"]
            },
            "minItems": 2,
            "maxItems": 4
        });

        let valid_instance = json!([
            { "id": 1, "name": "Item 1" },
            { "id": 2, "name": "Item 2" }
        ]);

        let invalid_instance = json!([
            { "id": 1 }, // Missing name
            { "name": "Item 2" } // Missing id
        ]);

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
        assert!(validate_json_schema(&schema, &invalid_instance).is_err());
    }

    #[test]
    fn test_number_validation() {
        let schema = json!({
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "multipleOf": 0.5
        });

        let valid_instance = json!(50.0);
        let invalid_instance = json!(150.0);

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
        assert!(validate_json_schema(&schema, &invalid_instance).is_err());
    }

    #[test]
    fn test_string_validation() {
        let schema = json!({
            "type": "string",
            "minLength": 5,
            "maxLength": 10,
            "pattern": "^[A-Za-z]+$"
        });

        let valid_instance = json!("Hello");
        let invalid_instance = json!("Hi123");

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
        assert!(validate_json_schema(&schema, &invalid_instance).is_err());
    }

    #[test]
    fn test_performance() {
        let schema = json!({
            "type": "object",
            "properties": {
                "data": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "id": { "type": "integer" },
                            "value": { "type": "string" }
                        },
                        "required": ["id", "value"]
                    }
                }
            }
        });

        // Create a large instance
        let mut data = Vec::new();
        for i in 0..1000 {
            data.push(json!({
                "id": i,
                "value": format!("Value {}", i)
            }));
        }
        let instance = json!({ "data": { "data": data } });

        // Measure validation time
        let start = Instant::now();
        let result = validate_json_schema(&schema, &instance);
        let duration = start.elapsed();
        assert!(result.is_ok());
        println!("Validation of 1000 items took: {duration:?}");
        assert!(
            duration.as_millis() < 100,
            "Validation took too long: {duration:?}"
        );
    }

    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen_test]
    fn test_wasm_compatibility() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "integer" }
            },
            "required": ["name", "age"]
        });

        let valid_instance = json!({
            "name": "John",
            "age": 30
        });

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
    }

    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen_test]
    fn test_wasm_complex_validation() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "integer" },
                "items": {
                    "type": "array",
                    "items": { "type": "string" }
                }
            },
            "required": ["name", "age"]
        });

        let valid_instance = json!({
            "name": "John",
            "age": 30,
            "items": ["item1", "item2"]
        });

        assert!(validate_json_schema(&schema, &valid_instance).is_ok());
    }
}