use serde_json::Value;
use std::fmt;
mod engine;
#[derive(Debug, Clone)]
pub enum VldSchemarsError {
Validation(vld::error::VldError),
Deserialization(String),
}
impl fmt::Display for VldSchemarsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VldSchemarsError::Validation(e) => write!(f, "Schema validation error: {}", e),
VldSchemarsError::Deserialization(e) => write!(f, "Deserialization error: {}", e),
}
}
}
impl std::error::Error for VldSchemarsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
VldSchemarsError::Validation(e) => Some(e),
VldSchemarsError::Deserialization(_) => None,
}
}
}
impl From<vld::error::VldError> for VldSchemarsError {
fn from(e: vld::error::VldError) -> Self {
VldSchemarsError::Validation(e)
}
}
pub fn validate_with_schema(schema: &Value, value: &Value) -> Result<(), vld::error::VldError> {
engine::validate_value_against_schema(
schema,
value,
&[],
engine::Ctx {
root: schema,
depth: 0,
},
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropertyInfo {
pub name: String,
pub schema_type: Option<String>,
pub required: bool,
pub schema: Value,
}
pub fn list_properties(schema: &Value) -> Vec<PropertyInfo> {
let mut result = Vec::new();
let properties = match schema.get("properties").and_then(|p| p.as_object()) {
Some(p) => p,
None => return result,
};
let required_set: 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 (name, prop_schema) in properties {
let schema_type = prop_schema
.get("type")
.and_then(|t| t.as_str())
.map(String::from);
result.push(PropertyInfo {
name: name.clone(),
schema_type,
required: required_set.contains(name.as_str()),
schema: prop_schema.clone(),
});
}
result.sort_unstable_by(|a, b| a.name.cmp(&b.name));
result
}
pub fn schema_type(schema: &Value) -> Option<String> {
schema
.get("type")
.and_then(|t| t.as_str())
.map(String::from)
}
pub fn is_required(schema: &Value, field: &str) -> bool {
schema
.get("required")
.and_then(|r| r.as_array())
.map(|arr| arr.iter().any(|v| v.as_str() == Some(field)))
.unwrap_or(false)
}
pub fn get_property<'a>(schema: &'a Value, field: &str) -> Option<&'a Value> {
schema
.get("properties")
.and_then(|p| p.as_object())
.and_then(|props| props.get(field))
}
pub fn schemas_equal(a: &Value, b: &Value) -> bool {
a == b
}
pub fn overlay_constraints(base: &Value, overlay: &Value) -> Value {
let mut result = base.clone();
if let (Some(result_obj), Some(overlay_obj)) = (result.as_object_mut(), overlay.as_object()) {
for (key, value) in overlay_obj {
match key.as_str() {
"properties" => {
if let (Some(base_props), Some(overlay_props)) = (
result_obj
.get_mut("properties")
.and_then(|p| p.as_object_mut()),
value.as_object(),
) {
for (prop_name, prop_schema) in overlay_props {
if let Some(existing) = base_props.get_mut(prop_name) {
if let (Some(existing_obj), Some(overlay_prop_obj)) =
(existing.as_object_mut(), prop_schema.as_object())
{
for (k, v) in overlay_prop_obj {
existing_obj.entry(k.clone()).or_insert_with(|| v.clone());
}
}
} else {
base_props.insert(prop_name.clone(), prop_schema.clone());
}
}
}
}
"required" => {
if let Some(overlay_required) = value.as_array() {
let base_required = result_obj
.entry("required")
.or_insert_with(|| Value::Array(vec![]));
if let Some(arr) = base_required.as_array_mut() {
for item in overlay_required {
if !arr.contains(item) {
arr.push(item.clone());
}
}
}
}
}
_ => {
result_obj
.entry(key.clone())
.or_insert_with(|| value.clone());
}
}
}
}
result
}
pub fn to_openapi3(value: &mut Value) {
match value {
Value::Array(items) => items.iter_mut().for_each(to_openapi3),
Value::Object(map) => {
if let Some(Value::Array(prefix)) = map.remove("prefixItems") {
let items = match <[Value; 1]>::try_from(prefix) {
Ok([one]) => one,
Err(many) => serde_json::json!({ "anyOf": many }),
};
map.insert("items".into(), items);
}
if let Some(Value::Array(types)) = map.get("type") {
let rest: Vec<Value> = types.iter().filter(|t| *t != "null").cloned().collect();
if rest.len() < types.len() {
map.insert("nullable".into(), Value::Bool(true));
match <[Value; 1]>::try_from(rest) {
Ok([one]) => map.insert("type".into(), one),
Err(rest) if rest.is_empty() => map.insert("type".into(), "null".into()),
Err(rest) => map.insert("type".into(), Value::Array(rest)),
};
}
}
for key in ["anyOf", "oneOf"] {
let Some(Value::Array(branches)) = map.get(key) else {
continue;
};
let rest: Vec<Value> = branches
.iter()
.filter(|b| !is_null_schema(b))
.cloned()
.collect();
if rest.len() == branches.len() {
continue;
}
map.remove(key);
map.insert("nullable".into(), Value::Bool(true));
match <[Value; 1]>::try_from(rest) {
Ok([Value::Object(one)]) if !one.contains_key("$ref") => {
for (k, v) in one {
map.entry(k).or_insert(v);
}
}
Ok([one]) => {
map.insert("allOf".into(), Value::Array(vec![one]));
}
Err(rest) if rest.is_empty() => {
map.insert("type".into(), "null".into());
}
Err(rest) => {
map.insert(key.into(), Value::Array(rest));
}
}
}
for (ex, inc, stricter) in [
("exclusiveMinimum", "minimum", std::cmp::Ordering::Greater),
("exclusiveMaximum", "maximum", std::cmp::Ordering::Less),
] {
let Some(n) = map.get(ex).and_then(Value::as_f64) else {
continue;
};
let n_value = map.remove(ex).unwrap_or_default();
let inclusive_wins = map
.get(inc)
.and_then(Value::as_f64)
.and_then(|m| m.partial_cmp(&n))
.is_some_and(|o| o == stricter);
if !inclusive_wins {
map.insert(inc.into(), n_value);
map.insert(ex.into(), Value::Bool(true));
}
}
if is_null_schema(&Value::Object(map.clone())) {
for k in ["type", "const", "enum", "nullable"] {
map.remove(k);
}
map.insert("type".into(), "string".into());
map.insert("nullable".into(), Value::Bool(true));
map.insert("enum".into(), serde_json::json!([null]));
return;
}
map.values_mut().for_each(to_openapi3);
}
_ => {}
}
}
fn is_null_schema(v: &Value) -> bool {
v.get("type").is_some_and(|t| t == "null")
|| v.get("const").is_some_and(Value::is_null)
|| v.get("enum") == Some(&serde_json::json!([null]))
}
#[cfg(any(feature = "schemars-0", feature = "schemars-1"))]
pub(crate) fn rewrite_refs(value: &mut Value, prefix: &str) {
match value {
Value::Object(map) => {
for (key, v) in map.iter_mut() {
match v {
Value::String(r) if key == "$ref" => {
let name = ["#/components/schemas/", "#/$defs/", "#/definitions/"]
.iter()
.find_map(|p| r.strip_prefix(p));
if let Some(name) = name {
*r = format!("{prefix}{name}");
}
}
_ => rewrite_refs(v, prefix),
}
}
}
Value::Array(items) => items.iter_mut().for_each(|v| rewrite_refs(v, prefix)),
_ => {}
}
}