@wtfalch/email 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +390 -12
  2. package/dist/imip/compose.d.ts +5 -0
  3. package/dist/imip/compose.js +84 -0
  4. package/dist/imip/index.d.ts +15 -0
  5. package/dist/imip/index.js +14 -0
  6. package/dist/imip/lookup.d.ts +21 -0
  7. package/dist/imip/lookup.js +26 -0
  8. package/dist/imip/parse.d.ts +11 -0
  9. package/dist/imip/parse.js +116 -0
  10. package/dist/imip/types.d.ts +57 -0
  11. package/dist/imip/types.js +9 -0
  12. package/dist/mailbox/client.d.ts +28 -1
  13. package/dist/mailbox/client.js +51 -0
  14. package/dist/mailbox/fake/mailbox.js +567 -7
  15. package/dist/mailbox/index.d.ts +16 -8
  16. package/dist/mailbox/index.js +8 -4
  17. package/dist/mailbox/mail.css +13 -0
  18. package/dist/mailbox/mailboxes.d.ts +95 -1
  19. package/dist/mailbox/mailboxes.js +243 -1
  20. package/dist/mailbox/mutate.d.ts +21 -0
  21. package/dist/mailbox/mutate.js +71 -0
  22. package/dist/mailbox/quoted.d.ts +94 -0
  23. package/dist/mailbox/quoted.js +158 -0
  24. package/dist/mailbox/react/Composer.js +13 -1
  25. package/dist/mailbox/react/Mail.js +273 -33
  26. package/dist/mailbox/react/ThreadView.d.ts +13 -1
  27. package/dist/mailbox/react/ThreadView.js +5 -4
  28. package/dist/mailbox/react/index.d.ts +3 -1
  29. package/dist/mailbox/react/index.js +2 -1
  30. package/dist/mailbox/react/quotedHtml.d.ts +105 -0
  31. package/dist/mailbox/react/quotedHtml.js +163 -0
  32. package/dist/mailbox/sieve.d.ts +76 -0
  33. package/dist/mailbox/sieve.js +241 -0
  34. package/dist/mailbox/snooze.d.ts +48 -0
  35. package/dist/mailbox/snooze.js +176 -0
  36. package/dist/mailbox/submit.d.ts +56 -2
  37. package/dist/mailbox/submit.js +145 -11
  38. package/dist/mailbox/threads.js +2 -0
  39. package/dist/mailbox/types.d.ts +60 -0
  40. package/dist/mailbox/vacation.d.ts +32 -0
  41. package/dist/mailbox/vacation.js +79 -0
  42. package/dist/postmaster/apply.d.ts +154 -1
  43. package/dist/postmaster/apply.js +336 -1
  44. package/dist/postmaster/audit.d.ts +22 -1
  45. package/dist/postmaster/audit.js +7 -0
  46. package/dist/postmaster/client.d.ts +49 -0
  47. package/dist/postmaster/client.js +43 -0
  48. package/dist/postmaster/index.d.ts +6 -3
  49. package/dist/postmaster/index.js +5 -2
  50. package/dist/postmaster/mail-copy.d.ts +169 -0
  51. package/dist/postmaster/mail-copy.js +259 -0
  52. package/dist/postmaster/objects.js +11 -0
  53. package/dist/postmaster/org-mail.d.ts +117 -0
  54. package/dist/postmaster/org-mail.js +206 -0
  55. package/dist/postmaster/overview.d.ts +4 -0
  56. package/dist/postmaster/queue.d.ts +111 -0
  57. package/dist/postmaster/queue.js +64 -0
  58. package/dist/postmaster/writes.d.ts +59 -0
  59. package/dist/postmaster/writes.js +106 -0
  60. package/package.json +8 -3
