jmap-mail-types 0.1.2

RFC 8621 JMAP for Mail data types (Mailbox, Thread, Email, Identity, EmailSubmission, SearchSnippet)
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
784
785
786
787
//! JMAP MDN types (RFC 9007).
//!
//! Covers all request/response types for `MDN/send` (§3.1) and `MDN/parse` (§3.3),
//! plus the [`Mdn`] object and its sub-types.
//!
//! All items are gated by the `mdn` feature flag (enabled at the module level in
//! `lib.rs` via `#[cfg(feature = "mdn")]`).

use std::collections::HashMap;

use jmap_types::{Id, PatchObject, SetError};
use serde::{Deserialize, Serialize};

/// Capability URI for JMAP MDN (RFC 9007 §2).
pub const JMAP_MDN_URI: &str = "urn:ietf:params:jmap:mdn";

/// Whether the MDN was triggered manually or automatically (RFC 9007 §2,
/// derived from RFC 8098 disposition-mode action-mode).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ActionMode {
    /// The user manually caused the MDN to be sent.
    ManualAction,
    /// The MDN was sent automatically without user involvement.
    AutomaticAction,
}

impl std::fmt::Display for ActionMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ActionMode::ManualAction => "manual-action",
            ActionMode::AutomaticAction => "automatic-action",
        })
    }
}

/// Whether the MDN itself was sent manually or automatically (RFC 9007 §2,
/// derived from RFC 8098 disposition-mode sending-mode).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SendingMode {
    /// The user explicitly requested the MDN be sent.
    MdnSentManually,
    /// The MDN was generated and sent automatically.
    MdnSentAutomatically,
}

impl std::fmt::Display for SendingMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            SendingMode::MdnSentManually => "mdn-sent-manually",
            SendingMode::MdnSentAutomatically => "mdn-sent-automatically",
        })
    }
}

/// The disposition type — what happened to the original message
/// (RFC 9007 §2, derived from RFC 8098 disposition-type).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DispositionType {
    /// The message was deleted without being displayed.
    Deleted,
    /// The message was dispatched to a further destination.
    Dispatched,
    /// The message was displayed to the user.
    Displayed,
    /// The message was processed in some manner without being displayed.
    Processed,
}

impl std::fmt::Display for DispositionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            DispositionType::Deleted => "deleted",
            DispositionType::Dispatched => "dispatched",
            DispositionType::Displayed => "displayed",
            DispositionType::Processed => "processed",
        })
    }
}

/// RFC 8098 disposition field — describes the action taken on the original message
/// (RFC 9007 §2).
///
/// Construct with [`Disposition::new`] rather than struct-literal syntax (the
/// struct is `#[non_exhaustive]` to allow future fields).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Disposition {
    /// Whether the MDN was triggered manually or automatically.
    pub action_mode: ActionMode,
    /// Whether the MDN itself was sent manually or automatically.
    pub sending_mode: SendingMode,
    /// What happened to the original message.
    ///
    /// Wire name is `type` (a Rust keyword — accessed as `type_` in code).
    #[serde(rename = "type")]
    pub type_: DispositionType,
    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl Disposition {
    /// Construct a [`Disposition`] from its three required fields.
    pub fn new(action_mode: ActionMode, sending_mode: SendingMode, type_: DispositionType) -> Self {
        Self {
            action_mode,
            sending_mode,
            type_,
            extra: serde_json::Map::new(),
        }
    }
}

