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
//! Converts Zod-like schemas to JSON Schema.
//!
//! This module provides functionality to convert type schemas to JSON Schema format.
//! Note: In Rust, we use serde_json::Value directly instead of Zod schemas.
//! This module provides a similar interface for compatibility.
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
type JsonSchema7Type = serde_json::Value;
/// Cache for schema conversions. Since Rust doesn't have WeakMap with object identity,
/// we use a simple HashMap with schema identifiers (JSON strings).
/// In practice, this would be keyed by the schema's canonical JSON representation.
lazy_static::lazy_static! {
static ref SCHEMA_CACHE: RwLock<HashMap<String, JsonSchema7Type>> = RwLock::new(HashMap::new());
}
/// Converts a JSON Schema (as Value) to JSON Schema format.
/// This is a simple pass-through since we already have JSON values in Rust.
pub fn zod_to_json_schema(schema: &Value) -> JsonSchema7Type {
// Try to use cache based on schema string representation
let schema_key = schema.to_string();
// Check cache first
if let Ok(cache) = SCHEMA_CACHE.read() {
if let Some(cached) = cache.get(&schema_key) {
return cached.clone();
}
}
// For JSON schema, we just return the value as-is since it's already valid JSON
// In a real implementation, this might validate and normalize the schema
let result = schema.clone();
// Store in cache
if let Ok(mut cache) = SCHEMA_CACHE.write() {
cache.insert(schema_key, result.clone());
}
result
}
/// Convenience function to create a JSON schema from a JSON schema string.
pub fn parse_json_schema(schema_str: &str) -> Result<JsonSchema7Type, serde_json::Error> {
let parsed: Value = serde_json::from_str(schema_str)?;
Ok(zod_to_json_schema(&parsed))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zod_to_json_schema() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string" }
}
});
let result = zod_to_json_schema(&schema);
assert_eq!(result.get("type").unwrap(), "object");
}
#[test]
fn test_parse_json_schema() {
let schema_str = r#"{"type": "string"}"#;
let result = parse_json_schema(schema_str).unwrap();
assert_eq!(result.get("type").unwrap(), "string");
}
}