jmap-mail-types 0.4.1

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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
//! Email/query filter and comparator types (RFC 8621 §4.4).
//!
//! Provides [`EmailFilterCondition`] — the mail-specific condition object for
//! Email/query — and the [`EmailFilter`] type alias for convenience.
//!
//! The generic [`Filter`], [`FilterOperator`], and [`Operator`] types used here
//! are defined in `jmap-types` (RFC 8620 §5.5).

use jmap_metadata_types::MetadataTextMatch;
use jmap_types::{Id, UTCDate, impl_string_enum};
use serde::{Deserialize, Serialize};

use crate::keyword::Keyword;

pub use jmap_types::{Filter, FilterOperator, Operator};

/// Concrete filter type for Email/query (RFC 8621 §4.4).
pub type EmailFilter = Filter<EmailFilterCondition>;

/// Concrete filter type for Mailbox/query (RFC 8621 §2.3).
///
/// The condition struct is [`MailboxFilterCondition`](crate::MailboxFilterCondition).
pub type MailboxFilter = Filter<crate::mailbox::MailboxFilterCondition>;

/// Concrete filter type for EmailSubmission/query (RFC 8621 §7.3).
///
/// The condition struct is
/// [`EmailSubmissionFilterCondition`](crate::EmailSubmissionFilterCondition).
pub type EmailSubmissionFilter = Filter<crate::submission::EmailSubmissionFilterCondition>;

/// Filter condition for Email objects (RFC 8621 §4.4.1).
///
/// All fields are optional.  If zero properties are specified, the condition
/// evaluates to `true` for every Email (RFC 8621 §4.4.1).  When multiple
/// properties are specified, ALL must apply (equivalent to splitting into
/// one-property conditions under AND).
///
/// Unknown properties are rejected (`#[serde(deny_unknown_fields)]`, which
/// composes with the `#[serde(untagged)]` [`Filter`]), so a misspelt clause
/// fails the decode instead of matching every Email; servers map the
/// failure to RFC 8620 §5.5 `unsupportedFilter`.
///
/// # Excluded from extras preservation
///
/// This type is **out of scope** for the workspace extras-preservation
/// policy: it carries no flatten-extras `extra` field. Filter clauses the
/// server does not understand are a query-correctness hazard — silently
/// preserving an unrecognised clause and round-tripping it back to the
/// client can return the wrong set of records with no error signal.
///
/// ## What to do instead
///
/// **IETF-track path.** Vendors who need both capability-level declaration
/// and filterability for custom fields should use
/// `draft-ietf-jmap-metadata` (capability URI
/// `urn:ietf:params:jmap:metadata`), which adds namespace-keyed
/// `metadata` / `privateMetadata` properties to each listed data type,
/// with per-type schema discovery via the capability's `dataTypes`
/// (`namespaces` / `supportsVendorNamespaces` / `maxDepth`) and
/// `metadataExists` / `metadataTextContains` / `metadataTextEquals`
/// conditions on that type's own `/query` filter
/// (draft-ietf-jmap-metadata-04 §1.2.1, §3.6). Helpers live in
/// `jmap-metadata-types`, `jmap-metadata-server`, and
/// `jmap-metadata-client`.
///
/// **Pre-IETF escape.** Vendors who cannot wait for the metadata draft can
/// either escape the filter tree to `serde_json::Value` or fork
/// `EmailFilterCondition`. See
/// `crate-jmap-calendars-types/PLAN.md` for the hybrid sloppy-value
/// pattern.
///
/// Cross-reference: bd JMAP-lbdy "Decision: filter algebra excluded".
///
/// # Construction from outside this crate
///
/// The struct is `#[non_exhaustive]`: struct literal syntax and functional
/// record update (`{ field: val, ..Default::default() }`) are unavailable to
/// external callers.  Use [`Default::default`] and then mutate the fields you
/// need:
///
/// ```rust
/// use jmap_mail_types::EmailFilterCondition;
/// use jmap_mail_types::{Keyword};
/// use jmap_types::Id;
///
/// let mut cond = EmailFilterCondition::default();
/// cond.in_mailbox = Some(Id::from("inbox-id"));
/// cond.has_keyword = Some(Keyword::from(jmap_mail_types::SEEN));
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EmailFilterCondition {
    /// A Mailbox id; the Email must be in this Mailbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_mailbox: Option<Id>,

    /// A list of Mailbox ids; the Email must be in at least one Mailbox not in
    /// this list (used to exclude trash/spam from results).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_mailbox_other_than: Option<Vec<Id>>,

    /// The `receivedAt` of the Email must be before this date-time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<UTCDate>,

    /// The `receivedAt` of the Email must be on or after this date-time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<UTCDate>,

    /// The `size` of the Email must be >= this value (bytes).
    ///
    /// RFC 8620 §1.3 defines `UnsignedInt` as limited to the range
    /// [0, 2^53-1].  Values above that threshold may not round-trip correctly
    /// through JSON parsers that use IEEE 754 doubles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_size: Option<u64>,

    /// The `size` of the Email must be < this value (bytes).
    ///
    /// Same 2^53-1 constraint as `min_size` (RFC 8620 §1.3).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_size: Option<u64>,

    /// All Emails in the same Thread must have this keyword.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub all_in_thread_have_keyword: Option<Keyword>,

    /// At least one Email in the same Thread must have this keyword.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub some_in_thread_have_keyword: Option<Keyword>,

    /// No Email in the same Thread may have this keyword.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub none_in_thread_have_keyword: Option<Keyword>,

    /// This Email must have this keyword.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_keyword: Option<Keyword>,

    /// This Email must not have this keyword.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_keyword: Option<Keyword>,

    /// The `hasAttachment` property of the Email must equal this value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_attachment: Option<bool>,

    /// Matches text across From, To, Cc, Bcc, Subject, and body parts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,

    /// Matches text in the From header field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,

    /// Matches text in the To header field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,

    /// Matches text in the Cc header field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cc: Option<String>,

    /// Matches text in the Bcc header field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<String>,

    /// Matches text in the Subject header field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,

    /// Matches text in a body part of the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    /// Arbitrary header field match.  RFC 8621 §4.4.1 requires exactly 1 or 2
    /// elements: the first is the header field name; the second (optional) is
    /// the value to match.
    ///
    /// **Invariant**: when `Some`, the `Vec` must have exactly 1 or 2 elements.
    /// This is enforced at deserialization time (supplying 0 or 3+ elements is
    /// rejected with an error).  Code that constructs an
    /// `EmailFilterCondition` directly and sets `header` is responsible for
    /// upholding this invariant; serialization does not re-validate.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_header"
    )]
    pub header: Option<Vec<String>>,

    /// draft-ietf-jmap-metadata-04 §3.6 `metadataExists`: a value must be
    /// present at this path in the object's `metadata`. The path is a
    /// namespace identifier, optionally followed by an RFC 6901 JSON
    /// Pointer into the namespace value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata_exists: Option<String>,

    /// -04 §3.6 `privateMetadataExists`: as `metadata_exists`, against the
    /// authenticated user's `privateMetadata`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub private_metadata_exists: Option<String>,

    /// -04 §3.6 `metadataTextContains`: substring match under the
    /// `i;unicode-casemap` collation on the `metadata` string at a path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata_text_contains: Option<MetadataTextMatch>,

    /// -04 §3.6 `privateMetadataTextContains`: as
    /// `metadata_text_contains`, against `privateMetadata`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub private_metadata_text_contains: Option<MetadataTextMatch>,

    /// -04 §3.6 `metadataTextEquals`: exact code-point match on the
    /// `metadata` string at a path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata_text_equals: Option<MetadataTextMatch>,

    /// -04 §3.6 `privateMetadataTextEquals`: as `metadata_text_equals`,
    /// against `privateMetadata`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub private_metadata_text_equals: Option<MetadataTextMatch>,
}