/// An MDN object as defined in RFC 9007 §2.
///
/// Represents either a to-be-sent MDN (in [`MdnSendRequest`]) or a parsed MDN
/// (in [`MdnParseResponse`]).
///
/// The struct is `#[non_exhaustive]` to allow future fields without a breaking
/// version bump. Construct with [`Mdn::new`] rather than struct-literal syntax;
/// set optional fields directly after construction.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Mdn {
    /// The JMAP email ID of the message this MDN is for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub for_email_id: Option<Id>,

    /// Subject of the MDN message (defaults to auto-generated if absent).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,

    /// Human-readable explanation in the text/plain part of the MDN.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_body: Option<String>,

    /// If `true`, the original message is attached to the MDN.
    ///
    /// Defaults to `false` when deserialized from a request that omits the field.
    #[serde(default)]
    pub include_original_message: bool,

    /// Identifying information for the MUA that generated the MDN.
    #[serde(rename = "reportingUA", skip_serializing_if = "Option::is_none")]
    pub reporting_ua: Option<String>,

    /// Disposition describing the action taken on the original message.
    pub disposition: Disposition,

    /// Gateway or MTA name through which the MDN passed (server-set on parse).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mdn_gateway: Option<String>,

    /// Original recipient address as per RFC 8098 Original-Recipient header (server-set).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub original_recipient: Option<String>,

    /// Final recipient address (the address to which the message was delivered).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub final_recipient: Option<String>,

    /// Message-ID of the original message (server-set on parse).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub original_message_id: Option<String>,

    /// Error descriptions from the MDN (server-set on parse).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<Vec<String>>,

    /// RFC 9007-defined MDN extension headers, keyed by header name.
    ///
    /// Wire name is `extensionFields` per RFC 9007 §2 (normative).
    /// The §3.1 example incorrectly uses `extension`; the §2 definition
    /// is authoritative.
    ///
    /// These values become MIME-level headers on the generated MDN
    /// (e.g. `X-AcmeCorp-Tracking: abc123` here is emitted into the
    /// `message/disposition-notification` MIME part). For vendor /
    /// site fields that should live on the JMAP-level `Mdn` JSON
    /// object instead — and not on the generated MIME — see
    /// [`Self::extra`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extension_fields: Option<HashMap<String, String>>,
    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md).
    ///
    /// Distinct from RFC 9007 [`Self::extension_fields`] above: that
    /// field carries RFC 9007-defined MDN extension headers that the
    /// server emits into the generated MIME-level
    /// `message/disposition-notification` part; `extra` captures
    /// JMAP-level vendor / site fields on the `Mdn` JSON object itself
    /// (e.g. `acmeCorpSendPriority: "high"` as a server-side dispatch
    /// hint that never leaves JMAP).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl Mdn {
    /// Construct an [`Mdn`] with the required `disposition` field.
    ///
    /// All optional fields are initialised to `None` / `false`. Set them
    /// directly after construction as needed, e.g.:
    ///
    /// ```rust
    /// # use jmap_mail_types::mdn::{Mdn, Disposition, ActionMode, SendingMode, DispositionType};
    /// let mut mdn = Mdn::new(Disposition::new(
    ///     ActionMode::ManualAction,
    ///     SendingMode::MdnSentManually,
    ///     DispositionType::Displayed,
    /// ));
    /// mdn.subject = Some("Read: Hello".to_owned());
    /// ```
    pub fn new(disposition: Disposition) -> Self {
        Self {
            for_email_id: None,
            subject: None,
            text_body: None,
            include_original_message: false,
            reporting_ua: None,
            disposition,
            mdn_gateway: None,
            original_recipient: None,
            final_recipient: None,
            original_message_id: None,
            error: None,
            extension_fields: None,
            extra: serde_json::Map::new(),
        }
    }
}

/// Request object for `MDN/send` (RFC 9007 §3.1).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MdnSendRequest {
    /// The account to act on.
    pub account_id: Id,
    /// The identity to use as the MDN sender.
    pub identity_id: Id,
    /// Map of client-assigned creation IDs to [`Mdn`] objects to send.
    pub send: HashMap<String, Mdn>,
    /// Patches to apply to Email objects on successful send.
    ///
    /// Keys are Email IDs OR `#creationId` references that the
    /// dispatcher resolves to real Email IDs (RFC 8620 §5.7). The map
    /// is keyed by `String` rather than [`Id`] because `Id`'s contract
    /// (RFC 8620 §1.2: URL-safe base64 alphabet) does not admit the
    /// `#`-prefix used by creation-id references; values are
    /// [`PatchObject`] (RFC 8620 §5.3). This matches the canonical
    /// SetResponse pattern in `jmap-types::methods` where
    /// creation-id-keyed maps use `HashMap<String, _>` and
    /// real-id-keyed maps use `HashMap<Id, _>`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_success_update_email: Option<HashMap<String, PatchObject>>,
    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl MdnSendRequest {
    /// Construct an [`MdnSendRequest`] from its three required fields.
    ///
    /// `on_success_update_email` defaults to `None` and `extra` defaults
    /// to empty. Set them directly after construction as needed.
    pub fn new(account_id: Id, identity_id: Id, send: HashMap<String, Mdn>) -> Self {
        Self {
            account_id,
            identity_id,
            send,
            on_success_update_email: None,
            extra: serde_json::Map::new(),
        }
    }
}

