Skip to main content

eui_core/host/
package.rs

1//! Catalog negotiation and declarative app packages (VAPP-82: a manifest +
2//! A2UI templates + bindings, data never code).
3
4use std::collections::HashSet;
5
6use serde::{Deserialize, Serialize};
7use serde_json::{json, Map, Value};
8
9use super::policy::matches_pattern;
10use super::query::parse_records_json;
11use super::record_store::RECORDS_SCHEME;
12use super::records::{is_record_kind, validate_record_schema};
13use super::sources::parse_source;
14use super::exposes::{validate_package_exposes, validate_upstreams};
15use super::tools::validate_tools;
16use crate::catalog::{A2UI_BASIC_CATALOG_ID, A2UI_VERSION, CORE_CATALOG_ID, CORE_LITE_CATALOG_ID};
17use crate::types::ExtensionDef;
18
19/// VAPP-161: the package format version this host reads
20/// (catalog/host.json `package.formatVersion`; docs/package-format.md). A
21/// package without `formatVersion` is version 1; every version-1 package
22/// is a valid version-2 package.
23pub const PACKAGE_FORMAT_VERSION: u32 = 2;
24/// `package.extensions.versionPattern`.
25pub const EXTENSION_VERSION_PATTERN: &str = "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$";
26
27/// VAPP-161: an extension as a host registered it ([`available_extensions`]).
28#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
29pub struct AvailableExtension {
30    pub id: String,
31    /// `None` = satisfies any version.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub version: Option<String>,
34    /// `None` = not checked.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub components: Option<Vec<String>>,
37}
38
39/// A host's extension catalogs as [`validate_package_with`] checks them:
40/// the version when set (an empty one is unset), the components then the
41/// macros.
42pub fn available_extensions(defs: &[ExtensionDef]) -> Vec<AvailableExtension> {
43    defs.iter()
44        .map(|d| AvailableExtension {
45            id: d.id.clone(),
46            version: d.version.clone().filter(|v| !v.is_empty()),
47            components: Some(d.components.keys().chain(d.macros.iter().flat_map(|m| m.keys())).cloned().collect()),
48        })
49        .collect()
50}
51
52/// `^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$` → the three parts (as JS
53/// `Number`s).
54fn semver(v: &str) -> Option<[f64; 3]> {
55    let mut parts = v.split('.');
56    let mut out = [0.0; 3];
57    for slot in &mut out {
58        let p = parts.next()?;
59        if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) || (p.len() > 1 && p.starts_with('0')) {
60            return None;
61        }
62        *slot = p.parse().ok()?;
63    }
64    parts.next().is_none().then_some(out)
65}
66
67/// Caret: `have` has `want`'s major and is not lower.
68pub fn version_satisfies(have: &str, want: &str) -> bool {
69    let (Some([h_major, h_minor, h_patch]), Some([w_major, w_minor, w_patch])) = (semver(have), semver(want)) else { return false };
70    h_major == w_major && (h_minor > w_minor || (h_minor == w_minor && h_patch >= w_patch))
71}
72
73/// The core, the core lite, the A2UI basic catalog, then every registered
74/// extension id in order, de-duplicated.
75pub fn supported_catalog_ids<S: AsRef<str>>(extension_ids: &[S]) -> Vec<String> {
76    let mut out: Vec<String> = Vec::new();
77    for id in [CORE_CATALOG_ID, CORE_LITE_CATALOG_ID, A2UI_BASIC_CATALOG_ID].into_iter().chain(extension_ids.iter().map(AsRef::as_ref)) {
78        if !out.iter().any(|x| x == id) {
79            out.push(id.to_string());
80        }
81    }
82    out
83}
84
85/// A2UI's `a2uiClientCapabilities`.
86pub fn client_capabilities<S: AsRef<str>>(extension_ids: &[S]) -> Value {
87    json!({"v0.9": {"supportedCatalogIds": supported_catalog_ids(extension_ids)}})
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct PackageIssue {
92    pub path: String,
93    pub message: String,
94}
95
96fn issue(path: impl Into<String>, message: impl Into<String>) -> PackageIssue {
97    PackageIssue { path: path.into(), message: message.into() }
98}
99
100/// `^(\/([^/~]|~[01])*)*$`: empty, or `/`-separated segments whose `~` is
101/// always `~0` / `~1`.
102fn is_pointer(s: &str) -> bool {
103    if s.is_empty() {
104        return true;
105    }
106    if !s.starts_with('/') {
107        return false;
108    }
109    let mut chars = s.chars().peekable();
110    while let Some(c) = chars.next() {
111        if c == '~' && !matches!(chars.next(), Some('0' | '1')) {
112            return false;
113        }
114    }
115    true
116}
117
118/// Every problem with a package, each with a JSON pointer into it.
119/// `catalog_ids` = the supported ids (default: [`supported_catalog_ids`] of
120/// none). A declared extension only has to be in `catalog_ids`
121/// ([`validate_package_with`] checks versions and components too).
122pub fn validate_package<S: AsRef<str>>(pkg: &Value, catalog_ids: &[S]) -> Vec<PackageIssue> {
123    validate_package_with(pkg, catalog_ids, None)
124}
125
126/// [`validate_package`] with the host's registered `extensions` (versions
127/// and components); `None` = a declared extension only has to be in
128/// `catalog_ids`.
129pub fn validate_package_with<S: AsRef<str>>(pkg: &Value, catalog_ids: &[S], extensions: Option<&[AvailableExtension]>) -> Vec<PackageIssue> {
130    let mut issues = Vec::new();
131    let Some(p) = pkg.as_object() else { return vec![issue("", "a package is an object")] };
132    if let Some(version) = p.get("formatVersion") {
133        match version.as_f64().filter(|v| v.fract() == 0.0 && *v >= 1.0) {
134            None => issues.push(issue("/formatVersion", "formatVersion is a positive integer")),
135            Some(v) if v > f64::from(PACKAGE_FORMAT_VERSION) => {
136                issues.push(issue("/formatVersion", format!("format version {} is newer than this host ({PACKAGE_FORMAT_VERSION})", crate::json::number_to_string(v))))
137            }
138            Some(_) => {}
139        }
140    }
141    for key in ["id", "name", "version", "catalogId"] {
142        if p.get(key).and_then(Value::as_str).is_none_or(str::is_empty) {
143            issues.push(issue(format!("/{key}"), format!("{key} is a required string")));
144        }
145    }
146    if let Some(catalog_id) = p.get("catalogId").and_then(Value::as_str).filter(|s| !s.is_empty()) {
147        if !catalog_ids.iter().any(|c| c.as_ref() == catalog_id) {
148            issues.push(issue("/catalogId", format!("unsupported catalog {catalog_id}")));
149        }
150    }
151    match p.get("templates").and_then(Value::as_object).filter(|t| !t.is_empty()) {
152        None => issues.push(issue("/templates", "templates is a non-empty object")),
153        Some(templates) => {
154            for (id, template) in templates {
155                let at = format!("/templates/{id}");
156                let Some(template) = template.as_object() else {
157                    issues.push(issue(at, "a template is an object"));
158                    continue;
159                };
160                match template.get("components").and_then(Value::as_array).filter(|c| !c.is_empty()) {
161                    None => issues.push(issue(format!("{at}/components"), "components is a non-empty array")),
162                    Some(components) => {
163                        let mut ids: HashSet<&str> = HashSet::new();
164                        for (i, c) in components.iter().enumerate() {
165                            let id = c.as_object().filter(|o| o.get("component").is_some_and(Value::is_string)).and_then(|o| o.get("id")).and_then(Value::as_str);
166                            match id {
167                                None => issues.push(issue(format!("{at}/components/{i}"), "a component needs an id and a component")),
168                                Some(id) if ids.contains(id) => issues.push(issue(format!("{at}/components/{i}/id"), format!("duplicate id {id}"))),
169                                Some(id) => {
170                                    ids.insert(id);
171                                }
172                            }
173                        }
174                        if !ids.contains("root") {
175                            issues.push(issue(format!("{at}/components"), "no component has the id root"));
176                        }
177                    }
178                }
179                if let Some(bindings) = template.get("bindings") {
180                    match bindings.as_array() {
181                        None => issues.push(issue(format!("{at}/bindings"), "bindings is an array")),
182                        Some(list) => {
183                            for (i, b) in list.iter().enumerate() {
184                                let bp = format!("{at}/bindings/{i}");
185                                let b = b.as_object();
186                                if b.and_then(|o| o.get("path")).and_then(Value::as_str).is_none_or(|p| !is_pointer(p)) {
187                                    issues.push(issue(format!("{bp}/path"), "path is a JSON pointer"));
188                                }
189                                if b.and_then(|o| o.get("source")).and_then(Value::as_str).is_none_or(|s| parse_source(s).is_none()) {
190                                    issues.push(issue(format!("{bp}/source"), "source is a scheme:name URI"));
191                                }
192                            }
193                        }
194                    }
195                }
196            }
197        }
198    }
199    if let Some(functions) = p.get("functions") {
200        let ok = functions.as_array().is_some_and(|list| list.iter().all(|f| f.as_str().is_some_and(|s| !s.is_empty())));
201        if !ok {
202            issues.push(issue("/functions", "functions is a list of names or prefix* patterns"));
203        }
204    }
205    // VAPP-122: `records` = the app's kinds, each with a schema.
206    if let Some(records) = p.get("records") {
207        match records.as_object() {
208            None => issues.push(issue("/records", "records is an object of kinds")),
209            Some(kinds) => {
210                let mut names: Vec<&String> = kinds.keys().collect();
211                names.sort();
212                for kind in names {
213                    let def = &kinds[kind];
214                    let at = format!("/records/{kind}");
215                    if !is_record_kind(kind) {
216                        issues.push(issue(&at, "a kind is lowercase letters, digits and underscores"));
217                    }
218                    match def.as_object() {
219                        None => issues.push(issue(&at, "a kind is {schema, title?}")),
220                        Some(def) => issues.extend(validate_record_schema(def.get("schema").unwrap_or(&Value::Null), &format!("{at}/schema"))),
221                    }
222                }
223            }
224        }
225    }
226    // VAPP-107: `sources` = the binding sources the package's surfaces may
227    // follow; a template binding outside it is an issue.
228    if let Some(sources) = p.get("sources") {
229        match sources.as_array().filter(|list| list.iter().all(|f| f.as_str().is_some_and(|s| !s.is_empty()))) {
230            None => issues.push(issue("/sources", "sources is a list of scheme:name sources or prefix* patterns")),
231            Some(list) => {
232                let allowed: Vec<String> = list.iter().filter_map(Value::as_str).map(str::to_string).collect();
233                for (id, template) in p.get("templates").and_then(Value::as_object).into_iter().flatten() {
234                    for (i, b) in template.get("bindings").and_then(Value::as_array).into_iter().flatten().enumerate() {
235                        if let Some(source) = b.get("source").and_then(Value::as_str).filter(|s| parse_source(s).is_some()) {
236                            if !source_allowed(Some(&allowed), source) {
237                                issues.push(issue(format!("/templates/{id}/bindings/{i}/source"), format!("source {source} is not in the package's sources")));
238                            }
239                        }
240                    }
241                }
242            }
243        }
244    }
245    // VAPP-161: a `records:<kind>` binding names a declared kind.
246    for (id, template) in p.get("templates").and_then(Value::as_object).into_iter().flatten() {
247        let Some(bindings) = template.as_object().and_then(|t| t.get("bindings")).and_then(Value::as_array) else { continue };
248        for (i, b) in bindings.iter().enumerate() {
249            let Some(parsed) = b.as_object().and_then(|o| o.get("source")).and_then(Value::as_str).and_then(parse_source) else { continue };
250            if parsed.scheme != RECORDS_SCHEME {
251                continue;
252            }
253            if !p.get("records").and_then(Value::as_object).is_some_and(|r| r.contains_key(&parsed.name)) {
254                issues.push(issue(format!("/templates/{id}/bindings/{i}/source"), format!("records:{} names no declared kind", parsed.name)));
255            }
256        }
257    }
258    // VAPP-190: the named queries parse clean, read a declared kind, and a
259    // records binding's `query=` names one of them.
260    if let Some(queries) = p.get("queries") {
261        match queries.as_object() {
262            None => issues.push(issue("/queries", "queries is an object of named queries")),
263            Some(queries) => {
264                let mut names: Vec<&String> = queries.keys().collect();
265                names.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
266                for name in names {
267                    let at = format!("/queries/{name}");
268                    if !is_query_name(name) {
269                        issues.push(issue(at.clone(), "a query name is a letter, then letters, digits and underscores"));
270                    }
271                    let q = &queries[name];
272                    for i in parse_records_json(q, None).1 {
273                        issues.push(issue(format!("{at}{}", i.path), i.message));
274                    }
275                    let from = q.as_object().and_then(|o| o.get("from")).and_then(Value::as_str).map(super::js_trim).unwrap_or("");
276                    if !from.is_empty() && !from.contains("${") && !p.get("records").and_then(Value::as_object).is_some_and(|r| r.contains_key(from)) {
277                        issues.push(issue(format!("{at}/from"), format!("records:{from} names no declared kind")));
278                    }
279                }
280            }
281        }
282    }
283    for (id, template) in p.get("templates").and_then(Value::as_object).into_iter().flatten() {
284        let Some(bindings) = template.as_object().and_then(|t| t.get("bindings")).and_then(Value::as_array) else { continue };
285        for (i, b) in bindings.iter().enumerate() {
286            let Some(parsed) = b.as_object().and_then(|o| o.get("source")).and_then(Value::as_str).and_then(parse_source) else { continue };
287            let Some(name) = parsed.params.get("query") else { continue };
288            if parsed.scheme != RECORDS_SCHEME && !(parsed.scheme == "exp" && parsed.name == "records") {
289                continue;
290            }
291            if !p.get("queries").and_then(Value::as_object).is_some_and(|q| q.contains_key(name)) {
292                issues.push(issue(format!("/templates/{id}/bindings/{i}/source"), format!("query {name} names no package query")));
293            }
294        }
295    }
296    // VAPP-191: every expression in a template parses and type-checks.
297    issues.extend(super::expressions::validate_package_expressions(p));
298    if let Some(tools) = p.get("tools") {
299        issues.extend(validate_tools(tools));
300    }
301    if let Some(upstreams) = p.get("upstreams") {
302        issues.extend(validate_upstreams(upstreams));
303    }
304    if let Some(exposes) = p.get("exposes") {
305        issues.extend(validate_package_exposes(exposes, p.get("records"), p.get("upstreams")));
306    }
307    if let Some(list) = p.get("extensions") {
308        issues.extend(validate_extensions(list, catalog_ids, extensions));
309    }
310    issues
311}
312
313fn validate_extensions<S: AsRef<str>>(list: &Value, catalog_ids: &[S], available: Option<&[AvailableExtension]>) -> Vec<PackageIssue> {
314    let Some(list) = list.as_array() else { return vec![issue("/extensions", "extensions is a list of {id, version, components?}")] };
315    let mut issues = Vec::new();
316    let mut seen: HashSet<&str> = HashSet::new();
317    for (i, ext) in list.iter().enumerate() {
318        let at = format!("/extensions/{i}");
319        let Some(ext) = ext.as_object() else {
320            issues.push(issue(at, "an extension is {id, version, components?}"));
321            continue;
322        };
323        let id = ext.get("id").and_then(Value::as_str).filter(|s| !s.is_empty());
324        if id.is_none() {
325            issues.push(issue(format!("{at}/id"), "id is a required string"));
326        }
327        let version = ext.get("version").and_then(Value::as_str).filter(|v| semver(v).is_some());
328        if version.is_none() {
329            issues.push(issue(format!("{at}/version"), "version is MAJOR.MINOR.PATCH"));
330        }
331        let components: Option<Vec<&str>> = match ext.get("components") {
332            None => Some(Vec::new()),
333            Some(c) => c.as_array().and_then(|l| l.iter().map(|c| c.as_str().filter(|s| !s.is_empty())).collect()),
334        };
335        if components.is_none() {
336            issues.push(issue(format!("{at}/components"), "components is a list of component names"));
337        }
338        let Some(id) = id else { continue };
339        if !seen.insert(id) {
340            issues.push(issue(format!("{at}/id"), format!("duplicate extension {id}")));
341            continue;
342        }
343        let have = available.and_then(|a| a.iter().find(|a| a.id == id));
344        if !catalog_ids.iter().any(|c| c.as_ref() == id) || (available.is_some() && have.is_none()) {
345            issues.push(issue(format!("{at}/id"), format!("extension {id} is not available on this host")));
346            continue;
347        }
348        let Some(have) = have else { continue };
349        if let (Some(version), Some(have_version)) = (version, have.version.as_deref()) {
350            if !version_satisfies(have_version, version) {
351                issues.push(issue(format!("{at}/version"), format!("extension {id} {have_version} does not satisfy ^{version}")));
352            }
353        }
354        if let Some(have_components) = &have.components {
355            for (j, name) in components.iter().flatten().enumerate() {
356                if !have_components.iter().any(|c| c == name) {
357                    issues.push(issue(format!("{at}/components/{j}"), format!("extension {id} has no component {name}")));
358                }
359            }
360        }
361    }
362    issues
363}
364
365/// VAPP-107: may a package whose `sources` list is `allowed` follow this
366/// source URI? `None` = yes; else the URI's `scheme:name` (scheme
367/// lower-cased, the query dropped) must match a listed source exactly or a
368/// `prefix*` pattern.
369pub fn source_allowed(allowed: Option<&[String]>, source: &str) -> bool {
370    let Some(allowed) = allowed else { return true };
371    let Some(parsed) = parse_source(source) else { return false };
372    let name = format!("{}:{}", parsed.scheme, parsed.name);
373    allowed.iter().any(|p| matches_pattern(p, &name) || matches_pattern(p, source))
374}
375
376/// A package's `sources` allowlist (`None` = unset: any source).
377pub fn package_sources(pkg: &Value) -> Option<Vec<String>> {
378    pkg.get("sources").and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).map(str::to_string).collect())
379}
380
381/// A template as the messages that create it: createSurface, the components,
382/// the merged initial data, one bindDataModel per binding. `None` when the
383/// package has no such template. `data` = the caller's data (`Some(Null)` is
384/// a value, unlike `None`).
385pub fn template_messages(pkg: &Value, template_id: &str, surface_id: &str, data: Option<&Value>) -> Option<Vec<Value>> {
386    let template = pkg.get("templates").and_then(|t| t.get(template_id)).filter(|t| super::js_truthy(t))?;
387    let version = A2UI_VERSION;
388    let mut create = Map::new();
389    create.insert("surfaceId".into(), Value::String(surface_id.into()));
390    if let Some(catalog_id) = pkg.get("catalogId") {
391        create.insert("catalogId".into(), catalog_id.clone());
392    }
393    let mut components = Map::new();
394    components.insert("surfaceId".into(), Value::String(surface_id.into()));
395    if let Some(list) = template.get("components") {
396        components.insert("components".into(), list.clone());
397    }
398    let mut out = vec![json!({"version": version, "createSurface": create}), json!({"version": version, "updateComponents": components})];
399    if let Some(merged) = merge_data(template.get("data"), data) {
400        out.push(json!({"version": version, "updateDataModel": {"surfaceId": surface_id, "path": "/", "value": merged}}));
401    }
402    for b in template.get("bindings").and_then(Value::as_array).into_iter().flatten() {
403        let mut bind = Map::new();
404        bind.insert("surfaceId".into(), Value::String(surface_id.into()));
405        for key in ["path", "source"] {
406            if let Some(v) = b.get(key) {
407                bind.insert(key.into(), v.clone());
408            }
409        }
410        out.push(json!({"version": version, "bindDataModel": bind}));
411    }
412    Some(out)
413}
414
415/// The template's data under the caller's (objects merge one level deep in
416/// key order; anything else: the caller's wins). `None` = undefined.
417pub fn merge_data(base: Option<&Value>, over: Option<&Value>) -> Option<Value> {
418    match (base, over) {
419        (base, None) => base.cloned(),
420        (Some(Value::Object(b)), Some(Value::Object(o))) => {
421            let mut merged = b.clone();
422            for (k, v) in o {
423                merged.insert(k.clone(), v.clone());
424            }
425            Some(Value::Object(merged))
426        }
427        (_, Some(over)) => Some(over.clone()),
428    }
429}
430
431/// VAPP-190: a package query's name (catalog/host.json `package.records.query.queryNamePattern`).
432pub const QUERY_NAME_PATTERN: &str = "^[a-z][A-Za-z0-9_]{0,31}$";
433
434/// [`QUERY_NAME_PATTERN`] without a regex engine.
435pub fn is_query_name(name: &str) -> bool {
436    let b = name.as_bytes();
437    !b.is_empty() && b.len() <= 32 && b[0].is_ascii_lowercase() && b[1..].iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
438}