impl EmailFilterCondition {
    /// `true` if any of the six draft-ietf-jmap-metadata-04 §3.6
    /// `metadata*` / `privateMetadata*` fields is set.
    pub fn has_metadata_condition(&self) -> bool {
        self.metadata_exists.is_some()
            || self.private_metadata_exists.is_some()
            || self.metadata_text_contains.is_some()
            || self.private_metadata_text_contains.is_some()
            || self.metadata_text_equals.is_some()
            || self.private_metadata_text_equals.is_some()
    }
}

// ---------------------------------------------------------------------------
// ComparatorProperty (RFC 8621 §4.4.2)
// ---------------------------------------------------------------------------

/// The property to sort by in an [`EmailComparator`] (RFC 8621 §4.4.2).
///
/// When the variant is [`HasKeyword`](ComparatorProperty::HasKeyword),
/// [`AllInThreadHaveKeyword`](ComparatorProperty::AllInThreadHaveKeyword), or
/// [`SomeInThreadHaveKeyword`](ComparatorProperty::SomeInThreadHaveKeyword),
/// the `keyword` field on [`EmailComparator`] **MUST** also be set
/// (RFC 8621 §4.4.2).
///
/// Unknown property names from the server are preserved in
/// [`Other`](ComparatorProperty::Other) so they round-trip correctly.
///
/// # Excluded from extras preservation
///
/// This enum is **out of scope** for the workspace extras-preservation
/// policy: it is a control enum that backends must dispatch on to
/// determine the sort order, so a generic catch-all variant would be
/// meaningless for query execution. The `Other(String)` variant that
/// `ComparatorProperty` does carry exists only to preserve unknown
/// property names for client-side round-tripping; servers cannot
/// meaningfully sort by an unrecognised property without a registered
/// extension.
///
/// More broadly, filter / comparator algebra is excluded because
/// unrecognised clauses are a query-correctness hazard: silently dropping
/// or round-tripping a clause the server does not understand can return
/// the wrong set of records to the client without any error signal.
///
/// ## What to do instead
///
/// **IETF-track path.** Vendors who need both capability-level declaration
/// and filterability for custom fields should use
/// `draft-ietf-jmap-metadata` (capability URI
/// `urn:ietf:params:jmap:metadata`), which adds namespace-keyed
/// `metadata` / `privateMetadata` properties to each listed data type,
/// filterable through `metadata*` conditions on that type's own `/query`
/// (draft-ietf-jmap-metadata-04 §2, §3.6). Helpers live in
/// `jmap-metadata-types`, `jmap-metadata-server`, and
/// `jmap-metadata-client`.
///
/// **Pre-IETF escape.** Vendors who cannot wait for the metadata draft can
/// either escape to `serde_json::Value` or fork the per-crate
/// `FilterCondition` / `ComparatorProperty` types. See
/// `crate-jmap-calendars-types/PLAN.md` for the hybrid sloppy-value
/// pattern.
///
/// Cross-reference: bd JMAP-lbdy "Decision: filter algebra excluded".
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ComparatorProperty {
    /// Sort by `receivedAt`.
    ReceivedAt,
    /// Sort by message size in octets.
    Size,
    /// Sort by the text of the From header field.
    From,
    /// Sort by the text of the To header field.
    To,
    /// Sort by the decoded Subject.
    Subject,
    /// Sort by `sentAt`.
    SentAt,
    /// Sort by whether Emails in the Thread have the given `keyword`.
    HasKeyword,
    /// Sort by whether all Emails in the Thread have the given `keyword`.
    AllInThreadHaveKeyword,
    /// Sort by whether some Emails in the Thread have the given `keyword`.
    SomeInThreadHaveKeyword,
    /// A server-extension property name not listed above.
    Other(String),
}