@@ -0,0 +1,176 @@
1
+ import { JAM_FETCH } from "./client.js";
2
+ import { MailError, guard } from "./errors.js";
3
+ import { findRole, mailboxes } from "./mailboxes.js";
4
+ /**
5
+ * Snooze: take a thread out of the Inbox until a time, then put it back.
6
+ *
7
+ * **JMAP has no snooze, so this is two halves.** `snoozeThread` moves the
8
+ * thread into a top-level mailbox named Snoozed (made on first use) and
9
+ * stamps each message with a keyword holding the wake time.
10
+ * `wakeSnoozed` moves every thread whose time has come back to the Inbox,
11
+ * unread. Nothing in a mail server calls `wakeSnoozed`; the host runs it on
12
+ * a timer. That is the part of snooze that is server work, and a library
13
+ * cannot own a clock.
14
+ *
15
+ * **The wake time is a keyword, `$snoozed:<unix seconds>`.** A message has
16
+ * no free-form property to hold a date, and a keyword is stored, searchable
17
+ * and survives every client. RFC 8621 keywords may contain `:` and digits.
18
+ */
19
+ /** The name the Snoozed mailbox is found and made by. */
20
+ export const SNOOZED_MAILBOX = 'Snoozed';
21
+ const WAKE = '$snoozed:';
22
+ /** RFC 6901 §3: `~` and `/` inside a pointer segment are escaped. A keyword
23
+ * read back from the server may hold either, so a patch key built from one
24
+ * must escape. */
25
+ function pointer(segment) {
26
+ return segment.replaceAll('~', '~0').replaceAll('/', '~1');
27
+ }
28
+ function wakeKeyword(until) {
29
+ return `${WAKE}${Math.floor(until.getTime() / 1000)}`;
30
+ }
31
+ /** The wake time a message carries, in milliseconds, or `null`. */
32
+ function wakeTime(keywords) {
33
+ for (const keyword of Object.keys(keywords ?? {})) {
34
+ if (!keyword.startsWith(WAKE))
35
+ continue;
36
+ const seconds = Number(keyword.slice(WAKE.length));
37
+ if (Number.isInteger(seconds))
38
+ return seconds * 1000;
39
+ }
40
+ return null;
41
+ }
42
+ function refused(result, operation) {
43
+ const notUpdated = result.notUpdated;
44
+ const first = notUpdated ? Object.values(notUpdated)[0] : undefined;
45
+ if (first) {
46
+ throw new MailError(first.description ?? `the server refused to ${operation}`, {
47
+ type: first.type ?? 'unknown',
48
+ operation,
49
+ });
50
+ }
51
+ }
52
+ function findSnoozed(tree) {
53
+ return tree.find((box) => box.name === SNOOZED_MAILBOX && box.parentId === null);
54
+ }
55
+ /**
56
+ * Snooze a thread until `until`: out of every mailbox, into Snoozed.
57
+ *
58
+ * Messages in Sent or Drafts stay where they are. They are my own copies,
59
+ * not mail waiting for me, and waking files into the Inbox: a sent reply
60
+ * moved into Snoozed would come back as if it had been received.
61
+ *
62
+ * Snoozing a thread that is already snoozed moves its wake time; the old
63
+ * one is removed rather than left beside it. A time in the past is allowed
64
+ * and simply wakes on the next `wakeSnoozed`, since what "now" is belongs
65
+ * to the host's clock, not this call's.
66
+ *
67
+ * Returns the ids of the messages that moved.
68
+ */
69
+ export async function snoozeThread(client, threadId, until, options = {}) {
70
+ if (Number.isNaN(until.getTime())) {
71
+ throw new MailError('snooze needs a valid date', {
72
+ type: 'invalidArguments',
73
+ operation: 'snooze',
74
+ });
75
+ }
76
+ const { jam, accountId } = await client.connect();
77
+ const tree = options.mailboxes ?? (await mailboxes(client));
78
+ return guard('snooze', async () => {
79
+ let snoozedId = findSnoozed(tree)?.id;
80
+ if (!snoozedId) {
81
+ const [made] = await jam.api.Mailbox.set({ accountId, create: { snoozed: { name: SNOOZED_MAILBOX, parentId: null } } }, JAM_FETCH);
82
+ snoozedId = made.created?.snoozed?.id;
83
+ if (!snoozedId) {
84
+ const failure = Object.values((made.notCreated ?? {}))[0];
85
+ throw new MailError(failure?.description ?? 'the server would not make a Snoozed mailbox', {
86
+ type: failure?.type ?? 'unknown',
87
+ operation: 'snooze',
88
+ });
89
+ }
90
+ }
91
+ const [thread] = await jam.api.Thread.get({ accountId, ids: [threadId] }, JAM_FETCH);
92
+ const ids = thread.list?.[0]?.emailIds ?? [];
93
+ if (ids.length === 0) {
94
+ throw new MailError(`no thread ${threadId} on this account`, {
95
+ type: 'notFound',
96
+ operation: 'snooze',
97
+ });
98
+ }
99
+ const [found] = await jam.api.Email.get({ accountId, ids, properties: ['keywords', 'mailboxIds'] }, JAM_FETCH);
100
+ const mine = new Set([findRole(tree, 'sent')?.id, findRole(tree, 'drafts')?.id]);
101
+ const moving = [];
102
+ const stale = new Set();
103
+ for (const email of found.list) {
104
+ if (Object.keys(email.mailboxIds ?? {}).some((box) => mine.has(box)))
105
+ continue;
106
+ moving.push(email.id);
107
+ for (const keyword of Object.keys(email.keywords ?? {})) {
108
+ if (keyword.startsWith(WAKE))
109
+ stale.add(keyword);
110
+ }
111
+ }
112
+ if (moving.length === 0)
113
+ return [];
114
+ const patch = { mailboxIds: { [snoozedId]: true } };
115
+ for (const keyword of stale)
116
+ patch[`keywords/${pointer(keyword)}`] = null;
117
+ patch[`keywords/${pointer(wakeKeyword(until))}`] = true;
118
+ const update = {};
119
+ for (const id of moving)
120
+ update[id] = patch;
121
+ const [result] = await jam.api.Email.set({ accountId, update: update }, JAM_FETCH);
122
+ refused(result, 'snooze');
123
+ return moving;
124
+ });
125
+ }
126
+ /**
127
+ * Wake every snoozed thread whose time is at or before `now`: back to the
128
+ * Inbox, unread, wake time removed.
129
+ *
130
+ * Meant for a timer the host runs, every minute or so. `now` is a
131
+ * parameter so the host's clock decides, and a test can pass its own.
132
+ * Returns the ids of the threads that woke; an account that has never
133
+ * snoozed anything returns none without making a mailbox.
134
+ */
135
+ export async function wakeSnoozed(client, now = new Date(), options = {}) {
136
+ const { jam, accountId } = await client.connect();
137
+ const tree = options.mailboxes ?? (await mailboxes(client));
138
+ const snoozed = findSnoozed(tree);
139
+ if (!snoozed)
140
+ return [];
141
+ const inbox = findRole(tree, 'inbox');
142
+ if (!inbox) {
143
+ throw new MailError('the account has no Inbox to wake mail into', {
144
+ type: 'notFound',
145
+ operation: 'wake',
146
+ });
147
+ }
148
+ return guard('wake', async () => {
149
+ const [query] = await jam.api.Email.query({ accountId, filter: { inMailbox: snoozed.id } }, JAM_FETCH);
150
+ if (query.ids.length === 0)
151
+ return [];
152
+ const [found] = await jam.api.Email.get({ accountId, ids: query.ids, properties: ['threadId', 'keywords'] }, JAM_FETCH);
153
+ const update = {};
154
+ const woke = new Set();
155
+ for (const email of found.list) {
156
+ const at = wakeTime(email.keywords);
157
+ if (at === null || at > now.getTime())
158
+ continue;
159
+ const patch = {
160
+ mailboxIds: { [inbox.id]: true },
161
+ 'keywords/$seen': null,
162
+ };
163
+ for (const keyword of Object.keys(email.keywords ?? {})) {
164
+ if (keyword.startsWith(WAKE))
165
+ patch[`keywords/${pointer(keyword)}`] = null;
166
+ }
167
+ update[email.id] = patch;
168
+ woke.add(email.threadId);
169
+ }
170
+ if (woke.size === 0)
171
+ return [];
172
+ const [result] = await jam.api.Email.set({ accountId, update: update }, JAM_FETCH);
173
+ refused(result, 'wake');
174
+ return [...woke];
175
+ });
176
+ }
@@ -1,7 +1,35 @@
1
1
  import { type MailClient } from './client.ts';
