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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::card::{Card, CardId, CardSettings, validate_card_element_content, validate_element_id};
use crate::message::MessageId;
use crate::{Error, Result};

use super::message::validate_message_id;
use super::{HttpMethod, HttpRequest, OpenApiClient, OpenApiTransport, parse_openapi_response};

const CARD_ENTITY_PATH: &str = "/open-apis/cardkit/v1/cards";
const CALLBACK_CARD_UPDATE_PATH: &str = "/open-apis/interactive/v1/card/update";
const MESSAGE_PATH: &str = "/open-apis/im/v1/messages";
const MAX_CARD_SETTINGS_CHARS: usize = 100_000;
const MAX_CARD_UPDATE_UUID_CHARS: usize = 64;
const MAX_CARD_UPDATE_SEQUENCE: u32 = i32::MAX as u32;

impl<T> OpenApiClient<T>
where
    T: OpenApiTransport,
{
    /// Replaces the content of a sent interactive message by `message_id`.
    ///
    /// The card must explicitly set `config.update_multi=true`, as required by
    /// the official message-card update API.
    pub async fn update_message_card(&self, message_id: &MessageId, card: &Card) -> Result<()> {
        validate_message_id(message_id)?;
        card.validate_for_message_update()?;
        let path = format!("{MESSAGE_PATH}/{}", message_id.0);
        let request = UpdateMessageCardRequest {
            content: serde_json::to_string(card)?,
        };
        let _: Value = self.patch_tenant_json(&path, &request).await?;
        Ok(())
    }

    /// Updates a message card using the token from a card action callback.
    ///
    /// The callback must be acknowledged successfully before this request is
    /// sent. Lark/Feishu callback tokens remain valid for 30 minutes and can be
    /// used at most twice.
    pub async fn update_message_card_with_callback_token(
        &self,
        callback_token: &str,
        card: &Card,
    ) -> Result<()> {
        validate_callback_token(callback_token)?;
        card.validate()?;
        let request = CallbackCardUpdateRequest {
            token: callback_token,
            card,
        };
        let _: Value = self
            .post_tenant_json(CALLBACK_CARD_UPDATE_PATH, &request)
            .await?;
        Ok(())
    }

    /// Creates a CardKit entity and returns its `card_id`.
    ///
    /// A card entity is valid for 14 days and can be referenced by one sent
    /// message. It is the required starting point for later element-level or
    /// streaming CardKit updates.
    pub async fn create_card_entity(&self, card: &Card) -> Result<CardId> {
        let request = self.prepare_card_entity_create(card)?;
        let token = self.tenant_access_token().await?;
        self.send_prepared_card_entity_create(request.with_bearer_auth(token))
            .await
    }

    pub(crate) fn prepare_card_entity_create(&self, card: &Card) -> Result<HttpRequest> {
        card.validate()?;
        let payload = CardEntityPayload::from_card(card)?;
        self.json_request(HttpMethod::Post, CARD_ENTITY_PATH, &payload)
    }

    pub(crate) async fn send_prepared_card_entity_create(
        &self,
        request: HttpRequest,
    ) -> Result<CardId> {
        let response = self.transport.send_json(request).await?;
        let response: CreateCardEntityResponse = parse_openapi_response(response)?;
        CardId::new(response.data.card_id)
    }

    /// Replaces all content of a CardKit entity by `card_id`.
    ///
    /// `options.sequence` must be strictly greater than the sequence used by
    /// the previous CardKit operation on the same entity.
    pub async fn update_card_entity(
        &self,
        card_id: &CardId,
        card: &Card,
        options: CardUpdateOptions,
    ) -> Result<()> {
        card_id.validate()?;
        card.validate()?;
        options.validate()?;
        let path = format!("{CARD_ENTITY_PATH}/{}", card_id.as_str());
        let request = UpdateCardEntityRequest {
            card: CardEntityPayload::from_card(card)?,
            sequence: options.sequence,
            uuid: options.uuid,
        };
        let _: Value = self.put_tenant_json(&path, &request).await?;
        Ok(())
    }

    /// Updates the streaming configuration or summary of a CardKit entity.
    ///
    /// `options.sequence` must be strictly greater than the sequence used by
    /// the previous CardKit operation on the same entity.
    pub async fn update_card_settings(
        &self,
        card_id: &CardId,
        settings: &CardSettings,
        options: CardUpdateOptions,
    ) -> Result<()> {
        card_id.validate()?;
        settings.validate()?;
        options.validate()?;
        let settings = serde_json::to_string(settings)?;
        if settings.chars().count() > MAX_CARD_SETTINGS_CHARS {
            return Err(Error::Validation(format!(
                "serialized card settings must be at most {MAX_CARD_SETTINGS_CHARS} characters"
            )));
        }
        let path = format!("{CARD_ENTITY_PATH}/{}/settings", card_id.as_str());
        let request = UpdateCardSettingsRequest {
            settings,
            sequence: options.sequence,
            uuid: options.uuid,
        };
        let _: Value = self.patch_tenant_json(&path, &request).await?;
        Ok(())
    }

    /// Replaces the full text of one streaming CardKit text element.
    ///
    /// The target card must already have streaming mode enabled. When the
    /// previous text is a prefix of `content`, Lark/Feishu renders only the
    /// appended suffix with its configured typewriter effect.
    pub async fn update_card_element_content(
        &self,
        card_id: &CardId,
        element_id: &str,
        content: &str,
        options: CardUpdateOptions,
    ) -> Result<()> {
        card_id.validate()?;
        validate_element_id(element_id)?;
        validate_card_element_content(content)?;
        options.validate()?;
        let path = format!(
            "{CARD_ENTITY_PATH}/{}/elements/{element_id}/content",
            card_id.as_str()
        );
        let request = UpdateCardElementContentRequest {
            content,
            sequence: options.sequence,
            uuid: options.uuid,
        };
        let _: Value = self.put_tenant_json(&path, &request).await?;
        Ok(())
    }
}

