lark-channel 0.5.0

Lark/Feishu Channel SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
use serde_json::{Map, Value, json};
use url::Url;

use crate::{Error, Result};

use super::{Card, CardStreamingConfig, validate_element_id};

/// Supported visual styles for a CardKit button.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CardButtonStyle {
    #[default]
    Default,
    Primary,
    Danger,
}

impl CardButtonStyle {
    fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Primary => "primary",
            Self::Danger => "danger",
        }
    }
}

/// A CardKit 2.0 body element.
///
/// Constructors cover common Channel workflows. [`CardElement::raw`] is an
/// escape hatch for official CardKit components not modeled here yet.
#[derive(Debug, Clone, PartialEq)]
pub struct CardElement(Value);

impl CardElement {
    /// Creates a native CardKit Markdown component.
    pub fn markdown(content: impl Into<String>) -> Self {
        Self(json!({ "tag": "markdown", "content": content.into() }))
    }

    /// Creates a plain-text `div` component.
    pub fn text(content: impl Into<String>) -> Self {
        Self(json!({
            "tag": "div",
            "text": { "tag": "plain_text", "content": content.into() }
        }))
    }

    /// Creates a divider component.
    pub fn divider() -> Self {
        Self(json!({ "tag": "hr" }))
    }

    /// Creates a button that emits a `card.action.trigger` callback.
    pub fn callback_button(label: impl Into<String>, value: Value) -> Result<Self> {
        if !value.is_object() {
            return Err(Error::Validation(
                "card callback button value must be a JSON object".to_owned(),
            ));
        }
        Ok(Self(json!({
            "tag": "button",
            "text": { "tag": "plain_text", "content": label.into() },
            "type": "default",
            "behaviors": [{ "type": "callback", "value": value }]
        })))
    }

    /// Creates a button that opens the same URL on all supported clients.
    pub fn open_url_button(label: impl Into<String>, url: impl Into<String>) -> Result<Self> {
        let url = url.into();
        let url = Url::parse(&url)?.to_string();
        Ok(Self(json!({
            "tag": "button",
            "text": { "tag": "plain_text", "content": label.into() },
            "type": "default",
            "behaviors": [{ "type": "open_url", "default_url": url }]
        })))
    }

    /// Creates an element from an official CardKit JSON object.
    pub fn raw(value: Value) -> Result<Self> {
        let object = value.as_object().ok_or_else(|| {
            Error::Validation("raw card element must be a JSON object".to_owned())
        })?;
        if object.get("tag").and_then(Value::as_str).is_none() {
            return Err(Error::Validation(
                "raw card element must contain a string tag".to_owned(),
            ));
        }
        Ok(Self(value))
    }

    /// Assigns the CardKit component identifier used by later update APIs.
    pub fn element_id(mut self, element_id: impl Into<String>) -> Result<Self> {
        let element_id = element_id.into();
        validate_element_id(&element_id)?;
        self.object_mut()?
            .insert("element_id".to_owned(), Value::String(element_id));
        Ok(self)
    }

    /// Assigns an identifier to this component's nested `plain_text` element.
    ///
    /// Use this identifier when targeting a value created by [`CardElement::text`]
    /// with the CardKit streaming content API. [`CardElement::element_id`] keeps
    /// assigning the outer component identifier.
    pub fn plain_text_element_id(mut self, element_id: impl Into<String>) -> Result<Self> {
        let element_id = element_id.into();
        validate_element_id(&element_id)?;
        let object = self.object_mut()?;
        if object.get("tag").and_then(Value::as_str) != Some("div") {
            return Err(Error::Validation(
                "plain-text element_id is only supported for CardElement::text".to_owned(),
            ));
        }
        let text = object
            .get_mut("text")
            .and_then(Value::as_object_mut)
            .filter(|text| text.get("tag").and_then(Value::as_str) == Some("plain_text"))
            .ok_or_else(|| {
                Error::Validation(
                    "plain-text element_id requires a nested plain_text element".to_owned(),
                )
            })?;
        text.insert("element_id".to_owned(), Value::String(element_id));
        Ok(self)
    }