2
2
  import type { Draft, EmailAddress, MailIdentity, MailboxNode, Queued, Sent } from './types.ts';
3
- /** The JMAP `Email` object a draft becomes. Exported so the shape can be
4
- * asserted without a server. */
3
+ /**
4
+ * The JMAP `Email` object a draft becomes. Exported so the shape can be
5
+ * asserted without a server.
6
+ *
7
+ * **A `calendar` part moves the whole body under `bodyStructure`.** RFC 8621
8
+ * §4.6: a created `Email` MUST NOT mix `bodyStructure` with `textBody`/
9
+ * `htmlBody`/`attachments`, and a `text/calendar` part has nowhere to go in
10
+ * any of those three, so it forces the explicit form -- one
11
+ * `multipart/alternative` holding the readable text (and `html`, if the
12
+ * draft has one) beside the calendar part, the shape #99 found every mail
13
+ * client uses for iTIP. `draft.attachments` has nowhere to go alongside it
14
+ * without folding it into the same structure by hand, which nothing here
15
+ * needs yet (#97 ships compose and parse only), so the two are refused
16
+ * together rather than silently dropping one.
17
+ *
18
+ * **The `method=` parameter rides in the part's own `type` string, not a
19
+ * `header:Content-Type`.** Both name the same header, and RFC 8621 §4.6
20
+ * forbids setting it twice; Stalwart does not enforce that itself and would
21
+ * emit two `Content-Type` headers. Its `Email/set` writes whatever string
22
+ * `type` holds onto the wire unparsed -- `ContentType::new(content_type)`
23
+ * (`crates/jmap/src/email/set.rs:516,562` @
24
+ * `02503015580abd6706923d34e9d8e501e76f8634`) treats it as an opaque token,
25
+ * appending only the `charset`/`name` attributes this package's own
26
+ * `partId` path adds, never stripping or validating what came before them
27
+ * (mail-builder `ContentType::write_header`,
28
+ * `src/headers/content_type.rs:49-63` @
29
+ * `0e87ce2d426d39fcad192df1581fd6776faabd0b`, the commit tagged `v1.0.0`
30
+ * that Stalwart's `Cargo.lock` pins) -- so `text/calendar; method=COUNTER`
31
+ * survives verbatim. See the PR for the full citation.
32
+ */
5
33
  export declare function draftToEmail(draft: Draft, from: readonly EmailAddress[], draftsMailboxId: string): Record<string, unknown>;
