use std::collections::BTreeMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::catalog::{Catalogs, FORMS_CATALOG_ID};
pub const A2UI_VERSION: &str = "v0.9.1";
pub const A2UI_MIME_TYPE: &str = "application/a2ui+json";
#[derive(Debug, thiserror::Error)]
pub enum A2uiError {
#[error("line {line} is not an A2UI v0.9.1 message: {source}. Send one message per line.")]
Line {
line: usize,
#[source]
source: serde_json::Error,
},
#[error("'{path}' is not a data model path: a path starts with '/', like '/user/name'")]
Path {
path: String,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct A2uiMessage {
pub version: String,
#[serde(flatten)]
pub body: A2uiBody,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum A2uiBody {
CreateSurface(CreateSurface),
UpdateComponents(UpdateComponents),
UpdateDataModel(UpdateDataModel),
DeleteSurface(DeleteSurface),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateSurface {
pub surface_id: String,
pub catalog_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub theme: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub send_data_model: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateComponents {
pub surface_id: String,
pub components: Vec<Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateDataModel {
pub surface_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DeleteSurface {
pub surface_id: String,
}
impl A2uiMessage {
fn new(body: A2uiBody) -> Self {
Self { version: A2UI_VERSION.to_string(), body }
}
pub fn create_surface(surface_id: impl Into<String>) -> Self {
Self::new(A2uiBody::CreateSurface(CreateSurface {
surface_id: surface_id.into(),
catalog_id: FORMS_CATALOG_ID.to_string(),
theme: None,
send_data_model: None,
}))
}
pub fn update_components(surface_id: impl Into<String>, components: Vec<Value>) -> Self {
Self::new(A2uiBody::UpdateComponents(UpdateComponents {
surface_id: surface_id.into(),
components,
}))
}
pub fn update_data_model(
surface_id: impl Into<String>,
path: Option<String>,
value: Option<Value>,
) -> Self {
Self::new(A2uiBody::UpdateDataModel(UpdateDataModel {
surface_id: surface_id.into(),
path,
value,
}))
}
pub fn delete_surface(surface_id: impl Into<String>) -> Self {
Self::new(A2uiBody::DeleteSurface(DeleteSurface { surface_id: surface_id.into() }))
}
pub fn surface_id(&self) -> &str {
match &self.body {
A2uiBody::CreateSurface(body) => &body.surface_id,
A2uiBody::UpdateComponents(body) => &body.surface_id,
A2uiBody::UpdateDataModel(body) => &body.surface_id,
A2uiBody::DeleteSurface(body) => &body.surface_id,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct A2uiClientMessage {
pub version: String,
#[serde(flatten)]
pub body: A2uiClientBody,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum A2uiClientBody {
Action(ClientAction),
Error(ClientError),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ClientAction {
pub name: String,
pub surface_id: String,
pub source_component_id: String,
pub timestamp: String,
#[serde(default)]
pub context: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ClientError {
pub code: String,
pub surface_id: String,
pub path: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum DynamicString {
Literal(String),
Binding(DataBinding),
Call(FunctionCall),
}
impl DynamicString {
pub fn literal(value: impl Into<String>) -> Self {
Self::Literal(value.into())
}
pub fn path(path: impl Into<String>) -> Self {
Self::Binding(DataBinding { path: path.into() })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DataBinding {
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FunctionCall {
pub call: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub args: BTreeMap<String, Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub return_type: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(transparent)]
pub struct DataModel(Value);
impl DataModel {
pub fn new(value: Value) -> Self {
Self(value)
}
pub fn value(&self) -> &Value {
&self.0
}
pub fn get(&self, pointer: &str) -> Option<&Value> {
if pointer.is_empty() || pointer == "/" {
return Some(&self.0);
}
self.0.pointer(pointer)
}
pub fn apply(&mut self, path: Option<&str>, value: Option<Value>) -> Result<(), A2uiError> {
let value = value.filter(|value| !value.is_null());
let path = path.unwrap_or("/");
if path == "/" || path.is_empty() {
self.0 = value.unwrap_or(Value::Null);
return Ok(());
}
let invalid = || A2uiError::Path { path: path.to_string() };
let rest = path.strip_prefix('/').ok_or_else(invalid)?;
let tokens: Vec<String> =
rest.split('/').map(|token| token.replace("~1", "/").replace("~0", "~")).collect();
let Some((last, parents)) = tokens.split_last() else {
return Err(invalid());
};
let setting = value.is_some();
let mut node = &mut self.0;
for token in parents {
if setting && !node.is_object() && !node.is_array() {
*node = Value::Object(serde_json::Map::new());
}
node = match (node, setting) {
(Value::Object(map), true) => map
.entry(token.clone())
.or_insert_with(|| Value::Object(serde_json::Map::new())),
(Value::Object(map), false) => match map.get_mut(token) {
Some(next) => next,
None => return Ok(()),
},
(Value::Array(items), _) => match token.parse::<usize>() {
Ok(index) if index < items.len() => &mut items[index],
_ if setting => return Err(invalid()),
_ => return Ok(()),
},
_ => return Ok(()),
};
}
match (node, value) {
(Value::Object(map), Some(value)) => {
map.insert(last.clone(), value);
}
(Value::Object(map), None) => {
map.remove(last);
}
(Value::Array(items), Some(value)) => match last.parse::<usize>() {
Ok(index) if index < items.len() => items[index] = value,
Ok(index) if index == items.len() => items.push(value),
_ => return Err(invalid()),
},
(Value::Array(items), None) => {
if let Ok(index) = last.parse::<usize>()
&& index < items.len()
{
items.remove(index);
}
}
(node, Some(value)) => {
let mut map = serde_json::Map::new();
map.insert(last.clone(), value);
*node = Value::Object(map);
}
(_, None) => {}
}
Ok(())
}
}
pub fn encode_jsonl(messages: &[A2uiMessage]) -> String {
let mut out = String::new();
for message in messages {
out.push_str(&serde_json::to_string(message).unwrap_or_default());
out.push('\n');
}
out
}
pub fn decode_jsonl(text: &str) -> Result<Vec<A2uiMessage>, A2uiError> {
text.lines()
.enumerate()
.filter(|(_, line)| !line.trim().is_empty())
.map(|(index, line)| {
serde_json::from_str(line).map_err(|source| A2uiError::Line { line: index + 1, source })
})
.collect()
}
pub fn stable_id(seed: &str) -> String {
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0100_0000_01b3;
let hash = seed.bytes().fold(OFFSET, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(PRIME));
format!("id_{hash:016x}")
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct A2uiCapabilities {
#[serde(rename = "1.0", default, skip_serializing_if = "Option::is_none")]
pub v1_0: Option<CapabilitySet>,
#[serde(rename = "v0.9", default, skip_serializing_if = "Option::is_none")]
pub v0_9: Option<CapabilitySet>,
}
impl A2uiCapabilities {
pub fn forms() -> Self {
let set = CapabilitySet {
supported_catalog_ids: vec![FORMS_CATALOG_ID.to_string()],
accepts_inline_catalogs: false,
};
Self { v1_0: Some(set.clone()), v0_9: Some(set) }
}
pub fn of(catalogs: &Catalogs) -> Self {
let set = CapabilitySet {
supported_catalog_ids: catalogs
.iter()
.map(|catalog| catalog.id().to_string())
.collect(),
accepts_inline_catalogs: false,
};
Self { v1_0: Some(set.clone()), v0_9: Some(set) }
}
pub fn preferred(&self) -> Option<super::wire::A2uiVersion> {
use super::wire::A2uiVersion;
if self.v1_0.is_some() {
Some(A2uiVersion::V1_0)
} else if self.v0_9.is_some() {
Some(A2uiVersion::V0_9_1)
} else {
None
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CapabilitySet {
pub supported_catalog_ids: Vec<String>,
#[serde(default)]
pub accepts_inline_catalogs: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn messages_round_trip_through_the_upstream_wire_shape() {
let wire = json!({
"version": "v0.9.1",
"updateDataModel": { "surfaceId": "s", "path": "/to", "value": "ana@example.com" }
});
let message: A2uiMessage = serde_json::from_value(wire.clone()).unwrap();
assert_eq!(
message,
A2uiMessage::update_data_model(
"s",
Some("/to".to_string()),
Some(json!("ana@example.com"))
)
);
assert_eq!(serde_json::to_value(&message).unwrap(), wire);
}
#[test]
fn an_unknown_body_or_field_is_not_a_message() {
for wire in [
json!({ "version": "v0.9.1", "callFunction": { "call": "x" } }),
json!({ "version": "v0.9.1", "deleteSurface": { "surfaceId": "s", "extra": 1 } }),
] {
assert!(serde_json::from_value::<A2uiMessage>(wire.clone()).is_err(), "{wire}");
}
}
#[test]
fn decoding_names_the_line_that_fails() {
let error = decode_jsonl(
"{\"version\":\"v0.9.1\",\"deleteSurface\":{\"surfaceId\":\"s\"}}\n\nnope\n",
)
.unwrap_err();
assert!(matches!(error, A2uiError::Line { line: 3, .. }), "{error}");
}
#[test]
fn the_data_model_sets_and_removes_values_in_objects_and_arrays() {
let mut model = DataModel::new(json!({ "rows": [{ "a": 1 }] }));
model.apply(Some("/rows/0/a"), Some(json!(2))).unwrap();
model.apply(Some("/rows/1"), Some(json!({ "a": 3 }))).unwrap();
model.apply(Some("/a~1b"), Some(json!("slash"))).unwrap();
assert_eq!(model.value(), &json!({ "rows": [{ "a": 2 }, { "a": 3 }], "a/b": "slash" }));
model.apply(Some("/rows/0"), None).unwrap();
model.apply(Some("/missing/deep"), None).unwrap();
assert_eq!(model.value(), &json!({ "rows": [{ "a": 3 }], "a/b": "slash" }));
assert!(model.apply(Some("rows"), Some(json!(1))).is_err());
assert!(model.apply(Some("/rows/7"), Some(json!(1))).is_err());
model.apply(None, Some(json!({ "fresh": true }))).unwrap();
assert_eq!(model.value(), &json!({ "fresh": true }));
}
}