# exerra/cf-imap architecture

> Architecture diagram of the GitHub repository exerra/cf-imap, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-09-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/exerra/cf-imap
- Repository: https://github.com/exerra/cf-imap

## Overview

#### Purpose and runtime
`cf-imap` is a TypeScript IMAP4 client designed specifically for Cloudflare Workers. It opens and manages IMAP sessions over Workers-compatible sockets, supports IMAP4rev1/rev2 behavior, and exposes mailbox, message, flag, and IDLE operations. Its public entry point is `src/index.ts`.

#### Public client and session lifecycle
`CFImap` in `src/index.ts` is the primary API boundary. Callers construct it with server, TLS, authentication, and timeout options; then invoke `connect()` from a Worker request handler. The lifecycle is:
1. Open socket and establish implicit TLS or negotiate STARTTLS.
2. Discover capabilities and negotiate IMAP4rev2 where supported.
3. Authenticate, execute commands, and consume server responses.
4. End the session through `logout()` / `close()` and socket shutdown.

Related exported request/result types are centralized in `src/types/emails.ts`.

#### IMAP command transport and response framing
The client’s control plane is tag-based IMAP command execution: commands are serialized onto one socket, then correlated with tagged completion responses while collecting untagged data and continuations. `src/utils/imapStream.ts` is the streaming/framing layer for reading IMAP response lines and literals, including long message payloads without treating the protocol as a single buffered response. `src/utils/imapList.ts` parses structured IMAP LIST-style responses.

This transport boundary is responsible for command failures becoming `ImapError`, socket drops becoming regular errors, and applying the configured read timeout.

#### Capability-dependent protocol behavior
Connection setup and command construction in `src/index.ts` adapt to server capability advertisements. Important branches include implicit TLS on port 993 versus STARTTLS elsewhere, `AUTHENTICATE PLAIN` before conditional `LOGIN`, enabling IMAP4rev2 when advertised, and refusing rev1-only/deprecated semantics where rev2 removes them.

Mailbox naming is also protocol-version dependent: rev2 uses UTF-8 names, while rev1 sessions require modified UTF-7 conversion. Namespace discovery, folder listing, select/examine, status, close/unselect, copy/move, append, expunge, and IDLE all pass through this same session-aware command boundary.

#### Search and message retrieval
`src/utils/search.ts` translates high-level search criteria into IMAP SEARCH commands and parses both legacy `SEARCH` and rev2 `ESEARCH` results. Search can operate on sequence numbers or UIDs and supplies UTF-8 charset handling for non-ASCII criteria.

Fetching is orchestrated by `src/index.ts`: it requests headers or complete RFC message content, associates IMAP metadata such as sequence number, UID, flags, size, and internal date, and returns the normalized email model defined in `src/types/emails.ts`.

#### MIME decoding pipeline
Raw fetched messages cross into a local parsing pipeline rather than an external email service. `src/utils/mime.ts` parses MIME structure, multipart bodies, text/HTML parts, attachments, content IDs, encodings, and raw message representation. `src/utils/decodeMime.ts` decodes encoded headers/content and supports normalized fields such as subject, address lists, headers, body variants, and attachment base64/content.

The resulting application-facing email object is the boundary between IMAP wire responses and consumer code: `src/types/emails.ts`, `src/utils/mime.ts`, and `src/utils/decodeMime.ts`.

