@wtfalch/email 0.13.0 → 0.14.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 (44) hide show
  1. package/README.md +66 -4
  2. package/dist/mailbox/client.d.ts +22 -1
  3. package/dist/mailbox/client.js +45 -0
  4. package/dist/mailbox/fake/mailbox.js +205 -5
  5. package/dist/mailbox/index.d.ts +11 -7
  6. package/dist/mailbox/index.js +5 -3
  7. package/dist/mailbox/mail.css +13 -0
  8. package/dist/mailbox/mailboxes.d.ts +95 -1
  9. package/dist/mailbox/mailboxes.js +243 -1
  10. package/dist/mailbox/mutate.d.ts +21 -0
  11. package/dist/mailbox/mutate.js +71 -0
  12. package/dist/mailbox/quoted.d.ts +94 -0
  13. package/dist/mailbox/quoted.js +158 -0
  14. package/dist/mailbox/react/Composer.js +13 -1
  15. package/dist/mailbox/react/Mail.js +273 -33
  16. package/dist/mailbox/react/ThreadView.d.ts +13 -1
  17. package/dist/mailbox/react/ThreadView.js +5 -4
  18. package/dist/mailbox/react/index.d.ts +3 -1
  19. package/dist/mailbox/react/index.js +2 -1
  20. package/dist/mailbox/react/layout.d.ts +13 -8
  21. package/dist/mailbox/react/layout.js +36 -7
  22. package/dist/mailbox/react/quotedHtml.d.ts +105 -0
  23. package/dist/mailbox/react/quotedHtml.js +163 -0
  24. package/dist/mailbox/snooze.d.ts +48 -0
  25. package/dist/mailbox/snooze.js +176 -0
  26. package/dist/mailbox/submit.d.ts +26 -0
  27. package/dist/mailbox/submit.js +88 -7
  28. package/dist/mailbox/threads.js +2 -0
  29. package/dist/mailbox/types.d.ts +40 -0
  30. package/dist/postmaster/apply.d.ts +154 -1
  31. package/dist/postmaster/apply.js +336 -1
  32. package/dist/postmaster/audit.d.ts +22 -1
  33. package/dist/postmaster/audit.js +7 -0
  34. package/dist/postmaster/client.d.ts +49 -0
  35. package/dist/postmaster/client.js +43 -0
  36. package/dist/postmaster/index.d.ts +4 -3
  37. package/dist/postmaster/index.js +3 -2
  38. package/dist/postmaster/objects.js +11 -0
  39. package/dist/postmaster/overview.d.ts +4 -0
  40. package/dist/postmaster/queue.d.ts +111 -0
  41. package/dist/postmaster/queue.js +64 -0
  42. package/dist/postmaster/writes.d.ts +59 -0
  43. package/dist/postmaster/writes.js +106 -0
  44. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { type MailClient } from './client.ts';
2
- import type { MailboxNode, MailboxRole } from './types.ts';
2
+ import type { MailboxNode, MailboxRight, MailboxRights, MailboxRole } from './types.ts';
3
3
  /** A mailbox as the server returns it, before the tree is built. */
