1use std::collections::HashMap;
2
3use crate::cbor;
4
5#[derive(Debug, Clone)]
12pub enum LocalizedString {
13 Plain(String),
15 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 pub fn plain(text: impl Into<String>) -> Self {
28 Self::Plain(text.into())
29 }
30
31 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 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 pub fn resolve(&self, lang: &str) -> &str {
54 match self {
55 Self::Plain(text) => text.as_str(),
56 Self::Localized(map) => {
57 if let Some(text) = map.get(lang) {
59 return text.as_str();
60 }
61 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 map.values().next().map(|s| s.as_str()).unwrap_or("")
71 }
72 }
73 }
74
75 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#[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 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 pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
129 self.0.get(key)
130 }
131
132 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 pub fn contains_key(&self, key: &str) -> bool {
141 self.0.contains_key(key)
142 }
143
144 pub fn is_empty(&self) -> bool {
146 self.0.is_empty()
147 }
148
149 pub fn iter(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
151 self.0.iter()
152 }
153
154 pub fn len(&self) -> usize {
156 self.0.len()
157 }
158
159 pub fn extend(&mut self, other: Metadata) {
161 self.0.extend(other.0);
162 }
163}
164
165impl 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
175impl 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
182impl 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
196impl 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#[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#[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 #[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#[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
312pub 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 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}