fn validate_callback_token(callback_token: &str) -> Result<()> {
    if callback_token.trim().is_empty() {
        return Err(Error::Validation(
            "card callback token must not be empty".to_owned(),
        ));
    }
    Ok(())
}

/// Required sequencing and optional idempotency values for CardKit updates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CardUpdateOptions {
    /// Strictly increasing operation sequence for one CardKit entity.
    pub sequence: u32,
    /// Optional request de-duplication key accepted by CardKit update APIs.
    pub uuid: Option<String>,
}

impl CardUpdateOptions {
    /// Creates update options with the required CardKit operation sequence.
    pub fn new(sequence: u32) -> Self {
        Self {
            sequence,
            uuid: None,
        }
    }

    /// Sets the optional CardKit update idempotency key.
    pub fn uuid(mut self, uuid: impl Into<String>) -> Self {
        self.uuid = Some(uuid.into());
        self
    }

    fn validate(&self) -> Result<()> {
        if !(1..=MAX_CARD_UPDATE_SEQUENCE).contains(&self.sequence) {
            return Err(Error::Validation(format!(
                "card update sequence must be between 1 and {MAX_CARD_UPDATE_SEQUENCE}"
            )));
        }
        if let Some(uuid) = &self.uuid {
            if uuid.is_empty() {
                return Err(Error::Validation(
                    "card update uuid must not be empty".to_owned(),
                ));
            }
            if uuid.chars().count() > MAX_CARD_UPDATE_UUID_CHARS {
                return Err(Error::Validation(format!(
                    "card update uuid must be at most {MAX_CARD_UPDATE_UUID_CHARS} characters"
                )));
            }
        }
        Ok(())
    }
}

#[derive(Debug, Serialize)]
struct UpdateMessageCardRequest {
    content: String,
}

#[derive(Debug, Serialize)]
struct CallbackCardUpdateRequest<'a> {
    token: &'a str,
    card: &'a Card,
}

#[derive(Debug, Serialize)]
struct CardEntityPayload {
    r#type: &'static str,
    data: String,
}

impl CardEntityPayload {
    fn from_card(card: &Card) -> Result<Self> {
        Ok(Self {
            r#type: "card_json",
            data: serde_json::to_string(card)?,
        })
    }
}

#[derive(Debug, Serialize)]
struct UpdateCardEntityRequest {
    card: CardEntityPayload,
    sequence: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    uuid: Option<String>,
}

#[derive(Debug, Serialize)]
struct UpdateCardSettingsRequest {
    settings: String,
    sequence: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    uuid: Option<String>,
}

#[derive(Debug, Serialize)]
struct UpdateCardElementContentRequest<'a> {
    content: &'a str,
    sequence: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    uuid: Option<String>,
}