6
34
  /** The patch that files a sent message: out of Drafts, into Sent, no longer a
7
35
  * draft. */
@@ -29,12 +57,38 @@ export type SendOptions = {
29
57
  * byte-identical to a plain send. Travels as RFC 4865's `holdFor` SMTP
30
58
  * parameter, which the server validates as 1..=999999999. */
31
59
  delay?: number;
60
+ /** A draft `saveDraft()` stored. It is replaced by the message sent, so
61
+ * Drafts is left without it. What goes out is always the `Draft` passed
62
+ * to `send()`, never what was last saved. */
63
+ draftId?: string;
64
+ };
65
+ export type SaveDraftOptions = {
66
+ /** The identity to fill `from` with, when the caller already has it. */
67
+ identity?: MailIdentity;
68
+ /** The mailbox tree, when the caller already has it. */
69
+ mailboxes?: readonly MailboxNode[];
32
70
  };
33
71
  export type CancelOptions = {
34
72
  /** The mailbox tree, when the caller already has it. Saves a
35
73
  * `Mailbox/get`. */
36
74
  mailboxes?: readonly MailboxNode[];
37
75
  };
76
+ /**
77
+ * Store a draft in Drafts, so it survives the compose sheet closing.
78
+ *
79
+ * Called with the id it returned last time, it replaces that draft rather
80
+ * than adding a second. RFC 8621 messages are immutable, so "replace" is a
81
+ * create followed by a destroy; the id changes every save,
82
+ * which is why the new one is returned. The thread does not change, because
83
+ * the draft keeps its `inReplyTo` and `references`.
84
+ *
85
+ * `from` is filled from the identity when the draft has none, as `send()`
86
+ * does, so a saved draft reads the same as the message it becomes.
87
+ */
88
+ export declare function saveDraft(client: MailClient, draft: Draft, draftId?: string, options?: SaveDraftOptions): Promise<{
89
+ id: string;
90
+ threadId: string;
91
+ }>;
38
92
  /**
39
93
  * Send a draft.
40
94
  *
@@ -47,6 +47,54 @@ function checkDelay(delay) {
47
47
  * Without an envelope the server derives recipients from the headers, but
48
48
  * it strips the Bcc header before delivery, so a delayed send has to list
49
49
  * every recipient explicitly here or the blind ones are silently dropped. */
