//! The JSON Schemas of what an operator writes, published in //! `schemas/json/` for editors to complete and check as they're written //! (a file's `$schema`): an app file, `.json` (`app`), and a view, //! `views/.json` (`view`). A view's is made from the component catalog //! (`catalog::COMPONENTS`), an app file's from HUD's own lexicons of its //! parts (`schemas/place.hud.{frame,page,signIn,tabFirst}.json`). They say //! the shape alone: HUD's loader (`operator::load`, `hud check`) holds a //! file to everything else (what its calls draw, its lexicons, its paths). //! Each object HUD refuses an unknown key of refuses one here too, but a //! view's optional key (`?key`, `view::load`), which any of its objects //! may hold. use crate::catalog::{COMPONENTS, Given, Ty}; use serde_json::{Map, Value, json}; /// Where the schemas are published: `schemas/json/` of HUD's repository, /// as its `main` has them. pub const BASE: &str = "https://knotless.dev/chadtmiller.com/hud/raw/main/schemas/json"; /// The JSON Schema draft the schemas are written in. const DRAFT: &str = "https://json-schema.org/draft/2020-12/schema"; /// An object of `properties`, refusing any other key, requiring /// `required`. fn closed(properties: Value, required: &[&str]) -> Value { let mut o = json!({ "type": "object", "properties": properties, "additionalProperties": false, }); if !required.is_empty() { o["required"] = json!(required); } o } /// A view's object of `properties`: `closed`, but for an optional key /// (`?key`), which any of a view's objects may hold. fn strict(properties: Value, required: &[&str]) -> Value { let mut o = closed(properties, required); o["patternProperties"] = json!({ "^\\?": {} }); o } /// The schema `#/$defs/` of the schema it is in. fn def(name: &str) -> Value { json!({ "$ref": format!("#/$defs/{name}") }) } /// A prop's literal value of `ty`, as `Ty::check_literal` takes it. fn literal(ty: Ty) -> Value { let objects = |min: u64, max: u64| json!({ "type": "array", "minItems": min, "maxItems": max, "items": { "type": "object" } }); match ty { Ty::Text => json!({ "type": ["string", "number"] }), Ty::Short => json!({ "type": "string", "maxLength": 40 }), Ty::Url | Ty::Href | Ty::Time | Ty::Path => json!({ "type": "string" }), Ty::Gate => json!({ "anyOf": [{ "type": "string" }, closed( json!({ "$kit": { "type": "string", "description": "A semver requirement the version of the kit drawing it meets, as >=0.3.0." } }), &["$kit"], )] }), Ty::Number => json!({ "type": "number" }), Ty::Int => json!({ "type": "integer", "minimum": 1, "maximum": 100 }), Ty::Between(min, max) => json!({ "type": "integer", "minimum": min, "maximum": max }), Ty::Open => json!({ "anyOf": [{ "type": "object" }, { "const": false }] }), Ty::Items => objects(0, crate::catalog::MAX_LITERAL_ITEMS as u64), Ty::Tabs => objects(2, 6), Ty::Cases => objects(1, 4), Ty::Info | Ty::Srcset => objects(1, 4), Ty::Options => { json!({ "type": "array", "minItems": 2, "maxItems": 6, "items": strict(json!({ "label": { "type": "string", "minLength": 1, "maxLength": 40 }, "value": { "type": "string", "minLength": 1, "maxLength": 128 }, }), &["label", "value"]) }) } Ty::Record => json!(false), Ty::Any => json!({}), Ty::Strings => { json!({ "type": "array", "items": { "anyOf": [{ "type": "string" }, def("binding")] } }) } Ty::Nouns => json!({ "type": "array", "minItems": 2, "maxItems": 2, "items": { "type": "string", "minLength": 1, "maxLength": 32 } }), Ty::AspectRatio => strict( json!({ "width": { "type": "integer", "minimum": 1 }, "height": { "type": "integer", "minimum": 1 } }), &["width", "height"], ), Ty::Flag => json!({ "type": "boolean" }), Ty::Labels => json!({ "anyOf": [{ "type": "object" }, { "type": "array", "items": { "type": "string" } }] }), Ty::OneOf(words) => json!({ "enum": words }), Ty::Words { keys, values } => { let mut word = json!({ "type": "string", "minLength": 1, "maxLength": 64 }); if let Some(values) = values { word["enum"] = json!(values); } let mut o = json!({ "type": "object", "minProperties": 1, "maxProperties": 32, "additionalProperties": word }); if let Some(keys) = keys { o["propertyNames"] = json!({ "enum": keys }); } o } Ty::Where => json!({ "type": "object", "minProperties": 1, "maxProperties": 4 }), Ty::Fields | Ty::Writes => json!({ "type": "array" }), Ty::Given => json!({ "type": "object", "maxProperties": 8 }), Ty::Row | Ty::More | Ty::Create | Ty::Delete | Ty::Interaction | Ty::Call { .. } | Ty::Deletes | Ty::Select | Ty::Group => json!({ "type": "object" }), } } /// A prop of `ty`, given as `given` says: a literal, a binding, either, or /// either or a root binding. fn prop(ty: Ty, given: Given) -> Value { match given { Given::Literal => literal(ty), Given::Binding => def("binding"), Given::Either => json!({ "anyOf": [literal(ty), def("binding")] }), Given::EitherOrRoot => json!({ "anyOf": [literal(ty), def("binding"), def("root")] }), } } /// A layout's node: one of the catalog's components, its props each what /// the catalog says, and its children where it takes them. fn node() -> Value { let names: Vec<&str> = COMPONENTS.iter().map(|c| c.name).collect(); let cases: Vec = COMPONENTS .iter() .map(|c| { let props: Map = c .props .iter() .map(|p| (p.name.to_string(), prop(p.ty, p.given))) .collect(); let required: Vec<&str> = c.props.iter().filter(|p| p.required).map(|p| p.name).collect(); let children = match c.children { true => json!({ "type": "array", "items": def("node") }), false => json!(false), }; json!({ "if": { "properties": { "component": { "const": c.name } }, "required": ["component"] }, "then": { "description": c.notes, "properties": { "props": strict(Value::Object(props), &required), "children": children }, }, }) }) .collect(); let mut node = strict( json!({ "component": { "enum": names, "description": "One of the catalog's components." }, "props": { "type": "object" }, "children": { "type": "array", "items": def("node") }, "fallback": { "allOf": [def("node")], "description": "What a kit that doesn't know the component draws in its place, where it has no children." }, }), &["component"], ); node["allOf"] = json!(cases); node } /// The `$defs` of a view's schema: a node, a binding and a root binding, /// a mode, a query view's and an app page's, a join, a summary and a head. fn view_defs() -> Value { let any = json!({}); let path = json!({ "type": "string", "description": "Keys joined by dots, as a.b.0." }); let layout = def("node"); json!({ "node": node(), "binding": { "description": "A value read from the scope: {\"$\": path}, or {\"$\": [paths]}, the first usable.", "type": "object", "properties": { "$": { "anyOf": [ { "type": "string" }, { "type": "array", "minItems": 1, "maxItems": 4, "items": { "type": "string" } }, ] } }, "required": ["$"], "additionalProperties": false, }, "root": { "description": "A value read from the view's own scope: {\"$root\": path}.", "type": "object", "properties": { "$root": { "type": "string" } }, "required": ["$root"], "additionalProperties": false, }, "mode": strict(json!({ "join": { "type": "array", "items": def("join") }, "summary": def("summary"), "head": def("head"), "layout": layout, }), &["layout"]), "queryMode": strict(json!({ "items": path, "cursor": path, "latest": path, "join": { "type": "array", "items": def("join") }, "summary": def("summary"), "head": def("head"), "layout": layout, "fresh": { "type": "boolean" }, }), &["layout"]), "pageMode": strict(json!({ "join": { "type": "array", "items": def("join") }, "layout": layout, "tag": { "type": "object" }, "pages": { "type": "string" }, "head": def("head"), }), &["layout"]), "join": strict(json!({ "as": { "type": "string" }, "ref": path, "each": path, "backlinks": { "type": "object" }, "counts": { "type": "object" }, "collection": { "type": "string" }, "orderBy": { "type": "array", "items": { "type": "string" } }, "limit": { "type": "integer", "minimum": 1, "maximum": crate::view::JOIN_LIMIT_MAX }, "join": { "type": "array", "items": def("join") }, "query": { "type": "string" }, "params": { "type": "object" }, "service": { "type": "string" }, "say": { "type": "object" }, "when": any, "unless": any, "fresh": { "type": "boolean" }, }), &["as"]), "summary": strict(json!({ "noun": literal(Ty::Nouns), "label": any, "by": any, "detail": { "type": "object" }, }), &["noun"]), "head": strict( crate::view::HEAD.iter().map(|k| (k.to_string(), json!({}))).collect::>().into(), &[], ), }) } /// The JSON Schema of a view (`views/.json`, a `place.hud.view`). pub fn view() -> Value { let text = |max: u64| json!({ "type": "string", "minLength": 1, "maxLength": max }); let measure = json!({ "enum": crate::view::MEASURES }); let mut schema = strict( json!({ "$schema": { "type": "string" }, "$type": { "const": crate::view::TYPE }, "collection": { "type": "string", "description": "The NSID of the collection whose records it draws." }, "method": { "type": "string", "description": "The NSID of the query whose answers it draws." }, "service": { "type": "string", "description": "The service a method view's query is called at, as did:web:api.bsky.app#bsky_appview." }, "description": text(200), "origins": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "type": "string" } }, "thumbnails": { "type": "array", "minItems": 1, "maxItems": 8, "items": strict( json!({ "from": { "type": "string" }, "to": { "type": "string" } }), &["from", "to"]) }, "pageSize": { "type": "integer", "minimum": 1, "maximum": 100 }, "list": def("mode"), "record": def("mode"), "query": def("queryMode"), "domain": { "type": "string", "description": "The domain of the app whose page it draws." }, "page": def("pageMode"), "interactions": { "type": "object" }, "signIn": text(80), "launch": { "type": "array" }, "records": { "type": "array" }, "app": text(40), "profile": { "type": "object" }, "activity": text(20), "measure": measure, "measureWhen": { "type": "array", "minItems": 1, "maxItems": 8, "items": strict( json!({ "when": { "type": "string" }, "measure": measure }), &["when", "measure"]) }, }), &["description"], ); let o = schema.as_object_mut().expect("an object"); o.insert("$schema".into(), json!(DRAFT)); o.insert("$id".into(), json!(format!("{BASE}/view.json"))); o.insert("title".into(), json!("A HUD view (place.hud.view)")); o.insert( "description".into(), json!("A view: how HUD draws a collection's records, a query's answers or an app's page. A key written ?key is optional: a HUD that finds a problem in it leaves it out."), ); o.insert("$defs".into(), view_defs()); schema } /// The schema of a lexicon's value `v`, a def of `nsid`, the defs it /// refers to added to `defs` (`#/$defs/.`): an object refusing /// keys it doesn't name, as HUD does with an app file's parts. fn from_lexicon(nsid: &str, v: &Value, defs: &mut Map) -> Value { let mut out = match v["type"].as_str() { Some("object") => { let properties: Map = v["properties"] .as_object() .into_iter() .flatten() .map(|(k, p)| (k.clone(), from_lexicon(nsid, p, defs))) .collect(); let required: Vec<&str> = v["required"] .as_array() .into_iter() .flatten() .filter_map(Value::as_str) .collect(); closed(Value::Object(properties), &required) } Some("array") => json!({ "type": "array", "items": from_lexicon(nsid, &v["items"], defs) }), Some("ref") => { let full = crate::lexicon::full_ref(nsid, v["ref"].as_str().unwrap_or_default()); lexicon_def(&full, defs) } Some(t @ ("string" | "integer" | "boolean")) => json!({ "type": t }), _ => json!({}), }; for (from, to) in [ ("description", "description"), ("maxLength", "maxLength"), ("minLength", "minLength"), ("minimum", "minimum"), ("maximum", "maximum"), ("default", "default"), ("knownValues", "examples"), ("enum", "enum"), ("const", "const"), ] { if let Some(x) = v.get(from) { let key = match (v["type"].as_str(), from) { (Some("array"), "maxLength") => "maxItems", (Some("array"), "minLength") => "minItems", _ => to, }; out[key] = x.clone(); } } out } /// A reference to the lexicon def `full` (`nsid#def`), its schema added to /// `defs` under `nsid.def` if it isn't there. fn lexicon_def(full: &str, defs: &mut Map) -> Value { let (nsid, name) = full.split_once('#').expect("a full ref names its def"); let key = format!("{nsid}.{name}"); if !defs.contains_key(&key) { defs.insert(key.clone(), json!({})); let doc = crate::lexicon::bundled(nsid).expect("HUD bundles the lexicons it refers to"); let schema = from_lexicon(nsid, &doc["defs"][name], defs); defs.insert(key.clone(), schema); } def(&key) } /// The JSON Schema of an app file (`.json`). HUD reads the keys it /// names, its frame, pages, sign-in screen and tabs' `first` as their /// lexicons describe them; any other key is its clients' (its `look`). pub fn app() -> Value { let mut defs = Map::new(); let frame = lexicon_def("place.hud.frame#main", &mut defs); let page = lexicon_def("place.hud.page#main", &mut defs); let sign_in = lexicon_def("place.hud.signIn#main", &mut defs); let first = lexicon_def("place.hud.tabFirst#main", &mut defs); let path = json!({ "type": "string", "pattern": "^/" }); let call = json!({ "description": "A tool call that draws what a view draws: query (args method, params), describe_app (domain), get_record (uri) or list_records (collection).", "type": "object", "properties": { "name": { "enum": ["query", "describe_app", "get_record", "list_records"] }, "args": { "type": "object" }, }, "required": ["name"], }); let procedure = json!({ "type": "object", "properties": { "method": { "type": "string" }, "service": { "type": "string" }, "input": {}, }, "required": ["method", "service"], }); let head_text = json!({ "type": "string", "minLength": 1, "maxLength": crate::operator::HEAD_TEXT }); let head: Map = crate::operator::HEAD .iter() .map(|k| { let v = match *k { "image" => json!({ "type": "string", "pattern": "^https://" }), "twitter" => json!({ "type": "string", "pattern": "^@[A-Za-z0-9_]{1,15}$" }), _ => head_text.clone(), }; (k.to_string(), v) }) .collect(); let head = closed(Value::Object(head), &["siteName"]); json!({ "$schema": DRAFT, "$id": format!("{BASE}/app.json"), "title": "A HUD app file (.json)", "description": "An app served by HUD (HUD_APPS): its tabs and routes, each a tool call, and what its clients draw around them.", "type": "object", "properties": { "$schema": { "type": "string" }, "hud": { "type": "string", "description": "The HUD versions the app runs on, a semver requirement, as >=0.2.0. A HUD older than it needs refuses the app." }, "kits": closed(json!({ "oldest": { "type": "string", "description": "The oldest kit, the HUD version of the renderer an app's build in people's hands was made with, its clients still serve, as 0.2.0: hud check warns where a view uses a component or prop newer than it with no kit gate or fallback around it." } }), &["oldest"]), "domain": { "type": "string", "description": "The app's domain, as its file is named." }, "name": { "type": "string", "minLength": 1 }, "tabs": { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "label": { "type": "string" }, "call": call, "guest": { "anyOf": [{ "const": "call" }, call] }, "first": first, }, "required": ["label", "call"], } }, "routes": { "type": "array", "items": { "type": "object", "properties": { "path": path, "call": call, "tab": { "type": "string" }, "pager": { "const": true }, "under": path, }, "required": ["path", "call"], } }, "push": { "type": "object", "properties": { "register": procedure, "unregister": procedure, "open": { "type": "array", "items": { "type": "object", "properties": { "when": { "type": "object", "minProperties": 1 }, "path": path }, "required": ["when", "path"], } }, }, "required": ["register", "unregister"], }, "refresh": closed(json!({ "method": { "type": "string" }, "service": { "type": "string" } }), &["method", "service"]), "permissions": { "type": "array", "minItems": 1, "maxItems": crate::operator::SETS, "items": closed(json!({ "include": { "type": "string" }, "service": { "type": "string" } }), &["include"]) }, "head": head, "frame": frame, "pages": { "type": "array", "maxItems": crate::operator::PAGES, "items": page }, "signIn": sign_in, }, "required": ["domain", "name", "tabs"], "$defs": defs, }) } #[cfg(test)] mod tests { use super::*; /// The schemas `schemas/json/` publishes are those HUD makes: `just /// json-schemas` writes them again. #[test] fn the_published_schemas_are_current() { for (name, made) in [("app", app()), ("view", view())] { let path = format!( "{}/../../schemas/json/{name}.json", env!("CARGO_MANIFEST_DIR") ); let published: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); assert!( published == made, "{path} is not current: run just json-schemas" ); } } /// Each component's props are described by the catalog: a literal of /// its type, a binding, either, or a root binding too. #[test] fn a_node_follows_the_catalog() { let view = view(); let cases = view["$defs"]["node"]["allOf"].as_array().unwrap(); assert_eq!(cases.len(), COMPONENTS.len()); // A record is never a literal: bound alone. assert_eq!(literal(Ty::Record), json!(false)); let of = |name: &str| { let case = cases .iter() .find(|c| c["if"]["properties"]["component"]["const"] == name); case.unwrap()["then"]["properties"].clone() }; let stack = of("Stack"); assert_eq!( stack["props"]["properties"]["gap"], json!({ "enum": ["none", "xs", "sm", "md", "lg"] }) ); assert_eq!(stack["children"]["items"], def("node")); assert_eq!(of("Header")["children"], json!(false)); assert_eq!( of("Fields")["props"]["properties"]["record"], def("binding") ); assert!( of("Fields")["props"]["required"] .as_array() .unwrap() .contains(&json!("record")) ); } /// A lexicon's def reads as a schema: its objects refusing keys they /// don't name, its arrays' lengths their items', its known values /// examples, its refs `$defs`, once each even where it refers to /// itself. #[test] fn a_lexicon_reads_as_a_schema() { let mut defs = Map::new(); let doc = json!({ "type": "object", "required": ["a"], "properties": { "a": { "type": "string", "maxLength": 10, "knownValues": ["x"], "description": "A." }, "b": { "type": "array", "maxLength": 3, "minLength": 1, "items": { "type": "integer", "minimum": 1 } }, "c": { "type": "ref", "ref": "#self" }, "d": { "type": "unknown" }, "e": { "type": "boolean", "default": true }, }, }); let schema = from_lexicon("place.hud.frame", &doc, &mut defs); assert_eq!(schema["additionalProperties"], false); assert_eq!(schema["required"], json!(["a"])); assert_eq!( schema["properties"]["a"], json!({ "type": "string", "description": "A.", "maxLength": 10, "examples": ["x"] }) ); assert_eq!( schema["properties"]["b"], json!({ "type": "array", "items": { "type": "integer", "minimum": 1 }, "maxItems": 3, "minItems": 1 }) ); assert_eq!(schema["properties"]["c"], def("place.hud.frame.self")); assert_eq!(schema["properties"]["d"], json!({})); assert_eq!( schema["properties"]["e"], json!({ "type": "boolean", "default": true }) ); // A def the lexicon doesn't have is any value. assert_eq!(defs["place.hud.frame.self"], json!({})); let app = app(); let frame = &app["$defs"]["place.hud.frame.main"]; assert_eq!(frame["additionalProperties"], false); assert_eq!( frame["properties"]["action"]["$ref"], "#/$defs/place.hud.frame.action" ); assert_eq!( app["properties"]["pages"]["items"], def("place.hud.page.main") ); } }