impl_string_enum!(ComparatorProperty, "an Email comparator property string",
    "receivedAt"              => ReceivedAt,
    "size"                    => Size,
    "from"                    => From,
    "to"                      => To,
    "subject"                 => Subject,
    "sentAt"                  => SentAt,
    "hasKeyword"              => HasKeyword,
    "allInThreadHaveKeyword"  => AllInThreadHaveKeyword,
    "someInThreadHaveKeyword" => SomeInThreadHaveKeyword,
);

// ---------------------------------------------------------------------------
// EmailComparator (RFC 8621 §4.4.2)
// ---------------------------------------------------------------------------

/// Sort comparator for Email/query (RFC 8621 §4.4.2).
///
/// When `property` is one of the keyword-based variants
/// ([`ComparatorProperty::HasKeyword`], [`ComparatorProperty::AllInThreadHaveKeyword`],
/// [`ComparatorProperty::SomeInThreadHaveKeyword`]), the `keyword` field
/// **MUST** also be set.  `is_ascending` defaults to `true` per RFC 8620 §5.5.
///
/// # Excluded from extras preservation
///
/// This type is **out of scope** for the workspace extras-preservation
/// policy: it carries no flatten-extras `extra` field, and its
/// [`ComparatorProperty`] field is a closed control enum that backends
/// must dispatch on. See [`ComparatorProperty`] and
/// [`EmailFilterCondition`] for the rationale and for the two recommended
/// paths (`draft-ietf-jmap-metadata`, bd JMAP-ua37; or the pre-IETF
/// sloppy-value escape).
///
/// Cross-reference: bd JMAP-lbdy "Decision: filter algebra excluded".
///
/// # Construction
///
/// Use [`EmailComparator::new`] to construct from outside this crate.
/// The struct is `#[non_exhaustive]`; struct literal syntax is not available
/// to external callers.
///
/// ```rust
/// use jmap_mail_types::{EmailComparator, ComparatorProperty};
///
/// let mut cmp = EmailComparator::new(ComparatorProperty::ReceivedAt);
/// cmp.is_ascending = false;  // sort descending
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmailComparator {
    /// The property to sort by.
    pub property: ComparatorProperty,

    /// If `true`, sort ascending; if `false`, sort descending.
    /// Defaults to `true` per RFC 8620 §5.5.
    #[serde(default = "bool_true", skip_serializing_if = "is_true")]
    pub is_ascending: bool,

    /// Collation algorithm (e.g. `"i;ascii-casemap"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collation: Option<String>,

    /// Required when `property` is one of the keyword-based variants
    /// (RFC 8621 §4.4.2).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub keyword: Option<Keyword>,
}

impl EmailComparator {
    /// Construct an [`EmailComparator`] for the given property.
    ///
    /// `is_ascending` defaults to `true` (RFC 8620 §5.5 default).
    /// `collation` and `keyword` default to `None`.
    ///
    /// Set fields directly after construction:
    ///
    /// ```rust
    /// use jmap_mail_types::{EmailComparator, ComparatorProperty};
    /// use jmap_mail_types::Keyword;
    ///
    /// let mut cmp = EmailComparator::new(ComparatorProperty::HasKeyword);
    /// cmp.keyword = Some(Keyword::from("$flagged"));
    /// cmp.is_ascending = false;
    /// ```
    pub fn new(property: ComparatorProperty) -> Self {
        Self {
            property,
            is_ascending: true,
            collation: None,
            keyword: None,
        }
    }
}

// ---------------------------------------------------------------------------
// MailboxComparator (RFC 8621 §2.3) and EmailSubmissionComparator (§7.3)
// ---------------------------------------------------------------------------

