Skip to main content

eui_core/host/
contract.rs

1//! The host API contract (`catalog/host.json`) as constants, plus the client
2//! messages every platform host sends (`tests/host_fixtures.rs` gates the
3//! constants against the JSON).
4
5use serde_json::{json, Map, Value};
6
7use crate::catalog::A2UI_VERSION;
8
9pub const HOST_CONTRACT_VERSION: u32 = 3;
10/// The four A2UI v0.9 server messages.
11pub const A2UI_MESSAGE_KINDS: &[&str] = &["createSurface", "updateComponents", "updateDataModel", "deleteSurface"];
12/// The two Exponential UI extensions.
13pub const EXTENSION_MESSAGE_KINDS: &[&str] = &["applyTemplate", "bindDataModel"];
14/// Every message kind the router takes, A2UI first.
15pub const MESSAGE_KINDS: &[&str] = &["createSurface", "updateComponents", "updateDataModel", "deleteSurface", "applyTemplate", "bindDataModel"];
16/// What the router turns a message into.
17pub const OP_KINDS: &[&str] = &["create", "components", "data", "bind", "delete", "send"];
18pub const HOST_ERROR_CODES: &[&str] =
19    &["VALIDATION_FAILED", "INVALID_MESSAGE", "UNSUPPORTED_CATALOG", "SURFACE_NOT_FOUND", "TEMPLATE_NOT_FOUND", "FUNCTION_NOT_FOUND", "FUNCTION_DENIED", "SOURCE_DENIED", "RENDER_FAILED"];
20pub const VALIDATION_FAILED: &str = "VALIDATION_FAILED";
21pub const INVALID_MESSAGE: &str = "INVALID_MESSAGE";
22pub const UNSUPPORTED_CATALOG: &str = "UNSUPPORTED_CATALOG";
23pub const SURFACE_NOT_FOUND: &str = "SURFACE_NOT_FOUND";
24pub const TEMPLATE_NOT_FOUND: &str = "TEMPLATE_NOT_FOUND";
25pub const FUNCTION_NOT_FOUND: &str = "FUNCTION_NOT_FOUND";
26pub const FUNCTION_DENIED: &str = "FUNCTION_DENIED";
27/// VAPP-107: a `bindDataModel` outside a package surface's `sources`.
28pub const SOURCE_DENIED: &str = "SOURCE_DENIED";
29/// A component's painter failed (`paint.errorCode`).
30pub const RENDER_FAILED: &str = "RENDER_FAILED";
31pub const FUNCTION_DECISIONS: &[&str] = &["allow", "ask", "deny", "not_found"];
32/// The default function policy's `default`.
33pub const DEFAULT_FUNCTION_DECISION: &str = "allow";
34pub const DEFAULT_URL_SCHEMES: &[&str] = &["https", "http", "mailto", "tel"];
35/// VAPP-107: the hosts `decide_url` denies by default (`urls.privateHosts`,
36/// the rule itself is [`super::is_private_host`]).
37pub const PRIVATE_HOSTS: &[&str] = &["localhost", "*.localhost", "*.local", "0.0.0.0/8", "10.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "::", "::1", "fe80::/10", "fc00::/7", "::ffff:<private IPv4>", "::<private IPv4>", "64:ff9b::<private IPv4>", "2002:<private IPv4>::/48"];
38pub const URL_REASONS: &[&str] = &["invalid", "scheme", "host", "private"];
39pub const MEDIA_RULE_KEYS: &[&str] = &["prefix", "headers"];
40pub const MEDIA_OPTION_KEYS: &[&str] = &["baseUrl", "rules", "schemes", "hosts", "allowPrivate"];
41/// The media loader's schemes when the host lists none (no `file`).
42pub const DEFAULT_MEDIA_SCHEMES: &[&str] = &["https", "http", "data"];
43/// `media.limits`: what every image loader enforces.
44pub const MEDIA_MAX_BYTES: u64 = 20_971_520;
45pub const MEDIA_TIMEOUT_MS: u64 = 30_000;
46pub const MEDIA_MAX_PIXELS: u64 = 33_554_432;
47/// The renderer → host hook a failed painter calls (`paint.hook`).
48pub const PAINT_ERROR_HOOK: &str = "onPaintError";
49/// A binding source URI (`<scheme>:<name>[?k=v&…]`).
50pub const SOURCE_PATTERN: &str = "^([a-zA-Z][a-zA-Z0-9+.-]*):([^?]+)(?:\\?(.*))?$";
51pub const MCP_MIME_TYPES: &[&str] = &["application/json+a2ui", "application/a2ui+json"];
52pub const MCP_ACTION_TOOL: &str = "a2ui_event";
53pub const SSE_EVENTS: &[&str] = &["message", "a2ui"];
54pub const PACKAGE_REQUIRED: &[&str] = &["id", "name", "version", "catalogId", "templates"];
55/// Round 2: what a host hands each surface besides messages — the
56/// `SurfaceSettings` keys, the host formatter's methods, the commands.
57pub const SURFACE_SETTINGS: &[&str] = &["locale", "timeZone", "strings", "mode", "density", "contrast", "theme"];
58pub const SURFACE_FORMATTER: &[&str] = &["number", "currency", "percent", "date", "relativeTime", "plural"];
59pub const SURFACE_COMMANDS: &[&str] = &["focus", "announce", "scrollIntoView", "scrollToIndex"];
60
61/// VAPP-122: how the `bind` action appends its params (`sources.paramsEncoding`).
62pub const SOURCE_PARAMS_ENCODING: &str = "sourceWithParams: keys sorted; key and value percent-encoded (everything but A-Z a-z 0-9 - _ . ! ~ * ' ( )); null skipped; an object or array as JSON; after ? or &";
63/// VAPP-122: a record kind's name (`package.records.kindPattern`).
64pub const RECORD_KIND_PATTERN: &str = "^[a-z][a-z0-9_]{0,31}$";
65
66/// `catalog/host.json` without its `$comment`s, rebuilt from the constants.
67pub fn host_contract() -> Value {
68    use super::{exposes as ex, record_store as rs, signature as sig, tools};
69    json!({
70        "version": HOST_CONTRACT_VERSION,
71        "a2uiVersion": A2UI_VERSION,
72        "messages": {"a2ui": A2UI_MESSAGE_KINDS, "extensions": EXTENSION_MESSAGE_KINDS},
73        "ops": {"kinds": OP_KINDS},
74        "clientMessages": {"errorCodes": HOST_ERROR_CODES},
75        "functions": {"decisions": FUNCTION_DECISIONS, "defaultPolicy": {"allow": [], "ask": [], "deny": [], "default": DEFAULT_FUNCTION_DECISION}},
76        "urls": {"defaultSchemes": DEFAULT_URL_SCHEMES, "privateHosts": PRIVATE_HOSTS, "reasons": URL_REASONS},
77        "media": {
78            "ruleKeys": MEDIA_RULE_KEYS,
79            "optionKeys": MEDIA_OPTION_KEYS,
80            "defaultSchemes": DEFAULT_MEDIA_SCHEMES,
81            "limits": {"maxBytes": MEDIA_MAX_BYTES, "timeoutMs": MEDIA_TIMEOUT_MS, "maxPixels": MEDIA_MAX_PIXELS},
82        },
83        "sources": {"pattern": SOURCE_PATTERN, "paramsEncoding": SOURCE_PARAMS_ENCODING},
84        "transport": {"mcpMimeTypes": MCP_MIME_TYPES, "mcpActionTool": MCP_ACTION_TOOL, "sseEvents": SSE_EVENTS},
85        "negotiation": {},
86        "package": {
87            "required": PACKAGE_REQUIRED,
88            "formatVersion": super::package::PACKAGE_FORMAT_VERSION,
89            "records": {
90                "kindPattern": RECORD_KIND_PATTERN,
91                "reserved": super::records::RECORD_RESERVED_KEYS,
92                "types": super::records::RECORD_FIELD_TYPES,
93                "formats": super::records::RECORD_FORMATS,
94                "scheme": rs::RECORDS_SCHEME,
95                "functions": rs::RECORDS_FUNCTIONS,
96                "query": {"sortDefault": rs::RECORDS_SORT_DEFAULT, "orderDefault": rs::RECORDS_ORDER_DEFAULT, "limitDefault": rs::RECORDS_LIMIT_DEFAULT, "limitMax": rs::RECORDS_LIMIT_MAX, "queryNamePattern": super::package::QUERY_NAME_PATTERN, "reserved": rs::RECORDS_RESERVED_PARAMS},
97            },
98            "tools": {"idPattern": tools::TOOL_ID_PATTERN, "kinds": tools::TOOL_KINDS, "transports": tools::TOOL_TRANSPORTS, "functionPrefix": tools::TOOL_FUNCTION_PREFIX},
99            "exposes": {
100                "limits": {"namePattern": ex::EXPOSE_NAME_PATTERN, "nameMax": ex::EXPOSE_NAME_MAX, "titleMax": ex::EXPOSE_TITLE_MAX, "descriptionMax": ex::EXPOSE_DESCRIPTION_MAX, "maxTools": ex::EXPOSE_MAX_TOOLS, "separator": ex::EXPOSE_SEPARATOR},
101                "runKinds": ex::EXPOSE_RUN_KINDS,
102                "recordOps": ex::EXPOSE_RECORD_OPS,
103                "readRecordOps": ex::EXPOSE_READ_RECORD_OPS,
104                "readOpWords": ex::EXPOSE_READ_OP_WORDS,
105                "destructiveWords": ex::EXPOSE_DESTRUCTIVE_WORDS,
106                "actionPattern": ex::EXPOSE_ACTION_PATTERN,
107            },
108            "extensions": {"versionPattern": super::package::EXTENSION_VERSION_PATTERN},
109            "signature": {"alg": sig::PACKAGE_FILE_SIGNATURE_ALG, "context": sig::PACKAGE_FILE_SIGNATURE_CONTEXT, "keyPrefix": sig::AUTHOR_KEY_PREFIX, "nameMax": sig::AUTHOR_NAME_MAX, "statuses": sig::PACKAGE_FILE_STATUSES},
110        },
111        "paint": {"hook": PAINT_ERROR_HOOK, "errorCode": RENDER_FAILED},
112        "surface": {"settings": SURFACE_SETTINGS, "formatter": SURFACE_FORMATTER, "commands": SURFACE_COMMANDS},
113    })
114}
115
116/// A client error message (A2UI v0.9 `error`); `path` only when given.
117pub fn error_message(code: &str, surface_id: &str, message: &str, path: Option<&str>) -> Value {
118    let mut error = Map::new();
119    error.insert("code".into(), Value::String(code.into()));
120    error.insert("surfaceId".into(), Value::String(surface_id.into()));
121    error.insert("message".into(), Value::String(message.into()));
122    if let Some(path) = path {
123        error.insert("path".into(), Value::String(path.into()));
124    }
125    json!({"version": A2UI_VERSION, "error": error})
126}
127
128/// A client action message (A2UI v0.9 `action`). `context` null = `{}`;
129/// `payload` only when it has keys (JS `Object.keys(payload).length`).
130pub fn action_message(surface_id: &str, component_id: &str, name: &str, context: Value, payload: Option<Value>, timestamp: &str) -> Value {
131    let mut action = Map::new();
132    action.insert("name".into(), Value::String(name.into()));
133    action.insert("surfaceId".into(), Value::String(surface_id.into()));
134    action.insert("sourceComponentId".into(), Value::String(component_id.into()));
135    action.insert("timestamp".into(), Value::String(timestamp.into()));
136    action.insert("context".into(), if context.is_null() { Value::Object(Map::new()) } else { context });
137    if let Some(payload) = payload {
138        let has_keys = match &payload {
139            Value::Object(o) => !o.is_empty(),
140            Value::Array(a) => !a.is_empty(),
141            Value::String(s) => !s.is_empty(),
142            _ => false,
143        };
144        if has_keys {
145            action.insert("payload".into(), payload);
146        }
147    }
148    json!({"version": A2UI_VERSION, "action": action})
149}