widevin 0.3.0

Lightweight Rust Devin provider library
Documentation
use serde_json::{Map, Value, json};

/// The small Cascade/Gemini wire adaptation; caller schemas remain unchanged.
pub(crate) fn normalize_google_schema(value: &Value) -> Value {
    if value == &Value::Bool(true) {
        return json!({});
    }
    if value == &Value::Bool(false) {
        return json!({"not": {}});
    }
    let Some(object) = value.as_object() else {
        return value.clone();
    };
    let mut node = object.clone();
    normalize_types(&mut node);
    for key in ["properties", "$defs", "definitions", "patternProperties"] {
        if let Some(map) = node.get(key).and_then(Value::as_object) {
            let normalized = map
                .iter()
                .map(|(name, schema)| (name.clone(), normalize_google_schema(schema)))
                .collect::<Map<_, _>>();
            node.insert(key.into(), Value::Object(normalized));
        }
    }
    for key in ["items", "additionalProperties", "not", "if", "then", "else"] {
        if let Some(value) = node.get(key) {
            if value.is_object() || key != "additionalProperties" {
                let normalized = normalize_google_schema(value);
                node.insert(key.into(), normalized);
            }
        }
    }
    for key in ["anyOf", "oneOf", "allOf", "prefixItems"] {
        if let Some(values) = node.get(key).and_then(Value::as_array) {
            let normalized = values.iter().map(normalize_google_schema).collect();
            node.insert(key.into(), Value::Array(normalized));
        }
    }
    if node.get("type").is_some_and(|kind| kind == "object") {
        node.entry("properties").or_insert_with(|| json!({}));
        let keys = node
            .get("properties")
            .and_then(Value::as_object)
            .map(|map| map.keys().cloned().collect::<Vec<_>>())
            .unwrap_or_default();
        node.entry("propertyOrdering")
            .or_insert_with(|| json!(keys));
    }
    node.remove("$schema");
    node.remove("additionalProperties");
    Value::Object(node)
}

fn type_specific_keys() -> &'static [(&'static str, &'static [&'static str])] {
    &[
        (
            "array",
            &[
                "items",
                "prefixItems",
                "minItems",
                "maxItems",
                "uniqueItems",
                "contains",
            ],
        ),
        (
            "object",
            &[
                "properties",
                "required",
                "additionalProperties",
                "propertyOrdering",
                "patternProperties",
            ],
        ),
        ("string", &["minLength", "maxLength", "pattern", "format"]),
        (
            "number",
            &[
                "minimum",
                "maximum",
                "exclusiveMinimum",
                "exclusiveMaximum",
                "multipleOf",
            ],
        ),
        (
            "integer",
            &[
                "minimum",
                "maximum",
                "exclusiveMinimum",
                "exclusiveMaximum",
                "multipleOf",
            ],
        ),
    ]
}

fn normalize_types(node: &mut Map<String, Value>) {
    if let Some(types) = node.get("type").and_then(Value::as_array).cloned() {
        let mut non_null = Vec::new();
        for kind in &types {
            if kind != "null" && !non_null.contains(kind) {
                non_null.push(kind.clone());
            }
        }
        if types.contains(&json!("null")) {
            node.insert("nullable".into(), json!(true));
        }
        node.remove("type");
        if non_null.len() == 1 {
            node.insert("type".into(), non_null[0].clone());
        } else if !non_null.is_empty() && !node.get("anyOf").is_some_and(Value::is_array) {
            let mut branches = non_null
                .into_iter()
                .map(|kind| json!({"type": kind}))
                .collect::<Vec<_>>();
            let keys = type_specific_keys()
                .iter()
                .flat_map(|(_, keys)| keys.iter().copied())
                .collect::<std::collections::BTreeSet<_>>();
            for key in keys {
                if let Some(value) = node.remove(key) {
                    for branch in &mut branches {
                        if type_specific_keys()
                            .iter()
                            .any(|(kind, keys)| branch["type"] == *kind && keys.contains(&key))
                        {
                            branch[key] = value.clone();
                        }
                    }
                }
            }
            node.insert("anyOf".into(), Value::Array(branches));
        }
    }
    if let Some(variants) = node.get("anyOf").and_then(Value::as_array).cloned() {
        let kept = variants
            .iter()
            .filter(|branch| branch.get("type").is_none_or(|kind| kind != "null"))
            .cloned()
            .collect::<Vec<_>>();
        if kept.len() != variants.len() {
            node.insert("nullable".into(), json!(true));
            if kept.is_empty() {
                node.remove("anyOf");
            } else if kept.len() == 1 && kept[0].is_object() {
                let branch = kept[0].as_object().expect("object");
                // Parent and branch constraints are conjunctive. Flatten only
                // disjoint keywords rather than choosing a potentially weaker value.
                let overlaps = branch
                    .keys()
                    .any(|key| key != "anyOf" && node.contains_key(key));
                if overlaps {
                    node.insert("anyOf".into(), Value::Array(kept));
                } else {
                    node.remove("anyOf");
                    for (key, value) in branch {
                        node.entry(key.clone()).or_insert_with(|| value.clone());
                    }
                }
            } else {
                node.insert("anyOf".into(), Value::Array(kept));
            }
        }
    }
    if node.get("type").is_some_and(|kind| kind == "null") {
        node.remove("type");
        node.insert("nullable".into(), json!(true));
    }
}