/// Response object for `MDN/send` (RFC 9007 §3.1).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MdnSendResponse {
    /// The account the operation was performed on.
    pub account_id: Id,
    /// Map of client creation IDs to the MDN objects that were successfully sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sent: Option<HashMap<String, Mdn>>,
    /// Map of client creation IDs to [`SetError`] objects for MDNs that
    /// could not be sent. Matches the canonical
    /// `SetResponse.not_created: HashMap<String, SetError>` pattern in
    /// `jmap-types::methods`. The keys are creation IDs (clients
    /// assign them via the request's `send` map), which is why the
    /// key type is `String` rather than [`Id`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_sent: Option<HashMap<String, SetError>>,
    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl MdnSendResponse {
    /// Construct an [`MdnSendResponse`] from the required `account_id`.
    ///
    /// `sent`, `not_sent`, and `extra` default to `None` / empty. Set
    /// them directly after construction as needed.
    pub fn new(account_id: Id) -> Self {
        Self {
            account_id,
            sent: None,
            not_sent: None,
            extra: serde_json::Map::new(),
        }
    }
}

/// Request object for `MDN/parse` (RFC 9007 §3.3).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MdnParseRequest {
    /// The account to act on.
    pub account_id: Id,
    /// Blob IDs to parse as MDN messages.
    pub blob_ids: Vec<Id>,
    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl MdnParseRequest {
    /// Construct an [`MdnParseRequest`] from its two required fields.
    ///
    /// `extra` defaults to empty. Set it directly after construction as
    /// needed.
    pub fn new(account_id: Id, blob_ids: Vec<Id>) -> Self {
        Self {
            account_id,
            blob_ids,
            extra: serde_json::Map::new(),
        }
    }
}