#[derive(Debug, Deserialize)]
struct CreateCardEntityResponse {
    data: CreateCardEntityData,
}

#[derive(Debug, Deserialize)]
struct CreateCardEntityData {
    card_id: String,
}

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

    use super::*;
    use crate::card::MAX_CARD_ELEMENT_CONTENT_CHARS;
    use crate::lark_openapi::test_support::{FakeTransport, block_on};
    use crate::lark_openapi::{HttpMethod, HttpResponse};
    use crate::message::{MessageContent, MessageId, Recipient};
    use crate::{Card, CardId, ChannelConfig};

    #[test]
    fn update_message_card_patches_serialized_shared_card() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().markdown("updated").build().expect("card");

        block_on(client.update_message_card(&MessageId("om_123".to_owned()), &card))
            .expect("updated message card");

        let calls = transport.calls();
        assert_eq!(calls[1].method, HttpMethod::Patch);
        assert_eq!(
            calls[1].url.as_str(),
            "https://open.feishu.cn/open-apis/im/v1/messages/om_123"
        );
        let content: Value =
            serde_json::from_str(calls[1].body["content"].as_str().expect("content string"))
                .expect("card json");
        assert_eq!(content["schema"], "2.0");
        assert_eq!(content["config"]["update_multi"], true);
        assert_eq!(content["body"]["elements"][0]["content"], "updated");
    }

    #[test]
    fn update_message_card_rejects_url_path_delimiters_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().text("hello").build().expect("card");

        for message_id in ["om_1/extra", "om_1?x=1", "om_1#fragment", "om_1%2Fextra"] {
            let error =
                block_on(client.update_message_card(&MessageId(message_id.to_owned()), &card))
                    .expect_err("unsafe message_id must fail");
            assert!(matches!(error, Error::Validation(_)));
        }
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn update_message_card_with_callback_token_posts_card_json() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder()
            .markdown("Delayed update")
            .build()
            .expect("card");

        block_on(client.update_message_card_with_callback_token("c-callback-1", &card))
            .expect("updated callback card");

        let calls = transport.calls();
        assert_eq!(calls[1].method, HttpMethod::Post);
        assert_eq!(
            calls[1].url.as_str(),
            "https://open.feishu.cn/open-apis/interactive/v1/card/update"
        );
        assert_eq!(calls[1].body["token"], "c-callback-1");
        assert_eq!(calls[1].body["card"]["schema"], "2.0");
        assert_eq!(
            calls[1].body["card"]["body"]["elements"][0]["content"],
            "Delayed update"
        );
    }

    #[test]
    fn update_message_card_with_callback_token_rejects_empty_token_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().text("hello").build().expect("card");

        for callback_token in ["", "   "] {
            let error =
                block_on(client.update_message_card_with_callback_token(callback_token, &card))
                    .expect_err("empty callback token must fail");
            assert!(matches!(error, Error::Validation(_)));
        }
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn create_card_entity_posts_card_json_and_validates_response_id() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "data": { "card_id": "7355372766134157313" }
                }),
            ),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().text("hello").build().expect("card");

        let card_id = block_on(client.create_card_entity(&card)).expect("card entity");

        assert_eq!(card_id, CardId("7355372766134157313".to_owned()));
        let calls = transport.calls();
        assert_eq!(calls[1].method, HttpMethod::Post);
        assert_eq!(
            calls[1].url.as_str(),
            "https://open.feishu.cn/open-apis/cardkit/v1/cards"
        );
        assert_eq!(calls[1].body["type"], "card_json");
        let data: Value =
            serde_json::from_str(calls[1].body["data"].as_str().expect("data string"))
                .expect("card json");
        assert_eq!(data["schema"], "2.0");
        assert_eq!(data["body"]["elements"][0]["text"]["content"], "hello");
    }

    #[test]
    fn create_card_entity_rejects_invalid_response_card_id() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "data": { "card_id": "card/unsafe" }
                }),
            ),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().text("hello").build().expect("card");

        let error = block_on(client.create_card_entity(&card))
            .expect_err("unsafe response card_id must fail");

        assert!(matches!(error, Error::Validation(_)));
        assert_eq!(transport.calls().len(), 2);
    }

    #[test]
    fn update_card_entity_puts_sequence_uuid_and_card_json() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().markdown("done").build().expect("card");
        let card_id = CardId::new("7355372766134157313").expect("card id");

        block_on(client.update_card_entity(
            &card_id,
            &card,
            CardUpdateOptions::new(2).uuid("card-update-2"),
        ))
        .expect("updated card entity");

        let calls = transport.calls();
        assert_eq!(calls[1].method, HttpMethod::Put);
        assert_eq!(
            calls[1].url.as_str(),
            "https://open.feishu.cn/open-apis/cardkit/v1/cards/7355372766134157313"
        );
        assert_eq!(calls[1].body["sequence"], 2);
        assert_eq!(calls[1].body["uuid"], "card-update-2");
        assert_eq!(calls[1].body["card"]["type"], "card_json");
        let data: Value =
            serde_json::from_str(calls[1].body["card"]["data"].as_str().expect("data string"))
                .expect("card json");
        assert_eq!(data["body"]["elements"][0]["content"], "done");
    }

    #[test]
    fn update_card_entity_rejects_invalid_sequence_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().text("hello").build().expect("card");
        let card_id = CardId::new("7355372766134157313").expect("card id");

        let error = block_on(client.update_card_entity(&card_id, &card, CardUpdateOptions::new(0)))
            .expect_err("zero sequence must fail");

        assert!(matches!(
            error,
            Error::Validation(message) if message.contains("card update sequence")
        ));
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn update_card_entity_rejects_invalid_uuid_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card = Card::builder().text("hello").build().expect("card");
        let card_id = CardId::new("7355372766134157313").expect("card id");

        for uuid in [String::new(), "x".repeat(65)] {
            let error = block_on(client.update_card_entity(
                &card_id,
                &card,
                CardUpdateOptions::new(1).uuid(uuid),
            ))
            .expect_err("invalid card update uuid must fail");
            assert!(matches!(error, Error::Validation(_)));
        }
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn update_card_settings_patches_serialized_settings_and_options() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card_id = CardId::new("7355372766134157313").expect("card id");
        let settings = CardSettings::new()
            .streaming_mode(false)
            .summary("Finished");

        block_on(client.update_card_settings(
            &card_id,
            &settings,
            CardUpdateOptions::new(3).uuid("settings-3"),
        ))
        .expect("updated card settings");

        let calls = transport.calls();
        assert_eq!(calls[1].method, HttpMethod::Patch);
        assert_eq!(
            calls[1].url.as_str(),
            "https://open.feishu.cn/open-apis/cardkit/v1/cards/7355372766134157313/settings"
        );
        assert_eq!(calls[1].body["sequence"], 3);
        assert_eq!(calls[1].body["uuid"], "settings-3");
        let settings: Value =
            serde_json::from_str(calls[1].body["settings"].as_str().expect("settings string"))
                .expect("settings json");
        assert_eq!(settings["config"]["streaming_mode"], false);
        assert_eq!(settings["config"]["summary"]["content"], "Finished");
    }

    #[test]
    fn update_card_element_content_puts_full_text_and_options() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card_id = CardId::new("7355372766134157313").expect("card id");

        block_on(client.update_card_element_content(
            &card_id,
            "stream_md",
            "Full accumulated Markdown",
            CardUpdateOptions::new(2).uuid("content-2"),
        ))
        .expect("updated card element content");

        let calls = transport.calls();
        assert_eq!(calls[1].method, HttpMethod::Put);
        assert_eq!(
            calls[1].url.as_str(),
            "https://open.feishu.cn/open-apis/cardkit/v1/cards/7355372766134157313/elements/stream_md/content"
        );
        assert_eq!(calls[1].body["content"], "Full accumulated Markdown");
        assert_eq!(calls[1].body["sequence"], 2);
        assert_eq!(calls[1].body["uuid"], "content-2");
    }

    #[test]
    fn update_card_settings_rejects_empty_or_oversized_settings_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card_id = CardId::new("7355372766134157313").expect("card id");

        for settings in [
            CardSettings::new(),
            CardSettings::new().summary("x".repeat(MAX_CARD_SETTINGS_CHARS + 1)),
        ] {
            let error = block_on(client.update_card_settings(
                &card_id,
                &settings,
                CardUpdateOptions::new(1),
            ))
            .expect_err("invalid settings must fail");
            assert!(matches!(error, Error::Validation(_)));
        }
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn update_card_element_content_rejects_invalid_inputs_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card_id = CardId::new("7355372766134157313").expect("card id");

        for (element_id, content) in [
            ("1-invalid", "content".to_owned()),
            ("stream_md", String::new()),
            ("stream_md", "".repeat(MAX_CARD_ELEMENT_CONTENT_CHARS + 1)),
        ] {
            let error = block_on(client.update_card_element_content(
                &card_id,
                element_id,
                &content,
                CardUpdateOptions::new(1),
            ))
            .expect_err("invalid element update must fail");
            assert!(matches!(error, Error::Validation(_)));
        }
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn streaming_card_updates_accept_unicode_and_exact_documented_limits() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
            HttpResponse::json(200, json!({ "code": 0, "msg": "ok", "data": {} })),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card_id = CardId::new("7355372766134157313").expect("card id");
        let empty_settings = serde_json::to_string(&CardSettings::new().summary(""))
            .expect("empty summary settings");
        let settings = CardSettings::new()
            .summary("".repeat(MAX_CARD_SETTINGS_CHARS - empty_settings.chars().count()));
        let serialized_settings = serde_json::to_string(&settings).expect("settings");
        assert_eq!(serialized_settings.chars().count(), MAX_CARD_SETTINGS_CHARS);
        let unicode_uuid = "".repeat(MAX_CARD_UPDATE_UUID_CHARS);

        block_on(client.update_card_settings(
            &card_id,
            &settings,
            CardUpdateOptions::new(1).uuid(unicode_uuid.clone()),
        ))
        .expect("exact-limit settings update");
        block_on(client.update_card_element_content(
            &card_id,
            "stream_md",
            &"".repeat(MAX_CARD_ELEMENT_CONTENT_CHARS),
            CardUpdateOptions::new(MAX_CARD_UPDATE_SEQUENCE),
        ))
        .expect("exact-limit content update");

        let calls = transport.calls();
        assert_eq!(calls[1].body["uuid"], unicode_uuid);
        assert_eq!(calls[1].body["sequence"], 1);
        assert_eq!(calls[2].body["sequence"], MAX_CARD_UPDATE_SEQUENCE);
        assert_eq!(
            calls[2].body["content"]
                .as_str()
                .expect("content")
                .chars()
                .count(),
            MAX_CARD_ELEMENT_CONTENT_CHARS
        );
    }

    #[test]
    fn streaming_card_updates_reject_invalid_options_before_authentication() {
        let transport = FakeTransport::new(vec![]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());
        let card_id = CardId::new("7355372766134157313").expect("card id");
        let settings = CardSettings::new().streaming_mode(true);

        let settings_error =
            block_on(client.update_card_settings(&card_id, &settings, CardUpdateOptions::new(0)))
                .expect_err("zero sequence must fail");
        assert!(matches!(settings_error, Error::Validation(_)));

        let content_error = block_on(client.update_card_element_content(
            &card_id,
            "stream_md",
            "content",
            CardUpdateOptions::new(1).uuid("".repeat(MAX_CARD_UPDATE_UUID_CHARS + 1)),
        ))
        .expect_err("oversized uuid must fail");
        assert!(matches!(content_error, Error::Validation(_)));
        assert!(transport.calls().is_empty());
    }

    #[test]
    fn create_message_serializes_card_entity_reference() {
        let transport = FakeTransport::new(vec![
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "tenant_access_token": "tenant-token-1",
                    "expire": 7200
                }),
            ),
            HttpResponse::json(
                200,
                json!({
                    "code": 0,
                    "msg": "ok",
                    "data": { "message_id": "om_card" }
                }),
            ),
        ]);
        let client = OpenApiClient::new(ChannelConfig::new("cli_a", "secret"), transport.clone());

        let message_id = block_on(client.create_message(
            Recipient::Chat("oc_123".to_owned()),
            MessageContent::CardReference {
                card_id: CardId::new("7355372766134157313").expect("card id"),
            },
        ))
        .expect("card reference message");

        assert_eq!(message_id, MessageId("om_card".to_owned()));
        let body = &transport.calls()[1].body;
        assert_eq!(body["msg_type"], "interactive");
        let content: Value =
            serde_json::from_str(body["content"].as_str().expect("content string"))
                .expect("card reference json");
        assert_eq!(
            content,
            json!({ "type": "card", "data": { "card_id": "7355372766134157313" } })
        );
    }
}