50
+ /**
51
+ * Refuse to replace anything that is not a draft.
52
+ *
53
+ * Replacing is a destroy, and an id is only a string: a caller that passed a
54
+ * received message's id by mistake would delete it for good. So the id is
55
+ * read first, and anything without `$draft` is refused. An id that no longer
56
+ * exists is allowed through: the old draft is already gone, which is what
57
+ * replacing it wanted.
58
+ */
59
+ async function checkIsDraft(jam, accountId, draftId, operation) {
60
+ const [found] = await jam.api.Email.get({ accountId, ids: [draftId], properties: ['keywords'] }, JAM_FETCH);
61
+ const email = found.list?.[0];
62
+ if (email && !email.keywords?.$draft) {
63
+ throw new MailError(`${draftId} is not a draft, so it will not be replaced`, {
64
+ type: 'invalidArguments',
65
+ operation,
66
+ });
67
+ }
68
+ }
69
+ /** A replaced draft that could not be destroyed, other than because it was
70
+ * already gone. The new one exists, so the message says so. */
71
+ function checkReplaced(notDestroyed, draftId, savedAs, operation) {
72
+ const failure = notDestroyed?.[draftId];
73
+ if (!failure || failure.type === 'notFound')
74
+ return;
75
+ throw new MailError(`saved as ${savedAs}, but the earlier draft ${draftId} could not be removed: ${failure.description ?? failure.type}`, { type: failure.type ?? 'unknown', operation });
76
+ }
77
+ /**
78
+ * Create `email` in Drafts, then destroy `draftId` if one was given.
79
+ *
80
+ * Two `Email/set` calls, not one. RFC 8620 §5.3 applies a create and a
81
+ * destroy in the same call independently, so a server may destroy the old
82
+ * draft while refusing the new one, and the draft would be lost. The destroy
83
+ * is only sent once the create has succeeded.
84
+ */
85
+ async function createReplacing(jam, accountId, email, draftId, operation) {
86
+ if (draftId)
87
+ await checkIsDraft(jam, accountId, draftId, operation);
88
+ const [created] = await jam.api.Email.set({ accountId, create: { draft: email } }, JAM_FETCH);
89
+ const result = created.created?.draft;
90
+ if (!result)
91
+ failed('draft', created.notCreated);
92
+ if (draftId) {
93
+ const [destroyed] = await jam.api.Email.set({ accountId, destroy: [draftId] }, JAM_FETCH);
94
+ checkReplaced(destroyed.notDestroyed, draftId, result.id, operation);
95
+ }
96
+ return result;
97
+ }
50
98
  function uniqueAddresses(addresses) {
51
99
  const seen = new Set();
52
100
  const result = [];
@@ -58,9 +106,43 @@ function uniqueAddresses(addresses) {
58
106
  }
59
107
  return result;
60
108
  }