    /// Changes the style of a button element.
    pub fn button_style(mut self, style: CardButtonStyle) -> Result<Self> {
        let object = self.object_mut()?;
        if object.get("tag").and_then(Value::as_str) != Some("button") {
            return Err(Error::Validation(
                "card button style is only supported for button elements".to_owned(),
            ));
        }
        object.insert("type".to_owned(), Value::String(style.as_str().to_owned()));
        Ok(self)
    }

    /// Returns the element JSON value.
    pub fn as_value(&self) -> &Value {
        &self.0
    }

    /// Consumes the element and returns its JSON value.
    pub fn into_value(self) -> Value {
        self.0
    }

    fn object_mut(&mut self) -> Result<&mut Map<String, Value>> {
        self.0
            .as_object_mut()
            .ok_or_else(|| Error::Validation("card element must be a JSON object".to_owned()))
    }
}

impl Serialize for CardElement {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for CardElement {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::raw(Value::deserialize(deserializer)?).map_err(D::Error::custom)
    }
}

/// Fluent builder for a CardKit 2.0 card.
#[derive(Debug, Clone)]
pub struct CardBuilder {
    config: Map<String, Value>,
    header_title: Option<String>,
    header_subtitle: Option<String>,
    header_template: Option<String>,
    elements: Vec<Value>,
}

impl Default for CardBuilder {
    fn default() -> Self {
        let mut config = Map::new();
        config.insert("update_multi".to_owned(), Value::Bool(true));
        Self {
            config,
            header_title: None,
            header_subtitle: None,
            header_template: None,
            elements: Vec::new(),
        }
    }
}

impl CardBuilder {
    /// Creates an empty builder with `config.update_multi=true`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the card header title.
    pub fn header(mut self, title: impl Into<String>) -> Self {
        self.header_title = Some(title.into());
        self
    }

