use serde_json::{json, Map, Value};
use crate::catalog::A2UI_VERSION;
pub const HOST_CONTRACT_VERSION: u32 = 3;
pub const A2UI_MESSAGE_KINDS: &[&str] = &["createSurface", "updateComponents", "updateDataModel", "deleteSurface"];
pub const EXTENSION_MESSAGE_KINDS: &[&str] = &["applyTemplate", "bindDataModel"];
pub const MESSAGE_KINDS: &[&str] = &["createSurface", "updateComponents", "updateDataModel", "deleteSurface", "applyTemplate", "bindDataModel"];
pub const OP_KINDS: &[&str] = &["create", "components", "data", "bind", "delete", "send"];
pub const HOST_ERROR_CODES: &[&str] =
&["VALIDATION_FAILED", "INVALID_MESSAGE", "UNSUPPORTED_CATALOG", "SURFACE_NOT_FOUND", "TEMPLATE_NOT_FOUND", "FUNCTION_NOT_FOUND", "FUNCTION_DENIED", "SOURCE_DENIED", "RENDER_FAILED", "ACTION_FAILED"];
pub const VALIDATION_FAILED: &str = "VALIDATION_FAILED";
pub const INVALID_MESSAGE: &str = "INVALID_MESSAGE";
pub const UNSUPPORTED_CATALOG: &str = "UNSUPPORTED_CATALOG";
pub const SURFACE_NOT_FOUND: &str = "SURFACE_NOT_FOUND";
pub const TEMPLATE_NOT_FOUND: &str = "TEMPLATE_NOT_FOUND";
pub const FUNCTION_NOT_FOUND: &str = "FUNCTION_NOT_FOUND";
pub const FUNCTION_DENIED: &str = "FUNCTION_DENIED";
pub const SOURCE_DENIED: &str = "SOURCE_DENIED";
pub const RENDER_FAILED: &str = "RENDER_FAILED";
pub const ACTION_FAILED: &str = "ACTION_FAILED";
pub const FUNCTION_DECISIONS: &[&str] = &["allow", "ask", "deny", "not_found"];
pub const DEFAULT_FUNCTION_DECISION: &str = "allow";
pub const DEFAULT_URL_SCHEMES: &[&str] = &["https", "http", "mailto", "tel"];
pub 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"];
pub const URL_REASONS: &[&str] = &["invalid", "scheme", "host", "private"];
pub const MEDIA_RULE_KEYS: &[&str] = &["prefix", "headers"];
pub const MEDIA_OPTION_KEYS: &[&str] = &["baseUrl", "rules", "schemes", "hosts", "allowPrivate"];
pub const DEFAULT_MEDIA_SCHEMES: &[&str] = &["https", "http", "data"];
pub const MEDIA_MAX_BYTES: u64 = 20_971_520;
pub const MEDIA_TIMEOUT_MS: u64 = 30_000;
pub const MEDIA_MAX_PIXELS: u64 = 33_554_432;
pub const PAINT_ERROR_HOOK: &str = "onPaintError";
pub const SOURCE_PATTERN: &str = "^([a-zA-Z][a-zA-Z0-9+.-]*):([^?]+)(?:\\?(.*))?$";
pub const MCP_MIME_TYPES: &[&str] = &["application/json+a2ui", "application/a2ui+json"];
pub const MCP_ACTION_TOOL: &str = "a2ui_event";
pub const SSE_EVENTS: &[&str] = &["message", "a2ui"];
pub const PACKAGE_REQUIRED: &[&str] = &["id", "name", "version", "catalogId", "templates"];
pub const SURFACE_SETTINGS: &[&str] = &["locale", "timeZone", "strings", "mode", "density", "contrast", "theme", "readOnly"];
pub const SURFACE_FORMATTER: &[&str] = &["number", "currency", "percent", "date", "relativeTime", "plural"];
pub const SURFACE_COMMANDS: &[&str] = &["focus", "announce", "scrollIntoView", "scrollToIndex"];
pub 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 &";
pub const RECORD_KIND_PATTERN: &str = "^[a-z][a-z0-9_]{0,31}$";
pub fn host_contract() -> Value {
use super::{actions as act, exposes as ex, record_store as rs, signature as sig, tests as pt, tools};
json!({
"version": HOST_CONTRACT_VERSION,
"a2uiVersion": A2UI_VERSION,
"messages": {"a2ui": A2UI_MESSAGE_KINDS, "extensions": EXTENSION_MESSAGE_KINDS},
"ops": {"kinds": OP_KINDS},
"clientMessages": {"errorCodes": HOST_ERROR_CODES},
"functions": {"decisions": FUNCTION_DECISIONS, "defaultPolicy": {"allow": [], "ask": [], "deny": [], "default": DEFAULT_FUNCTION_DECISION}},
"urls": {"defaultSchemes": DEFAULT_URL_SCHEMES, "privateHosts": PRIVATE_HOSTS, "reasons": URL_REASONS},
"media": {
"ruleKeys": MEDIA_RULE_KEYS,
"optionKeys": MEDIA_OPTION_KEYS,
"defaultSchemes": DEFAULT_MEDIA_SCHEMES,
"limits": {"maxBytes": MEDIA_MAX_BYTES, "timeoutMs": MEDIA_TIMEOUT_MS, "maxPixels": MEDIA_MAX_PIXELS},
},
"sources": {"pattern": SOURCE_PATTERN, "paramsEncoding": SOURCE_PARAMS_ENCODING},
"transport": {"mcpMimeTypes": MCP_MIME_TYPES, "mcpActionTool": MCP_ACTION_TOOL, "sseEvents": SSE_EVENTS},
"negotiation": {},
"package": {
"required": PACKAGE_REQUIRED,
"formatVersion": super::package::PACKAGE_FORMAT_VERSION,
"records": {
"kindPattern": RECORD_KIND_PATTERN,
"reserved": super::records::RECORD_RESERVED_KEYS,
"types": super::records::RECORD_FIELD_TYPES,
"formats": super::records::RECORD_FORMATS,
"scheme": rs::RECORDS_SCHEME,
"functions": rs::RECORDS_FUNCTIONS,
"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},
},
"actions": {
"limits": {"actions": act::ACTION_LIMIT_ACTIONS, "steps": act::ACTION_LIMIT_STEPS, "maxSteps": act::ACTION_LIMIT_MAX_STEPS},
"namePattern": act::ACTION_NAME_PATTERN,
"stepKinds": act::ACTION_STEP_KINDS,
"callPrefix": act::ACTION_CALL_PREFIX,
"batchFunction": act::RECORDS_BATCH_FUNCTION,
},
"tests": {
"limits": {"tests": pt::PACKAGE_TEST_LIMIT_TESTS, "gotMax": pt::PACKAGE_TEST_LIMIT_GOT_MAX},
"defaults": {"now": pt::PACKAGE_TEST_DEFAULT_NOW, "as": pt::PACKAGE_TEST_DEFAULT_AS, "role": pt::PACKAGE_TEST_DEFAULT_ROLE},
"roles": pt::PACKAGE_TEST_ROLES,
"kinds": pt::PACKAGE_TEST_KINDS,
},
"tools": {"idPattern": tools::TOOL_ID_PATTERN, "kinds": tools::TOOL_KINDS, "transports": tools::TOOL_TRANSPORTS, "functionPrefix": tools::TOOL_FUNCTION_PREFIX},
"exposes": {
"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},
"runKinds": ex::EXPOSE_RUN_KINDS,
"recordOps": ex::EXPOSE_RECORD_OPS,
"readRecordOps": ex::EXPOSE_READ_RECORD_OPS,
"readOpWords": ex::EXPOSE_READ_OP_WORDS,
"destructiveWords": ex::EXPOSE_DESTRUCTIVE_WORDS,
"actionPattern": ex::EXPOSE_ACTION_PATTERN,
},
"extensions": {"versionPattern": super::package::EXTENSION_VERSION_PATTERN},
"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},
},
"paint": {"hook": PAINT_ERROR_HOOK, "errorCode": RENDER_FAILED},
"surface": {"settings": SURFACE_SETTINGS, "formatter": SURFACE_FORMATTER, "commands": SURFACE_COMMANDS},
})
}
pub fn error_message(code: &str, surface_id: &str, message: &str, path: Option<&str>) -> Value {
let mut error = Map::new();
error.insert("code".into(), Value::String(code.into()));
error.insert("surfaceId".into(), Value::String(surface_id.into()));
error.insert("message".into(), Value::String(message.into()));
if let Some(path) = path {
error.insert("path".into(), Value::String(path.into()));
}
json!({"version": A2UI_VERSION, "error": error})
}
pub fn action_message(surface_id: &str, component_id: &str, name: &str, context: Value, payload: Option<Value>, timestamp: &str) -> Value {
let mut action = Map::new();
action.insert("name".into(), Value::String(name.into()));
action.insert("surfaceId".into(), Value::String(surface_id.into()));
action.insert("sourceComponentId".into(), Value::String(component_id.into()));
action.insert("timestamp".into(), Value::String(timestamp.into()));
action.insert("context".into(), if context.is_null() { Value::Object(Map::new()) } else { context });
if let Some(payload) = payload {
let has_keys = match &payload {
Value::Object(o) => !o.is_empty(),
Value::Array(a) => !a.is_empty(),
Value::String(s) => !s.is_empty(),
_ => false,
};
if has_keys {
action.insert("payload".into(), payload);
}
}
json!({"version": A2UI_VERSION, "action": action})
}