/// Response object for `MDN/parse` (RFC 9007 §3.3).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MdnParseResponse {
    /// The account the operation was performed on.
    pub account_id: Id,
    /// Map of blob IDs that were successfully parsed to their [`Mdn`] representation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parsed: Option<HashMap<Id, Mdn>>,
    /// Blob IDs that could not be parsed as MDN messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_parsable: Option<Vec<Id>>,
    /// Blob IDs that were not found in the account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_found: Option<Vec<Id>>,
    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl MdnParseResponse {
    /// Construct an [`MdnParseResponse`] from the required `account_id`.
    ///
    /// `parsed`, `not_parsable`, `not_found`, and `extra` default to
    /// `None` / empty. Set them directly after construction as needed.
    pub fn new(account_id: Id) -> Self {
        Self {
            account_id,
            parsed: None,
            not_parsable: None,
            not_found: None,
            extra: serde_json::Map::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Round-trip test for [`Disposition`] against the wire format specified
    /// in RFC 9007 §2.
    ///
    /// Wire values are taken directly from the spec text — this is the independent
    /// oracle.
    #[test]
    fn disposition_roundtrip() {
        // Spec §2: actionMode values are "manual-action" and "automatic-action"
        // Spec §2: sendingMode values are "mdn-sent-manually" and "mdn-sent-automatically"
        // Spec §2: type values are "deleted", "dispatched", "displayed", "processed"
        let json = r#"{"actionMode":"manual-action","sendingMode":"mdn-sent-manually","type":"displayed"}"#;
        let d: Disposition = serde_json::from_str(json).unwrap();
        assert_eq!(d.action_mode, ActionMode::ManualAction);
        assert_eq!(d.sending_mode, SendingMode::MdnSentManually);
        assert_eq!(d.type_, DispositionType::Displayed);

        let serialized = serde_json::to_string(&d).unwrap();
        assert_eq!(serialized, json);
    }

    /// Round-trip test for [`Mdn`] verifying camelCase wire names and
    /// `include_original_message` default behaviour.
    ///
    /// Field names taken from RFC 9007 §2 (normative definition).
    #[test]
    fn mdn_camel_case_wire_names() {
        // Minimal MDN — only required field is `disposition`.
        // Spec §2: includeOriginalMessage defaults to false.
        let json = r#"{
            "forEmailId": "e1",
            "subject": "Read: Hello",
            "textBody": "This is a receipt.",
            "reportingUA": "Acme Mail 1.0; example.com",
            "disposition": {
                "actionMode": "manual-action",
                "sendingMode": "mdn-sent-manually",
                "type": "displayed"
            }
        }"#;
        let mdn: Mdn = serde_json::from_str(json).unwrap();
        assert_eq!(mdn.for_email_id.as_ref().map(|id| id.as_ref()), Some("e1"));
        assert_eq!(mdn.subject.as_deref(), Some("Read: Hello"));
        assert!(!mdn.include_original_message, "should default to false");
        assert_eq!(mdn.disposition.type_, DispositionType::Displayed);
    }

    /// Verify `extensionFields` wire name (not `extension`).
    ///
    /// RFC 9007 §2 uses `extensionFields` (normative).
    /// The §3.1 example incorrectly uses `extension` — we follow §2.
    #[test]
    fn extension_fields_wire_name() {
        let json = r#"{"disposition":{"actionMode":"manual-action","sendingMode":"mdn-sent-manually","type":"processed"},"extensionFields":{"X-Custom":"value"}}"#;
        let mdn: Mdn = serde_json::from_str(json).unwrap();
        let fields = mdn.extension_fields.as_ref().unwrap();
        assert_eq!(fields.get("X-Custom").map(|s| s.as_str()), Some("value"));

        let serialized = serde_json::to_string(&mdn).unwrap();
        assert!(
            serialized.contains("extensionFields"),
            "must use extensionFields not extension"
        );
    }

    /// Verify all four DispositionType variants serialize to lowercase per spec §2.
    #[test]
    fn disposition_type_lowercase() {
        // Spec §2: all type values are lowercase
        let cases = [
            (DispositionType::Deleted, "\"deleted\""),
            (DispositionType::Dispatched, "\"dispatched\""),
            (DispositionType::Displayed, "\"displayed\""),
            (DispositionType::Processed, "\"processed\""),
        ];
        for (variant, expected) in &cases {
            let got = serde_json::to_string(variant).unwrap();
            assert_eq!(&got, expected, "DispositionType wire value mismatch");
        }
    }

    /// Verify ActionMode and SendingMode wire values per spec §2.
    #[test]
    fn action_and_sending_mode_wire_values() {
        // Spec §2: actionMode values
        assert_eq!(
            serde_json::to_string(&ActionMode::ManualAction).unwrap(),
            "\"manual-action\""
        );
        assert_eq!(
            serde_json::to_string(&ActionMode::AutomaticAction).unwrap(),
            "\"automatic-action\""
        );
        // Spec §2: sendingMode values
        assert_eq!(
            serde_json::to_string(&SendingMode::MdnSentManually).unwrap(),
            "\"mdn-sent-manually\""
        );
        assert_eq!(
            serde_json::to_string(&SendingMode::MdnSentAutomatically).unwrap(),
            "\"mdn-sent-automatically\""
        );
    }

    /// Verify MdnSendRequest round-trips with camelCase field names.
    ///
    /// Field names taken from RFC 9007 §3.1.
    #[test]
    fn mdn_send_request_roundtrip() {
        // Wire JSON uses camelCase per spec §3.1
        let json = r#"{
            "accountId": "acc1",
            "identityId": "idt1",
            "send": {
                "k1": {
                    "forEmailId": "e1",
                    "disposition": {
                        "actionMode": "manual-action",
                        "sendingMode": "mdn-sent-manually",
                        "type": "displayed"
                    }
                }
            }
        }"#;
        let req: MdnSendRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.account_id.as_ref(), "acc1");
        assert_eq!(req.identity_id.as_ref(), "idt1");
        assert!(req.send.contains_key("k1"));
        assert!(req.on_success_update_email.is_none());
    }

    /// Verify MdnSendRequest round-trips with `onSuccessUpdateEmail`
    /// populated — the typed shape `HashMap<Id, PatchObject>` MUST be
    /// wire-byte-identical to a `HashMap<String, Object>` because both
    /// `Id` and `PatchObject` are `#[serde(transparent)]`.
    ///
    /// Oracle: hand-written JSON literal taken from RFC 9007 §3.1
    /// (`onSuccessUpdateEmail` field shape) and RFC 8620 §5.3
    /// (PatchObject path-key syntax with the `keywords/$mdnsent`
    /// example used in the MDN/send acceptance flow).
    #[test]
    fn mdn_send_request_on_success_update_email_roundtrip() {
        // Raw-string fence is `r##"..."##` because the JSON body itself
        // contains a `#` (in the `#k1` creation-id reference key) — a
        // single-`#` raw-string fence would terminate prematurely.
        let json = r##"{
            "accountId": "acc1",
            "identityId": "idt1",
            "send": {
                "k1": {
                    "forEmailId": "e1",
                    "disposition": {
                        "actionMode": "manual-action",
                        "sendingMode": "mdn-sent-manually",
                        "type": "displayed"
                    }
                }
            },
            "onSuccessUpdateEmail": {
                "#k1": { "keywords/$mdnsent": true }
            }
        }"##;
        let req: MdnSendRequest = serde_json::from_str(json).unwrap();

        // Verify the typed shape: String key (creation-id may carry
        // `#`-prefix per RFC 8620 §5.7; `Id` would lie about its
        // alphabet contract), PatchObject value.
        let patches = req
            .on_success_update_email
            .as_ref()
            .expect("onSuccessUpdateEmail must deserialize as Some");
        let patch = patches
            .get("#k1")
            .expect("patch for #k1 must be present after round-trip");
        assert_eq!(
            patch.as_map().get("keywords/$mdnsent"),
            Some(&serde_json::json!(true)),
            "patch leaf must round-trip the boolean true"
        );
        assert_eq!(patch.as_map().len(), 1, "exactly one leaf in the patch");

        // Re-serialize and compare just the `onSuccessUpdateEmail` subtree
        // structurally. Comparing the whole document would also pick up the
        // pre-existing `Mdn::include_original_message` serialise-default
        // behaviour, which is unrelated to this migration.
        //
        // Equality of these two subtrees proves that `PatchObject` is
        // wire-byte-identical to a plain `Object` — i.e. that
        // `#[serde(transparent)]` is doing what we claim it does.
        let re_serialized = serde_json::to_value(&req).unwrap();
        let original: serde_json::Value = serde_json::from_str(json).unwrap();
        assert_eq!(
            re_serialized.get("onSuccessUpdateEmail"),
            original.get("onSuccessUpdateEmail"),
            "onSuccessUpdateEmail must round-trip wire-byte-identical \
             through HashMap<String, PatchObject>"
        );
    }

    /// Verify MdnParseResponse round-trips with camelCase field names.
    ///
    /// Field names taken from RFC 9007 §3.3.
    #[test]
    fn mdn_parse_response_roundtrip() {
        // Wire JSON uses camelCase per spec §3.3
        let json = r#"{
            "accountId": "acc1",
            "notParsable": ["blob2"],
            "notFound": ["blob3"]
        }"#;
        let resp: MdnParseResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.account_id.as_ref(), "acc1");
        assert!(resp.parsed.is_none());
        assert_eq!(resp.not_parsable.as_deref(), Some(&[Id::from("blob2")][..]));
        assert_eq!(resp.not_found.as_deref(), Some(&[Id::from("blob3")][..]));
    }

    // ── Extras-preservation policy tests (JMAP-lbdy.2) ───────────────────
    //
    // One round-trip preservation test per migrated type. Each asserts
    // that an unknown vendor / site / private-extension field survives
    // deserialize/serialize unchanged. Per workspace AGENTS.md
    // "Extras-preservation policy for vendor/site fields".

    /// `Disposition.extra` captures vendor fields and preserves them.
    #[test]
    fn disposition_preserves_vendor_extras() {
        let raw = serde_json::json!({
            "actionMode": "manual-action",
            "sendingMode": "mdn-sent-manually",
            "type": "displayed",
            "acmeCorpDispositionFlag": "auto-ack"
        });
        let d: Disposition = serde_json::from_value(raw).unwrap();
        assert_eq!(
            d.extra
                .get("acmeCorpDispositionFlag")
                .and_then(|v| v.as_str()),
            Some("auto-ack")
        );
        let back = serde_json::to_value(&d).unwrap();
        assert_eq!(back["acmeCorpDispositionFlag"], "auto-ack");
    }

    /// `Mdn.extra` captures vendor fields and preserves them. Distinct from
    /// the typed RFC 9007 `extensionFields` member which carries
    /// MDN-extension headers only.
    #[test]
    fn mdn_preserves_vendor_extras() {
        let raw = serde_json::json!({
            "forEmailId": "e1",
            "disposition": {
                "actionMode": "manual-action",
                "sendingMode": "mdn-sent-manually",
                "type": "displayed"
            },
            "acmeCorpClientTrace": "ua-42"
        });
        let mdn: Mdn = serde_json::from_value(raw).unwrap();
        assert_eq!(
            mdn.extra
                .get("acmeCorpClientTrace")
                .and_then(|v| v.as_str()),
            Some("ua-42")
        );
        let back = serde_json::to_value(&mdn).unwrap();
        assert_eq!(back["acmeCorpClientTrace"], "ua-42");
    }

    /// `MdnSendRequest.extra` captures vendor fields and preserves them.
    #[test]
    fn mdn_send_request_preserves_vendor_extras() {
        let raw = serde_json::json!({
            "accountId": "a1",
            "identityId": "i1",
            "send": {},
            "acmeCorpRequestTag": "batch-7"
        });
        let req: MdnSendRequest = serde_json::from_value(raw).unwrap();
        assert_eq!(
            req.extra.get("acmeCorpRequestTag").and_then(|v| v.as_str()),
            Some("batch-7")
        );
        let back = serde_json::to_value(&req).unwrap();
        assert_eq!(back["acmeCorpRequestTag"], "batch-7");
    }

    /// `MdnSendResponse.extra` captures vendor fields and preserves them.
    #[test]
    fn mdn_send_response_preserves_vendor_extras() {
        let raw = serde_json::json!({
            "accountId": "a1",
            "acmeCorpServerTrace": "node-3"
        });
        let resp: MdnSendResponse = serde_json::from_value(raw).unwrap();
        assert_eq!(
            resp.extra
                .get("acmeCorpServerTrace")
                .and_then(|v| v.as_str()),
            Some("node-3")
        );
        let back = serde_json::to_value(&resp).unwrap();
        assert_eq!(back["acmeCorpServerTrace"], "node-3");
    }

    /// `MdnParseRequest.extra` captures vendor fields and preserves them.
    #[test]
    fn mdn_parse_request_preserves_vendor_extras() {
        let raw = serde_json::json!({
            "accountId": "a1",
            "blobIds": ["b1"],
            "acmeCorpParseHint": "lenient"
        });
        let req: MdnParseRequest = serde_json::from_value(raw).unwrap();
        assert_eq!(
            req.extra.get("acmeCorpParseHint").and_then(|v| v.as_str()),
            Some("lenient")
        );
        let back = serde_json::to_value(&req).unwrap();
        assert_eq!(back["acmeCorpParseHint"], "lenient");
    }

    /// `MdnParseResponse.extra` captures vendor fields and preserves them.
    #[test]
    fn mdn_parse_response_preserves_vendor_extras() {
        let raw = serde_json::json!({
            "accountId": "a1",
            "acmeCorpStatus": "complete"
        });
        let resp: MdnParseResponse = serde_json::from_value(raw).unwrap();
        assert_eq!(
            resp.extra.get("acmeCorpStatus").and_then(|v| v.as_str()),
            Some("complete")
        );
        let back = serde_json::to_value(&resp).unwrap();
        assert_eq!(back["acmeCorpStatus"], "complete");
    }

    /// Each Mdn*Request and Mdn*Response constructor produces a value
    /// whose serialised wire form matches the minimal RFC 9007 §3.1 /
    /// §3.3 shape, with no `extra` keys.
    ///
    /// Independent oracle: the expected JSON is hand-written from RFC
    /// 9007 §3.1 (`MDN/send` request/response shape) and §3.3
    /// (`MDN/parse` request/response shape), not produced by the code
    /// under test.
    #[test]
    fn mdn_request_response_constructors_match_spec_minimal_shape() {
        let account_id = Id::try_from("a1").unwrap();
        let identity_id = Id::try_from("i1").unwrap();
        let blob_id = Id::try_from("b1").unwrap();

        // MdnSendRequest: required accountId, identityId, send map.
        let send_req = MdnSendRequest::new(account_id.clone(), identity_id, HashMap::new());
        let expected = serde_json::json!({
            "accountId": "a1",
            "identityId": "i1",
            "send": {}
        });
        assert_eq!(serde_json::to_value(&send_req).unwrap(), expected);

        // MdnSendResponse: required accountId only.
        let send_resp = MdnSendResponse::new(account_id.clone());
        let expected = serde_json::json!({ "accountId": "a1" });
        assert_eq!(serde_json::to_value(&send_resp).unwrap(), expected);

        // MdnParseRequest: required accountId and blobIds.
        let parse_req = MdnParseRequest::new(account_id.clone(), vec![blob_id]);
        let expected = serde_json::json!({
            "accountId": "a1",
            "blobIds": ["b1"]
        });
        assert_eq!(serde_json::to_value(&parse_req).unwrap(), expected);

        // MdnParseResponse: required accountId only.
        let parse_resp = MdnParseResponse::new(account_id);
        let expected = serde_json::json!({ "accountId": "a1" });
        assert_eq!(serde_json::to_value(&parse_resp).unwrap(), expected);
    }
}