    /// Sets the optional card header subtitle.
    pub fn header_subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.header_subtitle = Some(subtitle.into());
        self
    }

    /// Sets the official CardKit header color template name.
    pub fn header_template(mut self, template: impl Into<String>) -> Self {
        self.header_template = Some(template.into());
        self
    }

    /// Sets a raw CardKit config field.
    pub fn config(mut self, key: impl Into<String>, value: Value) -> Self {
        self.config.insert(key.into(), value);
        self
    }

    /// Enables or disables CardKit streaming mode.
    pub fn streaming_mode(mut self, enabled: bool) -> Self {
        self.config
            .insert("streaming_mode".to_owned(), Value::Bool(enabled));
        self
    }

    /// Enables streaming mode with a typed CardKit rendering configuration.
    pub fn streaming(mut self, config: CardStreamingConfig) -> Self {
        self.config
            .insert("streaming_mode".to_owned(), Value::Bool(true));
        self.config
            .insert("streaming_config".to_owned(), Value::from(config));
        self
    }

    /// Sets the card summary shown in chat previews.
    pub fn summary(mut self, content: impl Into<String>) -> Self {
        self.config
            .insert("summary".to_owned(), json!({ "content": content.into() }));
        self
    }

    /// Appends a typed or raw CardKit body element.
    pub fn element(mut self, element: CardElement) -> Self {
        self.elements.push(element.into_value());
        self
    }

    /// Appends a native Markdown component.
    pub fn markdown(self, content: impl Into<String>) -> Self {
        self.element(CardElement::markdown(content))
    }

    /// Appends a plain-text component.
    pub fn text(self, content: impl Into<String>) -> Self {
        self.element(CardElement::text(content))
    }

    /// Appends a divider component.
    pub fn divider(self) -> Self {
        self.element(CardElement::divider())
    }

    /// Builds and validates the complete CardKit 2.0 card.
    pub fn build(self) -> Result<Card> {
        if self.header_title.is_none()
            && (self.header_subtitle.is_some() || self.header_template.is_some())
        {
            return Err(Error::Validation(
                "card header subtitle or template requires a header title".to_owned(),
            ));
        }

        let header = self.header_title.map(|title| {
            let mut header = Map::new();
            header.insert(
                "title".to_owned(),
                json!({ "tag": "plain_text", "content": title }),
            );
            if let Some(subtitle) = self.header_subtitle {
                header.insert(
                    "subtitle".to_owned(),
                    json!({ "tag": "plain_text", "content": subtitle }),
                );
            }
            if let Some(template) = self.header_template {
                header.insert("template".to_owned(), Value::String(template));
            }
            Value::Object(header)
        });

        Card::from_parts(self.config, header, self.elements)
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn builds_common_cardkit_v2_components() {
        let callback = CardElement::callback_button("Approve", json!({ "choice": "approve" }))
            .expect("callback button")
            .button_style(CardButtonStyle::Primary)
            .expect("button style")
            .element_id("approve_button")
            .expect("element id");
        let link =
            CardElement::open_url_button("Docs", "https://open.feishu.cn").expect("link button");

        let card = Card::builder()
            .header("Deployment")
            .header_subtitle("Production")
            .header_template("blue")
            .markdown("**Ready**")
            .text("Review the change")
            .divider()
            .element(callback)
            .element(link)
            .build()
            .expect("card");

        assert_eq!(card.as_value()["schema"], "2.0");
        assert_eq!(card.as_value()["config"]["update_multi"], true);
        assert_eq!(card.as_value()["header"]["title"]["content"], "Deployment");
        assert_eq!(card.as_value()["body"]["elements"][0]["tag"], "markdown");
        assert_eq!(
            card.as_value()["body"]["elements"][3]["behaviors"][0],
            json!({ "type": "callback", "value": { "choice": "approve" } })
        );
        assert_eq!(
            card.as_value()["body"]["elements"][4]["behaviors"][0]["default_url"],
            "https://open.feishu.cn/"
        );
    }

    #[test]
    fn rejects_non_object_callback_values() {
        let error = CardElement::callback_button("Approve", json!("approve"))
            .expect_err("string callback value must fail");

        assert!(matches!(
            error,
            Error::Validation(message)
                if message == "card callback button value must be a JSON object"
        ));
    }

    #[test]
    fn rejects_invalid_element_ids() {
        let error = CardElement::markdown("hello")
            .element_id("1-invalid")
            .expect_err("invalid id must fail");

        assert!(matches!(error, Error::Validation(_)));
    }

    #[test]
    fn builds_streaming_card_with_summary_and_element_id() {
        let markdown = CardElement::markdown("Thinking...")
            .element_id("stream_md")
            .expect("element id");
        let card = Card::builder()
            .streaming(CardStreamingConfig::new())
            .summary("[Generating...]")
            .element(markdown)
            .build()
            .expect("streaming card");

        assert_eq!(card.as_value()["config"]["streaming_mode"], true);
        assert_eq!(
            card.as_value()["config"]["streaming_config"]["print_frequency_ms"]["default"],
            70
        );
        assert_eq!(
            card.as_value()["config"]["summary"]["content"],
            "[Generating...]"
        );
        assert_eq!(
            card.as_value()["body"]["elements"][0]["element_id"],
            "stream_md"
        );
    }

    #[test]
    fn assigns_plain_text_streaming_id_without_replacing_outer_component_id() {
        let text = CardElement::text("Thinking...")
            .element_id("stream_container")
            .expect("outer component id")
            .plain_text_element_id("stream_text")
            .expect("nested plain-text id");

        assert_eq!(text.as_value()["element_id"], "stream_container");
        assert_eq!(text.as_value()["text"]["element_id"], "stream_text");
    }

    #[test]
    fn rejects_plain_text_id_for_components_without_nested_plain_text() {
        for element in [
            CardElement::markdown("Thinking..."),
            CardElement::callback_button("Continue", json!({ "choice": "continue" }))
                .expect("button"),
        ] {
            let error = element
                .plain_text_element_id("stream_text")
                .expect_err("only a text div can expose a streaming plain-text target");
            assert!(matches!(error, Error::Validation(_)));
        }
    }

    #[test]
    fn rejects_empty_cards() {
        let error = Card::builder().build().expect_err("empty card must fail");

        assert!(matches!(
            error,
            Error::Validation(message)
                if message == "card must contain a header or at least one body element"
        ));
    }
}