This commit is contained in:
Daniel Eggert authored and GitHub committed 2026-07-18 20:57:21 +02:00
1 parent 1057994e93
commit e67fc89e63
10 files changed
+893 -8

No files matched your search

+9 -1
View File
@@ -100,7 +100,15 @@ extension Flag {
/// `\Flagged` - The message has been marked for attention.
///
/// Defined in [RFC 3501](https://datatracker.ietf.org/doc/html/rfc3501).
/// Defined in [RFC 9051](https://www.rfc-editor.org/rfc/rfc9051.html).
///
/// A flagged message can additionally carry one of seven colors, encoded as
/// a 3-bit mask via the ``Keyword/colorBit0``, ``Keyword/colorBit1``, and
/// ``Keyword/colorBit2`` keywords ([RFC 9979](https://www.rfc-editor.org/rfc/rfc9979.html)).
/// Prefer the higher-level ``FlaggedState`` API for reading and updating a
/// message's flagged mark and its color.
///
/// - SeeAlso: ``FlaggedState``
public static let flagged = Self("\\Flagged")
/// `\Deleted` - The message has been deleted.
@@ -152,23 +152,166 @@ extension Flag.Keyword {
/// A non-standard keyword for marking non-spam messages. Prefer ``notJunk`` for standard usage.
public static let unregistered_notJunk = Self(unchecked: "NotJunk")
/// The `$MailFlagBit0` keyword for color marking (bit 0).
/// The `$MailFlagBit0` keyword, bit 0 of a flagged message's color.
///
/// A color-flag keyword for messages, where different bits represent different colors.
/// Together with ``colorBit1`` and ``colorBit2``, this keyword forms a 3-bit
/// mask that gives a `\Flagged` message one of seven colors. Prefer the
/// higher-level ``FlaggedState`` API for reading and updating a message's flagged
/// state and color.
///
/// - SeeAlso: [RFC 9979 Section 3](https://www.rfc-editor.org/rfc/rfc9979.html#section-3)
/// - SeeAlso: ``FlaggedState``
public static let colorBit0 = Self(unchecked: "$MailFlagBit0")
/// The `$MailFlagBit1` keyword for color marking (bit 1).
/// The `$MailFlagBit1` keyword, bit 1 of a flagged message's color.
///
/// A color-flag keyword for messages.
/// Together with ``colorBit0`` and ``colorBit2``, this keyword forms a 3-bit
/// mask that gives a `\Flagged` message one of seven colors. Prefer the
/// higher-level ``FlaggedState`` API for reading and updating a message's flagged
/// state and color.
///
/// - SeeAlso: [RFC 9979 Section 3](https://www.rfc-editor.org/rfc/rfc9979.html#section-3)
/// - SeeAlso: ``FlaggedState``
public static let colorBit1 = Self(unchecked: "$MailFlagBit1")
/// The `$MailFlagBit2` keyword for color marking (bit 2).
/// The `$MailFlagBit2` keyword, bit 2 of a flagged message's color.
///
/// A color-flag keyword for messages.
/// Together with ``colorBit0`` and ``colorBit1``, this keyword forms a 3-bit
/// mask that gives a `\Flagged` message one of seven colors. Prefer the
/// higher-level ``FlaggedState`` API for reading and updating a message's flagged
/// state and color.
///
/// - SeeAlso: [RFC 9979 Section 3](https://www.rfc-editor.org/rfc/rfc9979.html#section-3)
/// - SeeAlso: ``FlaggedState``
public static let colorBit2 = Self(unchecked: "$MailFlagBit2")
/// The `$MDNSent` keyword, indicating a Message Disposition Notification has been sent for this message.
public static let mdnSent = Self(unchecked: "$MDNSent")
// MARK: RFC 9979
/// The `$autosent` keyword, marking a message that was generated and sent
/// automatically on the user's behalf, such as a vacation auto-reply.
///
/// Advisory; set by the server on delivery of the user's copy.
///
/// - SeeAlso: [RFC 9979 Section 7.1](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.1)
public static let autoSent = Self(unchecked: "$autosent")
/// The `$canunsubscribe` keyword, indicating the message carries a
/// [RFC 8058](https://datatracker.ietf.org/doc/html/rfc8058)-compliant
/// `List-Unsubscribe` header that a client can use for one-click unsubscribe.
///
/// Advisory; set by the server on delivery after its own reputation checks.
///
/// - SeeAlso: [RFC 9979 Section 6.1](https://www.rfc-editor.org/rfc/rfc9979.html#section-6.1)
public static let canUnsubscribe = Self(unchecked: "$canunsubscribe")
/// The `$followed` keyword, indicating the user is particularly interested in
/// future messages in the thread.
///
/// Set and cleared by the client. Mutually exclusive with ``muted``: if both
/// appear on a thread, the thread is treated as followed.
///
/// - SeeAlso: [RFC 9979 Section 7.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.2)
public static let followed = Self(unchecked: "$followed")
/// The `$hasattachment` keyword, indicating the message has one or more attachments.
///
/// Advisory; set by the server on delivery, or by the client when neither
/// ``hasAttachment`` nor ``hasNoAttachment`` is set. Mutually exclusive with
/// ``hasNoAttachment``.
///
/// - SeeAlso: [RFC 9979 Section 4.1](https://www.rfc-editor.org/rfc/rfc9979.html#section-4.1)
public static let hasAttachment = Self(unchecked: "$hasattachment")
/// The `$hasmemo` keyword, applied to a message that has an associated memo
/// (a message bearing the ``memo`` keyword) in the same thread.
///
/// Advisory; set and cleared by the client. Mutually exclusive with ``memo``.
///
/// - SeeAlso: [RFC 9979 Section 5.1](https://www.rfc-editor.org/rfc/rfc9979.html#section-5.1)
public static let hasMemo = Self(unchecked: "$hasmemo")
/// The `$hasnoattachment` keyword, explicitly indicating the message has no
/// attachments (as opposed to not yet having been analyzed).
///
/// Advisory; set by the server on delivery, or by the client when neither
/// ``hasAttachment`` nor ``hasNoAttachment`` is set. Mutually exclusive with
/// ``hasAttachment``.
///
/// - SeeAlso: [RFC 9979 Section 4.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-4.2)
public static let hasNoAttachment = Self(unchecked: "$hasnoattachment")
/// The `$imported` keyword, marking a message that was imported from another
/// system rather than received through normal mail delivery.
///
/// Advisory; set by the server during import.
///
/// - SeeAlso: [RFC 9979 Section 7.3](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.3)
public static let imported = Self(unchecked: "$imported")
/// The `$istrusted` keyword, indicating the server verified the sender's
/// identity with a high degree of confidence.
///
/// Advisory; set by the server on delivery. Servers must apply it with care,
/// and never solely on the basis of SPF, DKIM, or DMARC.
///
/// - SeeAlso: [RFC 9979 Section 7.4](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.4)
public static let isTrusted = Self(unchecked: "$istrusted")
/// The `$maskedemail` keyword, indicating the message arrived via a masked
/// email alias created to protect the user's primary address.
///
/// Advisory; set by the server on delivery.
///
/// - SeeAlso: [RFC 9979 Section 7.5](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.5)
public static let maskedEmail = Self(unchecked: "$maskedemail")
/// The `$memo` keyword, identifying a message as a note-to-self regarding
/// another message in the same thread.
///
/// Set and cleared by the client. Mutually exclusive with ``hasMemo``, which
/// is applied to the annotated message.
///
/// - SeeAlso: [RFC 9979 Section 5.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-5.2)
public static let memo = Self(unchecked: "$memo")
/// The `$muted` keyword, indicating the user is not interested in future
/// messages in the thread.
///
/// Set and cleared by the client. Mutually exclusive with ``followed``: if
/// both appear on a thread, the thread is treated as followed.
///
/// - SeeAlso: [RFC 9979 Section 7.6](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.6)
public static let muted = Self(unchecked: "$muted")
/// The `$new` keyword, indicating the message should be emphasized as if it
/// were new — typically a snoozed message that has just returned to the inbox.
///
/// Advisory; set by the server. Clients clear it once the user interacts with
/// the message.
///
/// - SeeAlso: [RFC 9979 Section 7.7](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.7)
public static let new = Self(unchecked: "$new")
/// The `$notify` keyword, indicating the client should present a notification
/// for the message.
///
/// Set by the server on delivery, or by client filtering rules. Clients may
/// clear it once the user interacts with the message.
///
/// - SeeAlso: [RFC 9979 Section 7.8](https://www.rfc-editor.org/rfc/rfc9979.html#section-7.8)
public static let notify = Self(unchecked: "$notify")
/// The `$unsubscribed` keyword, recording that the user has attempted to
/// unsubscribe from the message's mailing list.
///
/// Set by the client after a one-click unsubscribe attempt. Must not be set if
/// the attempt definitely failed.
///
/// - SeeAlso: [RFC 9979 Section 6.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-6.2)
public static let unsubscribed = Self(unchecked: "$unsubscribed")
}
// MARK: - String Literal
@@ -0,0 +1,356 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// The flagged state of a message: either ``unflagged``, or ``flagged(_:)`` with
/// a ``Color``.
///
/// IMAP's `\Flagged` system flag ([RFC 9051](https://www.rfc-editor.org/rfc/rfc9051.html))
/// marks a message as needing attention.
/// [RFC 9979](https://www.rfc-editor.org/rfc/rfc9979.html) extends this: a
/// flagged message's mark may be shown in one of seven colors, encoded as a
/// 3-bit mask across the ``Flag/Keyword/colorBit0``, ``Flag/Keyword/colorBit1``,
/// and ``Flag/Keyword/colorBit2`` keywords (see ``Color``).
///
/// `FlaggedState` models the message-level concept that ``Flag`` does not: a
/// single ``Flag`` is one keyword on the wire, whereas a `FlaggedState` value
/// combines the `\Flagged` mark and its color into the one thing a user actually
/// sets.
///
/// Decode a message's current state with ``init(flags:mapUnassignedTo:)``, and
/// turn a desired state into the flags to store with ``flagChanges``:
///
/// ```swift
/// // What state is the message in?
/// let state = FlaggedState(flags: message.flags) // .unflagged, or .flagged(.red), ...
///
/// // Flag a message green, or remove its mark entirely:
/// let toGreen = FlaggedState.flagged(.green).flagChanges
/// let toClear = FlaggedState.unflagged.flagChanges
/// ```
///
/// A color is only meaningful while `\Flagged` is set, and this type keeps the
/// two consistent: ``init(flags:mapUnassignedTo:)`` reports an unflagged message
/// as ``unflagged`` regardless of any color bits present, and ``flagChanges`` never
/// sets color bits without also setting `\Flagged`. The invalid "colored but not
/// flagged" state therefore can't arise through this API.
///
/// Through this API a flagged message *always* carries a color: the bit pattern
/// with no color bits set is ``Color/red``, so ``Color/red`` is equivalent to
/// "flagged, but no color keywords present" — including messages flagged by
/// clients that predate or ignore RFC 9979. A client that does not want to deal
/// with colors at all can simply set ``Flag/flagged`` directly instead of using
/// `FlaggedState`.
///
/// RFC 9979 leaves one bit combination (`111`) unassigned. `FlaggedState` folds
/// it into a real color so that callers only ever deal with the seven colors.
/// The rare client that needs to preserve those bits verbatim across a decode /
/// re-encode should use ``RawFlaggedState`` instead.
///
/// - SeeAlso: ``Flag``
/// - SeeAlso: ``RawFlaggedState``
/// - SeeAlso: [RFC 9979 Section 3](https://www.rfc-editor.org/rfc/rfc9979.html#section-3)
public enum FlaggedState: Hashable, Sendable {
/// The message is not flagged, and therefore has no color.
case unflagged
/// The message is flagged, and its mark has the given ``Color``.
case flagged(Color)
/// One of the seven flag colors defined in
/// [RFC 9979 Section 3](https://www.rfc-editor.org/rfc/rfc9979.html#section-3).
///
/// Each color is a 3-bit mask across the ``Flag/Keyword/colorBit0``,
/// ``Flag/Keyword/colorBit1``, and ``Flag/Keyword/colorBit2`` keywords:
///
/// | Color | bit 0 | bit 1 | bit 2 |
/// | ---------- | ----- | ----- | ----- |
/// | ``red`` | 0 | 0 | 0 |
/// | ``orange`` | 1 | 0 | 0 |
/// | ``yellow`` | 0 | 1 | 0 |
/// | ``green`` | 1 | 1 | 0 |
/// | ``blue`` | 0 | 0 | 1 |
/// | ``purple`` | 1 | 0 | 1 |
/// | ``gray`` | 0 | 1 | 1 |
///
/// RFC 9979 assigns no color to the eighth combination, `111`. It does not
/// appear here: ``FlaggedState`` and its ``FlaggedState/init(flags:mapUnassignedTo:)``
/// fold it into a real color. To preserve that pattern verbatim, use
/// ``RawFlaggedState`` and its ``RawFlaggedState/flaggedUnassigned`` case.
public enum Color: Sendable, Hashable, CaseIterable {
/// No color bits set.
case red
/// ``Flag/Keyword/colorBit0`` set.
case orange
/// ``Flag/Keyword/colorBit1`` set.
case yellow
/// ``Flag/Keyword/colorBit0`` and ``Flag/Keyword/colorBit1`` set.
case green
/// ``Flag/Keyword/colorBit2`` set.
case blue
/// ``Flag/Keyword/colorBit0`` and ``Flag/Keyword/colorBit2`` set.
case purple
/// ``Flag/Keyword/colorBit1`` and ``Flag/Keyword/colorBit2`` set.
case gray
}
/// The IMAP flags that must be set and cleared on a message to put it into a
/// given ``FlaggedState`` (or ``RawFlaggedState``).
///
/// Obtain an `Update` from ``FlaggedState/flagChanges`` or ``RawFlaggedState/flagChanges``.
///
/// Apply an `Update` with two `STORE` commands. Issue `STORE -FLAGS
/// (flagsToClear)` *before* `STORE +FLAGS (flagsToSet)`: clearing first means
/// the message transits through a valid intermediate color rather than the
/// unassigned `111` combination. (The two commands are not atomic, so another
/// client may still observe the intermediate state.) Skip either command when
/// its set is empty — for example, ``FlaggedState/unflagged``
/// produces an empty `flagsToSet` — since a `STORE` with an empty flag list is
/// a wasted round-trip. Only the ``FlaggedState/unflagged`` and
/// ``RawFlaggedState/unflagged`` states ever produce an empty side; every
/// `flagged` state has a non-empty `flagsToSet` (it always includes `\Flagged`)
/// and, except ``RawFlaggedState/flaggedUnassigned``, a non-empty `flagsToClear`.
///
/// Two separate `+FLAGS`/`-FLAGS` commands are used, rather than a single
/// `STORE FLAGS` that replaces the whole flag list atomically, precisely so
/// that unrelated keywords on the message (such as `\Seen` or `$Junk`) are
/// preserved.
///
/// The two operations together leave the message in the requested state
/// regardless of its prior flags, so there is no need to read the message's
/// current flags first.
public struct Update: Hashable, Sendable {
/// The flags that must be present (`STORE +FLAGS`).
public var flagsToSet: Set<Flag>
/// The flags that must be absent (`STORE -FLAGS`).
public var flagsToClear: Set<Flag>
/// Creates a new `Update`.
/// - parameter flagsToSet: The flags that must be present.
/// - parameter flagsToClear: The flags that must be absent.
public init(flagsToSet: Set<Flag>, flagsToClear: Set<Flag>) {
self.flagsToSet = flagsToSet
self.flagsToClear = flagsToClear
}
}
/// The ``Color`` of the mark when the message is ``flagged(_:)``, or `nil`
/// when it is ``unflagged``.
public var color: Color? {
switch self {
case .unflagged: nil
case .flagged(let color): color
}
}
/// The flags to set and clear to put a message into this state.
///
/// For a ``flagged(_:)`` state the returned ``Update`` always sets `\Flagged`
/// alongside the color bits and clears the color bits that don't belong to
/// the color. Setting `\Flagged` together with the color bits satisfies
/// [RFC 9979 Section 3.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-3.2),
/// which requires that color flags never be set unless `\Flagged` is also
/// set, so applying the update can never leave a message with color bits but
/// no `\Flagged` flag. For ``unflagged`` it clears `\Flagged` and all three
/// color bits — also required by Section 3.2 — and its ``Update/flagsToSet``
/// is empty.
///
/// ### Example
///
/// ```swift
/// let changes = FlaggedState.flagged(.green).flagChanges
/// // changes.flagsToSet == [\Flagged, $MailFlagBit0, $MailFlagBit1]
/// // changes.flagsToClear == [$MailFlagBit2]
/// ```
public var flagChanges: Update {
switch self {
case .unflagged: .unflagged
case .flagged(let color): .flagged(withColorBits: color.colorBits)
}
}
/// Reads a message's flagged state from its flags.
///
/// Returns ``unflagged`` when ``Flag/flagged`` is absent — even if color bits
/// are present — since a color is only meaningful on a flagged message.
/// Otherwise returns ``flagged(_:)`` with the decoded ``Color``.
///
/// RFC 9979 leaves the `111` bit combination unassigned and does not define
/// how it should be presented. This initializer reports it as
/// `mapUnassignedTo` — defaulting to ``Color/red``, but you may pass any
/// color — so the result is always one of the seven colors. The red default
/// is the library's choice, not an RFC requirement. Use ``RawFlaggedState``
/// if you need to tell the `111` pattern apart from red and preserve it
/// across a re-encode.
///
/// - parameter flags: The message's flags. Flag comparison is
/// case-insensitive.
/// - parameter mapUnassignedTo: The color to report for the RFC-unassigned
/// `111` bit combination. Defaults to ``Color/red``.
public init(flags: some Sequence<Flag>, mapUnassignedTo: Color = .red) {
self = FlaggedState(RawFlaggedState(flags: flags), mapUnassignedTo: mapUnassignedTo)
}
/// Collapses a ``RawFlaggedState`` to a `FlaggedState`, mapping its
/// ``RawFlaggedState/flaggedUnassigned`` case to a real ``Color``.
///
/// ``RawFlaggedState/unflagged`` and ``RawFlaggedState/flagged(_:)`` carry
/// over unchanged; ``RawFlaggedState/flaggedUnassigned`` becomes
/// ``flagged(_:)`` with `mapUnassignedTo`, which defaults to ``Color/red``
/// (see ``init(flags:mapUnassignedTo:)`` for why red is the default).
///
/// This is the lossy inverse of ``RawFlaggedState/init(_:)``.
///
/// - parameter raw: The state to collapse.
/// - parameter mapUnassignedTo: The color to map
/// ``RawFlaggedState/flaggedUnassigned`` to. Defaults to ``Color/red``.
public init(_ raw: RawFlaggedState, mapUnassignedTo: Color = .red) {
switch raw {
case .unflagged: self = .unflagged
case .flagged(let color): self = .flagged(color)
case .flaggedUnassigned: self = .flagged(mapUnassignedTo)
}
}
}
/// The flagged state of a message, preserving RFC 9979's unassigned `111` bit
/// pattern verbatim.
///
/// Most library users should use ``FlaggedState`` instead.
///
/// This is a lossless variant of ``FlaggedState`` for the rare client that must
/// round-trip a message's flags without altering them. Where ``FlaggedState``
/// folds the RFC-unassigned `111` combination into a real ``FlaggedState/Color``,
/// `RawFlaggedState` keeps it as the distinct ``flaggedUnassigned`` case so that
/// decoding and re-encoding a message leaves its stored bits unchanged.
///
/// **Prefer ``FlaggedState``.** Reach for `RawFlaggedState` only when faithful
/// round-tripping matters; for everything else — presentation, setting a color,
/// clearing the mark — the seven-color ``FlaggedState`` is simpler and sufficient.
/// Collapse it to a ``FlaggedState`` at any time with
/// ``FlaggedState/init(_:mapUnassignedTo:)``.
///
/// - SeeAlso: ``FlaggedState``
/// - SeeAlso: [RFC 9979 Section 3](https://www.rfc-editor.org/rfc/rfc9979.html#section-3)
public enum RawFlaggedState: Hashable, Sendable {
/// The message is not flagged, and therefore has no color.
case unflagged
/// The message is flagged, and its mark has the given ``FlaggedState/Color``.
case flagged(FlaggedState.Color)
/// The message is flagged and carries the RFC-unassigned `111` bit pattern
/// (all three of ``Flag/Keyword/colorBit0``, ``Flag/Keyword/colorBit1``, and
/// ``Flag/Keyword/colorBit2``).
///
/// RFC 9979 assigns no color to this combination. The RFC does not define
/// its appearance; map it to a real color for presentation with
/// ``FlaggedState/init(_:mapUnassignedTo:)``
/// (which defaults to ``FlaggedState/Color/red``). Its ``flagChanges`` writes the
/// `111` pattern back out verbatim.
case flaggedUnassigned
/// The flags to set and clear to put a message into this state.
///
/// Behaves like ``FlaggedState/flagChanges``, additionally handling
/// ``flaggedUnassigned`` by setting `\Flagged` plus all three color bits and
/// clearing nothing — writing the RFC-unassigned `111` pattern back verbatim.
public var flagChanges: FlaggedState.Update {
switch self {
case .unflagged: .unflagged
case .flagged(let color): .flagged(withColorBits: color.colorBits)
case .flaggedUnassigned: .flagged(withColorBits: FlaggedState.Color.allColorBits)
}
}
/// Reads a message's flagged state from its flags, preserving the unassigned
/// `111` pattern.
///
/// Returns ``unflagged`` when ``Flag/flagged`` is absent (even if color bits
/// are present), ``flaggedUnassigned`` when all three color bits are set, and
/// otherwise ``flagged(_:)`` with the decoded color.
///
/// - parameter flags: The message's flags. Flag comparison is
/// case-insensitive.
public init(flags: some Sequence<Flag>) {
let flags = Set(flags)
guard flags.contains(.flagged) else {
self = .unflagged
return
}
let bit0 = flags.contains(.keyword(.colorBit0))
let bit1 = flags.contains(.keyword(.colorBit1))
let bit2 = flags.contains(.keyword(.colorBit2))
switch (bit0, bit1, bit2) {
case (false, false, false): self = .flagged(.red)
case (true, false, false): self = .flagged(.orange)
case (false, true, false): self = .flagged(.yellow)
case (true, true, false): self = .flagged(.green)
case (false, false, true): self = .flagged(.blue)
case (true, false, true): self = .flagged(.purple)
case (false, true, true): self = .flagged(.gray)
case (true, true, true): self = .flaggedUnassigned // `111` is RFC-unassigned
}
}
/// Creates a `RawFlaggedState` from a ``FlaggedState``. This is lossless,
/// since every ``FlaggedState`` is also a `RawFlaggedState`.
///
/// Use ``FlaggedState/init(_:mapUnassignedTo:)`` for the lossy inverse.
public init(_ state: FlaggedState) {
switch state {
case .unflagged: self = .unflagged
case .flagged(let color): self = .flagged(color)
}
}
}
extension FlaggedState.Update {
/// The update that sets `\Flagged` plus exactly `colorBits`, and clears the
/// color bits that aren't in `colorBits`.
fileprivate static func flagged(withColorBits colorBits: Set<Flag>) -> Self {
Self(
flagsToSet: colorBits.union([.flagged]),
flagsToClear: FlaggedState.Color.allColorBits.subtracting(colorBits)
)
}
/// The update that clears `\Flagged` and all three color bits.
fileprivate static let unflagged = Self(
flagsToSet: [],
flagsToClear: FlaggedState.Color.allColorBits.union([.flagged])
)
}
extension FlaggedState.Color {
/// The color bits that are set for this color, as ``Flag`` values.
fileprivate var colorBits: Set<Flag> {
switch self {
case .red: []
case .orange: [.keyword(.colorBit0)]
case .yellow: [.keyword(.colorBit1)]
case .green: [.keyword(.colorBit0), .keyword(.colorBit1)]
case .blue: [.keyword(.colorBit2)]
case .purple: [.keyword(.colorBit0), .keyword(.colorBit2)]
case .gray: [.keyword(.colorBit1), .keyword(.colorBit2)]
}
}
/// The three color-bit flags, as ``Flag`` values.
fileprivate static let allColorBits: Set<Flag> = [
.keyword(.colorBit0),
.keyword(.colorBit1),
.keyword(.colorBit2),
]
}
@@ -47,6 +47,24 @@ public struct UseAttribute: Hashable, Sendable {
/// Holds messages that have been deleted or marked for deletion.
public static let trash = Self("\\Trash")
/// Holds messages that have been temporarily removed from the user's
/// attention and scheduled to reappear at a later "awaken" time.
///
/// - SeeAlso: [RFC 9979 Section 8.1](https://www.rfc-editor.org/rfc/rfc9979.html#section-8.1)
public static let snoozed = Self("\\Snoozed")
/// Holds messages that have been composed but are scheduled to be sent at a
/// future time rather than immediately.
///
/// - SeeAlso: [RFC 9979 Section 8.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-8.2)
public static let scheduled = Self("\\Scheduled")
/// Holds messages bearing the ``Flag/Keyword/memo`` keyword: user-created
/// notes or annotations regarding other messages.
///
/// - SeeAlso: [RFC 9979 Section 8.3](https://www.rfc-editor.org/rfc/rfc9979.html#section-8.3)
public static let memos = Self("\\Memos")
internal let stringValue: String
/// Creates a new `UseAttribute` from the raw `String`. Note that
@@ -52,6 +52,8 @@ Message flags and flag management.
- ``Flag``
- ``Flag/Keyword``
- ``FlaggedState``
- ``RawFlaggedState``
- ``PermanentFlag``
- ``UseAttribute``
- ``AttributeFlag``
@@ -193,7 +195,7 @@ Additional specialized types for protocol extensions.
- ``KeyValue``
- ``GmailLabel``
- ``PreviewText``
- ``SortData``
- ``SortCriterion``
- ``SearchCorrelator``
- ``OptionExtensionKind``
- ``OptionValueComp``
@@ -204,6 +204,10 @@ The base protocol is implemented throughout NIOIMAPCore with types like ``Comman
[RFC 9738](https://datatracker.ietf.org/doc/html/rfc9738) (February 2024) allows servers to advertise a maximum number of messages that can be stored in a mailbox. Check ``Capability/messageLimit(_:)`` for the server's message limit.
### RFC 9979: Further IMAP/JMAP Keywords and Mailbox Name Attributes
[RFC 9979](https://datatracker.ietf.org/doc/html/rfc9979) (May 2026) registers a set of message keywords and mailbox name attributes that were already in use across mail servers and clients, so that implementations can rely on their meaning without name collisions. The message keywords are available as ``Flag/Keyword`` constants — for example ``Flag/Keyword/hasAttachment``, ``Flag/Keyword/memo``, ``Flag/Keyword/muted``, and ``Flag/Keyword/notify``. The three flag-color keywords ``Flag/Keyword/colorBit0``, ``Flag/Keyword/colorBit1``, and ``Flag/Keyword/colorBit2`` encode one of seven colors on a `\Flagged` message; use the higher-level ``FlaggedState`` (or the lossless ``RawFlaggedState``) to read and update a flagged message's color. The mailbox name attributes are available as ``UseAttribute/snoozed``, ``UseAttribute/scheduled``, and ``UseAttribute/memos``.
### draft-ietf-mailmaint-imap-uidbatches: UIDBATCHES Extension
The [UIDBATCHES extension](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-imap-uidbatches/) allows the server to return ranges of UIDs more efficiently when there are large contiguous sequences of UIDs. The ``UIDBatchesResponse`` type supports this efficient UID batch representation.
@@ -462,6 +462,23 @@ extension GrammarParser {
try parseUseAttribute_fixed(expected: "\\Trash", returning: .trash, buffer: &buffer, tracker: tracker)
}
func parseUseAttribute_snoozed(buffer: inout ParseBuffer, tracker: StackTracker) throws -> UseAttribute {
try parseUseAttribute_fixed(expected: "\\Snoozed", returning: .snoozed, buffer: &buffer, tracker: tracker)
}
func parseUseAttribute_scheduled(buffer: inout ParseBuffer, tracker: StackTracker) throws -> UseAttribute {
try parseUseAttribute_fixed(
expected: "\\Scheduled",
returning: .scheduled,
buffer: &buffer,
tracker: tracker
)
}
func parseUseAttribute_memos(buffer: inout ParseBuffer, tracker: StackTracker) throws -> UseAttribute {
try parseUseAttribute_fixed(expected: "\\Memos", returning: .memos, buffer: &buffer, tracker: tracker)
}
func parseUseAttribute_other(buffer: inout ParseBuffer, tracker: StackTracker) throws -> UseAttribute {
try PL.parseFixedString("\\", buffer: &buffer, tracker: tracker)
let att = try self.parseAtom(buffer: &buffer, tracker: tracker)
@@ -477,6 +494,9 @@ extension GrammarParser {
parseUseAttribute_junk,
parseUseAttribute_sent,
parseUseAttribute_trash,
parseUseAttribute_snoozed,
parseUseAttribute_scheduled,
parseUseAttribute_memos,
parseUseAttribute_other,
],
buffer: &buffer,
@@ -78,6 +78,62 @@ struct FlagKeywordTests {
.unregistered_redirected,
"Redirected"
),
EncodeFixture.flagKeyword(
.autoSent,
"$autosent"
),
EncodeFixture.flagKeyword(
.canUnsubscribe,
"$canunsubscribe"
),
EncodeFixture.flagKeyword(
.followed,
"$followed"
),
EncodeFixture.flagKeyword(
.hasAttachment,
"$hasattachment"
),
EncodeFixture.flagKeyword(
.hasMemo,
"$hasmemo"
),
EncodeFixture.flagKeyword(
.hasNoAttachment,
"$hasnoattachment"
),
EncodeFixture.flagKeyword(
.imported,
"$imported"
),
EncodeFixture.flagKeyword(
.isTrusted,
"$istrusted"
),
EncodeFixture.flagKeyword(
.maskedEmail,
"$maskedemail"
),
EncodeFixture.flagKeyword(
.memo,
"$memo"
),
EncodeFixture.flagKeyword(
.muted,
"$muted"
),
EncodeFixture.flagKeyword(
.new,
"$new"
),
EncodeFixture.flagKeyword(
.notify,
"$notify"
),
EncodeFixture.flagKeyword(
.unsubscribed,
"$unsubscribed"
),
])
func encode(_ fixture: EncodeFixture<Flag.Keyword>) {
fixture.checkEncoding()
@@ -0,0 +1,272 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
@_spi(NIOIMAPInternal) @testable import NIOIMAPCore
import Testing
@Suite("FlaggedState")
struct FlaggedStateTests {
static let bit0 = Flag.keyword(.colorBit0)
static let bit1 = Flag.keyword(.colorBit1)
static let bit2 = Flag.keyword(.colorBit2)
@Test(
"flagged(_:).flagChanges produces the RFC 9979 set/clear flags",
arguments: [
(FlaggedState.Color.red, Set([Flag.flagged]), Set([Self.bit0, Self.bit1, Self.bit2])),
(.orange, [.flagged, Self.bit0], [Self.bit1, Self.bit2]),
(.yellow, [.flagged, Self.bit1], [Self.bit0, Self.bit2]),
(.green, [.flagged, Self.bit0, Self.bit1], [Self.bit2]),
(.blue, [.flagged, Self.bit2], [Self.bit0, Self.bit1]),
(.purple, [.flagged, Self.bit0, Self.bit2], [Self.bit1]),
(.gray, [.flagged, Self.bit1, Self.bit2], [Self.bit0]),
] as [(FlaggedState.Color, Set<Flag>, Set<Flag>)]
)
func flaggedUpdate(_ color: FlaggedState.Color, _ expectedSet: Set<Flag>, _ expectedClear: Set<Flag>) {
let changes = FlaggedState.flagged(color).flagChanges
#expect(changes.flagsToSet == expectedSet)
#expect(changes.flagsToClear == expectedClear)
}
@Test(
"flagged(_:).flagChanges always sets \\Flagged, so a color is never set without it",
arguments: FlaggedState.Color.allCases
)
func flaggedUpdateAlwaysFlags(_ color: FlaggedState.Color) {
#expect(FlaggedState.flagged(color).flagChanges.flagsToSet.contains(.flagged))
}
@Test("unflagged.flagChanges unflags and clears all color bits")
func unflag() {
let changes = FlaggedState.unflagged.flagChanges
#expect(changes.flagsToSet == [])
#expect(changes.flagsToClear == [.flagged, Self.bit0, Self.bit1, Self.bit2])
}
@Test("Color.allCases is the seven RFC colors")
func allCasesAreTheSevenColors() {
#expect(FlaggedState.Color.allCases == [.red, .orange, .yellow, .green, .blue, .purple, .gray])
}
@Test(
"color reports the color for a flagged state and nil when unflagged",
arguments: FlaggedState.Color.allCases
)
func color(_ color: FlaggedState.Color) {
#expect(FlaggedState.flagged(color).color == color)
#expect(FlaggedState.unflagged.color == nil)
}
@Test(
"flagged(_:).flagChanges round-trips through FlaggedState(flags:)",
arguments: FlaggedState.Color.allCases
)
func roundTrip(_ color: FlaggedState.Color) {
let changes = FlaggedState.flagged(color).flagChanges
#expect(FlaggedState(flags: changes.flagsToSet) == .flagged(color))
}
/// Applies `changes` to `starting` the way two `STORE` commands would:
/// remove `flagsToClear`, then add `flagsToSet`.
static func apply(_ changes: FlaggedState.Update, to starting: Set<Flag>) -> Set<Flag> {
starting.subtracting(changes.flagsToClear).union(changes.flagsToSet)
}
@Test(
"flagged(_:).flagChanges scrubs stray color bits when applied to an already-colored message",
arguments: FlaggedState.Color.allCases
)
func flagChangesClearsStrayBits(_ color: FlaggedState.Color) {
// Start from a message that already carries every color bit (the `111`
// pattern) plus an unrelated flag. Applying `flagChanges` must leave
// exactly the requested color, exercising `flagsToClear`.
let starting: Set<Flag> = [.flagged, Self.bit0, Self.bit1, Self.bit2, .seen]
let result = Self.apply(FlaggedState.flagged(color).flagChanges, to: starting)
#expect(FlaggedState(flags: result) == .flagged(color))
// Unrelated flags are preserved.
#expect(result.contains(.seen))
}
@Test(
"unflagged.flagChanges clears \\Flagged and every color bit when applied to a flagged message",
arguments: FlaggedState.Color.allCases
)
func unflagClearsEverything(_ color: FlaggedState.Color) {
let starting = Self.apply(FlaggedState.flagged(color).flagChanges, to: [.seen])
let result = Self.apply(FlaggedState.unflagged.flagChanges, to: starting)
#expect(FlaggedState(flags: result) == .unflagged)
#expect(!result.contains(.flagged))
#expect(result.isDisjoint(with: [Self.bit0, Self.bit1, Self.bit2]))
#expect(result.contains(.seen))
}
@Test(
"FlaggedState(flags:) decodes the RFC 9979 bit patterns",
arguments: [
(Set([Flag.flagged]), FlaggedState.flagged(.red)),
([.flagged, Self.bit0], .flagged(.orange)),
([.flagged, Self.bit1], .flagged(.yellow)),
([.flagged, Self.bit0, Self.bit1], .flagged(.green)),
([.flagged, Self.bit2], .flagged(.blue)),
([.flagged, Self.bit0, Self.bit2], .flagged(.purple)),
([.flagged, Self.bit1, Self.bit2], .flagged(.gray)),
// Color bits are additive with unrelated flags:
([.flagged, Self.bit0, .seen, .answered], .flagged(.orange)),
] as [(Set<Flag>, FlaggedState)]
)
func decode(_ flags: Set<Flag>, _ expected: FlaggedState) {
#expect(FlaggedState(flags: flags) == expected)
}
@Test("FlaggedState(flags:) maps the unassigned 111 pattern to .red by default")
func decodeUnassignedDefaultsToRed() {
#expect(FlaggedState(flags: [.flagged, Self.bit0, Self.bit1, Self.bit2]) == .flagged(.red))
}
@Test("FlaggedState(flags:mapUnassignedTo:) maps the unassigned 111 pattern to a custom color")
func decodeUnassignedCustomMapping() {
#expect(
FlaggedState(flags: [.flagged, Self.bit0, Self.bit1, Self.bit2], mapUnassignedTo: .green)
== .flagged(.green)
)
}
@Test(
"FlaggedState(flags:) is unflagged whenever \\Flagged is absent",
arguments: [
// Not flagged -> unflagged, even if color bits are present.
Set<Flag>([]),
[Self.bit0],
[Self.bit0, Self.bit1, Self.bit2],
[.seen, Self.bit1],
]
)
func decodeUnflagged(_ flags: Set<Flag>) {
#expect(FlaggedState(flags: flags) == .unflagged)
}
@Test("FlaggedState(flags:) compares flags case-insensitively")
func decodeCaseInsensitive() {
let flags: [Flag] = [.extension("\\FLAGGED"), .keyword(Flag.Keyword("$mailflagbit1")!)]
#expect(FlaggedState(flags: flags) == .flagged(.yellow))
}
}
@Suite("RawFlaggedState")
struct RawFlaggedStateTests {
static let bit0 = Flag.keyword(.colorBit0)
static let bit1 = Flag.keyword(.colorBit1)
static let bit2 = Flag.keyword(.colorBit2)
@Test(
"init(flags:) decodes the RFC 9979 bit patterns, preserving the unassigned 111",
arguments: [
(Set([Flag.flagged]), RawFlaggedState.flagged(.red)),
([.flagged, Self.bit0], .flagged(.orange)),
([.flagged, Self.bit1], .flagged(.yellow)),
([.flagged, Self.bit0, Self.bit1], .flagged(.green)),
([.flagged, Self.bit2], .flagged(.blue)),
([.flagged, Self.bit0, Self.bit2], .flagged(.purple)),
([.flagged, Self.bit1, Self.bit2], .flagged(.gray)),
// The RFC-unassigned `111` is preserved as the distinct case.
([.flagged, Self.bit0, Self.bit1, Self.bit2], .flaggedUnassigned),
] as [(Set<Flag>, RawFlaggedState)]
)
func decode(_ flags: Set<Flag>, _ expected: RawFlaggedState) {
#expect(RawFlaggedState(flags: flags) == expected)
}
@Test(
"init(flags:) is unflagged whenever \\Flagged is absent",
arguments: [
Set<Flag>([]),
[Self.bit0],
[Self.bit0, Self.bit1, Self.bit2],
]
)
func decodeUnflagged(_ flags: Set<Flag>) {
#expect(RawFlaggedState(flags: flags) == .unflagged)
}
@Test("flaggedUnassigned.flagChanges sets all three color bits and clears nothing")
func unassignedUpdate() {
let changes = RawFlaggedState.flaggedUnassigned.flagChanges
#expect(changes.flagsToSet == [.flagged, Self.bit0, Self.bit1, Self.bit2])
#expect(changes.flagsToClear == [])
}
@Test(
"flagChanges round-trips through init(flags:) for every flagged case",
arguments: [
RawFlaggedState.flagged(.red), .flagged(.orange), .flagged(.yellow), .flagged(.green),
.flagged(.blue), .flagged(.purple), .flagged(.gray),
.flaggedUnassigned,
] as [RawFlaggedState]
)
func roundTrip(_ state: RawFlaggedState) {
#expect(RawFlaggedState(flags: state.flagChanges.flagsToSet) == state)
}
@Test(
"flagChanges scrubs stray color bits when applied to an already-colored message",
arguments: [
RawFlaggedState.flagged(.red), .flagged(.orange), .flagged(.yellow), .flagged(.green),
.flagged(.blue), .flagged(.purple), .flagged(.gray),
.flaggedUnassigned,
] as [RawFlaggedState]
)
func flagChangesClearsStrayBits(_ state: RawFlaggedState) {
// Start from a message carrying every color bit plus an unrelated flag,
// then apply `flagChanges` removing `flagsToClear` before adding `flagsToSet`.
let starting: Set<Flag> = [.flagged, Self.bit0, Self.bit1, Self.bit2, .seen]
let result = starting.subtracting(state.flagChanges.flagsToClear).union(state.flagChanges.flagsToSet)
#expect(RawFlaggedState(flags: result) == state)
#expect(result.contains(.seen))
}
@Test("unflagged.flagChanges unflags and clears all color bits")
func unflag() {
let changes = RawFlaggedState.unflagged.flagChanges
#expect(changes.flagsToSet == [])
#expect(changes.flagsToClear == [.flagged, Self.bit0, Self.bit1, Self.bit2])
}
@Test(
"FlaggedState(_:mapUnassignedTo:) folds .flaggedUnassigned into the given color and carries the rest over",
arguments: FlaggedState.Color.allCases
)
func collapseToFlaggedState(_ color: FlaggedState.Color) {
#expect(FlaggedState(RawFlaggedState.flaggedUnassigned, mapUnassignedTo: color) == .flagged(color))
#expect(FlaggedState(RawFlaggedState.flagged(color), mapUnassignedTo: .green) == .flagged(color))
#expect(FlaggedState(RawFlaggedState.unflagged, mapUnassignedTo: .green) == .unflagged)
}
@Test("FlaggedState(_:) defaults .flaggedUnassigned to .red")
func collapseDefaultsToRed() {
#expect(FlaggedState(RawFlaggedState.flaggedUnassigned) == .flagged(.red))
}
@Test(
"init(_:) losslessly lifts a FlaggedState",
arguments: [
(FlaggedState.unflagged, RawFlaggedState.unflagged),
(.flagged(.red), .flagged(.red)),
(.flagged(.gray), .flagged(.gray)),
] as [(FlaggedState, RawFlaggedState)]
)
func liftFromFlaggedState(_ state: FlaggedState, _ expected: RawFlaggedState) {
#expect(RawFlaggedState(state) == expected)
}
}
@@ -26,6 +26,9 @@ struct UseAttributeTests {
EncodeFixture.useAttribute(.junk, "\\Junk"),
EncodeFixture.useAttribute(.sent, "\\Sent"),
EncodeFixture.useAttribute(.trash, "\\Trash"),
EncodeFixture.useAttribute(.snoozed, "\\Snoozed"),
EncodeFixture.useAttribute(.scheduled, "\\Scheduled"),
EncodeFixture.useAttribute(.memos, "\\Memos"),
EncodeFixture.useAttribute(.init("\\test"), "\\test"),
])
func encode(_ fixture: EncodeFixture<UseAttribute>) {
@@ -65,6 +68,9 @@ struct UseAttributeTests {
ParseFixture.useAttribute("\\Trash", "", expected: .success(.trash)),
ParseFixture.useAttribute("\\Sent", "", expected: .success(.sent)),
ParseFixture.useAttribute("\\Drafts", "", expected: .success(.drafts)),
ParseFixture.useAttribute("\\Snoozed", "", expected: .success(.snoozed)),
ParseFixture.useAttribute("\\Scheduled", "", expected: .success(.scheduled)),
ParseFixture.useAttribute("\\Memos", "", expected: .success(.memos)),
ParseFixture.useAttribute("\\Other", " ", expected: .success(.init("\\Other"))),
])
func parse(_ fixture: ParseFixture<UseAttribute>) {