61
- /** The JMAP `Email` object a draft becomes. Exported so the shape can be
62
- * asserted without a server. */
109
+ /**
110
+ * The JMAP `Email` object a draft becomes. Exported so the shape can be
111
+ * asserted without a server.
112
+ *
113
+ * **A `calendar` part moves the whole body under `bodyStructure`.** RFC 8621
114
+ * §4.6: a created `Email` MUST NOT mix `bodyStructure` with `textBody`/
115
+ * `htmlBody`/`attachments`, and a `text/calendar` part has nowhere to go in
116
+ * any of those three, so it forces the explicit form -- one
117
+ * `multipart/alternative` holding the readable text (and `html`, if the
118
+ * draft has one) beside the calendar part, the shape #99 found every mail
119
+ * client uses for iTIP. `draft.attachments` has nowhere to go alongside it
120
+ * without folding it into the same structure by hand, which nothing here
121
+ * needs yet (#97 ships compose and parse only), so the two are refused
122
+ * together rather than silently dropping one.
123
+ *
124
+ * **The `method=` parameter rides in the part's own `type` string, not a
125
+ * `header:Content-Type`.** Both name the same header, and RFC 8621 §4.6
126
+ * forbids setting it twice; Stalwart does not enforce that itself and would
127
+ * emit two `Content-Type` headers. Its `Email/set` writes whatever string
128
+ * `type` holds onto the wire unparsed -- `ContentType::new(content_type)`
129
+ * (`crates/jmap/src/email/set.rs:516,562` @
130
+ * `02503015580abd6706923d34e9d8e501e76f8634`) treats it as an opaque token,
131
+ * appending only the `charset`/`name` attributes this package's own
132
+ * `partId` path adds, never stripping or validating what came before them
133
+ * (mail-builder `ContentType::write_header`,
134
+ * `src/headers/content_type.rs:49-63` @
135
+ * `0e87ce2d426d39fcad192df1581fd6776faabd0b`, the commit tagged `v1.0.0`
136
+ * that Stalwart's `Cargo.lock` pins) -- so `text/calendar; method=COUNTER`
137
+ * survives verbatim. See the PR for the full citation.
138
+ */
63
139
  export function draftToEmail(draft, from, draftsMailboxId) {
140
+ if (draft.calendar && draft.attachments?.length) {
141
+ throw new MailError('a calendar part cannot be combined with file attachments yet', {
142
+ type: 'invalidProperties',
143
+ operation: 'draftToEmail',
144
+ });
145
+ }
64
146
  const bodyValues = {};
65
147
  const textBody = [];
66
148
  const htmlBody = [];
@@ -78,6 +160,26 @@ export function draftToEmail(draft, from, draftsMailboxId) {
78
160
  bodyValues.text = { value: '' };
79
161
  textBody.push({ partId: 'text', type: 'text/plain' });
80
162
  }
163
+ let body;
164
+ if (draft.calendar) {
165
+ bodyValues.calendar = { value: draft.calendar.ics };
166
+ body = {
167
+ bodyStructure: {
168
+ type: 'multipart/alternative',
169
+ subParts: [
170
+ ...textBody,
171
+ ...htmlBody,
172
+ { partId: 'calendar', type: `text/calendar; method=${draft.calendar.method}` },
173
+ ],
174
+ },
175
+ };
176
+ }
177
+ else {
178
+ body = {
179
+ ...(textBody.length ? { textBody } : {}),
180
+ ...(htmlBody.length ? { htmlBody } : {}),
181
+ };
182
+ }
81
183
  return {
82
184
  mailboxIds: { [draftsMailboxId]: true },
83
185
  keywords: { $draft: true, $seen: true },
@@ -90,8 +192,7 @@ export function draftToEmail(draft, from, draftsMailboxId) {
90
192
  ...(draft.inReplyTo?.length ? { inReplyTo: draft.inReplyTo } : {}),
91
193
  ...(draft.references?.length ? { references: draft.references } : {}),
92
194
  bodyValues,
93
- ...(textBody.length ? { textBody } : {}),
94
- ...(htmlBody.length ? { htmlBody } : {}),
195
+ ...body,
95
196
  ...(draft.attachments?.length
96
197
  ? {
97
198
  attachments: draft.attachments.map((attachment) => ({
@@ -125,6 +226,44 @@ export function draftPatch(sentMailboxId, draftsMailboxId) {
125
226
  'keywords/$seen': null,
126
227
  };
127
228
  }
229
+ /**
230
+ * Store a draft in Drafts, so it survives the compose sheet closing.
231
+ *
232
+ * Called with the id it returned last time, it replaces that draft rather
233
+ * than adding a second. RFC 8621 messages are immutable, so "replace" is a
234
+ * create followed by a destroy; the id changes every save,
235
+ * which is why the new one is returned. The thread does not change, because
236
+ * the draft keeps its `inReplyTo` and `references`.
237
+ *
238
+ * `from` is filled from the identity when the draft has none, as `send()`
239
+ * does, so a saved draft reads the same as the message it becomes.
240
+ */
241
+ export async function saveDraft(client, draft, draftId, options = {}) {
242
+ const { jam, accountId } = await client.connect();
243
+ const tree = options.mailboxes ?? (await mailboxes(client));
244
+ const drafts = findRole(tree, 'drafts');
245
+ if (!drafts) {
246
+ throw new MailError('the account has no Drafts mailbox to save in', {
247
+ type: 'notFound',
248
+ operation: 'save draft',
249
+ });
250
+ }
251
+ let from = draft.from;
252
+ if (!from || from.length === 0) {
253
+ const identity = options.identity ?? (await identities(client)).find((one) => one.id === draft.identityId);
254
+ if (!identity) {
255
+ throw new MailError(`no identity ${draft.identityId} on this account`, {
256
+ type: 'notFound',
257
+ operation: 'save draft',
258
+ });
259
+ }
260
+ from = [{ name: identity.name, email: identity.email }];
261
+ }
262
+ return guard('save draft', async () => {
263
+ const email = await createReplacing(jam, accountId, draftToEmail(draft, from, drafts.id), draftId, 'save draft');
264
+ return { id: email.id, threadId: email.threadId };
265
+ });
266
+ }
128
267
  /**
129
268
  * Send a draft.
130
269
  *
@@ -187,14 +326,9 @@ export async function send(client, draft, options = {}) {
187
326
  rcptTo: uniqueAddresses([...draft.to, ...(draft.cc ?? []), ...(draft.bcc ?? [])]),
188
327
  }
189
328
  : undefined;
329
+ const { draftId } = options;
190
330
  return guard('send', async () => {
191
- const [created] = await jam.api.Email.set({
192
- accountId,
193
- create: { draft: draftToEmail(draft, from, drafts.id) },
194
- }, JAM_FETCH);
195
- const email = created.created?.draft;
196
- if (!email)
197
- failed('draft', created.notCreated);
331
+ const email = await createReplacing(jam, accountId, draftToEmail(draft, from, drafts.id), draftId, 'send');
198
332
  const [submitted] = await jam.api.EmailSubmission.set({
199
333
  accountId,
200
334
  create: {
@@ -1,5 +1,6 @@
1
1
  import { JAM_FETCH } from "./client.js";
2
2
  import { guard } from "./errors.js";
3
+ import { labelsOf } from "./mutate.js";
3
4
  /** What a list row needs from the newest message in each thread. */
4
5
  const SUMMARY_PROPERTIES = [
5
6
  'id',
@@ -76,6 +77,7 @@ export function summarise(threadId, latest, members) {
76
77
  hasAttachment: all.some((message) => message.hasAttachment === true),
77
78
  isFlagged: all.some((message) => keywords(message, '$flagged')),
78
79
  isDraft: keywords(latest, '$draft'),
80
+ labels: [...new Set(all.flatMap((message) => labelsOf(message.keywords)))].sort(),
79
81
  mailboxIds: [...mailboxIds],
80
82
  };
81
83
  }
@@ -5,6 +5,7 @@
5
5
  * should not have to turn that on to use this package. The JMAP wire types
6
6
  * stay behind the client.
7
7
  */
8
+ import type { CalendarPart } from '../imip/types.ts';
8
9
  /**
9
10
  * A mailbox address, with the display name when the message carried one.
10
11
  *
@@ -27,6 +28,10 @@ export type MailSession = {
27
28
  accountId: string;
28
29
  /** The account's display name. */
29
30
  accountName: string;
31
+ /** False when the account being read is not this login's own: a shared
32
+ * mailbox it is a member of, or one an ACL granted it. A composer can say
33
+ * which mailbox a reply will come from rather than assuming "me". */
34
+ isPersonal: boolean;
30
35
  isReadOnly: boolean;
31
36
  /** True when the account may submit mail, so a composer can be hidden
32
37
  * rather than failing at send. */
@@ -39,6 +44,32 @@ export type MailSession = {
39
44
  * not say, which RFC 8621 permits. */
40
45
  maxSizeAttachmentsPerEmail: number | null;
41
46
  };
47
+ /**
48
+ * One mailbox a login can read, as the session document names it.
49
+ *
50
+ * A person reaches more than their own mailbox whenever they belong to a
51
+ * shared one: the server puts every group the account is a member of, and
52
+ * everything an ACL grants it, into the same session alongside the personal
53
+ * account. Which one this package reads is fixed when the client is built
54
+ * (`MailClientOptions.accountId`), so an app that wants a switcher reads this
55
+ * list and builds a client per mailbox.
56
+ */
57
+ export type MailAccount = {
58
+ id: string;
59
+ /** The display name the server gives the account, usually its address. */
60
+ name: string;
61
+ /** False for a shared mailbox. */
62
+ isPersonal: boolean;
63
+ isReadOnly: boolean;
64
+ /** Whether mail can be sent from this account, so a shared mailbox that is
65
+ * read-only to this person does not offer a composer. */
66
+ maySubmit: boolean;
67
+ };
68
+ /** RFC 8621 §2's ten mailbox rights: what a login may do on one mailbox,
69
+ * its own or one shared with it. */
70
+ export type MailboxRight = 'mayReadItems' | 'mayAddItems' | 'mayRemoveItems' | 'maySetSeen' | 'maySetKeywords' | 'mayCreateChild' | 'mayRename' | 'maySubmit' | 'mayDelete' | 'mayShare';
71
+ /** Every right, each either granted or not. */
72
+ export type MailboxRights = Readonly<Record<MailboxRight, boolean>>;
42
73
  /** A mailbox with its children, as the tree the server's flat list describes. */
43
74
  export type MailboxNode = {
44
75
  id: string;
@@ -51,6 +82,13 @@ export type MailboxNode = {
51
82
  totalThreads: number;
52
83
  unreadThreads: number;
53
84
  isSubscribed: boolean;
85
+ /** What this login may do here — always present; the server derives it
86
+ * from ownership plus whatever `shareWith` grants. */
87
+ myRights: MailboxRights;
88
+ /** Every account this mailbox has been shared with, and the rights each
89
+ * was given. Empty when nobody but the owner can reach it. Keyed by
90
+ * account id, the same id `MailAccount.id` and `client.accounts()` use. */
91
+ shareWith: Readonly<Record<string, MailboxRights>>;
54
92
  /** The names from the root down to and including this one, e.g.
55
93
  * `['Archive', '2026']`. A stable label, and a sort key. */
56
94
  path: readonly string[];
@@ -77,6 +115,9 @@ export type ThreadSummary = {
77
115
  hasAttachment: boolean;
78
116
  isFlagged: boolean;
79
117
  isDraft: boolean;
118
+ /** Labels on any of the thread's messages, lowercase and sorted (see
119
+ * `setLabel`). */
120
+ labels: readonly string[];
80
121
  /** Every mailbox the thread's messages sit in. */
81
122
  mailboxIds: readonly string[];
82
123
  };
@@ -181,6 +222,12 @@ export type Draft = {
181
222
  /** Blobs to attach: freshly uploaded, or carried from a message being
182
223
  * forwarded. */
183
224
  attachments?: readonly DraftAttachment[];
225
+ /** A `COUNTER` or `DECLINECOUNTER` (`@wtfalch/email/imip`'s `counter`/
226
+ * `declineCounter`) to send alongside the text, RFC 6047 §2.4's shape
227
+ * every mail client uses for iTIP. `draftToEmail` sends it inline in a
228
+ * `multipart/alternative`; a draft with one may not also carry
229
+ * `attachments` (see `draftToEmail`'s doc comment for why). */
230
+ calendar?: CalendarPart;
184
231
  };
185
232
  export type DraftAttachment = {
186
233
  blobId: string;
@@ -228,6 +275,19 @@ export type Queued = {
228
275
  * assumption this type bakes in. */
229
276
  undoStatus: 'pending' | 'final' | 'canceled';
230
277
  };
278
+ /** RFC 8621 §8's out-of-office responder: one object per account, `null`
279
+ * fields left to the server's own defaults. */
280
+ export type VacationResponse = {
281
+ isEnabled: boolean;
282
+ /** The response starts here, or immediately when `null`. ISO 8601 UTC. */
283
+ fromDate: string | null;
284
+ /** The response ends here, or never when `null`. ISO 8601 UTC. */
285
+ toDate: string | null;
286
+ /** `null` lets the server pick an appropriate subject. */
287
+ subject: string | null;
288
+ textBody: string | null;
289
+ htmlBody: string | null;
290
+ };
231
291
  /** The per-type state strings a push event carries. A value that differs
232
292
  * from the one a previous call returned means that type changed. */
233
293
  export type ChangedState = {
@@ -0,0 +1,32 @@
1
+ import { type MailClient } from './client.ts';
2
+ import type { VacationResponse } from './types.ts';
3
+ /** The account's vacation response as it stands now. */
4
+ export declare function vacationResponse(client: MailClient): Promise<VacationResponse>;
5
+ export type VacationResponseOptions = {
6
+ /** Whether a message arriving now should get the auto-reply. */
7
+ isEnabled: boolean;
8
+ /** The window the response is sent in. `undefined` leaves a bound as the
9
+ * server already has it; `null` clears it -- immediately for `fromDate`,
10
+ * indefinitely for `toDate`. ISO 8601 UTC, as `Sent.sendAt` is. */
11
+ fromDate?: string | null;
12
+ toDate?: string | null;
13
+ /** `undefined` leaves it alone; `null` clears it back to the server's own
14
+ * default subject. */
15
+ subject?: string | null;
16
+ textBody?: string | null;
17
+ htmlBody?: string | null;
18
+ };
19
+ /**
20
+ * Set the vacation response: whether it is on, its window, and its message.
21
+ *
22
+ * A field left out of `options` is not sent, so the server keeps whatever it
23
+ * already has for that field; pass `null` to clear one. `isEnabled` is the
24
+ * only field that always goes -- **clearing the response, in the sense the
25
+ * host acts on, is `setVacationResponse(client, { isEnabled: false })`**,
26
+ * which leaves the dates and the message as they were so turning the
27
+ * responder back on does not need to resupply them.
28
+ */
29
+ export declare function setVacationResponse(client: MailClient, options: VacationResponseOptions): Promise<void>;
30
+ /** Turn the vacation response off, leaving its dates and message untouched.
31
+ * The one-field shorthand for `setVacationResponse(client, { isEnabled: false })`. */
32
+ export declare function clearVacationResponse(client: MailClient): Promise<void>;