use super::{schema_error, Refusal, RefusalRule};
use serde_json::Value;
use std::collections::BTreeSet;
fn invalid(path: &str, message: &'static str) -> Refusal {
schema_error(path).with_rule(RefusalRule::TitledValuesSchema { message })
}
pub(super) fn check_declaration(schema: &Value, path: &str) -> Result<(), Refusal> {
let Some(one_of) = schema.get("oneOf") else {
return Ok(());
};
if schema["type"] != "string" {
if one_of.as_array().is_some_and(|branches| {
branches
.iter()
.any(|branch| branch.get("const").is_some() && branch.get("properties").is_none())
}) {
return Err(invalid(
path,
"titled oneOf values require type: \"string\"",
));
}
return Ok(());
}
if super::credential(schema) {
return Err(invalid(
path,
"titled oneOf values cannot be credential references",
));
}
let branches = one_of
.as_array()
.filter(|branches| branches.len() >= 2)
.ok_or_else(|| {
invalid(
path,
"string oneOf must be an array of at least two titled values",
)
})?;
let mut constants = BTreeSet::new();
for branch in branches {
let fields = branch.as_object().filter(|fields| {
fields.keys().all(|key| matches!(key.as_str(), "const" | "title" | "description"))
}).ok_or_else(|| {
invalid(path, "string oneOf branches must be objects with only const, title, and optional description")
})?;
let constant = fields
.get("const")
.and_then(Value::as_str)
.ok_or_else(|| invalid(path, "each string oneOf branch needs a string const"))?;
if !fields
.get("title")
.and_then(Value::as_str)
.is_some_and(valid_title)
{
return Err(invalid(path, "each string oneOf branch needs a trimmed title of 1 to 80 characters without control characters"));
}
if fields
.get("description")
.is_some_and(|value| !value.is_string())
{
return Err(invalid(
path,
"a string oneOf branch description must be a string",
));
}
if !constants.insert(constant) {
return Err(invalid(path, "string oneOf consts must be unique"));
}
}
if schema.get("default").is_some_and(|value| {
value
.as_str()
.is_none_or(|value| !constants.contains(value))
}) {
return Err(invalid(
path,
"the default must equal one of the string oneOf consts",
));
}
Ok(())
}
fn valid_title(title: &str) -> bool {
title == title.trim()
&& (1..=80).contains(&title.chars().count())
&& !title.chars().any(char::is_control)
}
pub(super) fn constants(schema: &Value) -> Option<impl Iterator<Item = &Value> + Clone> {
let branches = schema.get("oneOf")?.as_array()?;
(schema["type"] == "string" && !super::is_opaque(schema))
.then(|| branches.iter().map(|branch| &branch["const"]))
}