use std::collections::BTreeMap;
use std::sync::{Arc, LazyLock};
use serde_json::{Map, Value, json};
use super::drawn::DrawnChart;
use super::scene::{DrawnDepth, DrawnScene};
pub const FORMS_CATALOG_ID: &str = "https://adk-rust.com/a2ui/catalogs/forms/1.0/catalog.json";
pub(crate) const LEFT_OUT: &[&str] = &["Image", "Icon", "Modal", "Video", "AudioPlayer"];
const FORBIDDEN_PROPERTIES: &[&str] = &["action", "event", "checks"];
const FORBIDDEN_FORMATS: &[&str] = &["uri", "uri-reference", "iri", "iri-reference", "url"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChildSlot {
One(&'static str),
Many(&'static str),
EachOf {
array: &'static str,
child: &'static str,
},
}
#[derive(Debug, Clone, Copy)]
pub struct ResolvedComponent<'a> {
pub id: &'a str,
pub component: &'a str,
pub props: &'a Value,
pub children: usize,
}
impl ResolvedComponent<'_> {
pub fn str(&self, name: &str) -> Option<&str> {
self.props.get(name).and_then(Value::as_str)
}
pub fn get(&self, name: &str) -> Option<&Value> {
self.props.get(name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HomeText {
H1,
H2,
H3,
H4,
H5,
Caption,
#[default]
Body,
}
impl HomeText {
pub fn variant(self) -> &'static str {
match self {
Self::H1 => "h1",
Self::H2 => "h2",
Self::H3 => "h3",
Self::H4 => "h4",
Self::H5 => "h5",
Self::Caption => "caption",
Self::Body => "body",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum HomeNode {
Text {
text: String,
variant: HomeText,
},
Row(Vec<HomeNode>),
Column(Vec<HomeNode>),
Card(Vec<HomeNode>),
Tabs(Vec<(String, HomeNode)>),
Divider,
Child(usize),
Chart(DrawnChart),
Scene(Box<HomeScene>),
Depth {
depth: DrawnDepth,
children: Vec<HomeNode>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct HomeScene {
pub scene: DrawnScene,
pub panels: Vec<HomePanel>,
pub text: Option<HomeNode>,
}
impl HomeScene {
pub fn new(scene: DrawnScene) -> Self {
Self { scene, panels: Vec::new(), text: None }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HomePanel {
pub anchor: String,
pub content: HomeNode,
}
impl HomeNode {
pub fn text(text: impl Into<String>) -> Self {
Self::Text { text: text.into(), variant: HomeText::Body }
}
pub fn caption(text: impl Into<String>) -> Self {
Self::Text { text: text.into(), variant: HomeText::Caption }
}
pub fn heading(level: u8, text: impl Into<String>) -> Self {
let variant = match level {
0 | 1 => HomeText::H1,
2 => HomeText::H2,
3 => HomeText::H3,
4 => HomeText::H4,
_ => HomeText::H5,
};
Self::Text { text: text.into(), variant }
}
}
pub trait ExtensionComponent: Send + Sync + 'static {
fn name(&self) -> &'static str;
fn schema(&self) -> Value;
fn children(&self) -> &'static [ChildSlot] {
&[]
}
fn usage(&self) -> &'static str;
fn allowed_parents(&self) -> &'static [&'static str] {
&[]
}
fn allowed_children(&self) -> &'static [&'static str] {
&[]
}
fn home(&self, component: &ResolvedComponent<'_>) -> Result<HomeNode, String>;
}
pub struct ExtensionSpec {
pub id: &'static str,
pub name: &'static str,
pub version: &'static str,
pub components: Vec<Arc<dyn ExtensionComponent>>,
}
impl std::fmt::Debug for ExtensionSpec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExtensionSpec")
.field("id", &self.id)
.field("components", &self.components.iter().map(|c| c.name()).collect::<Vec<_>>())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("extension catalog {catalog}: {detail}")]
pub struct CatalogError {
pub catalog: String,
pub detail: String,
}
const COMMON_TYPES_ID: &str = "https://a2ui.org/specification/v0_9/common_types.json";
const COMMON_TYPES_CATALOG: &str = "https://a2ui.org/specification/v0_9/catalog.json";
const FORMS_DOCUMENT: &str = include_str!("catalogs/forms-1.0.json");
const FORMS_DOCUMENT_V1_0: &str = include_str!("catalogs/forms-1.0.a2ui-1.0.json");
#[cfg(test)]
pub(crate) const COMMON_TYPES_V1_0: &str = include_str!("catalogs/common_types-1.0.json");
#[cfg(test)]
pub(crate) const CATALOG_DEFINITION_V1_0: &str =
include_str!("catalogs/catalog_definition-1.0.json");
const COMMON_TYPES_DOCUMENT: &str = include_str!("catalogs/common_types-0.9.1.json");
pub struct Catalog {
id: &'static str,
name: &'static str,
version: &'static str,
instructions: Option<String>,
document: Value,
components: BTreeMap<String, jsonschema::Validator>,
extensions: BTreeMap<String, Arc<dyn ExtensionComponent>>,
}
impl std::fmt::Debug for Catalog {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Catalog")
.field("id", &self.id)
.field("components", &self.components.keys().collect::<Vec<_>>())
.field("extensions", &self.extensions.keys().collect::<Vec<_>>())
.finish_non_exhaustive()
}
}
static FORMS: LazyLock<Catalog> = LazyLock::new(|| {
Catalog::compile(FORMS_CATALOG_ID, "forms", "1.0", FORMS_DOCUMENT)
.unwrap_or_else(|error| panic!("the embedded forms 1.0 catalog does not compile: {error}"))
});
impl Catalog {
pub fn forms() -> &'static Catalog {
&FORMS
}
pub fn extend(spec: ExtensionSpec) -> Result<Catalog, CatalogError> {
let refuse = |detail: String| CatalogError { catalog: spec.id.to_string(), detail };
if spec.id == FORMS_CATALOG_ID {
return Err(refuse("its id is the forms catalog's".to_string()));
}
if spec.id.trim().is_empty()
|| spec.name.trim().is_empty()
|| spec.version.trim().is_empty()
{
return Err(refuse("it needs an id, a name and a version".to_string()));
}
if spec.components.is_empty() {
return Err(refuse("it adds no components".to_string()));
}
let forms = Catalog::forms();
let mut document = forms.document.clone();
document["$id"] = json!(spec.id);
document["catalogId"] = json!(spec.id);
document["title"] = json!(format!("{} {}", spec.name, spec.version));
document["description"] = json!(format!(
"The forms 1.0 catalog and the components of {} {}",
spec.name, spec.version
));
let mut extensions: BTreeMap<String, Arc<dyn ExtensionComponent>> = BTreeMap::new();
for component in &spec.components {
let name = component.name();
if name.is_empty() || !name.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
return Err(refuse(format!(
"'{name}' is not a component name of letters and digits"
)));
}
if forms.has_component(name) {
return Err(refuse(format!("{name} is a forms component")));
}
if LEFT_OUT.contains(&name) {
return Err(refuse(format!("{name} is one of the components forms leaves out")));
}
if extensions.contains_key(name) {
return Err(refuse(format!("{name} is added twice")));
}
let schema = component.schema();
if let Some(why) = forbidden(&schema) {
return Err(refuse(format!("{name}'s schema {why}")));
}
document["components"][name] = schema;
if let Some(any) = document["$defs"]["anyComponent"]["oneOf"].as_array_mut() {
any.push(json!({ "$ref": format!("#/components/{name}") }));
}
extensions.insert(name.to_string(), Arc::clone(component));
}
let mut catalog = Catalog::compile_document(spec.id, spec.name, spec.version, document)
.map_err(refuse)?;
catalog.extensions = extensions;
Ok(catalog)
}
fn compile(
id: &'static str,
name: &'static str,
version: &'static str,
document: &str,
) -> Result<Self, String> {
let document: Value = serde_json::from_str(document).map_err(|error| error.to_string())?;
Self::compile_document(id, name, version, document)
}
fn compile_document(
id: &'static str,
name: &'static str,
version: &'static str,
document: Value,
) -> Result<Self, String> {
let common: Value =
serde_json::from_str(COMMON_TYPES_DOCUMENT).map_err(|error| error.to_string())?;
let registry = jsonschema::Registry::new()
.add(id, document.clone())
.and_then(|registry| registry.add(COMMON_TYPES_CATALOG, document.clone()))
.and_then(|registry| registry.add(COMMON_TYPES_ID, common))
.and_then(jsonschema::RegistryBuilder::prepare)
.map_err(|error| error.to_string())?;
let names: Vec<String> = document["components"]
.as_object()
.map(|components| components.keys().cloned().collect())
.unwrap_or_default();
let mut components = BTreeMap::new();
for component in names {
let schema = json!({ "$ref": format!("{id}#/components/{component}") });
let validator = jsonschema::options()
.with_registry(®istry)
.build(&schema)
.map_err(|error| format!("{component}: {error}"))?;
components.insert(component, validator);
}
Ok(Self {
id,
name,
version,
instructions: None,
document,
components,
extensions: BTreeMap::new(),
})
}
pub fn id(&self) -> &str {
self.id
}
pub fn label(&self) -> String {
format!("{} {}", self.name, self.version)
}
pub fn document(&self) -> &Value {
&self.document
}
#[must_use]
pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
pub fn document_for(&self, version: super::wire::A2uiVersion) -> Value {
if version == super::wire::A2uiVersion::V0_9_1 {
return self.document.clone();
}
if !self.is_extension() {
return serde_json::from_str(FORMS_DOCUMENT_V1_0).unwrap_or_default();
}
let mut components = Map::new();
for (name, extension) in &self.extensions {
let mut schema = schema_v1_0(&extension.schema());
if let Value::Object(map) = &mut schema {
let parents = extension.allowed_parents();
if !parents.is_empty() {
map.insert("allowedParents".to_string(), json!(parents));
}
let children = extension.allowed_children();
if !children.is_empty() {
map.insert("allowedChildren".to_string(), json!(children));
}
}
components.insert(name.clone(), schema);
}
let mut instructions: Vec<String> = self.usage().into_iter().map(str::to_string).collect();
if let Some(extra) = &self.instructions {
instructions.push(extra.clone());
}
json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": self.id,
"protocolVersion": "1.0",
"title": self.label(),
"description": format!(
"The components {} adds to {FORMS_CATALOG_ID}, which a surface mixes with it",
self.label()
),
"catalogId": self.id,
"instructions": instructions.join("\n"),
"components": components,
})
}
pub fn components(&self) -> impl Iterator<Item = &str> {
self.components.keys().map(String::as_str)
}
pub fn functions(&self) -> impl Iterator<Item = &str> {
self.document["functions"]
.as_object()
.into_iter()
.flat_map(|functions| functions.keys().map(String::as_str))
}
pub fn has_component(&self, component: &str) -> bool {
self.components.contains_key(component)
}
pub fn extensions(&self) -> impl Iterator<Item = &str> {
self.extensions.keys().map(String::as_str)
}
pub fn is_extension(&self) -> bool {
!self.extensions.is_empty()
}
pub(crate) fn extension(&self, component: &str) -> Option<&dyn ExtensionComponent> {
self.extensions.get(component).map(|extension| extension.as_ref())
}
pub(crate) fn usage(&self) -> Vec<&'static str> {
self.extensions.values().map(|extension| extension.usage()).collect()
}
pub(crate) fn schema_error(&self, component: &str, value: &Value) -> Option<String> {
let validator = self.components.get(component)?;
validator.iter_errors(value).next().map(|error| {
let error = error.to_owned();
let error = specific(&error);
let at = error.instance_path().as_str();
let why = shortened(&error.to_string());
if at.is_empty() { why } else { format!("{at}: {why}") }
})
}
}
fn schema_v1_0(schema: &Value) -> Value {
fn refs(value: &Value) -> Value {
match value {
Value::Object(map) => Value::Object(
map.iter()
.map(|(key, value)| match (key.as_str(), value) {
("$ref", Value::String(target)) => {
let relative = target
.split_once("common_types.json#")
.map(|(_, pointer)| format!("common_types.json#{pointer}"))
.unwrap_or_else(|| target.clone());
(key.clone(), Value::String(relative))
}
_ => (key.clone(), refs(value)),
})
.collect(),
),
Value::Array(items) => Value::Array(items.iter().map(refs).collect()),
other => other.clone(),
}
}
let mut out = refs(schema);
if let Value::Object(map) = &mut out {
if let Some(Value::Object(properties)) = map.get_mut("properties") {
properties.remove("id");
}
if let Some(Value::Array(required)) = map.get_mut("required") {
required.retain(|name| name != "id");
}
if map.get("additionalProperties") == Some(&Value::Bool(false)) {
map.remove("additionalProperties");
}
if let Some(Value::Array(all)) = map.get_mut("allOf") {
all.retain(|part| {
let target = part.get("$ref").and_then(Value::as_str).unwrap_or_default();
!target.ends_with("/ComponentCommon")
&& !target.ends_with("/CatalogComponentCommon")
});
if all.is_empty() {
map.remove("allOf");
}
}
}
out
}
fn specific<'e>(
error: &'e jsonschema::ValidationError<'static>,
) -> &'e jsonschema::ValidationError<'static> {
let context = match error.kind() {
jsonschema::error::ValidationErrorKind::OneOfNotValid { context }
| jsonschema::error::ValidationErrorKind::AnyOf { context } => context,
_ => return error,
};
let deepest = context
.iter()
.flatten()
.map(specific)
.max_by_key(|cause| cause.instance_path().as_str().matches('/').count());
match deepest {
Some(cause)
if cause.instance_path().as_str().len() > error.instance_path().as_str().len() =>
{
cause
}
_ => error,
}
}
const MAX_SCHEMA_ERROR_CHARS: usize = 300;
fn shortened(text: &str) -> String {
if text.chars().count() <= MAX_SCHEMA_ERROR_CHARS {
return text.to_string();
}
let kept: String = text.chars().take(MAX_SCHEMA_ERROR_CHARS).collect();
format!("{kept}…")
}
fn forbidden(schema: &Value) -> Option<String> {
match schema {
Value::Object(map) => {
for key in ["$defs", "definitions", "functions"] {
if map.contains_key(key) {
return Some(format!("declares {key}"));
}
}
if let Some(properties) = map.get("properties").and_then(Value::as_object)
&& let Some(property) =
FORBIDDEN_PROPERTIES.iter().find(|name| properties.contains_key(**name))
{
return Some(format!("declares the property '{property}'"));
}
if let Some(format) = map.get("format").and_then(Value::as_str)
&& FORBIDDEN_FORMATS.contains(&format)
{
return Some(format!("declares the string format '{format}'"));
}
map.values().find_map(forbidden)
}
Value::Array(items) => items.iter().find_map(forbidden),
_ => None,
}
}
#[derive(Clone)]
pub struct Catalogs(Arc<Vec<&'static Catalog>>);
impl Catalogs {
pub fn forms() -> Self {
Self(Arc::new(vec![Catalog::forms()]))
}
#[must_use]
pub fn with(self, catalog: &'static Catalog) -> Self {
if self.get(catalog.id()).is_some() {
return self;
}
let mut catalogs = (*self.0).clone();
catalogs.push(catalog);
Self(Arc::new(catalogs))
}
pub fn get(&self, id: &str) -> Option<&'static Catalog> {
self.0.iter().copied().find(|catalog| catalog.id() == id)
}
pub fn iter(&self) -> impl Iterator<Item = &'static Catalog> + '_ {
self.0.iter().copied()
}
}
impl Default for Catalogs {
fn default() -> Self {
Self::forms()
}
}
impl std::fmt::Debug for Catalogs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.0.iter().map(|catalog| catalog.id())).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::genui::A2uiVersion;
fn v1_0_meta() -> jsonschema::Validator {
let meta: Value = serde_json::from_str(CATALOG_DEFINITION_V1_0).unwrap();
let common: Value = serde_json::from_str(COMMON_TYPES_V1_0).unwrap();
let catalog = json!({ "$defs": { "anyComponent": {}, "anyFunction": {} } });
let registry = jsonschema::Registry::new()
.add("https://a2ui.org/specification/v1_0/common_types.json", common)
.and_then(|registry| {
registry.add("https://a2ui.org/specification/v1_0/catalog.json", catalog)
})
.and_then(jsonschema::RegistryBuilder::prepare)
.unwrap();
jsonschema::options().with_registry(®istry).build(&meta).unwrap()
}
struct Gauge;
impl ExtensionComponent for Gauge {
fn name(&self) -> &'static str {
"Gauge"
}
fn schema(&self) -> Value {
json!({
"type": "object",
"allOf": [{ "$ref": "#/$defs/CatalogComponentCommon" }],
"properties": {
"id": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/ComponentId" },
"component": { "const": "Gauge" },
"label": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/DynamicString" },
"value": { "type": "number" }
},
"required": ["id", "component", "label", "value"],
"additionalProperties": false
})
}
fn usage(&self) -> &'static str {
"Gauge: {label, value} one number on a dial"
}
fn allowed_parents(&self) -> &'static [&'static str] {
&["Card", "Column"]
}
fn home(&self, _gauge: &ResolvedComponent<'_>) -> Result<HomeNode, String> {
Ok(HomeNode::text("gauge"))
}
}
#[test]
fn catalogs_are_published_as_a2ui_1_0_documents_that_pass_the_1_0_meta_schema() {
let meta = v1_0_meta();
let forms = Catalog::forms().document_for(A2uiVersion::V1_0);
if let Some(error) = meta.iter_errors(&forms).next() {
panic!("forms 1.0 document: {error} at {}", error.instance_path());
}
assert_eq!(forms["functions"].as_object().unwrap().len(), 10);
assert!(forms["components"].get("Image").is_none());
assert!(forms["functions"].get("openUrl").is_none());
assert_eq!(forms["components"]["Text"]["properties"]["variant"]["enum"][2], "h3");
assert!(!forms["components"]["TextField"].to_string().contains("obscured"));
let gauges = Catalog::extend(ExtensionSpec {
id: "https://example.com/a2ui/catalogs/gauges/1.0/catalog.json",
name: "gauges",
version: "1.0",
components: vec![Arc::new(Gauge) as Arc<dyn ExtensionComponent>],
})
.unwrap()
.with_instructions("Use a gauge for one number against a known range.");
let document = gauges.document_for(A2uiVersion::V1_0);
if let Some(error) = meta.iter_errors(&document).next() {
panic!("extension 1.0 document: {error} at {}", error.instance_path());
}
assert_eq!(document["protocolVersion"], "1.0");
let gauge = &document["components"]["Gauge"];
assert!(document["components"].get("Text").is_none(), "only what the extension adds");
assert!(gauge["properties"].get("id").is_none());
assert_eq!(gauge["required"], json!(["component", "label", "value"]));
assert!(gauge.get("additionalProperties").is_none());
assert_eq!(gauge["properties"]["label"]["$ref"], "common_types.json#/$defs/DynamicString");
assert!(gauge.get("allOf").is_none(), "the envelope composes ComponentCommon");
assert_eq!(gauge["allowedParents"], json!(["Card", "Column"]));
assert!(document["instructions"].as_str().unwrap().contains("Gauge: {label, value}"));
assert!(document["instructions"].as_str().unwrap().contains("known range"));
assert!(gauges.document_for(A2uiVersion::V0_9_1)["components"]["Text"].is_object());
}
#[test]
fn the_forms_catalog_is_the_basic_catalog_without_what_can_fake_a_decision() {
let forms = Catalog::forms();
assert_eq!(
forms.components().collect::<Vec<_>>(),
vec![
"Button",
"Card",
"CheckBox",
"ChoicePicker",
"Column",
"DateTimeInput",
"Divider",
"List",
"Row",
"Slider",
"Tabs",
"Text",
"TextField"
]
);
assert_eq!(
forms.functions().collect::<Vec<_>>(),
vec![
"and",
"email",
"formatString",
"length",
"not",
"numeric",
"or",
"pluralize",
"regex",
"required"
]
);
assert_eq!(forms.document()["catalogId"], FORMS_CATALOG_ID);
}
#[test]
fn components_are_checked_against_their_schema() {
let forms = Catalog::forms();
let text = json!({ "id": "t", "component": "Text", "text": "Invoice INV-10" });
assert_eq!(forms.schema_error("Text", &text), None);
let bound = json!({ "id": "t", "component": "Text", "text": { "path": "/title" } });
assert_eq!(forms.schema_error("Text", &bound), None);
let extra = json!({ "id": "t", "component": "Text", "text": "x", "onClick": "y" });
assert!(forms.schema_error("Text", &extra).is_some());
let obscured = json!({
"id": "p", "component": "TextField", "label": "Password", "variant": "obscured"
});
assert!(forms.schema_error("TextField", &obscured).is_some());
let open = json!({
"id": "b", "component": "Button", "child": "t",
"action": { "functionCall": { "call": "openUrl", "args": { "url": "https://x.test" } } }
});
assert!(forms.schema_error("Button", &open).is_some(), "openUrl is not in the catalog");
}
#[test]
fn a_value_that_may_be_a_binding_or_a_list_names_what_broke_in_the_list() {
let forms = Catalog::forms();
let picker = json!({
"id": "c", "component": "ChoicePicker", "label": "Dock",
"options": [{ "label": "Dock 1", "value": "dock-1" }],
"value": ["dock-1", 5]
});
let error = forms.schema_error("ChoicePicker", &picker).expect("a number among strings");
assert!(error.starts_with("/value/1: "), "{error}");
assert!(!error.contains("oneOf"), "{error}");
}
#[test]
fn a_schema_error_quoting_a_long_value_is_shortened() {
let forms = Catalog::forms();
let long = json!({ "id": "t", "component": "Text", "text": vec![1; 400] });
let error = forms.schema_error("Text", &long).expect("a list is not text");
assert!(error.chars().count() <= MAX_SCHEMA_ERROR_CHARS + "/text: …".len(), "{error}");
assert!(error.ends_with('…'), "{error}");
}
}