4
4
  export type FlatMailbox = {
5
5
  id: string;
@@ -12,6 +12,8 @@ export type FlatMailbox = {
12
12
  totalThreads: number;
13
13
  unreadThreads: number;
14
14
  isSubscribed: boolean;
15
+ myRights?: MailboxRights;
16
+ shareWith?: Readonly<Record<string, MailboxRights>>;
15
17
  };
16
18
  /**
17
19
  * Build the mailbox tree from the flat list the server returns.
@@ -31,3 +33,95 @@ export declare function walk(nodes: readonly MailboxNode[]): Generator<MailboxNo
31
33
  export declare function findRole(nodes: readonly MailboxNode[], role: MailboxRole): MailboxNode | undefined;
32
34
  /** Every mailbox in the account, as a tree. */
33
35
  export declare function mailboxes(client: MailClient): Promise<readonly MailboxNode[]>;
36
+ /** What `createMailbox` returns: enough to act on the new folder without
37
+ * another round trip. Not a `MailboxNode` -- that needs the whole tree to
38
+ * fill in `path` and `children`, which is a second `mailboxes()` call
39
+ * nobody asked for. */
40
+ export type NewMailbox = {
41
+ id: string;
42
+ name: string;
43
+ parentId: string | null;
44
+ };
45
+ export type CreateMailboxOptions = {
46
+ /** The mailbox to nest under. `null` (the default) makes a top-level folder. */
47
+ parentId?: string | null;
48
+ };
49
+ /**
50
+ * Make a folder.
51
+ *
52
+ * Never given a role: a role names one of RFC 8621 §2's fixed purposes
53
+ * (Inbox, Drafts, ...) and only the server hands one out, at account
54
+ * provisioning. A folder a person makes here is always a plain one.
55
+ */
56
+ export declare function createMailbox(client: MailClient, name: string, options?: CreateMailboxOptions): Promise<NewMailbox>;
57
+ /**
58
+ * Rename a folder.
59
+ *
60
+ * Works on any mailbox, including one with a role: a role is a purpose, not
61
+ * a label, and the two are independent -- an Inbox called something else is
62
+ * still the Inbox `findRole` returns.
63
+ */
64
+ export declare function renameMailbox(client: MailClient, mailboxId: string, name: string): Promise<void>;
65
+ export type DeleteMailboxOptions = {
66
+ /** The mailbox tree, when the caller already has it. Saves a `Mailbox/get`. */
67
+ mailboxes?: readonly MailboxNode[];
68
+ };
69
+ /**
70
+ * Delete a folder from this account.
71
+ *
72
+ * **Refused when the mailbox carries a role** (Inbox, Drafts, Sent, Junk,
73
+ * Trash, Archive, ...). Deleting someone's Inbox is not a feature, and this
74
+ * is the one rule a client must never delegate to the server's own refusal
75
+ * -- a folder picker has no business reaching it in the first place. This
76
+ * is a folder inside one's own account, which is a different thing from
77
+ * deleting a whole *mailbox* (an account): that stays out of scope, because
78
+ * a mailbox is somebody's entire mail.
79
+ *
80
+ * **Also refused when the mailbox is not in the tree being checked.** A
81
+ * miss there is not proof the mailbox is role-free -- it just as easily
82
+ * means `options.mailboxes` was a filtered or stale subset, a cache read
83
+ * before the tree settled, or a caller's mistake. Deleting on "I could not
84
+ * find it" is deleting on "I could not check", and the one rule above does
85
+ * not get to depend on the tree being complete.
86
+ *
87
+ * A mailbox with children, or mail still in it, is the server's call to
88
+ * refuse; this does not guess at those.
89
+ */
90
+ export declare function deleteMailbox(client: MailClient, mailboxId: string, options?: DeleteMailboxOptions): Promise<void>;
91
+ /**
92
+ * Give another account rights on one folder, without account-level
93
+ * shared-mailbox membership: the RFC 8621 §2 `shareWith`/`myRights` pair,
94
+ * one grant per account, per mailbox.
95
+ *
96
+ * **Sent as a JSON Pointer patch key, `shareWith/<accountId>`, never as a
97
+ * whole `shareWith` object.** A whole-property `update` replaces every
98
+ * grant on the mailbox; a caller re-reading the tree first and sending it
99
+ * back would still lose a grant made by someone else between the read and
100
+ * the write, the same race `mailbox()` cannot close for any list-shaped
101
+ * property. The patch key touches exactly this one account's entry and
102
+ * nothing else's, so no read-before-write is needed here at all.
103
+ *
104
+ * `rights` need not be every right: an omitted one is refused, not
105
+ * granted -- the server fills in `false` for anything left out (confirmed
106
+ * against `stalwartlabs/stalwart` v0.16.20, `tests/src/jmap/contacts/acl.rs`,
107
+ * whose `AddressBook` uses the same `shareWith`/`myRights` machinery as
108
+ * `Mailbox`). A grant with nothing in it is refused before the wire, since
109
+ * sending one would silently add an entry to `shareWith` that lets its
110
+ * account do nothing at all -- a caller's mistake, not a share.
111
+ *
112
+ * **Only the ten named rights ever reach the wire.** `rights` is filtered
113
+ * against {@link RIGHT_KEYS} before anything else, rather than forwarded
114
+ * as the caller shaped it: a typo'd or made-up key (`notARight: true`) is
115
+ * not this function's business to send, and if it were the only truthy key
116
+ * the "grants nothing" refusal below would miss it entirely -- every real
117
+ * right would still read back `false`.
118
+ */
119
+ export declare function shareMailbox(client: MailClient, mailboxId: string, accountId: string, rights: Partial<Record<MailboxRight, boolean>>): Promise<void>;
120
+ /**
121
+ * Take back every right a colleague had on one folder. The mirror of
122
+ * {@link shareMailbox}, and the same reason it patches rather than
123
+ * replaces: `shareWith/<accountId>: null` deletes exactly that account's
124
+ * entry (RFC 8620 §5.3's rule for a patch value of `null`) and leaves
125
+ * every other grant on the mailbox untouched.
126
+ */
127
+ export declare function unshareMailbox(client: MailClient, mailboxId: string, accountId: string): Promise<void>;
@@ -1,5 +1,33 @@
1
1
  import { JAM_FETCH } from "./client.js";
2
- import { guard } from "./errors.js";
2
+ import { MailError, guard } from "./errors.js";
3
+ const RIGHT_KEYS = [
4
+ 'mayReadItems',
5
+ 'mayAddItems',
6
+ 'mayRemoveItems',
7
+ 'maySetSeen',
8
+ 'maySetKeywords',
9
+ 'mayCreateChild',
10
+ 'mayRename',
11
+ 'maySubmit',
12
+ 'mayDelete',
13
+ 'mayShare',
14
+ ];
15
+ /**
16
+ * Every right closed unless `partial` says otherwise. A grant on the wire
17
+ * -- `shareWith`'s per-account object, `myRights` -- is confirmed to come
18
+ * back with every key present once one is set (`stalwartlabs/stalwart`
19
+ * v0.16.20, `tests/src/jmap/contacts/acl.rs`: granting `{mayRead: true}`
20
+ * reads back with `mayWrite`, `mayDelete` and `mayShare` all explicit
21
+ * `false`), but a mailbox nobody has shared, an older fixture, or a
22
+ * hand-built `FlatMailbox` in a test may carry a partial object or none at
23
+ * all. This is what makes either shape safe to read as a `MailboxRights`.
24
+ */
25
+ function normaliseRights(partial) {
26
+ const out = {};
27
+ for (const key of RIGHT_KEYS)
28
+ out[key] = partial?.[key] === true;
29
+ return out;
30
+ }
3
31
  /** RFC 8621 §2: order by `sortOrder`, and break ties by name. */
4
32
  function compare(a, b) {
5
33
  if (a.sortOrder !== b.sortOrder)
@@ -52,6 +80,11 @@ export function buildTree(list) {
52
80
  totalThreads: mailbox.totalThreads,
53
81
  unreadThreads: mailbox.unreadThreads,
54
82
  isSubscribed: mailbox.isSubscribed,
83
+ myRights: normaliseRights(mailbox.myRights),
84
+ shareWith: Object.fromEntries(Object.entries(mailbox.shareWith ?? {}).map(([accountId, rights]) => [
85
+ accountId,
86
+ normaliseRights(rights),
87
+ ])),
55
88
  path,
56
89
  children,
57
90
  };
@@ -94,6 +127,8 @@ const MAILBOX_PROPERTIES = [
94
127
  'totalThreads',
95
128
  'unreadThreads',
96
129
  'isSubscribed',
130
+ 'myRights',
131
+ 'shareWith',
97
132
  ];
98
133
  /** Every mailbox in the account, as a tree. */
99
134
  export async function mailboxes(client) {
@@ -101,8 +136,215 @@ export async function mailboxes(client) {
101
136
  return guard('mailboxes', async () => {
102
137
  const [result] = await jam.api.Mailbox.get({
103
138
  accountId,
139
+ // `jmap-jam`'s `Mailbox` (from `jmap-rfc-types`) only covers RFC 8621's
140
+ // core properties, not the `shareWith`/`myRights` sharing extension --
141
+ // the same reason `snooze.ts:103` casts against `Mailbox/set`. Sent
142
+ // as plain strings regardless of what the type says.
104
143
  properties: MAILBOX_PROPERTIES,
105
144
  }, JAM_FETCH);
106
145
  return buildTree(result.list);
107
146
  });
108
147
  }
148
+ /**
149
+ * Make a folder.
150
+ *
151
+ * Never given a role: a role names one of RFC 8621 §2's fixed purposes
152
+ * (Inbox, Drafts, ...) and only the server hands one out, at account
153
+ * provisioning. A folder a person makes here is always a plain one.
154
+ */
155
+ export async function createMailbox(client, name, options = {}) {
156
+ const trimmed = name.trim();
157
+ if (!trimmed) {
158
+ throw new MailError('a folder needs a name', {
159
+ type: 'invalidArguments',
160
+ operation: 'create mailbox',
161
+ });
162
+ }
163
+ const { jam, accountId } = await client.connect();
164
+ const parentId = options.parentId ?? null;
165
+ return guard('create mailbox', async () => {
166
+ const [result] = await jam.api.Mailbox.set({ accountId, create: { folder: { name: trimmed, parentId } } }, JAM_FETCH);
167
+ const made = result.created?.folder;
168
+ if (!made) {
169
+ const failure = Object.values((result.notCreated ?? {}))[0];
170
+ throw new MailError(failure?.description ?? 'the server would not make the folder', {
171
+ type: failure?.type ?? 'unknown',
172
+ operation: 'create mailbox',
173
+ });
174
+ }
175
+ return { id: made.id, name: trimmed, parentId };
176
+ });
177
+ }
178
+ /**
179
+ * Rename a folder.
180
+ *
181
+ * Works on any mailbox, including one with a role: a role is a purpose, not
182
+ * a label, and the two are independent -- an Inbox called something else is
183
+ * still the Inbox `findRole` returns.
184
+ */
185
+ export async function renameMailbox(client, mailboxId, name) {
186
+ const trimmed = name.trim();
187
+ if (!trimmed) {
188
+ throw new MailError('a folder needs a name', {
189
+ type: 'invalidArguments',
190
+ operation: 'rename mailbox',
191
+ });
192
+ }
193
+ const { jam, accountId } = await client.connect();
194
+ return guard('rename mailbox', async () => {
195
+ const [result] = await jam.api.Mailbox.set({ accountId, update: { [mailboxId]: { name: trimmed } } }, JAM_FETCH);
196
+ const notUpdated = result.notUpdated;
197
+ const failure = notUpdated?.[mailboxId];
198
+ if (failure) {
199
+ throw new MailError(failure.description ?? 'the server refused to rename the folder', {
200
+ type: failure.type ?? 'unknown',
201
+ operation: 'rename mailbox',
202
+ });
203
+ }
204
+ });
205
+ }
206
+ /**
207
+ * Delete a folder from this account.
208
+ *
209
+ * **Refused when the mailbox carries a role** (Inbox, Drafts, Sent, Junk,
210
+ * Trash, Archive, ...). Deleting someone's Inbox is not a feature, and this
211
+ * is the one rule a client must never delegate to the server's own refusal
212
+ * -- a folder picker has no business reaching it in the first place. This
213
+ * is a folder inside one's own account, which is a different thing from
214
+ * deleting a whole *mailbox* (an account): that stays out of scope, because
215
+ * a mailbox is somebody's entire mail.
216
+ *
217
+ * **Also refused when the mailbox is not in the tree being checked.** A
218
+ * miss there is not proof the mailbox is role-free -- it just as easily
219
+ * means `options.mailboxes` was a filtered or stale subset, a cache read
220
+ * before the tree settled, or a caller's mistake. Deleting on "I could not
221
+ * find it" is deleting on "I could not check", and the one rule above does
222
+ * not get to depend on the tree being complete.
223
+ *
224
+ * A mailbox with children, or mail still in it, is the server's call to
225
+ * refuse; this does not guess at those.
226
+ */
227
+ export async function deleteMailbox(client, mailboxId, options = {}) {
228
+ const tree = options.mailboxes ?? (await mailboxes(client));
229
+ const target = [...walk(tree)].find((node) => node.id === mailboxId);
230
+ if (!target) {
231
+ throw new MailError(`mailbox ${mailboxId} is not in the tree checked for a role, so the delete is refused rather than risked`, { type: 'forbidden', operation: 'delete mailbox' });
232
+ }
233
+ if (target.role) {
234
+ throw new MailError(`"${target.name}" is the ${target.role} mailbox and cannot be deleted`, {
235
+ type: 'forbidden',
236
+ operation: 'delete mailbox',
237
+ });
238
+ }
239
+ const { jam, accountId } = await client.connect();
240
+ return guard('delete mailbox', async () => {
241
+ const [result] = await jam.api.Mailbox.set({ accountId, destroy: [mailboxId] }, JAM_FETCH);
242
+ const notDestroyed = result.notDestroyed;
243
+ const failure = notDestroyed?.[mailboxId];
244
+ if (failure) {
245
+ throw new MailError(failure.description ?? 'the server refused to delete the folder', {
246
+ type: failure.type ?? 'unknown',
247
+ operation: 'delete mailbox',
248
+ });
249
+ }
250
+ });
251
+ }
252
+ /** RFC 6901 §3, the same escape `mutate.ts` needs for a mailbox id inside a
253
+ * pointer segment: `~` and `/` are escaped, and an account id is the
254
+ * server's to shape, not this package's. */
255
+ function pointer(segment) {
256
+ return segment.replaceAll('~', '~0').replaceAll('/', '~1');
257
+ }
258
+ /**
259
+ * Give another account rights on one folder, without account-level
260
+ * shared-mailbox membership: the RFC 8621 §2 `shareWith`/`myRights` pair,
261
+ * one grant per account, per mailbox.
262
+ *
263
+ * **Sent as a JSON Pointer patch key, `shareWith/<accountId>`, never as a
264
+ * whole `shareWith` object.** A whole-property `update` replaces every
265
+ * grant on the mailbox; a caller re-reading the tree first and sending it
266
+ * back would still lose a grant made by someone else between the read and
267
+ * the write, the same race `mailbox()` cannot close for any list-shaped
268
+ * property. The patch key touches exactly this one account's entry and
269
+ * nothing else's, so no read-before-write is needed here at all.
270
+ *
271
+ * `rights` need not be every right: an omitted one is refused, not
272
+ * granted -- the server fills in `false` for anything left out (confirmed
273
+ * against `stalwartlabs/stalwart` v0.16.20, `tests/src/jmap/contacts/acl.rs`,
274
+ * whose `AddressBook` uses the same `shareWith`/`myRights` machinery as
275
+ * `Mailbox`). A grant with nothing in it is refused before the wire, since
276
+ * sending one would silently add an entry to `shareWith` that lets its
277
+ * account do nothing at all -- a caller's mistake, not a share.
278
+ *
279
+ * **Only the ten named rights ever reach the wire.** `rights` is filtered
280
+ * against {@link RIGHT_KEYS} before anything else, rather than forwarded
281
+ * as the caller shaped it: a typo'd or made-up key (`notARight: true`) is
282
+ * not this function's business to send, and if it were the only truthy key
283
+ * the "grants nothing" refusal below would miss it entirely -- every real
284
+ * right would still read back `false`.
285
+ */
286
+ export async function shareMailbox(client, mailboxId, accountId, rights) {
287
+ const target = accountId.trim();
288
+ if (!target) {
289
+ throw new MailError('sharing a folder needs the account to share it with', {
290
+ type: 'invalidArguments',
291
+ operation: 'share mailbox',
292
+ });
293
+ }
294
+ const granted = {};
295
+ for (const key of RIGHT_KEYS)
296
+ if (rights[key] === true)
297
+ granted[key] = true;
298
+ if (Object.keys(granted).length === 0) {
299
+ throw new MailError('a share needs at least one right granted, or it shares nothing', {
300
+ type: 'invalidArguments',
301
+ operation: 'share mailbox',
302
+ });
303
+ }
304
+ const { jam, accountId: myAccountId } = await client.connect();
305
+ return guard('share mailbox', async () => {
306
+ const [result] = await jam.api.Mailbox.set({
307
+ accountId: myAccountId,
308
+ update: { [mailboxId]: { [`shareWith/${pointer(target)}`]: granted } },
309
+ }, JAM_FETCH);
310
+ const notUpdated = result.notUpdated;
311
+ const failure = notUpdated?.[mailboxId];
312
+ if (failure) {
313
+ throw new MailError(failure.description ?? 'the server refused to share the folder', {
314
+ type: failure.type ?? 'unknown',
315
+ operation: 'share mailbox',
316
+ });
317
+ }
318
+ });
319
+ }
320
+ /**
321
+ * Take back every right a colleague had on one folder. The mirror of
322
+ * {@link shareMailbox}, and the same reason it patches rather than
323
+ * replaces: `shareWith/<accountId>: null` deletes exactly that account's
324
+ * entry (RFC 8620 §5.3's rule for a patch value of `null`) and leaves
325
+ * every other grant on the mailbox untouched.
326
+ */
327
+ export async function unshareMailbox(client, mailboxId, accountId) {
328
+ const target = accountId.trim();
329
+ if (!target) {
330
+ throw new MailError('revoking a share needs the account to revoke it from', {
331
+ type: 'invalidArguments',
332
+ operation: 'unshare mailbox',
333
+ });
334
+ }
335
+ const { jam, accountId: myAccountId } = await client.connect();
336
+ return guard('unshare mailbox', async () => {
337
+ const [result] = await jam.api.Mailbox.set({
338
+ accountId: myAccountId,
339
+ update: { [mailboxId]: { [`shareWith/${pointer(target)}`]: null } },
340
+ }, JAM_FETCH);
341
+ const notUpdated = result.notUpdated;
342
+ const failure = notUpdated?.[mailboxId];
343
+ if (failure) {
344
+ throw new MailError(failure.description ?? 'the server refused to unshare the folder', {
345
+ type: failure.type ?? 'unknown',
346
+ operation: 'unshare mailbox',
347
+ });
348
+ }
349
+ });
350
+ }
@@ -49,3 +49,24 @@ export declare function moveToRole(client: MailClient, threadId: string, role: M
49
49
  * its other filings. Patches a single pointer rather than the property.
50
50
  */
51
51
  export declare function removeFromMailbox(client: MailClient, threadId: string, mailboxId: string): Promise<readonly string[]>;
52
+ /** The keyword for a label, or a refusal naming why it cannot be one. */
53
+ export declare function labelKeyword(label: string): string;
54
+ /** The labels in a set of keywords, sorted. */
55
+ export declare function labelsOf(keywords: Readonly<Record<string, boolean>> | undefined): string[];
56
+ /** Put a label on every message in a thread, or take it off. Other labels
57
+ * and the thread's mailboxes are untouched. */
58
+ export declare function setLabel(client: MailClient, threadId: string, label: string, on: boolean): Promise<readonly string[]>;
59
+ export type ListLabelsOptions = {
60
+ /** How many of the newest messages to look at. Default 500. */
61
+ scan?: number;
62
+ };
63
+ /**
64
+ * The labels in use, sorted.
65
+ *
66
+ * **Read from the newest messages, not the whole account.** JMAP can
67
+ * search for one keyword but cannot list them, or filter by prefix, so
68
+ * this reads the keywords of the newest `scan` messages. A label used only
69
+ * on older mail is missing from the answer. Raise `scan` to look further
70
+ * back, at the cost of a larger response.
71
+ */
72
+ export declare function listLabels(client: MailClient, options?: ListLabelsOptions): Promise<readonly string[]>;
@@ -130,3 +130,74 @@ export async function moveToRole(client, threadId, role, options = {}) {
130
130
  export function removeFromMailbox(client, threadId, mailboxId) {
131
131
  return patchThread(client, threadId, { [`mailboxIds/${pointer(mailboxId)}`]: null }, 'move');
132
132
  }
133
+ /**
134
+ * Labels: a tag on a thread that is not a folder. One thread, several
135
+ * labels, and still in the Inbox -- the thing `moveThread` cannot do, since
136
+ * a message sits where it is filed.
137
+ *
138
+ * **A label is the keyword `$label:<name>`.** RFC 8621 keywords are
139
+ * case-insensitive, so a label is lowercased: "Finance" and "finance" are
140
+ * one label, and it reads back as "finance". A name with a character a
141
+ * keyword cannot hold (a space, any of `(){]%*"\`, anything outside
142
+ * printable ASCII) is refused rather than silently rewritten, so what is
143
+ * set is always what comes back.
144
+ */
145
+ const LABEL = '$label:';
146
+ /** The keyword for a label, or a refusal naming why it cannot be one. */
147
+ export function labelKeyword(label) {
148
+ const name = label.trim().toLowerCase();
149
+ if (!name || !/^[\x21-\x7e]+$/.test(name) || /[(){\]%*"\\]/.test(name)) {
150
+ throw new MailError(`"${label}" cannot be a label: use letters, digits and punctuation, with no spaces or any of (){]%*"\\`, { type: 'invalidArguments', operation: 'label' });
151
+ }
152
+ if (LABEL.length + name.length > 255) {
153
+ throw new MailError(`"${label}" is too long for a label`, {
154
+ type: 'invalidArguments',
155
+ operation: 'label',
156
+ });
157
+ }
158
+ return `${LABEL}${name}`;
159
+ }
160
+ /** The labels in a set of keywords, sorted. */
161
+ export function labelsOf(keywords) {
162
+ return Object.keys(keywords ?? {})
163
+ .filter((keyword) => keyword.startsWith(LABEL) && keywords?.[keyword])
164
+ .map((keyword) => keyword.slice(LABEL.length))
165
+ .sort();
166
+ }
167
+ /** Put a label on every message in a thread, or take it off. Other labels
168
+ * and the thread's mailboxes are untouched. */
169
+ export async function setLabel(client, threadId, label, on) {
170
+ const keyword = labelKeyword(label);
171
+ return patchThread(client, threadId, { [`keywords/${pointer(keyword)}`]: on ? true : null }, on ? 'label' : 'unlabel');
172
+ }
173
+ /**
174
+ * The labels in use, sorted.
175
+ *
176
+ * **Read from the newest messages, not the whole account.** JMAP can
177
+ * search for one keyword but cannot list them, or filter by prefix, so
178
+ * this reads the keywords of the newest `scan` messages. A label used only
179
+ * on older mail is missing from the answer. Raise `scan` to look further
180
+ * back, at the cost of a larger response.
181
+ */
182
+ export async function listLabels(client, options = {}) {
183
+ const { jam, accountId } = await client.connect();
184
+ const scan = options.scan ?? 500;
185
+ return guard('labels', async () => {
186
+ const [results] = await jam.requestMany((t) => {
187
+ const query = t.Email.query({
188
+ accountId,
189
+ sort: [{ property: 'receivedAt', isAscending: false }],
190
+ limit: scan,
191
+ });
192
+ const emails = t.Email.get({ accountId, ids: query.$ref('/ids'), properties: ['keywords'] });
193
+ // `query` has to come back too, or it is never sent (see `queued()`).
194
+ return { query, emails };
195
+ }, JAM_FETCH);
196
+ const found = new Set();
197
+ for (const email of results.emails.list) {
198
+ for (const label of labelsOf(email.keywords))
199
+ found.add(label);
200
+ }
201
+ return [...found].sort();
202
+ });
203
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Finding the line where a received message's own words end and the quoted
3
+ * history it carries begins.
4
+ *
5
+ * This is `quoteText` (./drafts.ts) run backwards: that one takes a message
6
+ * and adds the `>` markers so a reply can carry the original along; this one
7
+ * takes a message that already has them and finds where they start.
8
+ * Composing a reply is pure text-building with no failure mode. Reading one
9
+ * is a heuristic that can guess wrong on a message this package never wrote,
10
+ * so it gets its own module, its own contract, and its own tests for the
11
+ * cases it is known not to cover.
12
+ *
13
+ * **The result is a boundary, not a summary.** A caller collapsing the
14
+ * thread view renders `body` and offers `quoted` behind a disclosure; a
15
+ * caller that wants everything just concatenates them back. `body + quoted`
16
+ * is always exactly the original string: nothing is trimmed, reformatted or
17
+ * thrown away in either half. A message with no quoted history returns the
18
+ * whole thing as `body` and `''` as `quoted`; a bare forward that is nothing
19
+ * but quoted history returns `''` as `body` and the whole thing as `quoted`.
20
+ *
21
+ * **HTML quote detection is not in this file, on purpose.** The natural tool
22
+ * for `<blockquote>`, Gmail's `gmail_quote` class and Outlook's `<div
23
+ * style="border-top:...">` divider is the inert-`DOMParser` walk this
24
+ * package already has, in `mailbox/react/sanitise.ts` — reusing it beats
25
+ * writing a second HTML parser or reaching for a regex over markup. But that
26
+ * file lives under `mailbox/react/`, the browser-only half of this package
27
+ * (`mailDocument`'s own doc comment: "Browser only: it needs `DOMParser`"),
28
+ * while this module is exported from `mailbox/index.ts`, the JMAP client
29
+ * core that has no `react` peer dependency and has to keep working with no
30
+ * DOM at all — `MailClient` is plain fetch and JSON. Importing
31
+ * `sanitise.ts` from here would make the core depend on the UI layer it is
32
+ * built under, and would make `@wtfalch/email/mailbox` throw in Node the
33
+ * first time a caller touched an HTML message. The HTML half belongs beside
34
+ * `sanitise.ts`, under `mailbox/react/`, as its own follow-up; this ships
35
+ * the text half only. See the PR body for the issue this opens.
36
+ */
37
+ import type { Message } from './types.ts';
38
+ /** The boundary between a message's own text and the quoted history under
39
+ * it, materialised as the two slices on either side. Concatenating them
40
+ * always reproduces the original string. */
41
+ export type QuoteBoundary = {
42
+ /** The reader's own words: everything before the first quote marker. */
43
+ body: string;
44
+ /** The quoted history, verbatim from the first marker line to the end.
45
+ * `''` when the message carries none. */
46
+ quoted: string;
47
+ };
48
+ /**
49
+ * Where a received plain-text body's own words end and its quoted history
50
+ * begins.
51
+ *
52
+ * Covers three marker forms, deliberately not more:
53
+ * - `>` (and `>>`, nested) leading a line — but only when nothing but blank
54
+ * lines and further `>` lines follow it to the end of the message. A
55
+ * pasted diff (`> - old line`) or a Markdown quote (`> To be or not to
56
+ * be...`) followed by the sender's own text is not mail history and is
57
+ * left alone.
58
+ * - `On <when>, <who> wrote:` alone on a line.
59
+ * - `-----Original Message-----` alone on a line.
60
+ *
61
+ * Not covered, deliberately, because the issue budgets English and the
62
+ * marker forms above, not every locale:
63
+ * - a localised attribution or divider (French `Le ... a écrit :`, German
64
+ * `-----Ursprüngliche Nachricht-----`, Norwegian `-----Opprinnelig
65
+ * melding-----`, ...).
66
+ * - Apple Mail's `Begin forwarded message:` header (no dashes, no
67
+ * `wrote:`).
68
+ * - an attribution or divider line a client's own wrap split across two
69
+ * lines.
70
+ * - a genuine reply interleaved *between* two `>` blocks (quote, new text,
71
+ * quote): the trailing-only rule above is what keeps a pasted diff out of
72
+ * `quoted`, but it costs the same thing here on purpose — the first `>`
73
+ * line gets one attempt, finds real text after it, and gives up for the
74
+ * whole message rather than guessing which later `>` block is the real
75
+ * one. The entire message stays as `body`, unsplit. That is the safe
76
+ * direction to be wrong in: nothing new is ever lost into `quoted`, only
77
+ * nothing gets collapsed.
78
+ * - a stray `On ... wrote:` sentence that is someone's actual new writing,
79
+ * alone on its own line, rather than a header. Unlike the `>` leader this
80
+ * one is not checked for trailing content, so it is a real false
81
+ * positive: everything from that line to the end of the message —
82
+ * however much text that is — is read as quoted history and disappears
83
+ * from `body`.
84
+ *
85
+ * A message that trips none of the three markers keeps its whole text as
86
+ * `body` — the same answer this gives a message with no quoted history at
87
+ * all, which is the safe direction to be wrong in: nothing is hidden, it is
88
+ * just not collapsed.
89
+ */
90
+ export declare function splitQuoted(text: string): QuoteBoundary;
91
+ /** `splitQuoted` against a received message's own plain-text body. A
92
+ * message with no text body (HTML-only) has nothing to split: the whole
93
+ * boundary is empty, not a guess. */
94
+ export declare function quoteBoundary(message: Pick<Message, 'text'>): QuoteBoundary;