Skip to main content

act_types/
types.rs

1use std::collections::HashMap;
2
3use crate::cbor;
4
5// ── LocalizedString ──
6
7/// A localizable text value, matching the WIT `localized-string` variant.
8///
9/// - `Plain` — a single string in the component's `default-language`.
10/// - `Localized` — a map of BCP 47 language tags to text.
11#[derive(Debug, Clone)]
12pub enum LocalizedString {
13    /// A single string assumed to be in the component's `default-language`.
14    Plain(String),
15    /// Language tag → text map. MUST include the component's `default-language`.
16    Localized(HashMap<String, String>),
17}
18
19impl Default for LocalizedString {
20    fn default() -> Self {
21        Self::Plain(String::new())
22    }
23}
24
25impl LocalizedString {
26    /// Create a plain (non-localized) string.
27    pub fn plain(text: impl Into<String>) -> Self {
28        Self::Plain(text.into())
29    }
30
31    /// Create a localized string with a single language entry.
32    pub fn new(lang: impl Into<String>, text: impl Into<String>) -> Self {
33        let mut map = HashMap::new();
34        map.insert(lang.into(), text.into());
35        Self::Localized(map)
36    }
37
38    /// Look up text for a specific language tag.
39    ///
40    /// For `Plain`, always returns the text (it is assumed to match any language).
41    /// For `Localized`, performs exact key lookup.
42    pub fn get(&self, lang: &str) -> Option<&str> {
43        match self {
44            Self::Plain(text) => Some(text.as_str()),
45            Self::Localized(map) => map.get(lang).map(|s| s.as_str()),
46        }
47    }
48
49    /// Resolve to text for the given language, with fallback chain.
50    ///
51    /// - `Plain` → returns the plain string (assumed to be in `default_language`).
52    /// - `Localized` → exact match → prefix match → any entry.
53    pub fn resolve(&self, lang: &str) -> &str {
54        match self {
55            Self::Plain(text) => text.as_str(),
56            Self::Localized(map) => {
57                // 1. Exact match
58                if let Some(text) = map.get(lang) {
59                    return text.as_str();
60                }
61                // 2. Prefix match (e.g. "zh" matches "zh-Hans")
62                if let Some(text) = map
63                    .iter()
64                    .find(|(tag, _)| tag.starts_with(lang) || lang.starts_with(tag.as_str()))
65                    .map(|(_, text)| text.as_str())
66                {
67                    return text;
68                }
69                // 3. Any entry
70                map.values().next().map(|s| s.as_str()).unwrap_or("")
71            }
72        }
73    }
74
75    /// Get some text, regardless of language.
76    /// Useful when you don't have the default language available.
77    pub fn any_text(&self) -> &str {
78        match self {
79            Self::Plain(text) => text.as_str(),
80            Self::Localized(map) => map.values().next().map(|s| s.as_str()).unwrap_or(""),
81        }
82    }
83}
84
85impl From<String> for LocalizedString {
86    fn from(s: String) -> Self {
87        Self::Plain(s)
88    }
89}
90
91impl From<&str> for LocalizedString {
92    fn from(s: &str) -> Self {
93        Self::Plain(s.to_string())
94    }
95}
96
97impl From<Vec<(String, String)>> for LocalizedString {
98    fn from(v: Vec<(String, String)>) -> Self {
99        Self::Localized(v.into_iter().collect())
100    }
101}
102
103impl From<HashMap<String, String>> for LocalizedString {
104    fn from(map: HashMap<String, String>) -> Self {
105        Self::Localized(map)
106    }
107}
108
109// ── Metadata ──
110
111/// Key → value metadata, stored as JSON values internally.
112///
113/// Converts to/from WIT `list<tuple<string, list<u8>>>` (CBOR) at the boundary.
114#[derive(Debug, Clone, Default)]
115pub struct Metadata(HashMap<String, serde_json::Value>);
116
117impl Metadata {
118    pub fn new() -> Self {
119        Self(HashMap::new())
120    }
121
122    /// Insert a value. Overwrites any existing entry for the key.
123    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
124        self.0.insert(key.into(), value.into());
125    }
126
127    /// Get a value by key.
128    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
129        self.0.get(key)
130    }
131
132    /// Get a value by key, deserializing into a typed value.
133    pub fn get_as<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
134        self.0
135            .get(key)
136            .and_then(|v| serde_json::from_value(v.clone()).ok())
137    }
138
139    /// Check if a key exists.
140    pub fn contains_key(&self, key: &str) -> bool {
141        self.0.contains_key(key)
142    }
143
144    /// Returns true if there are no entries.
145    pub fn is_empty(&self) -> bool {
146        self.0.is_empty()
147    }
148
149    /// Iterate over key-value pairs.
150    pub fn iter(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
151        self.0.iter()
152    }
153
154    /// Number of entries.
155    pub fn len(&self) -> usize {
156        self.0.len()
157    }
158
159    /// Merge all entries from `other` into `self`. Entries in `other` overwrite existing keys.
160    pub fn extend(&mut self, other: Metadata) {
161        self.0.extend(other.0);
162    }
163}
164
165/// Convert from a JSON object value. Non-object values produce empty metadata.
166impl From<serde_json::Value> for Metadata {
167    fn from(value: serde_json::Value) -> Self {
168        match value {
169            serde_json::Value::Object(map) => Self(map.into_iter().collect()),
170            _ => Self::new(),
171        }
172    }
173}
174
175/// Convert to a JSON object value (consuming).
176impl From<Metadata> for serde_json::Value {
177    fn from(m: Metadata) -> Self {
178        serde_json::Value::Object(m.0.into_iter().collect())
179    }
180}
181
182/// Convert from WIT metadata (CBOR-encoded values).
183impl From<Vec<(String, Vec<u8>)>> for Metadata {
184    fn from(v: Vec<(String, Vec<u8>)>) -> Self {
185        Self(
186            v.into_iter()
187                .filter_map(|(k, cbor_bytes)| {
188                    let val = cbor::cbor_to_json(&cbor_bytes).ok()?;
189                    Some((k, val))
190                })
191                .collect(),
192        )
193    }
194}
195
196/// Convert to WIT metadata (CBOR-encoded values).
197impl From<Metadata> for Vec<(String, Vec<u8>)> {
198    fn from(m: Metadata) -> Self {
199        m.0.into_iter()
200            .map(|(k, v)| (k, cbor::to_cbor(&v)))
201            .collect()
202    }
203}
204
205use crate::constants::*;
206
207// ── Component info (act:component custom section) ──
208
209/// A capability required or optionally used by the component.
210#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
211pub struct ComponentCapability {
212    pub id: String,
213    pub required: bool,
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub description: Option<String>,
216}
217
218/// Component metadata stored in the `act:component` WASM custom section (CBOR-encoded).
219///
220/// Used by SDK macros (serialization) and host (deserialization).
221/// Standard WASM metadata fields (`version`, `description`) may also be read
222/// from their respective custom sections as fallback.
223///
224/// Extra keys (not matching `std:*` fields) are collected into `metadata`.
225#[non_exhaustive]
226#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
227pub struct ComponentInfo {
228    #[serde(rename = "std:name", default)]
229    pub name: String,
230    #[serde(rename = "std:version", default)]
231    pub version: String,
232    #[serde(rename = "std:description", default)]
233    pub description: String,
234    #[serde(
235        rename = "std:default-language",
236        default,
237        skip_serializing_if = "Option::is_none"
238    )]
239    pub default_language: Option<String>,
240    #[serde(
241        rename = "std:capabilities",
242        default,
243        skip_serializing_if = "Vec::is_empty"
244    )]
245    pub capabilities: Vec<ComponentCapability>,
246    /// Extra metadata keys not matching well-known `std:*` fields.
247    #[serde(flatten, default, skip_serializing_if = "HashMap::is_empty")]
248    pub metadata: HashMap<String, serde_json::Value>,
249}
250
251impl ComponentInfo {
252    pub fn new(
253        name: impl Into<String>,
254        version: impl Into<String>,
255        description: impl Into<String>,
256    ) -> Self {
257        Self {
258            name: name.into(),
259            version: version.into(),
260            description: description.into(),
261            ..Default::default()
262        }
263    }
264}
265
266// ── Error type ──
267
268/// Error type mapping to ACT `tool-error`.
269#[derive(Debug, Clone)]
270pub struct ActError {
271    pub kind: String,
272    pub message: String,
273}
274
275impl ActError {
276    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
277        Self {
278            kind: kind.into(),
279            message: message.into(),
280        }
281    }
282
283    pub fn not_found(message: impl Into<String>) -> Self {
284        Self::new(ERR_NOT_FOUND, message)
285    }
286
287    pub fn invalid_args(message: impl Into<String>) -> Self {
288        Self::new(ERR_INVALID_ARGS, message)
289    }
290
291    pub fn internal(message: impl Into<String>) -> Self {
292        Self::new(ERR_INTERNAL, message)
293    }
294
295    pub fn timeout(message: impl Into<String>) -> Self {
296        Self::new(ERR_TIMEOUT, message)
297    }
298
299    pub fn capability_denied(message: impl Into<String>) -> Self {
300        Self::new(ERR_CAPABILITY_DENIED, message)
301    }
302}
303
304impl std::fmt::Display for ActError {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        write!(f, "{}: {}", self.kind, self.message)
307    }
308}
309
310impl std::error::Error for ActError {}
311
312/// Result type for ACT operations.
313pub type ActResult<T> = Result<T, ActError>;
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use serde_json::json;
319
320    #[test]
321    fn localized_string_plain() {
322        let ls = LocalizedString::plain("hello");
323        assert_eq!(ls.resolve("en"), "hello");
324        assert_eq!(ls.any_text(), "hello");
325    }
326
327    #[test]
328    fn localized_string_from_str() {
329        let ls = LocalizedString::from("hello");
330        assert_eq!(ls.any_text(), "hello");
331    }
332
333    #[test]
334    fn localized_string_default() {
335        let ls = LocalizedString::default();
336        assert_eq!(ls.any_text(), "");
337    }
338
339    #[test]
340    fn localized_string_resolve_by_lang() {
341        let mut map = std::collections::HashMap::new();
342        map.insert("en".to_string(), "hello".to_string());
343        map.insert("ru".to_string(), "привет".to_string());
344        let ls = LocalizedString::Localized(map);
345        assert_eq!(ls.resolve("ru"), "привет");
346        assert_eq!(ls.resolve("en"), "hello");
347        // Unknown lang falls back to some entry
348        assert!(!ls.resolve("fr").is_empty());
349    }
350
351    #[test]
352    fn localized_string_resolve_prefix() {
353        let mut map = HashMap::new();
354        map.insert("zh-Hans".to_string(), "你好".to_string());
355        map.insert("en".to_string(), "hello".to_string());
356        let ls = LocalizedString::Localized(map);
357        assert_eq!(ls.resolve("zh"), "你好");
358    }
359
360    #[test]
361    fn localized_string_get() {
362        let ls = LocalizedString::new("en", "hello");
363        assert_eq!(ls.get("en"), Some("hello"));
364        assert_eq!(ls.get("ru"), None);
365    }
366
367    #[test]
368    fn localized_string_from_vec() {
369        let v = vec![("en".to_string(), "hi".to_string())];
370        let ls = LocalizedString::from(v);
371        assert_eq!(ls.resolve("en"), "hi");
372    }
373
374    #[test]
375    fn metadata_insert_and_get() {
376        let mut m = Metadata::new();
377        m.insert("std:read-only", true);
378        assert_eq!(m.get("std:read-only"), Some(&json!(true)));
379        assert_eq!(m.get_as::<bool>("std:read-only"), Some(true));
380    }
381
382    #[test]
383    fn metadata_to_json_empty() {
384        let json: serde_json::Value = Metadata::new().into();
385        assert_eq!(json, json!({}));
386    }
387
388    #[test]
389    fn metadata_to_json_with_values() {
390        let mut m = Metadata::new();
391        m.insert("std:read-only", true);
392        let json: serde_json::Value = m.into();
393        assert_eq!(json["std:read-only"], json!(true));
394    }
395
396    #[test]
397    fn metadata_from_vec() {
398        let v = vec![("key".to_string(), cbor::to_cbor(&42u32))];
399        let m = Metadata::from(v);
400        assert_eq!(m.get("key"), Some(&json!(42)));
401        assert_eq!(m.get_as::<u32>("key"), Some(42));
402    }
403}