Main entry points: [`src/index.ts`](https://github.com/exerra/cf-imap/blob/main/src/index.ts) (CFImap client), [`src/utils/imapStream.ts`](https://github.com/exerra/cf-imap/blob/main/src/utils/imapStream.ts) (IMAP stream framing), [`src/utils/search.ts`](https://github.com/exerra/cf-imap/blob/main/src/utils/search.ts) (Search translator), [`src/utils/mime.ts`](https://github.com/exerra/cf-imap/blob/main/src/utils/mime.ts) (MIME parser)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["Public API"]
  node_worker(("Worker caller<br/>Cloudflare Worker"))
  node_client["CFImap client<br/>public client<br/>[index.ts]"]
  node_email_types["Email models<br/>exported types<br/>[emails.ts]"]
end

subgraph group_session["IMAP Session"]
  node_socket["Worker socket<br/>socket transport"]
  node_connection["Connection setup<br/>session lifecycle<br/>[index.ts]"]
  node_command_transport["Tagged command transport<br/>IMAP control plane<br/>[index.ts]"]
  node_mailbox_ops["Mailbox operations<br/>session commands<br/>[index.ts]"]
  node_fetch["Message retrieval<br/>FETCH orchestration<br/>[index.ts]"]
end

subgraph group_parsing["Response &amp; Message Parsing"]
  node_stream["IMAP stream framing<br/>stream parser<br/>[imapStream.ts]"]
  node_list_parser["LIST parser<br/>response parser<br/>[imapList.ts]"]
  node_search["Search translator<br/>SEARCH/ESEARCH<br/>[search.ts]"]
  node_mime["MIME parser<br/>message parser<br/>[mime.ts]"]
  node_decode_mime["MIME decoder<br/>content decoder<br/>[decodeMime.ts]"]
end

node_worker -->|"constructs / connects"| node_client
node_client -->|"returns"| node_email_types
node_client -->|"manages lifecycle"| node_connection
node_connection -->|"opens TLS or STARTTLS"| node_socket
node_connection -->|"negotiates and authenticates"| node_command_transport
node_client -->|"executes commands"| node_command_transport
node_command_transport -->|"writes commands"| node_socket
node_socket -->|"server bytes"| node_stream
node_stream -->|"framed responses"| node_command_transport
node_client -->|"exposes"| node_mailbox_ops
node_mailbox_ops -->|"session-aware commands"| node_command_transport
node_client -->|"search requests"| node_search
node_search -->|"SEARCH / ESEARCH"| node_command_transport
node_client -->|"fetch requests"| node_fetch
node_fetch -->|"FETCH"| node_command_transport
node_stream -->|"LIST responses"| node_list_parser
node_fetch -->|"raw RFC message"| node_mime
node_mime -->|"parsed parts"| node_decode_mime
node_decode_mime -->|"normalized email"| node_email_types

click node_client "https://github.com/exerra/cf-imap/blob/main/src/index.ts"
click node_email_types "https://github.com/exerra/cf-imap/blob/main/src/types/emails.ts"
click node_connection "https://github.com/exerra/cf-imap/blob/main/src/index.ts"
click node_command_transport "https://github.com/exerra/cf-imap/blob/main/src/index.ts"
click node_stream "https://github.com/exerra/cf-imap/blob/main/src/utils/imapStream.ts"
click node_list_parser "https://github.com/exerra/cf-imap/blob/main/src/utils/imapList.ts"
click node_mailbox_ops "https://github.com/exerra/cf-imap/blob/main/src/index.ts"
click node_search "https://github.com/exerra/cf-imap/blob/main/src/utils/search.ts"
click node_fetch "https://github.com/exerra/cf-imap/blob/main/src/index.ts"
click node_mime "https://github.com/exerra/cf-imap/blob/main/src/utils/mime.ts"
click node_decode_mime "https://github.com/exerra/cf-imap/blob/main/src/utils/decodeMime.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_worker,node_client,node_email_types toneBlue
class node_socket,node_connection,node_command_transport,node_mailbox_ops,node_fetch toneAmber
class node_stream,node_list_parser,node_search,node_mime,node_decode_mime toneMint
```

## Components

### Public API

- **Worker caller**: Cloudflare Worker · Creates and uses IMAP sessions.
- [CFImap client](https://github.com/exerra/cf-imap/blob/main/src/index.ts): public client · Session-aware IMAP API and command orchestrator. · `src/index.ts`
- [Email models](https://github.com/exerra/cf-imap/blob/main/src/types/emails.ts): exported types · Application-facing request, result, and normalized email types. · `src/types/emails.ts`

### IMAP Session

- **Worker socket**: socket transport · Workers-compatible IMAP connection.
- [Connection setup](https://github.com/exerra/cf-imap/blob/main/src/index.ts): session lifecycle · TLS, capabilities, rev2 negotiation, authentication, and shutdown. · `src/index.ts`
- [Tagged command transport](https://github.com/exerra/cf-imap/blob/main/src/index.ts): IMAP control plane · Serializes commands and correlates tagged, untagged, and continuation responses. · `src/index.ts`
- [Mailbox operations](https://github.com/exerra/cf-imap/blob/main/src/index.ts): session commands · Namespace, folders, select, status, copy/move, append, expunge, and IDLE. · `src/index.ts`
- [Message retrieval](https://github.com/exerra/cf-imap/blob/main/src/index.ts): FETCH orchestration · Collects message metadata, headers, and RFC content. · `src/index.ts`

### Response & Message Parsing

- [IMAP stream framing](https://github.com/exerra/cf-imap/blob/main/src/utils/imapStream.ts): stream parser · Reads response lines and literals with timeout handling. · `src/utils/imapStream.ts`
- [LIST parser](https://github.com/exerra/cf-imap/blob/main/src/utils/imapList.ts): response parser · Parses structured mailbox listing responses. · `src/utils/imapList.ts`
- [Search translator](https://github.com/exerra/cf-imap/blob/main/src/utils/search.ts): SEARCH/ESEARCH · Builds criteria and parses sequence or UID results. · `src/utils/search.ts`
- [MIME parser](https://github.com/exerra/cf-imap/blob/main/src/utils/mime.ts): message parser · Parses multipart structure, bodies, attachments, and raw content. · `src/utils/mime.ts`
- [MIME decoder](https://github.com/exerra/cf-imap/blob/main/src/utils/decodeMime.ts): content decoder · Decodes encoded fields into normalized message content. · `src/utils/decodeMime.ts`

## Connections

- Worker caller → CFImap client: constructs / connects
- CFImap client → Email models: returns
- CFImap client → Connection setup: manages lifecycle
- Connection setup → Worker socket: opens TLS or STARTTLS
- Connection setup → Tagged command transport: negotiates and authenticates
- CFImap client → Tagged command transport: executes commands
- Tagged command transport → Worker socket: writes commands
- Worker socket → IMAP stream framing: server bytes
- IMAP stream framing → Tagged command transport: framed responses
- CFImap client → Mailbox operations: exposes
- Mailbox operations → Tagged command transport: session-aware commands
- CFImap client → Search translator: search requests
- Search translator → Tagged command transport: SEARCH / ESEARCH
- CFImap client → Message retrieval: fetch requests
- Message retrieval → Tagged command transport: FETCH
- IMAP stream framing → LIST parser: LIST responses
- Message retrieval → MIME parser: raw RFC message
- MIME parser → MIME decoder: parsed parts
- MIME decoder → Email models: normalized email