/// The property to sort by in a [`MailboxComparator`].
///
/// RFC 8621 §2.3: "The following Mailbox properties MUST be supported for
/// sorting: "sortOrder" "name"". Unknown names are kept in
/// [`Other`](MailboxComparatorProperty::Other) so they round-trip; a server
/// answers one it does not support with `unsupportedSort` (RFC 8620 §5.5).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MailboxComparatorProperty {
    /// Sort by `sortOrder`.
    SortOrder,
    /// Sort by `name`.
    Name,
    /// A property not listed above, kept so it round-trips; a server
    /// answers it with `unsupportedSort` (RFC 8620 §5.5).
    Other(String),
}

impl_string_enum!(MailboxComparatorProperty, "a Mailbox sort property string",
    "sortOrder" => SortOrder,
    "name"      => Name,
);

/// Sort comparator for `Mailbox/query` (RFC 8621 §2.3).
///
/// Out of scope for extras preservation for the same reason as
/// [`EmailComparator`]: backends dispatch on `property`.
///
/// Build one with [`MailboxComparator::new`]; the struct is
/// `#[non_exhaustive]`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MailboxComparator {
    /// The property to sort by.
    pub property: MailboxComparatorProperty,

    /// If `true`, sort ascending; if `false`, sort descending.
    /// Defaults to `true` per RFC 8620 §5.5.
    #[serde(default = "bool_true", skip_serializing_if = "is_true")]
    pub is_ascending: bool,

    /// Collation algorithm (e.g. `"i;unicode-casemap"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collation: Option<String>,
}

impl MailboxComparator {
    /// An ascending comparator on `property` with no collation
    /// (`isAscending` defaults to `true`, RFC 8620 §5.5).
    pub fn new(property: MailboxComparatorProperty) -> Self {
        Self {
            property,
            is_ascending: true,
            collation: None,
        }
    }
}

/// The property to sort by in an [`EmailSubmissionComparator`].
///
/// RFC 8621 §7.3: "The following EmailSubmission properties MUST be
/// supported for sorting: "emailId" "threadId" "sentAt"". Unknown names
/// are kept in [`Other`](EmailSubmissionComparatorProperty::Other) so they
/// round-trip; a server answers one it does not support with
/// `unsupportedSort` (RFC 8620 §5.5).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EmailSubmissionComparatorProperty {
    /// Sort by `emailId`.
    EmailId,
    /// Sort by `threadId`.
    ThreadId,
    /// Sort by `sentAt`.
    SentAt,
    /// A property not listed above, kept so it round-trips; a server
    /// answers it with `unsupportedSort` (RFC 8620 §5.5).
    Other(String),
}

impl_string_enum!(EmailSubmissionComparatorProperty, "an EmailSubmission sort property string",
    "emailId"  => EmailId,
    "threadId" => ThreadId,
    "sentAt"   => SentAt,
);

/// Sort comparator for `EmailSubmission/query` (RFC 8621 §7.3).
///
/// Out of scope for extras preservation for the same reason as
/// [`EmailComparator`]: backends dispatch on `property`.
///
/// Build one with [`EmailSubmissionComparator::new`]; the struct is
/// `#[non_exhaustive]`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmailSubmissionComparator {
    /// The property to sort by.
    pub property: EmailSubmissionComparatorProperty,

    /// If `true`, sort ascending; if `false`, sort descending.
    /// Defaults to `true` per RFC 8620 §5.5.
    #[serde(default = "bool_true", skip_serializing_if = "is_true")]
    pub is_ascending: bool,

    /// Collation algorithm (e.g. `"i;ascii-casemap"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collation: Option<String>,
}

impl EmailSubmissionComparator {
    /// An ascending comparator on `property` with no collation
    /// (`isAscending` defaults to `true`, RFC 8620 §5.5).
    pub fn new(property: EmailSubmissionComparatorProperty) -> Self {
        Self {
            property,
            is_ascending: true,
            collation: None,
        }
    }
}

/// The property to sort by in a [`SieveScriptComparator`].
///
/// RFC 9661 §2.5: "The following SieveScript properties MUST be supported
/// for sorting: name, isActive". Unknown names are kept in
/// [`Other`](SieveScriptComparatorProperty::Other) so they round-trip; a
/// server answers one it does not support with `unsupportedSort` (RFC 8620
/// §5.5).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SieveScriptComparatorProperty {
    /// Sort by `name`.
    Name,
    /// Sort by `isActive`.
    IsActive,
    /// A property not listed above, kept so it round-trips; a server
    /// answers it with `unsupportedSort` (RFC 8620 §5.5).
    Other(String),
}

impl_string_enum!(SieveScriptComparatorProperty, "a SieveScript sort property string",
    "name"     => Name,
    "isActive" => IsActive,
);

