1use crate::ident::is_identifier;
8use crate::schema::{check_catalog_definition, CompileError, SchemaError, SchemaSet};
9use serde_json::Value;
10use std::collections::BTreeMap;
11use std::sync::OnceLock;
12
13pub const BASIC_CATALOG_ID: &str =
15 "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json";
16
17const BASIC_CATALOG: &str = include_str!("../spec/v1_0/catalogs/basic/catalog.json");
18
19pub const ALLOWED_EXTERNAL_REF_TARGETS: &[&str] = &[
22 "ComponentId",
23 "Child",
24 "ChildList",
25 "DynamicString",
26 "DynamicNumber",
27 "DynamicBoolean",
28 "DynamicStringList",
29 "DynamicValue",
30 "AccessibilityAttributes",
31 "CheckRule",
32 "Checkable",
33 "Action",
34 "DataBinding",
35 "FunctionCall",
36];
37
38#[derive(Debug, Clone, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum ChildRef {
44 Single,
46 List,
48 Items(String),
51}
52
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
55pub struct ComponentDef {
56 pub children: BTreeMap<String, ChildRef>,
58 pub allowed_parents: Option<Vec<String>>,
60 pub allowed_children: Option<Vec<String>>,
62 pub actions: std::collections::BTreeSet<String>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Callers {
70 RendererOnly,
72 AgentOnly,
74 RendererOrAgent,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct FunctionDef {
81 pub return_type: String,
83 pub callers: Callers,
85 pub requires_user_activation: bool,
87}
88
89#[derive(Debug, Clone, thiserror::Error)]
91#[non_exhaustive]
92pub enum CatalogError {
93 #[error("catalog does not match catalog_definition.json: {}", join(.0))]
95 Schema(Vec<SchemaError>),
96 #[error("invalid catalog: {0}")]
99 Rule(String),
100 #[error(transparent)]
102 Compile(#[from] CompileError),
103}
104
105fn join(errors: &[SchemaError]) -> String {
106 errors
107 .iter()
108 .map(ToString::to_string)
109 .collect::<Vec<_>>()
110 .join("; ")
111}
112
113#[derive(Debug, Clone)]
115pub struct Catalog {
116 id: String,
117 document: Value,
118 components: BTreeMap<String, ComponentDef>,
119 functions: BTreeMap<String, FunctionDef>,
120}
121
122impl Catalog {
123 pub fn basic() -> &'static Catalog {
125 static BASIC: OnceLock<Catalog> = OnceLock::new();
126 BASIC.get_or_init(|| {
127 let document = serde_json::from_str(BASIC_CATALOG).expect("basic catalog is JSON");
128 Catalog::from_value(document).expect("the vendored basic catalog is valid")
129 })
130 }
131
132 pub fn from_value(document: Value) -> Result<Catalog, CatalogError> {
140 check_catalog_definition(&document).map_err(CatalogError::Schema)?;
141 let object = document
142 .as_object()
143 .ok_or_else(|| CatalogError::Rule("a catalog is a JSON object".into()))?;
144 match object.get("protocolVersion").and_then(Value::as_str) {
145 Some("1.0") => {}
146 Some(other) => {
147 return Err(CatalogError::Rule(format!(
148 "protocolVersion is {other:?}; this implementation reads 1.0 catalogs only"
149 )))
150 }
151 None => {
152 return Err(CatalogError::Rule(
153 "protocolVersion is missing, which means 0.9; this implementation reads 1.0 catalogs only".into(),
154 ))
155 }
156 }
157 let id = object
158 .get("catalogId")
159 .and_then(Value::as_str)
160 .unwrap_or_default()
161 .to_string();
162 let empty = serde_json::Map::new();
163 let component_docs = object
164 .get("components")
165 .and_then(Value::as_object)
166 .unwrap_or(&empty);
167 let function_docs = object
168 .get("functions")
169 .and_then(Value::as_object)
170 .unwrap_or(&empty);
171 let defs = object
172 .get("$defs")
173 .and_then(Value::as_object)
174 .unwrap_or(&empty);
175
176 let mut problems = Vec::new();
177 for (name, schema) in component_docs {
178 if !is_identifier(name) {
179 problems.push(format!("component name {name:?} is not an identifier"));
180 }
181 if discriminator(schema) != Some(name.as_str()) {
182 problems.push(format!(
183 "component {name:?} must declare \"component\": {{\"const\": {name:?}}}"
184 ));
185 }
186 check_names(schema, &mut problems);
187 }
188 for (name, schema) in function_docs {
189 let bare = name.strip_prefix('@').unwrap_or(name);
190 if !is_identifier(bare) {
191 problems.push(format!("function name {name:?} is not an identifier"));
192 }
193 check_names(schema, &mut problems);
194 }
195 for (name, schema) in defs {
196 if name == "anyComponent" || name == "anyFunction" {
197 continue;
198 }
199 if !is_identifier(name) {
200 problems.push(format!("$defs name {name:?} is not an identifier"));
201 }
202 check_names(schema, &mut problems);
203 }
204 let mut refs = Vec::new();
205 for section in [component_docs, function_docs, defs] {
206 for schema in section.values() {
207 collect_refs(schema, &mut refs);
208 }
209 }
210 for target in refs {
211 if let Some(problem) = ref_problem(&target, component_docs, function_docs, defs) {
212 problems.push(problem);
213 }
214 }
215 if !problems.is_empty() {
216 return Err(CatalogError::Rule(problems.join("; ")));
217 }
218
219 let components = component_docs
220 .iter()
221 .map(|(name, schema)| (name.clone(), component_def(schema)))
222 .collect();
223 let functions = function_docs
224 .iter()
225 .map(|(name, schema)| (name.clone(), function_def(schema)))
226 .collect();
227 let catalog = Catalog {
228 id,
229 document,
230 components,
231 functions,
232 };
233 SchemaSet::for_catalog(&catalog)?;
235 Ok(catalog)
236 }
237
238 pub fn id(&self) -> &str {
240 &self.id
241 }
242
243 pub fn document(&self) -> &Value {
245 &self.document
246 }
247
248 pub fn instructions(&self) -> Option<&str> {
250 self.document.get("instructions").and_then(Value::as_str)
251 }
252
253 pub fn components(&self) -> &BTreeMap<String, ComponentDef> {
255 &self.components
256 }
257
258 pub fn functions(&self) -> &BTreeMap<String, FunctionDef> {
260 &self.functions
261 }
262
263 pub fn component(&self, name: &str) -> Option<&ComponentDef> {
265 self.components.get(name)
266 }
267
268 pub fn function(&self, name: &str) -> Option<&FunctionDef> {
270 self.functions.get(name)
271 }
272
273 pub fn declares(&self, type_name: &str, name: &str) -> bool {
280 let Some(schema) = self.document.pointer(&format!(
281 "/components/{}",
282 type_name.replace('~', "~0").replace('/', "~1")
283 )) else {
284 return false;
285 };
286 declared(schema, name, &self.document, 0)
287 }
288
289 pub fn declares_own(&self, type_name: &str, name: &str) -> bool {
296 let Some(schema) = self.document.pointer(&format!(
297 "/components/{}",
298 type_name.replace('~', "~0").replace('/', "~1")
299 )) else {
300 return false;
301 };
302 own(schema, name, &self.document, 0)
303 }
304}
305
306fn discriminator(schema: &Value) -> Option<&str> {
309 property_maps(schema)
310 .into_iter()
311 .find_map(|properties| properties.get("component")?.get("const")?.as_str())
312}
313
314fn property_maps(schema: &Value) -> Vec<&serde_json::Map<String, Value>> {
317 let mut maps = Vec::new();
318 if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
319 maps.push(properties);
320 }
321 if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
322 for entry in all {
323 if let Some(properties) = entry.get("properties").and_then(Value::as_object) {
324 maps.push(properties);
325 }
326 }
327 }
328 maps
329}
330
331fn child_ref(property: &Value) -> Option<ChildRef> {
332 match property.get("$ref")?.as_str()? {
333 "common_types.json#/$defs/ComponentId" | "common_types.json#/$defs/Child" => {
334 Some(ChildRef::Single)
335 }
336 "common_types.json#/$defs/ChildList" => Some(ChildRef::List),
337 _ => None,
338 }
339}
340
341fn strings(value: Option<&Value>) -> Option<Vec<String>> {
342 Some(
343 value?
344 .as_array()?
345 .iter()
346 .filter_map(|item| item.as_str().map(String::from))
347 .collect(),
348 )
349}
350
351fn items_ref(property: &Value) -> Option<ChildRef> {
354 let items = property.get("items")?;
355 if child_ref(items) == Some(ChildRef::Single) {
356 return Some(ChildRef::List);
357 }
358 let fields = items.get("properties")?.as_object()?;
359 fields
360 .iter()
361 .find(|(_, field)| child_ref(field) == Some(ChildRef::Single))
362 .map(|(name, _)| ChildRef::Items(name.clone()))
363}
364
365fn component_def(schema: &Value) -> ComponentDef {
366 let mut children = BTreeMap::new();
367 let mut actions = std::collections::BTreeSet::new();
368 for properties in property_maps(schema) {
369 for (name, property) in properties {
370 if let Some(kind) = child_ref(property).or_else(|| items_ref(property)) {
371 children.insert(name.clone(), kind);
372 }
373 if property.get("$ref").and_then(Value::as_str)
374 == Some("common_types.json#/$defs/Action")
375 {
376 actions.insert(name.clone());
377 }
378 }
379 }
380 ComponentDef {
381 children,
382 allowed_parents: strings(schema.get("allowedParents")),
383 allowed_children: strings(schema.get("allowedChildren")),
384 actions,
385 }
386}
387
388fn function_def(schema: &Value) -> FunctionDef {
389 let callers = match schema.get("allowedCallers").and_then(Value::as_str) {
390 Some("agentOnly") => Callers::AgentOnly,
391 Some("rendererOrAgent") => Callers::RendererOrAgent,
392 _ => Callers::RendererOnly,
393 };
394 FunctionDef {
395 return_type: schema
396 .get("returnType")
397 .and_then(Value::as_str)
398 .unwrap_or("any")
399 .to_string(),
400 callers,
401 requires_user_activation: schema
402 .get("requiresUserActivation")
403 .and_then(Value::as_bool)
404 .unwrap_or(false),
405 }
406}
407
408const NON_SCHEMA_KEYS: &[&str] = &[
410 "metadata",
411 "examples",
412 "const",
413 "default",
414 "enum",
415 "description",
416];
417
418fn check_names(schema: &Value, problems: &mut Vec<String>) {
421 match schema {
422 Value::Object(object) => {
423 if let Some(properties) = object.get("properties").and_then(Value::as_object) {
424 for (name, property) in properties {
425 if name != "@path" && name != "@call" && !is_identifier(name) {
426 problems.push(format!("property name {name:?} is not an identifier"));
427 }
428 check_names(property, problems);
429 }
430 }
431 for (key, value) in object {
432 if key != "properties" && !NON_SCHEMA_KEYS.contains(&key.as_str()) {
433 check_names(value, problems);
434 }
435 }
436 }
437 Value::Array(items) => {
438 for item in items {
439 check_names(item, problems);
440 }
441 }
442 _ => {}
443 }
444}
445
446fn collect_refs(schema: &Value, refs: &mut Vec<String>) {
447 match schema {
448 Value::Object(object) => {
449 if let Some(target) = object.get("$ref").and_then(Value::as_str) {
450 refs.push(target.to_string());
451 }
452 if let Some(properties) = object.get("properties").and_then(Value::as_object) {
453 for property in properties.values() {
454 collect_refs(property, refs);
455 }
456 }
457 for (key, value) in object {
458 if key != "properties" && !NON_SCHEMA_KEYS.contains(&key.as_str()) {
459 collect_refs(value, refs);
460 }
461 }
462 }
463 Value::Array(items) => {
464 for item in items {
465 collect_refs(item, refs);
466 }
467 }
468 _ => {}
469 }
470}
471
472fn fragment_key(segment: &str) -> String {
475 let bytes = segment.as_bytes();
476 let mut decoded = Vec::with_capacity(bytes.len());
477 let mut i = 0;
478 while i < bytes.len() {
479 let hex = |b: u8| (b as char).to_digit(16);
480 match (
481 bytes[i],
482 bytes.get(i + 1).copied(),
483 bytes.get(i + 2).copied(),
484 ) {
485 (b'%', Some(h), Some(l)) if hex(h).is_some() && hex(l).is_some() => {
486 decoded.push((hex(h).unwrap() * 16 + hex(l).unwrap()) as u8);
487 i += 3;
488 }
489 (b, _, _) => {
490 decoded.push(b);
491 i += 1;
492 }
493 }
494 }
495 String::from_utf8_lossy(&decoded)
496 .replace("~1", "/")
497 .replace("~0", "~")
498}
499
500fn own(schema: &Value, name: &str, document: &Value, depth: usize) -> bool {
503 if depth > 16 {
504 return false;
505 }
506 if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
507 if let Some(property) = properties.get(name) {
508 let standard = match name {
509 "catalogId" => property.get("type").and_then(Value::as_str) == Some("string"),
510 "metadata" => {
511 property.get("type").and_then(Value::as_str) == Some("object")
512 && property
513 .get("properties")
514 .and_then(Value::as_object)
515 .is_some_and(|inner| {
516 inner.len() == 1 && inner.contains_key("extensions")
517 })
518 }
519 _ => false,
520 };
521 if !(standard && properties.contains_key("id")) {
522 return true;
523 }
524 }
525 }
526 if let Some(local) = schema
527 .get("$ref")
528 .and_then(Value::as_str)
529 .and_then(|target| target.strip_prefix('#'))
530 {
531 if let Some(target) = document.pointer(local) {
532 if own(target, name, document, depth + 1) {
533 return true;
534 }
535 }
536 }
537 ["allOf", "oneOf", "anyOf"].iter().any(|key| {
538 schema
539 .get(*key)
540 .and_then(Value::as_array)
541 .is_some_and(|parts| {
542 parts
543 .iter()
544 .any(|part| own(part, name, document, depth + 1))
545 })
546 })
547}
548
549fn declared(schema: &Value, name: &str, document: &Value, depth: usize) -> bool {
552 if depth > 16 {
553 return false;
554 }
555 if schema
556 .get("properties")
557 .and_then(Value::as_object)
558 .is_some_and(|properties| properties.contains_key(name))
559 {
560 return true;
561 }
562 if let Some(local) = schema
563 .get("$ref")
564 .and_then(Value::as_str)
565 .and_then(|target| target.strip_prefix('#'))
566 {
567 if let Some(target) = document.pointer(local) {
568 if declared(target, name, document, depth + 1) {
569 return true;
570 }
571 }
572 }
573 ["allOf", "oneOf", "anyOf"].iter().any(|key| {
574 schema
575 .get(*key)
576 .and_then(Value::as_array)
577 .is_some_and(|parts| {
578 parts
579 .iter()
580 .any(|part| declared(part, name, document, depth + 1))
581 })
582 })
583}
584
585fn ref_problem(
586 target: &str,
587 components: &serde_json::Map<String, Value>,
588 functions: &serde_json::Map<String, Value>,
589 defs: &serde_json::Map<String, Value>,
590) -> Option<String> {
591 if let Some(name) = target.strip_prefix("#/components/") {
592 return (!components.contains_key(&fragment_key(name)))
593 .then(|| format!("$ref {target:?} names no component of this catalog"));
594 }
595 if let Some(name) = target.strip_prefix("#/functions/") {
596 return (!functions.contains_key(&fragment_key(name)))
597 .then(|| format!("$ref {target:?} names no function of this catalog"));
598 }
599 if let Some(name) = target.strip_prefix("#/$defs/") {
600 if name == "anyComponent" || name == "anyFunction" {
601 return Some(format!(
602 "$ref {target:?} may not be referenced from inside the catalog"
603 ));
604 }
605 return (!defs.contains_key(&fragment_key(name)))
606 .then(|| format!("$ref {target:?} names no $defs entry of this catalog"));
607 }
608 if let Some(name) = target.strip_prefix("common_types.json#/$defs/") {
609 return (!ALLOWED_EXTERNAL_REF_TARGETS.contains(&name))
610 .then(|| format!("$ref {target:?} is not one of the common types a catalog may use"));
611 }
612 Some(format!(
613 "$ref {target:?} points outside the catalog and the common types, which is not allowed"
614 ))
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620 use serde_json::json;
621
622 #[test]
623 fn a_ref_fragment_is_percent_decoded_and_unescaped() {
624 assert_eq!(fragment_key("%F0%9D%91%A5Label"), "š„Label");
625 assert_eq!(fragment_key("a~1b~0c"), "a/b~c");
626 assert_eq!(fragment_key("100%"), "100%");
627 }
628
629 #[test]
630 fn an_array_of_component_ids_is_a_child_list() {
631 let catalog = Catalog::from_value(json!({
632 "protocolVersion": "1.0",
633 "catalogId": "slots",
634 "components": {"Slots": {
635 "type": "object",
636 "properties": {
637 "component": {"const": "Slots"},
638 "slots": {"type": "array", "items": {"$ref": "common_types.json#/$defs/ComponentId"}}
639 },
640 "required": ["component"]
641 }},
642 "$defs": {"anyComponent": {"oneOf": [{"$ref": "#/components/Slots"}]}, "anyFunction": false}
643 }))
644 .unwrap();
645 assert_eq!(
646 catalog.component("Slots").unwrap().children.get("slots"),
647 Some(&ChildRef::List)
648 );
649 }
650
651 #[test]
652 fn the_basic_catalog_loads_with_its_structure() {
653 let basic = Catalog::basic();
654 assert_eq!(basic.id(), BASIC_CATALOG_ID);
655 assert_eq!(basic.components().len(), 18);
656 assert_eq!(
657 basic.component("Column").unwrap().children.get("children"),
658 Some(&ChildRef::List)
659 );
660 assert_eq!(
661 basic.component("Button").unwrap().children.get("child"),
662 Some(&ChildRef::Single)
663 );
664 assert!(basic.component("Text").unwrap().children.is_empty());
665 assert_eq!(
666 basic.component("Tabs").unwrap().children.get("tabs"),
667 Some(&ChildRef::Items("child".into()))
668 );
669 assert!(basic
670 .component("Button")
671 .unwrap()
672 .actions
673 .contains("action"));
674 let open = basic.function("openUrl").unwrap();
675 assert!(open.requires_user_activation);
676 assert_eq!(open.callers, Callers::RendererOnly);
677 assert_eq!(
678 basic.function("required").unwrap().return_type,
679 "validationResult"
680 );
681 assert!(basic.instructions().unwrap().contains("formatString"));
682 }
683
684 fn minimal(extra: Value) -> Value {
685 let mut catalog = json!({
686 "protocolVersion": "1.0",
687 "catalogId": "example.com:test",
688 "components": {
689 "Label": {
690 "type": "object",
691 "properties": {
692 "component": {"const": "Label"},
693 "text": {"$ref": "common_types.json#/$defs/DynamicString"}
694 },
695 "required": ["component", "text"]
696 }
697 },
698 "functions": {},
699 "$defs": {
700 "anyComponent": {"oneOf": [{"$ref": "#/components/Label"}]},
701 "anyFunction": false
702 }
703 });
704 if let (Some(base), Some(extra)) = (catalog.as_object_mut(), extra.as_object()) {
705 for (key, value) in extra {
706 base.insert(key.clone(), value.clone());
707 }
708 }
709 catalog
710 }
711
712 #[test]
713 fn a_minimal_catalog_loads() {
714 let catalog = Catalog::from_value(minimal(json!({}))).unwrap();
715 assert_eq!(catalog.id(), "example.com:test");
716 }
717
718 #[test]
719 fn refuses_a_catalog_for_another_protocol_version() {
720 let error = Catalog::from_value(minimal(json!({"protocolVersion": "0.9"}))).unwrap_err();
721 assert!(error.to_string().contains("1.0 catalogs only"), "{error}");
722 let mut no_version = minimal(json!({}));
723 no_version
724 .as_object_mut()
725 .unwrap()
726 .remove("protocolVersion");
727 assert!(Catalog::from_value(no_version).is_err());
728 }
729
730 #[test]
731 fn refuses_a_reference_outside_the_catalog() {
732 let catalog = minimal(json!({
733 "$defs": {
734 "anyComponent": {"oneOf": [{"$ref": "#/components/Label"}]},
735 "anyFunction": false,
736 "Remote": {"$ref": "https://example.com/elsewhere.json"}
737 }
738 }));
739 let error = Catalog::from_value(catalog).unwrap_err();
740 assert!(error.to_string().contains("points outside"), "{error}");
741 }
742
743 #[test]
744 fn refuses_a_common_type_not_on_the_list() {
745 let catalog = minimal(json!({
746 "$defs": {
747 "anyComponent": {"oneOf": [{"$ref": "#/components/Label"}]},
748 "anyFunction": false,
749 "Sneaky": {"$ref": "common_types.json#/$defs/FunctionResponse"}
750 }
751 }));
752 let error = Catalog::from_value(catalog).unwrap_err();
753 assert!(
754 error.to_string().contains("not one of the common types"),
755 "{error}"
756 );
757 }
758
759 #[test]
760 fn refuses_a_component_whose_discriminator_does_not_match() {
761 let catalog = minimal(json!({
762 "components": {
763 "Label": {
764 "type": "object",
765 "properties": {"component": {"const": "Other"}},
766 "required": ["component"]
767 }
768 }
769 }));
770 let error = Catalog::from_value(catalog).unwrap_err();
771 assert!(error.to_string().contains("must declare"), "{error}");
772 }
773
774 #[test]
775 fn refuses_a_name_that_is_not_an_identifier() {
776 let catalog = minimal(json!({
777 "components": {
778 "Label": {
779 "type": "object",
780 "properties": {
781 "component": {"const": "Label"},
782 "font-size": {"type": "number"}
783 },
784 "required": ["component"]
785 }
786 }
787 }));
788 let error = Catalog::from_value(catalog).unwrap_err();
789 assert!(error.to_string().contains("\"font-size\""), "{error}");
790 }
791}