/// Sort comparator for `SieveScript/query` (RFC 9661 §2.5).
///
/// Out of scope for extras preservation for the same reason as
/// [`EmailComparator`]: servers dispatch on `property`.
///
/// Build one with [`SieveScriptComparator::new`]; the struct is
/// `#[non_exhaustive]`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SieveScriptComparator {
    /// The property to sort by.
    pub property: SieveScriptComparatorProperty,

    /// If `true`, sort ascending; if `false`, sort descending.
    /// Defaults to `true` per RFC 8620 §5.5.
    #[serde(default = "bool_true", skip_serializing_if = "is_true")]
    pub is_ascending: bool,

    /// Collation algorithm (e.g. `"i;unicode-casemap"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collation: Option<String>,
}

impl SieveScriptComparator {
    /// An ascending comparator on `property` with no collation
    /// (`isAscending` defaults to `true`, RFC 8620 §5.5).
    pub fn new(property: SieveScriptComparatorProperty) -> Self {
        Self {
            property,
            is_ascending: true,
            collation: None,
        }
    }
}

fn bool_true() -> bool {
    true
}

fn is_true(b: &bool) -> bool {
    *b
}

// ---------------------------------------------------------------------------
// Deserializer helpers
// ---------------------------------------------------------------------------

/// Deserialize `header` and enforce the 1–2 element constraint from RFC 8621 §4.4.1.
fn deserialize_header<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let v: Option<Vec<String>> = Option::deserialize(deserializer)?;
    if let Some(ref h) = v
        && (h.is_empty() || h.len() > 2)
    {
        return Err(serde::de::Error::custom(format!(
            "header must have 1 or 2 elements (RFC 8621 §4.4.1), got {}",
            h.len()
        )));
    }
    Ok(v)
}

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

    /// Oracle: RFC 8621 §4.4 example — filter by Mailbox id.
    /// Wire format from RFC 8621 §4.4 (line 3240 area of the RFC text).
    #[test]
    fn filter_condition_in_mailbox() {
        let json = r#"{"inMailbox":"fb666a55"}"#;
        let f: EmailFilter = serde_json::from_str(json).expect("must parse");
        match &f {
            Filter::Condition(c) => {
                assert_eq!(
                    c.in_mailbox.as_ref().map(|id| id.as_ref()),
                    Some("fb666a55")
                );
            }
            other => panic!("expected Condition, got {other:?}"),
        }
        let back = serde_json::to_string(&f).expect("serialize");
        assert_eq!(back, json);
    }

    /// Oracle: RFC 8620 §5.5 example — OR of two keyword conditions applied to Email.
    /// Adapted from the Todo/query example in RFC 8620 §5.5.
    #[test]
    fn filter_operator_or_two_keywords() {
        let json =
            r#"{"operator":"OR","conditions":[{"hasKeyword":"music"},{"hasKeyword":"video"}]}"#;
        let f: EmailFilter = serde_json::from_str(json).expect("must parse");
        match &f {
            Filter::Operator(op) => {
                assert_eq!(op.operator, Operator::Or);
                assert_eq!(op.conditions.len(), 2);
                match &op.conditions[0] {
                    Filter::Condition(c) => {
                        assert_eq!(c.has_keyword.as_deref(), Some("music"))
                    }
                    other => panic!("expected Condition, got {other:?}"),
                }
                match &op.conditions[1] {
                    Filter::Condition(c) => {
                        assert_eq!(c.has_keyword.as_deref(), Some("video"))
                    }
                    other => panic!("expected Condition, got {other:?}"),
                }
            }
            other => panic!("expected Operator, got {other:?}"),
        }
        let back = serde_json::to_string(&f).expect("serialize");
        assert_eq!(back, json);
    }

    /// Oracle: nested AND(OR(...)) structure roundtrips.
    #[test]
    fn nested_and_or_roundtrip() {
        let filter = EmailFilter::Operator(FilterOperator::new(
            Operator::And,
            vec![
                EmailFilter::Condition(EmailFilterCondition {
                    in_mailbox: Some(Id::from("inbox-id")),
                    ..Default::default()
                }),
                EmailFilter::Operator(FilterOperator::new(
                    Operator::Or,
                    vec![
                        EmailFilter::Condition(EmailFilterCondition {
                            has_keyword: Some(Keyword::from("$flagged")),
                            ..Default::default()
                        }),
                        EmailFilter::Condition(EmailFilterCondition {
                            has_keyword: Some(Keyword::from("$answered")),
                            ..Default::default()
                        }),
                    ],
                )),
            ],
        ));
        let json = serde_json::to_string(&filter).expect("serialize");
        let back: EmailFilter = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(filter, back);
    }

    /// Oracle: empty EmailFilterCondition serializes to `{}` and omits all fields.
    #[test]
    fn empty_condition_serializes_to_empty_object() {
        let c = EmailFilterCondition::default();
        let json = serde_json::to_string(&c).expect("serialize");
        assert_eq!(json, "{}");
    }

    /// Oracle: all scalar fields roundtrip correctly.
    #[test]
    fn all_scalar_fields_roundtrip() {
        let c = EmailFilterCondition {
            in_mailbox: Some(Id::from("mb1")),
            min_size: Some(1024),
            max_size: Some(65536),
            all_in_thread_have_keyword: Some(Keyword::from("$seen")),
            some_in_thread_have_keyword: Some(Keyword::from("$flagged")),
            none_in_thread_have_keyword: Some(Keyword::from("$draft")),
            has_keyword: Some(Keyword::from("$answered")),
            not_keyword: Some(Keyword::from("$junk")),
            has_attachment: Some(true),
            text: Some("hello".to_owned()),
            from: Some("alice@example.com".to_owned()),
            to: Some("bob@example.com".to_owned()),
            cc: Some("carol@example.com".to_owned()),
            bcc: Some("dave@example.com".to_owned()),
            subject: Some("Meeting".to_owned()),
            body: Some("agenda".to_owned()),
            ..Default::default()
        };
        let json = serde_json::to_string(&c).expect("serialize");
        let back: EmailFilterCondition = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(c, back);
    }

    /// Oracle: `header` with one element (field name only) is accepted.
    #[test]
    fn header_one_element_accepted() {
        let json = r#"{"header":["X-Spam-Status"]}"#;
        let c: EmailFilterCondition = serde_json::from_str(json).expect("must parse");
        let h = c.header.as_ref().expect("header must be present");
        assert_eq!(h.len(), 1);
        assert_eq!(h[0], "X-Spam-Status");
    }

    /// Oracle: `header` with two elements (field name + value) is accepted.
    #[test]
    fn header_two_elements_accepted() {
        let json = r#"{"header":["X-Spam-Status","Yes"]}"#;
        let c: EmailFilterCondition = serde_json::from_str(json).expect("must parse");
        let h = c.header.as_ref().expect("header must be present");
        assert_eq!(h.len(), 2);
        assert_eq!(h[0], "X-Spam-Status");
        assert_eq!(h[1], "Yes");
    }

    /// Oracle: RFC 8621 §4.4.1 — `header` with zero elements is a protocol error.
    #[test]
    fn header_zero_elements_rejected() {
        let json = r#"{"header":[]}"#;
        let err = serde_json::from_str::<EmailFilterCondition>(json)
            .expect_err("0-element header must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("header must have 1 or 2 elements"),
            "unexpected error: {msg}"
        );
    }

    /// Oracle: RFC 8621 §4.4.1 — `header` with three elements is a protocol error.
    #[test]
    fn header_three_elements_rejected() {
        let json = r#"{"header":["X-Foo","bar","extra"]}"#;
        let err = serde_json::from_str::<EmailFilterCondition>(json)
            .expect_err("3-element header must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("header must have 1 or 2 elements"),
            "unexpected error: {msg}"
        );
    }

    /// Oracle: `before` and `after` fields use UTCDate wire format (RFC 3339 UTC).
    #[test]
    fn date_fields_roundtrip() {
        let json = r#"{"before":"2024-01-15T12:00:00Z","after":"2024-01-01T00:00:00Z"}"#;
        let c: EmailFilterCondition = serde_json::from_str(json).expect("must parse");
        let back = serde_json::to_string(&c).expect("serialize");
        assert_eq!(back, json);
    }

    /// Oracle: `inMailboxOtherThan` is a list of Ids.
    #[test]
    fn in_mailbox_other_than_roundtrip() {
        let json = r#"{"inMailboxOtherThan":["trash-id","spam-id"]}"#;
        let c: EmailFilterCondition = serde_json::from_str(json).expect("must parse");
        let ids: Vec<&str> = c
            .in_mailbox_other_than
            .as_ref()
            .unwrap()
            .iter()
            .map(|id| id.as_ref())
            .collect();
        assert_eq!(ids, ["trash-id", "spam-id"]);
        let back = serde_json::to_string(&c).expect("serialize");
        assert_eq!(back, json);
    }

    // ---------------------------------------------------------------------------
    // MailboxComparator / EmailSubmissionComparator tests
    // ---------------------------------------------------------------------------

    /// Oracle: the RFC 8621 §2.3 sort-property names "sortOrder" and
    /// "name", and the RFC 8620 §5.5 `isAscending` default of true.
    #[test]
    fn mailbox_comparator_rfc8621_properties() {
        let c: MailboxComparator =
            serde_json::from_str(r#"{"property":"sortOrder"}"#).expect("must parse");
        assert_eq!(c.property, MailboxComparatorProperty::SortOrder);
        assert!(c.is_ascending);
        let c: MailboxComparator =
            serde_json::from_str(r#"{"property":"name","isAscending":false}"#).expect("must parse");
        assert_eq!(c.property, MailboxComparatorProperty::Name);
        assert!(!c.is_ascending);
        assert_eq!(
            serde_json::to_value(&c).unwrap(),
            serde_json::json!({"property":"name","isAscending":false})
        );
    }

    /// Oracle: hand-written JSON; an unknown property survives as `Other`
    /// and re-serializes byte-for-byte (AGENTS.md comparator rule).
    #[test]
    fn mailbox_comparator_unknown_property_round_trips() {
        let json = serde_json::json!({"property":"totalEmails"});
        let c: MailboxComparator = serde_json::from_value(json.clone()).expect("must parse");
        assert_eq!(
            c.property,
            MailboxComparatorProperty::Other("totalEmails".to_owned())
        );
        assert_eq!(serde_json::to_value(&c).unwrap(), json);
    }

    /// Oracle: the RFC 8621 §7.3 sort-property names "emailId",
    /// "threadId" and "sentAt".
    #[test]
    fn email_submission_comparator_rfc8621_properties() {
        for (wire, want) in [
            ("emailId", EmailSubmissionComparatorProperty::EmailId),
            ("threadId", EmailSubmissionComparatorProperty::ThreadId),
            ("sentAt", EmailSubmissionComparatorProperty::SentAt),
        ] {
            let json = serde_json::json!({ "property": wire });
            let c: EmailSubmissionComparator =
                serde_json::from_value(json.clone()).expect("must parse");
            assert_eq!(c.property, want);
            assert!(c.is_ascending);
            assert_eq!(serde_json::to_value(&c).unwrap(), json);
        }
        let c: EmailSubmissionComparator =
            serde_json::from_str(r#"{"property":"undoStatus"}"#).expect("must parse");
        assert_eq!(
            c.property,
            EmailSubmissionComparatorProperty::Other("undoStatus".to_owned())
        );
    }

    // ---------------------------------------------------------------------------
    // EmailComparator tests
    // ---------------------------------------------------------------------------

    /// Oracle: RFC 8621 §4.4.2 example — three-comparator sort array.
    /// Wire format taken verbatim from the RFC 8621 §4.4.2 example.
    #[test]
    fn comparator_example_from_rfc() {
        // Three comparators from RFC 8621 §4.4.2.
        // First: keyword sort (isAscending=false, keyword present).
        let json0 =
            r#"{"property":"someInThreadHaveKeyword","keyword":"$flagged","isAscending":false}"#;
        let c0: EmailComparator = serde_json::from_str(json0).expect("must parse");
        assert_eq!(c0.property, ComparatorProperty::SomeInThreadHaveKeyword);
        assert_eq!(c0.keyword.as_deref(), Some("$flagged"));
        assert!(!c0.is_ascending);

        // Second: subject sort with collation, isAscending defaults to true (omitted).
        let json1 = r#"{"property":"subject","collation":"i;ascii-casemap"}"#;
        let c1: EmailComparator = serde_json::from_str(json1).expect("must parse");
        assert_eq!(c1.property, ComparatorProperty::Subject);
        assert_eq!(c1.collation.as_deref(), Some("i;ascii-casemap"));
        assert!(c1.is_ascending);
        // isAscending is true (default) and must be omitted on serialization.
        let back1 = serde_json::to_string(&c1).expect("serialize");
        assert_eq!(back1, json1);

        // Third: receivedAt descending.
        let json2 = r#"{"property":"receivedAt","isAscending":false}"#;
        let c2: EmailComparator = serde_json::from_str(json2).expect("must parse");
        assert_eq!(c2.property, ComparatorProperty::ReceivedAt);
        assert!(!c2.is_ascending);
        let back2 = serde_json::to_string(&c2).expect("serialize");
        assert_eq!(back2, json2);
    }

    /// Oracle: isAscending defaults to true when absent; omitted from serialization
    /// when true (RFC 8620 §5.5 default).
    #[test]
    fn comparator_is_ascending_default_and_skip() {
        let json = r#"{"property":"receivedAt"}"#;
        let c: EmailComparator = serde_json::from_str(json).expect("must parse");
        assert!(c.is_ascending, "default must be true");
        let back = serde_json::to_string(&c).expect("serialize");
        assert_eq!(back, json, "isAscending:true must be omitted");
    }

    // ---------------------------------------------------------------------------
    // Filter ambiguity tests (JMAP-amk.2)
    // ---------------------------------------------------------------------------

    /// Oracle: RFC 8620 §5.5 — "unsupportedFilter: The "filter" is
    /// syntactically valid, but the server cannot process it"; RFC 8621
    /// §4.4.1 lists the Email FilterCondition properties, and
    /// `unknownField` / `in_mailbox` are not among them. An unknown or
    /// snake_case-misspelt property, at the top level or nested under an
    /// operator, must fail the decode rather than become an all-None
    /// condition that matches every Email.
    #[test]
    fn filter_unknown_fields_are_rejected() {
        for raw in [
            r#"{"unknownField":"value"}"#,
            r#"{"in_mailbox":"inbox"}"#,
            r#"{"inMailbox":"inbox","unknownField":1}"#,
            r#"{"operator":"AND","conditions":[{"operator":"NOT","conditions":[{"in_mailbox":"x"}]}]}"#,
            r#"{"operator":"AND","conditions":[],"inMailbox":"x"}"#,
        ] {
            assert!(
                serde_json::from_str::<EmailFilter>(raw).is_err(),
                "{raw} must be rejected"
            );
        }
        // Negative control: every RFC 8621 §4.4.1 property decodes.
        let all_known = r#"{"inMailbox":"m1","inMailboxOtherThan":["m2"],"before":"2024-01-01T00:00:00Z","after":"2023-01-01T00:00:00Z","minSize":1,"maxSize":2,"allInThreadHaveKeyword":"$seen","someInThreadHaveKeyword":"$seen","noneInThreadHaveKeyword":"$seen","hasKeyword":"$seen","notKeyword":"$draft","hasAttachment":true,"text":"t","from":"f","to":"t","cc":"c","bcc":"b","subject":"s","body":"b","header":["X-A","v"]}"#;
        let f: EmailFilter = serde_json::from_str(all_known).expect("all §4.4.1 properties decode");
        assert!(matches!(f, Filter::Condition(_)));
    }

    /// Oracle: an empty JSON object `{}` produces an empty condition (all None),
    /// which matches every Email per RFC 8621 §4.4.1.
    #[test]
    fn filter_empty_object_becomes_empty_condition() {
        let json = "{}";
        let f: EmailFilter = serde_json::from_str(json).expect("must parse");
        assert!(
            matches!(&f, Filter::Condition(c) if c == &EmailFilterCondition::default()),
            "empty object must yield all-None Condition"
        );
    }

    /// Oracle: EmailComparator::new produces expected defaults and correct JSON.
    /// RFC 8620 §5.5 — isAscending defaults to true and is omitted when true.
    #[test]
    fn comparator_new_constructor() {
        let cmp = EmailComparator::new(ComparatorProperty::ReceivedAt);
        assert_eq!(cmp.property, ComparatorProperty::ReceivedAt);
        assert!(cmp.is_ascending);
        assert!(cmp.collation.is_none());
        assert!(cmp.keyword.is_none());
        // isAscending:true is the default and must be omitted on the wire.
        let json = serde_json::to_string(&cmp).expect("serialize");
        assert_eq!(json, r#"{"property":"receivedAt"}"#);
    }

    /// Oracle: EmailComparator::new with field mutation produces correct JSON.
    /// RFC 8621 §4.4.2 — keyword-based comparator must include keyword field.
    #[test]
    fn comparator_new_with_mutation() {
        let mut cmp = EmailComparator::new(ComparatorProperty::HasKeyword);
        cmp.keyword = Some(Keyword::from("$flagged"));
        cmp.is_ascending = false;
        let json = serde_json::to_string(&cmp).expect("serialize");
        assert_eq!(
            json,
            r#"{"property":"hasKeyword","isAscending":false,"keyword":"$flagged"}"#
        );
    }

    /// Oracle: the `filter` of the draft-ietf-jmap-metadata-02 §6.7 example
    /// request, copied from the draft (-04 §3.6 still defines all three
    /// leaf conditions). The metadata leaves decode inside the `AND` tree
    /// and serialize back unchanged.
    #[test]
    fn metadata_conditions_survive_operator_tree() {
        let wire = serde_json::json!({
            "operator": "AND",
            "conditions": [
                { "inMailbox": "MB-inbox" },
                { "privateMetadataExists": "acme.example.com/memo" },
                {
                    "privateMetadataTextContains": {
                        "path":  "acme.example.com/memo",
                        "value": "follow up"
                    }
                }
            ]
        });
        let filter: EmailFilter = serde_json::from_value(wire.clone()).expect("decode");
        let Filter::Operator(op) = &filter else {
            panic!("expected an operator, got {filter:?}");
        };
        let leaves: Vec<&EmailFilterCondition> = op
            .conditions
            .iter()
            .map(|f| match f {
                Filter::Condition(c) => c,
                other => panic!("expected a condition, got {other:?}"),
            })
            .collect();
        assert!(!leaves[0].has_metadata_condition());
        assert_eq!(
            leaves[1].private_metadata_exists.as_deref(),
            Some("acme.example.com/memo")
        );
        assert!(leaves[1].has_metadata_condition());
        assert_eq!(
            leaves[2].private_metadata_text_contains,
            Some(MetadataTextMatch::new("acme.example.com/memo", "follow up"))
        );
        assert_eq!(serde_json::to_value(&filter).expect("encode"), wire);
    }

    /// Oracle: the six wire names of -04 §3.6 ("metadataExists",
    /// "privateMetadataExists", "metadataTextContains",
    /// "privateMetadataTextContains", "metadataTextEquals",
    /// "privateMetadataTextEquals") each decode; a misspelt one is still
    /// rejected by `deny_unknown_fields`.
    #[test]
    fn metadata_condition_names_decode_and_typos_reject() {
        let m = serde_json::json!({"path": "ns/k", "value": "v"});
        for (name, value) in [
            ("metadataExists", serde_json::json!("ns")),
            ("privateMetadataExists", serde_json::json!("ns")),
            ("metadataTextContains", m.clone()),
            ("privateMetadataTextContains", m.clone()),
            ("metadataTextEquals", m.clone()),
            ("privateMetadataTextEquals", m.clone()),
        ] {
            let c: EmailFilterCondition =
                serde_json::from_value(serde_json::json!({ name: value })).expect(name);
            assert!(c.has_metadata_condition(), "{name}");
        }
        assert!(
            serde_json::from_value::<EmailFilterCondition>(serde_json::json!({
                "metadataExist": "ns"
            }))
            .is_err()
        );
    }
}