@open-workspace/email 0.2.0 → 0.4.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 (223) hide show
  1. package/README.md +23 -20
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/0000_dry_moon_knight.sql +77 -0
  11. package/migrations/meta/0000_snapshot.json +248 -106
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +78 -26
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +90 -34
  127. package/worker/jmap/eventsource.ts +169 -0
  128. package/worker/jmap/methods.ts +1716 -361
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +207 -0
  131. package/worker/jmap/routes.ts +448 -86
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +84 -52
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +283 -171
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +871 -542
  184. package/worker/mail/safety-routes.ts +329 -202
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +153 -91
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +597 -227
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1761 -737
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +7 -14
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -126
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/migrations/0000_email.sql +0 -53
  218. package/shared/mail-rules.ts +0 -156
  219. package/worker/admin/report-routes.ts +0 -164
  220. package/worker/mail/reported-messages.ts +0 -68
  221. package/worker/mailbox/legacy-migrations.ts +0 -41
  222. package/worker/mailbox/migrations.ts +0 -10
  223. package/worker/mailbox/rules.ts +0 -110
@@ -1,10 +1,35 @@
1
+ import {
2
+ createDb,
3
+ describeIssues,
4
+ issueProperties,
5
+ } from "@open-workspace/core/module";
6
+ import type { Issue } from "@open-workspace/core/module";
7
+ import { and, eq, inArray } from "drizzle-orm";
8
+ import { z } from "zod";
9
+
10
+ import { MAX_COMPOSER_ATTACHMENT_COUNT } from "../../shared/mail";
11
+ import {
12
+ MAIL_ORGANIZE_SCOPE,
13
+ MAIL_READ_SCOPE,
14
+ MAIL_SEND_SCOPE,
15
+ } from "../../shared/permissions";
16
+ import { jmapPushSubscriptions } from "../db/schema";
17
+ import { submitOutgoing } from "../mail/outbound-service";
18
+ import { composeSchema } from "../mail/schemas";
19
+ import { describeComposerUpload, UploadValidationError } from "../mail/uploads";
1
20
  import { mailboxStub } from "../mailbox";
2
- import type { Email } from "../mailbox/schema";
3
21
  import type { JmapEmailFilter, JmapMailboxRow } from "../mailbox/jmap-store";
4
- import { submitOutgoing } from "../mail/outbound-service";
22
+ import type { Email } from "../mailbox/schema";
23
+ import {
24
+ newVerificationCode,
25
+ sendVerification,
26
+ subscriptionExpiry,
27
+ } from "./push";
28
+ import type { PushVapid } from "./push";
5
29
 
6
30
  const CORE = "urn:ietf:params:jmap:core";
7
31
  const MAX_OBJECTS = 500;
32
+ const MAX_CALLS = 32;
8
33
 
9
34
  export type JmapAccount = {
10
35
  id: string;
@@ -19,118 +44,347 @@ export type JmapAccount = {
19
44
  export type JmapContext = {
20
45
  env: Env;
21
46
  user: { id: string; name: string };
47
+ /** The OAuth client the token was issued to; push subscriptions belong to it. */
48
+ clientId: string;
49
+ /** The token's mail scopes; each method needs its own (`scopes` of its definition). */
50
+ scopes: readonly string[];
51
+ /** Signs pushes to Web Push services; null when push is not configured. */
52
+ vapid: PushVapid | null;
22
53
  accounts: JmapAccount[];
23
54
  requestUrl: string;
24
55
  defer: (task: Promise<unknown>) => void;
25
56
  };
26
57
 
27
- type Args = Record<string, unknown>;
28
- type Invocation = [string, Args, string];
58
+ type Json = z.core.util.JSONType;
59
+
60
+ type JsonObject = Record<string, Json>;
61
+
62
+ /** RFC 8620 §3.3: a request is the capabilities it uses and its method calls. */
63
+ export const jmapRequestSchema = z.object({
64
+ using: z.array(z.string()),
65
+ methodCalls: z.array(
66
+ z.tuple([z.string(), z.record(z.string(), z.json()), z.string()])
67
+ ),
68
+ createdIds: z.record(z.string(), z.string()).optional(),
69
+ });
70
+
71
+ export type JmapRequest = z.output<typeof jmapRequestSchema>;
72
+
73
+ type Invocation = [string, JsonObject, string];
29
74
 
30
75
  /** A request-level error (RFC 8620 §3.6.1), answered as a problem document. */
31
76
  export class JmapError extends Error {
32
- constructor(readonly type: string, message: string) {
77
+ constructor(
78
+ readonly type: string,
79
+ message: string
80
+ ) {
33
81
  super(message);
34
82
  }
35
83
  }
36
84
 
37
- /** A method-level error (RFC 8620 §3.6.2), answered in place of the method's response. */
85
+ /** The method-level errors (RFC 8620 §3.6.2, RFC 8621) these methods answer with. */
86
+ const methodErrorTypes = z.enum([
87
+ "accountNotFound",
88
+ "cannotCalculateChanges",
89
+ "forbidden",
90
+ "invalidArguments",
91
+ "invalidResultReference",
92
+ "requestTooLarge",
93
+ "stateMismatch",
94
+ "unknownMethod",
95
+ "unsupportedFilter",
96
+ "unsupportedSort",
97
+ ]);
98
+
99
+ type MethodErrorType = z.output<typeof methodErrorTypes>;
100
+
101
+ /** A method-level error, answered in place of the method's response. */
38
102
  class MethodError extends Error {
39
- constructor(readonly type: string, message?: string) {
103
+ constructor(
104
+ readonly type: MethodErrorType,
105
+ message?: string
106
+ ) {
40
107
  super(message ?? type);
41
108
  }
42
109
  }
43
110
 
44
- /** A draft from Email/set create; it lives only for the request that sends it. */
111
+ /** Uploaded blobs are named after their upload: `upl~<upload id>`. */
112
+ export const UPLOAD_BLOB = /^upl~(upl_[a-f0-9]{32})$/u;
113
+
114
+ /** An attachment of a draft: bytes from /jmap/upload. */
115
+ type DraftAttachment = {
116
+ uploadId: string;
117
+ name: string;
118
+ type: string;
119
+ disposition: "attachment" | "inline";
120
+ contentId: string | undefined;
121
+ };
122
+
123
+ /**
124
+ * A draft from Email/set create; it lives only for the request that sends
125
+ * it. It holds the message as the mail app's composer would send it.
126
+ */
45
127
  type Draft = {
46
128
  accountId: string;
47
- to: string[];
48
- cc: string[];
49
- bcc: string[];
50
- subject: string;
51
- bodyText: string;
52
- bodyHtml?: string;
129
+ compose: z.output<typeof composeSchema>;
130
+ attachments: DraftAttachment[];
53
131
  };
54
132
 
133
+ /** The Email property a composer field comes from. */
134
+ function draftProperty(field: string) {
135
+ if (field === "bodyText") return "textBody";
136
+
137
+ if (field === "bodyHtml") return "htmlBody";
138
+
139
+ return field;
140
+ }
141
+
142
+ /**
143
+ * A composer issue, at the Email property it is about. Issues about the
144
+ * message as a whole are about its recipients.
145
+ */
146
+ function draftIssue(issue: Issue): Issue {
147
+ const [field = "to", ...rest] = issue.path;
148
+
149
+ return { ...issue, path: [draftProperty(String(field)), ...rest] };
150
+ }
151
+
55
152
  type RequestState = {
56
153
  context: JmapContext;
57
154
  responses: Invocation[];
58
- createdIds: Record<string, string>;
155
+ createdIds: Map<string, string>;
59
156
  drafts: Map<string, Draft>;
60
157
  /** Responses a method adds after its own, e.g. an implicit Email/set. */
61
158
  after: Invocation[];
62
159
  };
63
160
 
64
- function isRecord(value: unknown): value is Record<string, unknown> {
65
- return typeof value === "object" && value !== null && !Array.isArray(value);
161
+ /** Arrays and objects are the JSON values a pointer steps into. */
162
+ function isJsonObject(value: Json): value is JsonObject {
163
+ return Object(value) === value && !Array.isArray(value);
66
164
  }
67
165
 
68
166
  // ---------------------------------------------------------------- references
69
167
 
70
168
  /** RFC 8620 §3.7: a JSON Pointer where `*` maps over an array. */
71
- function evaluatePointer(value: unknown, path: string): unknown {
169
+ function evaluatePointer(value: Json, path: string): Json {
72
170
  if (path === "") return value;
73
- const [head, ...rest] = path.slice(1).split("/").map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
171
+
172
+ const [head = "", ...rest] = path
173
+ .slice(1)
174
+ .split("/")
175
+ .map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
176
+
74
177
  const tail = rest.length ? `/${rest.join("/")}` : "";
75
- if (head === "*" && Array.isArray(value)) {
76
- return value.flatMap((item) => {
77
- const result = evaluatePointer(item, tail);
78
- return Array.isArray(result) ? result : [result];
79
- });
178
+
179
+ if (Array.isArray(value)) {
180
+ if (head === "*") {
181
+ return value.flatMap((item) => {
182
+ const result = evaluatePointer(item, tail);
183
+
184
+ return Array.isArray(result) ? result : [result];
185
+ });
186
+ }
187
+
188
+ const item = /^\d+$/u.test(head) ? value[Number(head)] : undefined;
189
+
190
+ if (item !== undefined) return evaluatePointer(item, tail);
191
+ } else if (isJsonObject(value) && Object.hasOwn(value, head)) {
192
+ const property = value[head];
193
+
194
+ if (property !== undefined) return evaluatePointer(property, tail);
80
195
  }
81
- if (Array.isArray(value) && /^\d+$/u.test(head!)) return evaluatePointer(value[Number(head)], tail);
82
- if (isRecord(value) && head! in value) return evaluatePointer(value[head!], tail);
83
- throw new MethodError("invalidResultReference", `Path ${path} does not resolve`);
196
+
197
+ throw new MethodError(
198
+ "invalidResultReference",
199
+ `Path ${path} does not resolve`
200
+ );
84
201
  }
85
202
 
86
- function resolveReferences(state: RequestState, args: Args): Args {
87
- const resolved: Args = {};
203
+ const resultReference = z.object({
204
+ resultOf: z.string(),
205
+ name: z.string(),
206
+ path: z.string(),
207
+ });
208
+
209
+ function resolveReferences(state: RequestState, args: JsonObject) {
210
+ const resolved: JsonObject = {};
211
+
88
212
  for (const [key, value] of Object.entries(args)) {
89
213
  if (!key.startsWith("#")) {
90
214
  resolved[key] = value;
91
215
  continue;
92
216
  }
217
+
93
218
  const name = key.slice(1);
94
- if (name in args) throw new MethodError("invalidArguments", `Both ${name} and #${name} given`);
95
- if (!isRecord(value) || typeof value.resultOf !== "string" || typeof value.name !== "string" || typeof value.path !== "string") {
96
- throw new MethodError("invalidResultReference");
219
+
220
+ if (Object.hasOwn(args, name)) {
221
+ throw new MethodError(
222
+ "invalidArguments",
223
+ `Both ${name} and #${name} given`
224
+ );
225
+ }
226
+
227
+ const reference = resultReference.safeParse(value);
228
+
229
+ if (!reference.success) {
230
+ throw new MethodError(
231
+ "invalidResultReference",
232
+ describeIssues(reference.error.issues)
233
+ );
97
234
  }
98
- const source = state.responses.find(([method, , callId]) => callId === value.resultOf && method === value.name);
99
- if (!source) throw new MethodError("invalidResultReference", `No ${value.name} result for ${value.resultOf}`);
100
- resolved[name] = evaluatePointer(source[1], value.path);
235
+
236
+ const { resultOf, name: methodName, path } = reference.data;
237
+
238
+ const source = state.responses.find(
239
+ ([response, , callId]) => callId === resultOf && response === methodName
240
+ );
241
+
242
+ if (!source) {
243
+ throw new MethodError(
244
+ "invalidResultReference",
245
+ `No ${methodName} result for ${resultOf}`
246
+ );
247
+ }
248
+
249
+ resolved[name] = evaluatePointer(source[1], path);
101
250
  }
251
+
102
252
  return resolved;
103
253
  }
104
254
 
255
+ // ---------------------------------------------------------------- arguments
256
+
257
+ /**
258
+ * Adds an issue that answers the method with `type` instead of
259
+ * invalidArguments: the arguments are well formed, but ask for something
260
+ * this server does not do.
261
+ */
262
+ function methodIssue(
263
+ context: z.RefinementCtx,
264
+ type: MethodErrorType,
265
+ message: string
266
+ ) {
267
+ context.addIssue({ code: "custom", message, params: { methodError: type } });
268
+ }
269
+
270
+ /** The method error an issue asks for, from `methodIssue`. */
271
+ function issueMethodError(issue: Issue) {
272
+ if (issue.code !== "custom") return null;
273
+ const type = methodErrorTypes.safeParse(issue.params?.methodError);
274
+
275
+ return type.success ? type.data : null;
276
+ }
277
+
278
+ /** A method's arguments, or the method error that answers them (RFC 8620 §3.6.2). */
279
+ function parseArguments<Schema extends z.ZodType>(
280
+ schema: Schema,
281
+ args: JsonObject
282
+ ): z.output<Schema> {
283
+ const parsed = schema.safeParse(args);
284
+
285
+ if (parsed.success) return parsed.data;
286
+ const { issues } = parsed.error;
287
+
288
+ for (const issue of issues) {
289
+ const type = issueMethodError(issue);
290
+
291
+ if (type) throw new MethodError(type, issue.message);
292
+ }
293
+
294
+ throw new MethodError("invalidArguments", describeIssues(issues));
295
+ }
296
+
297
+ const accountId = z.string();
298
+
299
+ /** Ids of objects to fetch or change; more than a request may hold is requestTooLarge. */
300
+ const idList = z.array(z.string()).superRefine((ids, context) => {
301
+ if (ids.length > MAX_OBJECTS) {
302
+ methodIssue(context, "requestTooLarge", `At most ${MAX_OBJECTS} ids`);
303
+ }
304
+ });
305
+
306
+ const properties = z.array(z.string()).nullish();
307
+
308
+ /** RFC 8620 §1.4 UTCDate; an offset is accepted too. */
309
+ const utcDate = z.iso.datetime({ offset: true });
310
+
311
+ /** Objects to create or patches to apply, each checked on its own (SetError per id). */
312
+ const setObjects = z.record(z.string(), z.json()).nullish();
313
+
314
+ const changesArguments = z.object({ accountId, sinceState: z.string() });
315
+
316
+ /** A SetError for an object whose properties failed `issues` (RFC 8620 §5.3). */
317
+ function invalidProperties(
318
+ issues: readonly Issue[],
319
+ options: { topLevel?: boolean } = {}
320
+ ) {
321
+ const names = issueProperties(issues, options);
322
+
323
+ for (const issue of issues) {
324
+ if (issue.code === "unrecognized_keys") names.push(...issue.keys);
325
+ }
326
+
327
+ return {
328
+ type: "invalidProperties",
329
+ properties: [...new Set(names)],
330
+ description: describeIssues(issues),
331
+ };
332
+ }
333
+
334
+ /** The `created`/`updated`/`not…` map of a /set response: null when empty. */
335
+ function setResult<Value extends Json>(entries: Map<string, Value>) {
336
+ return entries.size ? Object.fromEntries(entries) : null;
337
+ }
338
+
105
339
  // ------------------------------------------------------------------ helpers
106
340
 
107
- function account(state: RequestState, args: Args) {
108
- const found = state.context.accounts.find((item) => item.id === args.accountId);
341
+ /** The id a creation id stands for. */
342
+ function createdId(state: RequestState, creationId: string) {
343
+ return state.createdIds.get(creationId);
344
+ }
345
+
346
+ function account(state: RequestState, id: string) {
347
+ const found = state.context.accounts.find((item) => item.id === id);
348
+
109
349
  if (!found) throw new MethodError("accountNotFound");
350
+
110
351
  return found;
111
352
  }
112
353
 
113
- function stringIds(value: unknown, name = "ids") {
114
- if (!Array.isArray(value) || value.some((id) => typeof id !== "string")) {
115
- throw new MethodError("invalidArguments", `${name} must be a list of ids`);
116
- }
117
- if (value.length > MAX_OBJECTS) throw new MethodError("requestTooLarge");
118
- return value as string[];
119
- }
354
+ function pick<Value extends Json>(
355
+ object: Record<string, Value>,
356
+ wanted: readonly string[] | null | undefined
357
+ ) {
358
+ if (!wanted) return object;
120
359
 
121
- function pick<T extends Record<string, unknown>>(object: T, properties: unknown) {
122
- if (!Array.isArray(properties)) return object;
123
- return Object.fromEntries(Object.entries(object).filter(([key]) => key === "id" || properties.includes(key)));
360
+ return Object.fromEntries(
361
+ Object.entries(object).filter(
362
+ ([key]) => key === "id" || wanted.includes(key)
363
+ )
364
+ );
124
365
  }
125
366
 
126
367
  /** We cannot list changes, only say whether anything changed. */
127
- function changes(accountId: string, sinceState: unknown, state: string) {
368
+ function changes(owner: JmapAccount, sinceState: string, state: string) {
128
369
  if (sinceState !== state) throw new MethodError("cannotCalculateChanges");
129
- return { accountId, oldState: state, newState: state, hasMoreChanges: false, created: [], updated: [], destroyed: [] };
370
+
371
+ return {
372
+ accountId: owner.id,
373
+ oldState: state,
374
+ newState: state,
375
+ hasMoreChanges: false,
376
+ created: [],
377
+ updated: [],
378
+ destroyed: [],
379
+ };
130
380
  }
131
381
 
132
- const addresses = (list: Array<{ address: string; name?: string | null }> | null | undefined) =>
133
- list?.length ? list.map((item) => ({ name: item.name || null, email: item.address })) : null;
382
+ const addresses = (
383
+ list: { address: string; name?: string | null }[] | null | undefined
384
+ ) =>
385
+ list?.length
386
+ ? list.map((item) => ({ name: item.name || null, email: item.address }))
387
+ : null;
134
388
 
135
389
  // ------------------------------------------------------------------ mailbox
136
390
 
@@ -160,86 +414,217 @@ function mailboxObject(row: JmapMailboxRow, canSend: boolean) {
160
414
  };
161
415
  }
162
416
 
163
- async function mailboxGet(state: RequestState, args: Args) {
164
- const owner = account(state, args);
165
- const { state: mailboxState, mailboxes } = await mailboxStub(state.context.env, owner.id).jmapMailboxes(state.context.user.id);
166
- const ids = args.ids == null ? mailboxes.map((row) => row.id) : stringIds(args.ids);
417
+ const mailboxGetArguments = z.object({
418
+ accountId,
419
+ ids: idList.nullish(),
420
+ properties,
421
+ });
422
+
423
+ async function mailboxGet(
424
+ state: RequestState,
425
+ args: z.output<typeof mailboxGetArguments>
426
+ ) {
427
+ const owner = account(state, args.accountId);
428
+
429
+ const { state: mailboxState, mailboxes } = await mailboxStub(
430
+ state.context.env,
431
+ owner.id
432
+ ).jmapMailboxes(state.context.user.id);
433
+
434
+ const ids = args.ids ?? mailboxes.map((row) => row.id);
167
435
  const byId = new Map(mailboxes.map((row) => [row.id, row]));
436
+
168
437
  return {
169
438
  accountId: owner.id,
170
439
  state: mailboxState,
171
440
  list: ids.flatMap((id) => {
172
441
  const row = byId.get(id);
173
- return row ? [pick(mailboxObject(row, owner.canSend), args.properties)] : [];
442
+
443
+ return row
444
+ ? [pick(mailboxObject(row, owner.canSend), args.properties)]
445
+ : [];
174
446
  }),
175
447
  notFound: ids.filter((id) => !byId.has(id)),
176
448
  };
177
449
  }
178
450
 
179
- async function mailboxQuery(state: RequestState, args: Args) {
180
- const owner = account(state, args);
181
- const { state: mailboxState, mailboxes } = await mailboxStub(state.context.env, owner.id).jmapMailboxes(state.context.user.id);
182
- const filter = isRecord(args.filter) ? args.filter : {};
183
- const ids = mailboxes
184
- .filter((row) => !("role" in filter) || row.role === filter.role)
185
- .filter((row) => typeof filter.name !== "string" || row.name.toLowerCase().includes(filter.name.toLowerCase()))
186
- .map((row) => row.id);
187
- return { accountId: owner.id, queryState: mailboxState, canCalculateChanges: false, position: 0, ids, total: ids.length };
188
- }
451
+ const mailboxQueryArguments = z.object({
452
+ accountId,
453
+ filter: z
454
+ .object({
455
+ /** null matches the mailboxes without a role. */
456
+ role: z.string().nullable().optional(),
457
+ name: z.string().optional(),
458
+ })
459
+ .nullish(),
460
+ });
189
461
 
190
- // -------------------------------------------------------------------- email
462
+ async function mailboxQuery(
463
+ state: RequestState,
464
+ args: z.output<typeof mailboxQueryArguments>
465
+ ) {
466
+ const owner = account(state, args.accountId);
467
+
468
+ const { state: mailboxState, mailboxes } = await mailboxStub(
469
+ state.context.env,
470
+ owner.id
471
+ ).jmapMailboxes(state.context.user.id);
472
+
473
+ const role = args.filter?.role;
474
+ const name = args.filter?.name?.toLowerCase();
475
+
476
+ const ids = mailboxes.flatMap((row) =>
477
+ (role === undefined || row.role === role) &&
478
+ (name === undefined || row.name.toLowerCase().includes(name))
479
+ ? [row.id]
480
+ : []
481
+ );
191
482
 
192
- function emailFilter(value: unknown): JmapEmailFilter {
193
- if (value == null) return {};
194
- if (!isRecord(value)) throw new MethodError("unsupportedFilter");
195
- if ("operator" in value) {
196
- if (value.operator !== "AND" || !Array.isArray(value.conditions)) {
197
- throw new MethodError("unsupportedFilter", "Only AND filters are supported");
198
- }
199
- return Object.assign({}, ...value.conditions.map(emailFilter));
200
- }
201
- const supported = ["inMailbox", "inMailboxOtherThan", "before", "after", "text", "from", "to", "subject", "hasKeyword", "notKeyword", "hasAttachment"];
202
- const unknown = Object.keys(value).filter((key) => !supported.includes(key));
203
- if (unknown.length) throw new MethodError("unsupportedFilter", `Unsupported filter: ${unknown.join(", ")}`);
204
- for (const keyword of [value.hasKeyword, value.notKeyword]) {
205
- if (keyword !== undefined && keyword !== "$seen") {
206
- throw new MethodError("unsupportedFilter", "Only the $seen keyword is supported");
207
- }
208
- }
209
483
  return {
210
- ...(typeof value.inMailbox === "string" ? { inMailbox: value.inMailbox } : {}),
211
- ...(Array.isArray(value.inMailboxOtherThan) ? { inMailboxOtherThan: value.inMailboxOtherThan.map(String) } : {}),
212
- ...(typeof value.before === "string" ? { before: Date.parse(value.before) } : {}),
213
- ...(typeof value.after === "string" ? { after: Date.parse(value.after) } : {}),
214
- ...(typeof value.text === "string" ? { text: value.text } : {}),
215
- ...(typeof value.from === "string" ? { from: value.from } : {}),
216
- ...(typeof value.to === "string" ? { to: value.to } : {}),
217
- ...(typeof value.subject === "string" ? { subject: value.subject } : {}),
218
- ...(typeof value.hasKeyword === "string" ? { hasKeyword: value.hasKeyword } : {}),
219
- ...(typeof value.notKeyword === "string" ? { notKeyword: value.notKeyword } : {}),
220
- ...(typeof value.hasAttachment === "boolean" ? { hasAttachment: value.hasAttachment } : {}),
484
+ accountId: owner.id,
485
+ queryState: mailboxState,
486
+ canCalculateChanges: false,
487
+ position: 0,
488
+ ids,
489
+ total: ids.length,
221
490
  };
222
491
  }
223
492
 
224
- async function emailQuery(state: RequestState, args: Args) {
225
- const owner = account(state, args);
226
- const sort = Array.isArray(args.sort) ? args.sort : [];
227
- for (const comparator of sort) {
228
- if (!isRecord(comparator) || !["receivedAt", "sentAt"].includes(String(comparator.property))) {
229
- throw new MethodError("unsupportedSort", "Emails sort by receivedAt or sentAt");
493
+ // -------------------------------------------------------------------- email
494
+
495
+ /** The FilterCondition properties (RFC 8621 §4.4.1) Email/query supports. */
496
+ const emailCondition = {
497
+ inMailbox: z.string().optional(),
498
+ inMailboxOtherThan: z.array(z.string()).optional(),
499
+ before: utcDate.transform((date) => Date.parse(date)).optional(),
500
+ after: utcDate.transform((date) => Date.parse(date)).optional(),
501
+ text: z.string().optional(),
502
+ from: z.string().optional(),
503
+ to: z.string().optional(),
504
+ subject: z.string().optional(),
505
+ hasKeyword: z.string().optional(),
506
+ notKeyword: z.string().optional(),
507
+ hasAttachment: z.boolean().optional(),
508
+ };
509
+
510
+ const emailConditionKeys = Object.keys(emailCondition);
511
+
512
+ /**
513
+ * An Email/query filter, flattened into one condition. Other conditions,
514
+ * operators than AND, and keywords than $seen are valid JMAP the store
515
+ * cannot answer: unsupportedFilter.
516
+ */
517
+ const emailFilter: z.ZodType<JmapEmailFilter> = z.lazy(() =>
518
+ z
519
+ .record(z.string(), z.unknown())
520
+ .superRefine((filter, context) => {
521
+ const allowed = Object.hasOwn(filter, "operator")
522
+ ? ["operator", "conditions"]
523
+ : emailConditionKeys;
524
+
525
+ const unsupported = Object.keys(filter).filter(
526
+ (key) => !allowed.includes(key)
527
+ );
528
+
529
+ if (unsupported.length) {
530
+ methodIssue(
531
+ context,
532
+ "unsupportedFilter",
533
+ `Unsupported filter: ${unsupported.join(", ")}`
534
+ );
535
+ }
536
+ })
537
+ .pipe(
538
+ z.object({
539
+ operator: z.enum(["AND", "OR", "NOT"]).optional(),
540
+ conditions: z.array(emailFilter).optional(),
541
+ ...emailCondition,
542
+ })
543
+ )
544
+ .superRefine((filter, context) => {
545
+ if (filter.operator && filter.operator !== "AND") {
546
+ methodIssue(
547
+ context,
548
+ "unsupportedFilter",
549
+ "Only AND filters are supported"
550
+ );
551
+ }
552
+
553
+ if (filter.operator && !filter.conditions) {
554
+ context.addIssue({
555
+ code: "custom",
556
+ path: ["conditions"],
557
+ message: "A filter operator needs conditions",
558
+ });
559
+ }
560
+
561
+ for (const keyword of [filter.hasKeyword, filter.notKeyword]) {
562
+ if (keyword !== undefined && keyword !== "$seen") {
563
+ methodIssue(
564
+ context,
565
+ "unsupportedFilter",
566
+ "Only the $seen keyword is supported"
567
+ );
568
+ }
569
+ }
570
+ })
571
+ .transform(({ operator, conditions, ...condition }) => {
572
+ if (!operator) return condition;
573
+ // AND: every condition holds.
574
+ const merged: JmapEmailFilter = {};
575
+
576
+ for (const part of conditions ?? []) Object.assign(merged, part);
577
+
578
+ return merged;
579
+ })
580
+ );
581
+
582
+ const emailComparator = z
583
+ .object({
584
+ property: z.string(),
585
+ isAscending: z.boolean().optional(),
586
+ collation: z.string().optional(),
587
+ })
588
+ .superRefine((comparator, context) => {
589
+ if (!["receivedAt", "sentAt"].includes(comparator.property)) {
590
+ methodIssue(
591
+ context,
592
+ "unsupportedSort",
593
+ "Emails sort by receivedAt or sentAt"
594
+ );
230
595
  }
231
- }
232
- const ascending = isRecord(sort[0]) && sort[0].isAscending === true;
233
- const position = Math.max(0, Number(args.position ?? 0) || 0);
234
- const limit = Math.min(MAX_OBJECTS, Math.max(0, Number(args.limit ?? 100) || 100));
235
- const result = await mailboxStub(state.context.env, owner.id).jmapQueryEmails({
236
- userId: state.context.user.id,
237
- filter: emailFilter(args.filter),
238
- ascending,
239
- position,
240
- limit,
241
- collapseThreads: args.collapseThreads === true,
242
596
  });
597
+
598
+ const emailQueryArguments = z.object({
599
+ accountId,
600
+ filter: emailFilter.nullish(),
601
+ sort: z.array(emailComparator).nullish(),
602
+ position: z.number().int().nullish(),
603
+ limit: z.number().int().min(0).nullish(),
604
+ collapseThreads: z.boolean().nullish(),
605
+ });
606
+
607
+ async function emailQuery(
608
+ state: RequestState,
609
+ args: z.output<typeof emailQueryArguments>
610
+ ) {
611
+ const owner = account(state, args.accountId);
612
+ const ascending = args.sort?.[0]?.isAscending === true;
613
+ // Negative positions (from the end) are not supported; they start at the top.
614
+ const position = Math.max(0, args.position ?? 0);
615
+ const limit = Math.min(MAX_OBJECTS, args.limit ?? 100);
616
+
617
+ const result = await mailboxStub(state.context.env, owner.id).jmapQueryEmails(
618
+ {
619
+ userId: state.context.user.id,
620
+ filter: args.filter ?? {},
621
+ ascending,
622
+ position,
623
+ limit,
624
+ collapseThreads: args.collapseThreads === true,
625
+ }
626
+ );
627
+
243
628
  return {
244
629
  accountId: owner.id,
245
630
  queryState: result.state,
@@ -252,25 +637,80 @@ async function emailQuery(state: RequestState, args: Args) {
252
637
  }
253
638
 
254
639
  const defaultEmailProperties = [
255
- "id", "blobId", "threadId", "mailboxIds", "keywords", "size", "receivedAt", "messageId",
256
- "inReplyTo", "references", "sender", "from", "to", "cc", "bcc", "replyTo", "subject",
257
- "sentAt", "hasAttachment", "preview", "bodyValues", "textBody", "htmlBody", "attachments",
640
+ "id",
641
+ "blobId",
642
+ "threadId",
643
+ "mailboxIds",
644
+ "keywords",
645
+ "size",
646
+ "receivedAt",
647
+ "messageId",
648
+ "inReplyTo",
649
+ "references",
650
+ "sender",
651
+ "from",
652
+ "to",
653
+ "cc",
654
+ "bcc",
655
+ "replyTo",
656
+ "subject",
657
+ "sentAt",
658
+ "hasAttachment",
659
+ "preview",
660
+ "bodyValues",
661
+ "textBody",
662
+ "htmlBody",
663
+ "attachments",
258
664
  ];
259
665
 
666
+ const emailGetArguments = z.object({
667
+ accountId,
668
+ ids: idList.nullish(),
669
+ properties,
670
+ fetchTextBodyValues: z.boolean().nullish(),
671
+ fetchHTMLBodyValues: z.boolean().nullish(),
672
+ fetchAllBodyValues: z.boolean().nullish(),
673
+ maxBodyValueBytes: z.number().int().min(0).nullish(),
674
+ });
675
+
676
+ type EmailGetArguments = z.output<typeof emailGetArguments>;
677
+
260
678
  async function emailObject(
261
679
  env: Env,
262
680
  row: { email: Email; mailboxId: string; seen: boolean },
263
- args: Args,
681
+ args: EmailGetArguments
264
682
  ) {
265
683
  const { email } = row;
266
684
  const raw = `raw~${email.id}`;
267
- const textBody = [{
268
- partId: "text", blobId: raw, size: email.bodyText?.length ?? 0, name: null,
269
- type: "text/plain", charset: "utf-8", disposition: null, cid: null,
270
- }];
685
+
686
+ const textBody = [
687
+ {
688
+ partId: "text",
689
+ blobId: raw,
690
+ size: email.bodyText?.length ?? 0,
691
+ name: null,
692
+ type: "text/plain",
693
+ charset: "utf-8",
694
+ disposition: null,
695
+ cid: null,
696
+ },
697
+ ];
698
+
271
699
  const htmlBody = email.bodyHtmlR2Key
272
- ? [{ partId: "html", blobId: raw, size: 0, name: null, type: "text/html", charset: "utf-8", disposition: null, cid: null }]
700
+ ? [
701
+ {
702
+ partId: "html",
703
+ blobId: raw,
704
+ size: 0,
705
+ name: null,
706
+ type: "text/html",
707
+ charset: "utf-8",
708
+ disposition: null,
709
+ cid: null,
710
+ },
711
+ ]
273
712
  : textBody;
713
+
274
714
  const attachments = email.attachmentsJson.map((attachment) => ({
275
715
  partId: `att-${attachment.id}`,
276
716
  blobId: `att~${email.id}~${attachment.id}`,
@@ -281,33 +721,55 @@ async function emailObject(
281
721
  disposition: attachment.disposition,
282
722
  cid: attachment.contentId,
283
723
  }));
284
- const properties = Array.isArray(args.properties) ? args.properties as string[] : defaultEmailProperties;
285
- const maxBytes = Number(args.maxBodyValueBytes ?? 0) || 0;
724
+
725
+ const wanted = args.properties ?? defaultEmailProperties;
726
+ const maxBytes = args.maxBodyValueBytes ?? 0;
727
+
286
728
  const bodyValue = (value: string) => ({
287
- value: maxBytes && value.length > maxBytes ? value.slice(0, maxBytes) : value,
729
+ value:
730
+ maxBytes && value.length > maxBytes ? value.slice(0, maxBytes) : value,
288
731
  isEncodingProblem: false,
289
732
  isTruncated: Boolean(maxBytes && value.length > maxBytes),
290
733
  });
734
+
291
735
  const bodyValues: Record<string, ReturnType<typeof bodyValue>> = {};
292
- if (properties.includes("bodyValues")) {
293
- const wantText = args.fetchTextBodyValues === true || args.fetchAllBodyValues === true;
294
- const wantHtml = args.fetchHTMLBodyValues === true || args.fetchAllBodyValues === true;
295
- if (wantText || (wantHtml && !email.bodyHtmlR2Key)) bodyValues.text = bodyValue(email.bodyText ?? "");
736
+
737
+ if (wanted.includes("bodyValues")) {
738
+ const wantText =
739
+ args.fetchTextBodyValues === true || args.fetchAllBodyValues === true;
740
+
741
+ const wantHtml =
742
+ args.fetchHTMLBodyValues === true || args.fetchAllBodyValues === true;
743
+
744
+ if (wantText || (wantHtml && !email.bodyHtmlR2Key)) {
745
+ bodyValues.text = bodyValue(email.bodyText ?? "");
746
+ }
747
+
296
748
  if (wantHtml && email.bodyHtmlR2Key) {
297
749
  const object = await env.MAIL_STORAGE.get(email.bodyHtmlR2Key);
298
750
  bodyValues.html = bodyValue(object ? await object.text() : "");
299
751
  }
300
752
  }
753
+
301
754
  const timestamp = email.timelineAt.toISOString();
755
+ const keywords: Record<string, true> = row.seen ? { $seen: true } : {};
756
+
302
757
  const object = {
303
758
  id: email.id,
304
759
  blobId: raw,
305
760
  threadId: email.conversationId,
306
761
  mailboxIds: { [row.mailboxId]: true },
307
- keywords: row.seen ? { $seen: true } : {},
308
- size: (email.bodyText?.length ?? 0) + email.attachmentsJson.reduce((total, attachment) => total + attachment.size, 0),
762
+ keywords,
763
+ size:
764
+ (email.bodyText?.length ?? 0) +
765
+ email.attachmentsJson.reduce(
766
+ (total, attachment) => total + attachment.size,
767
+ 0
768
+ ),
309
769
  receivedAt: timestamp,
310
- messageId: email.messageIdHeader ? [email.messageIdHeader.replace(/^<|>$/gu, "")] : null,
770
+ messageId: email.messageIdHeader
771
+ ? [email.messageIdHeader.replaceAll(/^<|>$/gu, "")]
772
+ : null,
311
773
  inReplyTo: email.inReplyToJson?.length ? email.inReplyToJson : null,
312
774
  references: email.referencesJson?.length ? email.referencesJson : null,
313
775
  sender: null,
@@ -318,287 +780,678 @@ async function emailObject(
318
780
  replyTo: addresses(email.replyToJson),
319
781
  subject: email.subject,
320
782
  sentAt: timestamp,
321
- hasAttachment: attachments.some((attachment) => attachment.disposition === "attachment"),
783
+ hasAttachment: attachments.some(
784
+ (attachment) => attachment.disposition === "attachment"
785
+ ),
322
786
  preview: email.preview,
323
787
  bodyValues,
324
788
  textBody,
325
789
  htmlBody,
326
790
  attachments,
327
- bodyStructure: { partId: null, type: "multipart/mixed", subParts: [...htmlBody, ...attachments] },
791
+ bodyStructure: {
792
+ partId: null,
793
+ type: "multipart/mixed",
794
+ subParts: [...htmlBody, ...attachments],
795
+ },
328
796
  };
329
- return Object.fromEntries(Object.entries(object).filter(([key]) => key === "id" || properties.includes(key)));
797
+
798
+ return pick(object, wanted);
330
799
  }
331
800
 
332
- async function emailGet(state: RequestState, args: Args) {
333
- const owner = account(state, args);
334
- if (args.ids == null) throw new MethodError("requestTooLarge", "Ask for emails by id");
335
- const ids = stringIds(args.ids);
336
- const result = await mailboxStub(state.context.env, owner.id).jmapEmails(state.context.user.id, ids);
801
+ async function emailGet(state: RequestState, args: EmailGetArguments) {
802
+ const owner = account(state, args.accountId);
803
+
804
+ if (!args.ids) {
805
+ throw new MethodError("requestTooLarge", "Ask for emails by id");
806
+ }
807
+
808
+ const { ids } = args;
809
+
810
+ const result = await mailboxStub(state.context.env, owner.id).jmapEmails(
811
+ state.context.user.id,
812
+ ids
813
+ );
814
+
337
815
  const found = new Set(result.emails.map((row) => row.email.id));
816
+
338
817
  return {
339
818
  accountId: owner.id,
340
819
  state: result.state,
341
- list: await Promise.all(result.emails.map((row) => emailObject(state.context.env, row as never, args))),
820
+ list: await Promise.all(
821
+ result.emails.map((row) => emailObject(state.context.env, row, args))
822
+ ),
342
823
  notFound: ids.filter((id) => !found.has(id)),
343
824
  };
344
825
  }
345
826
 
346
- /** The keyword and mailbox changes in an Email/set update patch. */
347
- function emailPatch(patch: Args) {
348
- let seen: boolean | undefined;
349
- let target: string | undefined;
350
- for (const [key, value] of Object.entries(patch)) {
351
- if (key === "keywords" && isRecord(value)) {
352
- const keywords = Object.keys(value);
353
- if (keywords.some((keyword) => keyword !== "$seen")) return { error: "Only the $seen keyword is stored" };
354
- seen = value.$seen === true;
355
- } else if (key === "keywords/$seen") {
356
- seen = value === true;
357
- } else if (key.startsWith("keywords/")) {
358
- return { error: "Only the $seen keyword is stored" };
359
- } else if (key === "mailboxIds" && isRecord(value)) {
360
- const ids = Object.keys(value).filter((id) => value[id] === true);
361
- if (ids.length !== 1) return { error: "An email is in exactly one mailbox" };
362
- target = ids[0];
363
- } else if (key.startsWith("mailboxIds/")) {
364
- if (value === true) target = key.slice("mailboxIds/".length);
365
- } else {
366
- return { error: `${key} cannot be changed` };
827
+ /** A patch key is a JSON Pointer into the email (RFC 8620 §5.3). */
828
+ function patchPath(key: string) {
829
+ return key
830
+ .split("/")
831
+ .map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
832
+ }
833
+
834
+ /** Keywords and mailboxIds map their names to true (RFC 8621 §4.1.1). */
835
+ const trueSet = z.record(z.string(), z.literal(true));
836
+
837
+ /** One entry of a set: true adds it, null removes it. */
838
+ const setMember = z.literal(true).nullable();
839
+
840
+ /**
841
+ * An Email/set update patch: the $seen keyword and the one mailbox an email
842
+ * is in are all that change.
843
+ */
844
+ const emailPatch = z
845
+ .record(z.string(), z.json())
846
+ .transform((patch, context) => {
847
+ let seen: boolean | undefined;
848
+ let target: string | undefined;
849
+
850
+ for (const [key, value] of Object.entries(patch)) {
851
+ const path = patchPath(key);
852
+
853
+ const fail = (message: string) =>
854
+ context.addIssue({ code: "custom", path, message, input: value });
855
+
856
+ if (key === "keywords") {
857
+ const keywords = trueSet.safeParse(value);
858
+
859
+ if (!keywords.success) fail("keywords map keywords to true");
860
+ else if (Object.keys(keywords.data).some((name) => name !== "$seen")) {
861
+ fail("Only the $seen keyword is stored");
862
+ } else seen = Object.hasOwn(keywords.data, "$seen");
863
+ } else if (key === "keywords/$seen") {
864
+ const member = setMember.safeParse(value);
865
+
866
+ if (member.success) seen = member.data === true;
867
+ else fail("A keyword is set to true or null");
868
+ } else if (key.startsWith("keywords/")) {
869
+ fail("Only the $seen keyword is stored");
870
+ } else if (key === "mailboxIds") {
871
+ const mailboxIds = trueSet.safeParse(value);
872
+ const ids = mailboxIds.success ? Object.keys(mailboxIds.data) : [];
873
+
874
+ if (ids.length === 1) [target] = ids;
875
+ else fail("An email is in exactly one mailbox");
876
+ } else if (key.startsWith("mailboxIds/")) {
877
+ const member = setMember.safeParse(value);
878
+
879
+ if (!member.success) fail("A mailbox is set to true or null");
880
+ else if (member.data) target = key.slice("mailboxIds/".length);
881
+ } else {
882
+ fail(`${key} cannot be changed`);
883
+ }
884
+ }
885
+
886
+ return { seen, target };
887
+ });
888
+
889
+ const draftAddress = z.object({
890
+ name: z.string().nullish(),
891
+ email: z.string(),
892
+ });
893
+
894
+ const draftAddresses = z
895
+ .array(draftAddress)
896
+ .nullish()
897
+ .transform((list) => list?.map((item) => item.email) ?? []);
898
+
899
+ /** A body part of a draft names its value in bodyValues. */
900
+ const draftBodyPart = z.array(z.object({ partId: z.string() })).nullish();
901
+
902
+ const draftAttachment = z
903
+ .object({
904
+ blobId: z
905
+ .string()
906
+ .regex(UPLOAD_BLOB, "Attachments must be blobs uploaded to this account")
907
+ .transform((blobId) => blobId.replace(UPLOAD_BLOB, "$1")),
908
+ name: z.string().nullish(),
909
+ type: z.string().nullish(),
910
+ disposition: z.string().nullish(),
911
+ cid: z
912
+ .string()
913
+ .nullish()
914
+ .transform((cid) => cid?.replaceAll(/^<|>$/gu, "") || undefined),
915
+ })
916
+ .superRefine((part, context) => {
917
+ if (part.disposition === "inline" && !part.cid) {
918
+ context.addIssue({
919
+ code: "custom",
920
+ path: ["cid"],
921
+ message: "Inline attachments need a cid",
922
+ });
367
923
  }
924
+ })
925
+ .transform((part): DraftAttachment => ({
926
+ uploadId: part.blobId,
927
+ name: part.name ?? "attachment",
928
+ type: part.type ?? "application/octet-stream",
929
+ disposition: part.disposition === "inline" ? "inline" : "attachment",
930
+ contentId: part.disposition === "inline" ? part.cid : undefined,
931
+ }));
932
+
933
+ /** An Email/set create object (RFC 8621 §4.6): a message to send in this request. */
934
+ const draftSchema = z
935
+ .object({
936
+ to: draftAddresses,
937
+ cc: draftAddresses,
938
+ bcc: draftAddresses,
939
+ subject: z.string().nullish(),
940
+ bodyValues: z.record(z.string(), z.object({ value: z.string() })).nullish(),
941
+ textBody: draftBodyPart,
942
+ htmlBody: draftBodyPart,
943
+ attachments: z
944
+ .array(draftAttachment)
945
+ .max(
946
+ MAX_COMPOSER_ATTACHMENT_COUNT,
947
+ `At most ${MAX_COMPOSER_ATTACHMENT_COUNT} attachments per message`
948
+ )
949
+ .nullish()
950
+ .transform((list) => list ?? [])
951
+ .refine(
952
+ (list) =>
953
+ new Set(list.map((item) => item.uploadId)).size === list.length,
954
+ "Each blob can be attached once"
955
+ ),
956
+ })
957
+ .transform((input, context) => {
958
+ const values = new Map(Object.entries(input.bodyValues ?? {}));
959
+
960
+ const partText = (parts: { partId: string }[] | null | undefined) => {
961
+ const [first] = parts ?? [];
962
+
963
+ return first ? values.get(first.partId)?.value : undefined;
964
+ };
965
+
966
+ const bodyText = partText(input.textBody);
967
+ const bodyHtml = partText(input.htmlBody);
968
+
969
+ if (bodyText === undefined && bodyHtml === undefined) {
970
+ context.addIssue({
971
+ code: "custom",
972
+ path: ["textBody"],
973
+ message: "Give the message a textBody or htmlBody with bodyValues",
974
+ });
975
+ }
976
+
977
+ return {
978
+ to: input.to,
979
+ cc: input.cc,
980
+ bcc: input.bcc,
981
+ subject: input.subject ?? "",
982
+ bodyText: bodyText ?? "",
983
+ bodyHtml,
984
+ attachments: input.attachments,
985
+ };
986
+ });
987
+
988
+ const emailSetArguments = z.object({
989
+ accountId,
990
+ ifInState: z.string().nullish(),
991
+ create: setObjects,
992
+ update: setObjects,
993
+ destroy: idList.nullish(),
994
+ });
995
+
996
+ type EmailSetArguments = z.output<typeof emailSetArguments>;
997
+
998
+ /** Email/set creates drafts only to send them; changing or destroying mail is organizing. */
999
+ function emailSetScopes(args: EmailSetArguments) {
1000
+ const scopes: string[] = [];
1001
+
1002
+ if (args.create && Object.keys(args.create).length) {
1003
+ scopes.push(MAIL_SEND_SCOPE);
368
1004
  }
369
- return { seen, target };
370
- }
371
1005
 
372
- function draftFrom(owner: JmapAccount, input: Args): Draft | string {
373
- const list = (value: unknown) =>
374
- Array.isArray(value) ? value.flatMap((item) => isRecord(item) && typeof item.email === "string" ? [item.email] : []) : [];
375
- const bodyValues = isRecord(input.bodyValues) ? input.bodyValues : {};
376
- const partText = (parts: unknown) => {
377
- if (!Array.isArray(parts) || !isRecord(parts[0])) return undefined;
378
- const value = bodyValues[String(parts[0].partId)];
379
- return isRecord(value) && typeof value.value === "string" ? value.value : undefined;
380
- };
381
- const bodyText = partText(input.textBody);
382
- const bodyHtml = partText(input.htmlBody);
383
- if (bodyText === undefined && bodyHtml === undefined) return "Give the message a textBody or htmlBody with bodyValues";
384
- return {
385
- accountId: owner.id,
386
- to: list(input.to),
387
- cc: list(input.cc),
388
- bcc: list(input.bcc),
389
- subject: typeof input.subject === "string" ? input.subject : "",
390
- bodyText: bodyText ?? "",
391
- ...(bodyHtml !== undefined ? { bodyHtml } : {}),
392
- };
1006
+ if (
1007
+ (args.update && Object.keys(args.update).length) ||
1008
+ args.destroy?.length
1009
+ ) {
1010
+ scopes.push(MAIL_ORGANIZE_SCOPE);
1011
+ }
1012
+
1013
+ return scopes;
393
1014
  }
394
1015
 
395
- async function emailSet(state: RequestState, args: Args) {
396
- const owner = account(state, args);
1016
+ async function emailSet(state: RequestState, args: EmailSetArguments) {
1017
+ const owner = account(state, args.accountId);
397
1018
  const stub = mailboxStub(state.context.env, owner.id);
398
1019
  const oldState = await stub.jmapState();
399
- if (args.ifInState !== undefined && args.ifInState !== oldState) throw new MethodError("stateMismatch");
400
- const created: Args = {};
401
- const notCreated: Args = {};
402
- for (const [creationId, input] of Object.entries(isRecord(args.create) ? args.create : {})) {
403
- const draft = isRecord(input) ? draftFrom(owner, input) : "Invalid email";
404
- if (typeof draft === "string") {
405
- notCreated[creationId] = { type: "invalidProperties", description: draft };
1020
+
1021
+ if (args.ifInState != null && args.ifInState !== oldState) {
1022
+ throw new MethodError("stateMismatch");
1023
+ }
1024
+
1025
+ const created = new Map<string, JsonObject>();
1026
+ const notCreated = new Map<string, JsonObject>();
1027
+
1028
+ const drafts = Object.entries(args.create ?? {}).flatMap(
1029
+ ([creationId, input]) => {
1030
+ const parsed = draftSchema.safeParse(input);
1031
+
1032
+ if (!parsed.success) {
1033
+ notCreated.set(
1034
+ creationId,
1035
+ invalidProperties(parsed.error.issues, { topLevel: true })
1036
+ );
1037
+
1038
+ return [];
1039
+ }
1040
+
1041
+ const { attachments, ...message } = parsed.data;
1042
+
1043
+ // The rules the mail app's composer follows: valid, normalized and
1044
+ // deduplicated recipients within the limits, a body, content ids.
1045
+ const compose = composeSchema.safeParse({
1046
+ ...message,
1047
+ requestId: crypto.randomUUID(),
1048
+ mailboxId: owner.id,
1049
+ attachments: attachments.map((attachment) => ({
1050
+ uploadId: attachment.uploadId,
1051
+ disposition: attachment.disposition,
1052
+ contentId: attachment.contentId,
1053
+ })),
1054
+ });
1055
+
1056
+ if (!compose.success) {
1057
+ notCreated.set(
1058
+ creationId,
1059
+ invalidProperties(compose.error.issues.map(draftIssue), {
1060
+ topLevel: true,
1061
+ })
1062
+ );
1063
+
1064
+ return [];
1065
+ }
1066
+
1067
+ return [
1068
+ {
1069
+ creationId,
1070
+ draft: { accountId: owner.id, compose: compose.data, attachments },
1071
+ },
1072
+ ];
1073
+ }
1074
+ );
1075
+
1076
+ const missingBlobs = await Promise.all(
1077
+ drafts.map(async ({ draft }) => {
1078
+ try {
1079
+ // The name and type come with the email, after the bytes were uploaded.
1080
+ await Promise.all(
1081
+ draft.attachments.map((attachment) =>
1082
+ describeComposerUpload({
1083
+ env: state.context.env,
1084
+ mailboxId: owner.id,
1085
+ userId: state.context.user.id,
1086
+ uploadId: attachment.uploadId,
1087
+ filename: attachment.name,
1088
+ contentType: attachment.type,
1089
+ })
1090
+ )
1091
+ );
1092
+
1093
+ return null;
1094
+ } catch (error) {
1095
+ if (!(error instanceof UploadValidationError)) throw error;
1096
+
1097
+ return error.message;
1098
+ }
1099
+ })
1100
+ );
1101
+
1102
+ for (const [index, { creationId, draft }] of drafts.entries()) {
1103
+ const missing = missingBlobs[index];
1104
+
1105
+ if (missing) {
1106
+ notCreated.set(creationId, {
1107
+ type: "blobNotFound",
1108
+ description: missing,
1109
+ });
406
1110
  continue;
407
1111
  }
1112
+
408
1113
  // Drafts are not stored: one is sent by EmailSubmission/set in the same request.
409
1114
  const id = `draft-${crypto.randomUUID()}`;
410
1115
  state.drafts.set(id, draft);
411
- state.createdIds[creationId] = id;
412
- created[creationId] = { id, blobId: `draft~${id}`, threadId: id, size: draft.bodyText.length };
1116
+ state.createdIds.set(creationId, id);
1117
+ created.set(creationId, {
1118
+ id,
1119
+ blobId: `draft~${id}`,
1120
+ threadId: id,
1121
+ size: draft.compose.bodyText.length,
1122
+ });
413
1123
  }
414
1124
 
415
- const updated: Args = {};
416
- const notUpdated: Args = {};
417
- const reads: Array<[string, boolean]> = [];
1125
+ const updated = new Map<string, null>();
1126
+ const notUpdated = new Map<string, JsonObject>();
1127
+ const reads: [string, boolean][] = [];
418
1128
  const moves = new Map<string, string[]>();
419
- for (const [id, patch] of Object.entries(isRecord(args.update) ? args.update : {})) {
420
- const change = isRecord(patch) ? emailPatch(patch) : { error: "Invalid patch" };
421
- if ("error" in change && change.error) {
422
- notUpdated[id] = { type: "invalidProperties", description: change.error };
1129
+
1130
+ for (const [id, patch] of Object.entries(args.update ?? {})) {
1131
+ const change = emailPatch.safeParse(patch);
1132
+
1133
+ if (!change.success) {
1134
+ notUpdated.set(
1135
+ id,
1136
+ change.error.issues.some((issue) => issue.path.length === 0)
1137
+ ? { type: "invalidPatch", description: "A patch is an object" }
1138
+ : invalidProperties(change.error.issues)
1139
+ );
423
1140
  continue;
424
1141
  }
425
- const { seen, target } = change as { seen?: boolean; target?: string };
1142
+
1143
+ const { seen, target } = change.data;
1144
+
426
1145
  if (seen !== undefined) reads.push([id, seen]);
1146
+
427
1147
  if (target) moves.set(target, [...(moves.get(target) ?? []), id]);
428
- updated[id] = null;
1148
+ updated.set(id, null);
429
1149
  }
430
- for (const [id, seen] of reads) {
431
- if (!(await stub.setMessageRead(state.context.user.id, id, seen))) {
432
- delete updated[id];
433
- notUpdated[id] = { type: "notFound" };
1150
+
1151
+ const readResults = await Promise.all(
1152
+ reads.map(([id, seen]) =>
1153
+ stub.setMessageRead(state.context.user.id, id, seen)
1154
+ )
1155
+ );
1156
+
1157
+ for (const [index, [id]] of reads.entries()) {
1158
+ if (!readResults[index]) {
1159
+ updated.delete(id);
1160
+ notUpdated.set(id, { type: "notFound" });
434
1161
  }
435
1162
  }
436
- for (const [target, ids] of moves) {
437
- if (!(await stub.jmapMoveEmails(ids, target))) {
438
- for (const id of ids) {
439
- delete updated[id];
440
- notUpdated[id] = { type: "invalidProperties", description: `Emails cannot be moved to ${target}` };
441
- }
1163
+
1164
+ const moveTargets = [...moves];
1165
+
1166
+ const moved = await Promise.all(
1167
+ moveTargets.map(([target, ids]) => stub.jmapMoveEmails(ids, target))
1168
+ );
1169
+
1170
+ for (const [index, [target, ids]] of moveTargets.entries()) {
1171
+ if (moved[index]) continue;
1172
+
1173
+ for (const id of ids) {
1174
+ updated.delete(id);
1175
+ notUpdated.set(id, {
1176
+ type: "invalidProperties",
1177
+ properties: ["mailboxIds"],
1178
+ description: `Emails cannot be moved to ${target}`,
1179
+ });
442
1180
  }
443
1181
  }
444
1182
 
445
1183
  const destroyed: string[] = [];
446
- const notDestroyed: Args = {};
447
- const destroyIds = args.destroy == null ? [] : stringIds(args.destroy, "destroy");
1184
+ const notDestroyed = new Map<string, JsonObject>();
1185
+ const destroyIds = args.destroy ?? [];
1186
+
448
1187
  if (destroyIds.length) {
449
1188
  const { emails } = await stub.jmapEmails(state.context.user.id, destroyIds);
450
1189
  const inTrash = emails.filter((row) => row.mailboxId === "trash");
451
1190
  const elsewhere = emails.filter((row) => row.mailboxId !== "trash");
1191
+
452
1192
  // Mail goes to Trash first; destroying it there deletes its conversation.
453
- if (elsewhere.length) await stub.jmapMoveEmails(elsewhere.map((row) => row.email.id), "trash");
1193
+ if (elsewhere.length) {
1194
+ await stub.jmapMoveEmails(
1195
+ elsewhere.map((row) => row.email.id),
1196
+ "trash"
1197
+ );
1198
+ }
1199
+
454
1200
  if (inTrash.length) {
455
- await stub.permanentlyDeleteConversations([...new Set(inTrash.map((row) => row.email.conversationId))]);
1201
+ await stub.permanentlyDeleteConversations([
1202
+ ...new Set(inTrash.map((row) => row.email.conversationId)),
1203
+ ]);
456
1204
  }
1205
+
457
1206
  const found = new Set(emails.map((row) => row.email.id));
1207
+
458
1208
  for (const id of destroyIds) {
459
1209
  if (found.has(id)) destroyed.push(id);
460
- else notDestroyed[id] = { type: "notFound" };
1210
+ else notDestroyed.set(id, { type: "notFound" });
461
1211
  }
462
1212
  }
1213
+
463
1214
  return {
464
1215
  accountId: owner.id,
465
1216
  oldState,
466
1217
  newState: await stub.jmapState(),
467
- created: Object.keys(created).length ? created : null,
468
- updated: Object.keys(updated).length ? updated : null,
1218
+ created: setResult(created),
1219
+ updated: setResult(updated),
469
1220
  destroyed: destroyed.length ? destroyed : null,
470
- notCreated: Object.keys(notCreated).length ? notCreated : null,
471
- notUpdated: Object.keys(notUpdated).length ? notUpdated : null,
472
- notDestroyed: Object.keys(notDestroyed).length ? notDestroyed : null,
1221
+ notCreated: setResult(notCreated),
1222
+ notUpdated: setResult(notUpdated),
1223
+ notDestroyed: setResult(notDestroyed),
473
1224
  };
474
1225
  }
475
1226
 
476
1227
  // --------------------------------------------------- threads and identities
477
1228
 
478
- async function threadGet(state: RequestState, args: Args) {
479
- const owner = account(state, args);
480
- const ids = stringIds(args.ids);
481
- const result = await mailboxStub(state.context.env, owner.id).jmapThreads(ids);
482
- const threads = new Map(result.threads as Array<[string, string[]]>);
1229
+ const threadGetArguments = z.object({ accountId, ids: idList });
1230
+
1231
+ async function threadGet(
1232
+ state: RequestState,
1233
+ args: z.output<typeof threadGetArguments>
1234
+ ) {
1235
+ const owner = account(state, args.accountId);
1236
+
1237
+ const result = await mailboxStub(state.context.env, owner.id).jmapThreads(
1238
+ args.ids
1239
+ );
1240
+
1241
+ const threads = new Map(
1242
+ result.threads.map((thread) => [thread.id, thread.emailIds])
1243
+ );
1244
+
483
1245
  return {
484
1246
  accountId: owner.id,
485
1247
  state: result.state,
486
- list: ids.flatMap((id) => threads.has(id) ? [{ id, emailIds: threads.get(id)! }] : []),
487
- notFound: ids.filter((id) => !threads.has(id)),
1248
+ list: args.ids.flatMap((id) => {
1249
+ const emailIds = threads.get(id);
1250
+
1251
+ return emailIds ? [{ id, emailIds }] : [];
1252
+ }),
1253
+ notFound: args.ids.filter((id) => !threads.has(id)),
488
1254
  };
489
1255
  }
490
1256
 
491
- function identityGet(state: RequestState, args: Args) {
492
- const owner = account(state, args);
1257
+ const identityGetArguments = z.object({
1258
+ accountId,
1259
+ ids: idList.nullish(),
1260
+ properties,
1261
+ });
1262
+
1263
+ function identityGet(
1264
+ state: RequestState,
1265
+ args: z.output<typeof identityGetArguments>
1266
+ ) {
1267
+ const owner = account(state, args.accountId);
1268
+
493
1269
  const list = owner.canSend
494
- ? [{
495
- id: owner.id,
496
- name: owner.displayName,
497
- email: owner.address,
498
- replyTo: null,
499
- bcc: null,
500
- textSignature: "",
501
- htmlSignature: "",
502
- mayDelete: false,
503
- }]
1270
+ ? [
1271
+ {
1272
+ id: owner.id,
1273
+ name: owner.displayName,
1274
+ email: owner.address,
1275
+ replyTo: null,
1276
+ bcc: null,
1277
+ textSignature: "",
1278
+ htmlSignature: "",
1279
+ mayDelete: false,
1280
+ },
1281
+ ]
504
1282
  : [];
505
- const ids = args.ids == null ? list.map((identity) => identity.id) : stringIds(args.ids);
1283
+
1284
+ const ids = args.ids ?? list.map((identity) => identity.id);
1285
+
506
1286
  return {
507
1287
  accountId: owner.id,
508
1288
  state: "1",
509
- list: list.filter((identity) => ids.includes(identity.id)),
1289
+ list: list.flatMap((identity) =>
1290
+ ids.includes(identity.id) ? [pick(identity, args.properties)] : []
1291
+ ),
510
1292
  notFound: ids.filter((id) => id !== owner.id || !owner.canSend),
511
1293
  };
512
1294
  }
513
1295
 
514
- async function submissionSet(state: RequestState, args: Args, callId: string) {
515
- const owner = account(state, args);
516
- if (!owner.canSend) throw new MethodError("forbidden", "This account cannot send");
517
- const created: Args = {};
518
- const notCreated: Args = {};
1296
+ const submissionCreate = z.object({
1297
+ emailId: z.string(),
1298
+ identityId: z.string().optional(),
1299
+ });
1300
+
1301
+ const submissionSetArguments = z.object({
1302
+ accountId,
1303
+ create: setObjects,
1304
+ onSuccessDestroyEmail: z.array(z.string()).nullish(),
1305
+ onSuccessUpdateEmail: z.record(z.string(), z.json()).nullish(),
1306
+ });
1307
+
1308
+ const notADraft = {
1309
+ type: "invalidProperties",
1310
+ properties: ["emailId"],
1311
+ description: "Send an email created by Email/set earlier in the same request",
1312
+ };
1313
+
1314
+ /** Sends a draft as the account; a failure is the reason it was not sent. */
1315
+ async function sendDraft(
1316
+ state: RequestState,
1317
+ owner: JmapAccount,
1318
+ draft: Draft
1319
+ ) {
1320
+ try {
1321
+ return await submitOutgoing({
1322
+ env: state.context.env,
1323
+ requestUrl: state.context.requestUrl,
1324
+ compose: { ...draft.compose, userId: state.context.user.id },
1325
+ conversationId: `conv_${crypto.randomUUID().replaceAll("-", "")}`,
1326
+ related: null,
1327
+ forwarded: null,
1328
+ includeRelatedContext: false,
1329
+ fromAddress: owner.address,
1330
+ fromName: owner.displayName,
1331
+ defer: state.context.defer,
1332
+ });
1333
+ } catch (error) {
1334
+ return {
1335
+ error:
1336
+ error instanceof Error
1337
+ ? error.message
1338
+ : "The message could not be sent",
1339
+ };
1340
+ }
1341
+ }
1342
+
1343
+ async function submissionSet(
1344
+ state: RequestState,
1345
+ args: z.output<typeof submissionSetArguments>,
1346
+ callId: string
1347
+ ) {
1348
+ const owner = account(state, args.accountId);
1349
+
1350
+ if (!owner.canSend) {
1351
+ throw new MethodError("forbidden", "This account cannot send");
1352
+ }
1353
+
1354
+ const created = new Map<string, JsonObject>();
1355
+ const notCreated = new Map<string, JsonObject>();
519
1356
  const sentDrafts = new Map<string, string>();
520
- for (const [creationId, input] of Object.entries(isRecord(args.create) ? args.create : {})) {
521
- if (!isRecord(input) || typeof input.emailId !== "string") {
522
- notCreated[creationId] = { type: "invalidProperties", description: "emailId is required" };
1357
+
1358
+ for (const [creationId, input] of Object.entries(args.create ?? {})) {
1359
+ const parsed = submissionCreate.safeParse(input);
1360
+
1361
+ if (!parsed.success) {
1362
+ notCreated.set(creationId, invalidProperties(parsed.error.issues));
523
1363
  continue;
524
1364
  }
525
- const emailId = input.emailId.startsWith("#")
526
- ? state.createdIds[input.emailId.slice(1)]
527
- : input.emailId;
528
- const draft = emailId ? state.drafts.get(emailId) : undefined;
529
- if (!draft || draft.accountId !== owner.id) {
530
- notCreated[creationId] = {
531
- type: "invalidProperties",
532
- description: "Send an email created by Email/set earlier in the same request",
533
- };
1365
+
1366
+ const submission = parsed.data;
1367
+
1368
+ const emailId = submission.emailId.startsWith("#")
1369
+ ? createdId(state, submission.emailId.slice(1))
1370
+ : submission.emailId;
1371
+
1372
+ const draft = emailId === undefined ? undefined : state.drafts.get(emailId);
1373
+
1374
+ if (emailId === undefined || !draft || draft.accountId !== owner.id) {
1375
+ notCreated.set(creationId, notADraft);
534
1376
  continue;
535
1377
  }
536
- if (input.identityId !== undefined && input.identityId !== owner.id) {
537
- notCreated[creationId] = { type: "invalidProperties", description: "Unknown identity" };
1378
+
1379
+ if (
1380
+ submission.identityId !== undefined &&
1381
+ submission.identityId !== owner.id
1382
+ ) {
1383
+ notCreated.set(creationId, {
1384
+ type: "invalidProperties",
1385
+ properties: ["identityId"],
1386
+ description: "Unknown identity",
1387
+ });
538
1388
  continue;
539
1389
  }
540
- try {
541
- const submission = await submitOutgoing({
542
- env: state.context.env,
543
- requestUrl: state.context.requestUrl,
544
- compose: {
545
- requestId: crypto.randomUUID(),
546
- mailboxId: owner.id,
547
- to: draft.to,
548
- cc: draft.cc,
549
- bcc: draft.bcc,
550
- subject: draft.subject,
551
- bodyText: draft.bodyText,
552
- ...(draft.bodyHtml !== undefined ? { bodyHtml: draft.bodyHtml } : {}),
553
- attachments: [],
554
- userId: state.context.user.id,
555
- },
556
- conversationId: `conv_${crypto.randomUUID().replaceAll("-", "")}`,
557
- related: null,
558
- forwarded: null,
559
- includeRelatedContext: false,
560
- fromAddress: owner.address,
561
- fromName: owner.displayName,
562
- defer: state.context.defer,
563
- });
564
- const id = `sub-${submission.email.id}`;
565
- state.createdIds[creationId] = id;
566
- sentDrafts.set(id, emailId!);
567
- created[creationId] = {
568
- id,
569
- threadId: submission.email.conversationId,
570
- emailId: submission.email.id,
571
- sendAt: new Date().toISOString(),
572
- undoStatus: "final",
573
- };
574
- } catch (error) {
575
- notCreated[creationId] = {
1390
+
1391
+ // oxlint-disable-next-line eslint/no-await-in-loop -- submissions send mail in the order the client gave them
1392
+ const sent = await sendDraft(state, owner, draft);
1393
+
1394
+ if ("error" in sent) {
1395
+ notCreated.set(creationId, {
576
1396
  type: "forbiddenToSend",
577
- description: error instanceof Error ? error.message : "The message could not be sent",
578
- };
1397
+ description: sent.error,
1398
+ });
1399
+ continue;
579
1400
  }
1401
+
1402
+ const id = `sub-${sent.email.id}`;
1403
+ state.createdIds.set(creationId, id);
1404
+ sentDrafts.set(id, emailId);
1405
+ created.set(creationId, {
1406
+ id,
1407
+ threadId: sent.email.conversationId,
1408
+ emailId: sent.email.id,
1409
+ sendAt: new Date().toISOString(),
1410
+ undoStatus: "final",
1411
+ });
580
1412
  }
1413
+
581
1414
  // The sent copy is already in Sent; drafts were never stored, so the
582
1415
  // follow-up Email/set only reports them gone.
583
- const followUp = [args.onSuccessDestroyEmail, args.onSuccessUpdateEmail ? Object.keys(args.onSuccessUpdateEmail as Args) : null]
584
- .flatMap((value) => Array.isArray(value) ? value as string[] : [])
585
- .map((reference) => reference.startsWith("#") ? state.createdIds[reference.slice(1)] : reference)
586
- .flatMap((id) => id && sentDrafts.has(id) ? [sentDrafts.get(id)!] : []);
1416
+ const followUp = [
1417
+ ...(args.onSuccessDestroyEmail ?? []),
1418
+ ...Object.keys(args.onSuccessUpdateEmail ?? {}),
1419
+ ].flatMap((reference) => {
1420
+ const id = reference.startsWith("#")
1421
+ ? createdId(state, reference.slice(1))
1422
+ : reference;
1423
+
1424
+ const draftId = id === undefined ? undefined : sentDrafts.get(id);
1425
+
1426
+ return draftId === undefined ? [] : [draftId];
1427
+ });
1428
+
587
1429
  if (followUp.length) {
588
1430
  const stub = mailboxStub(state.context.env, owner.id);
589
1431
  const current = await stub.jmapState();
590
- state.after.push(["Email/set", {
591
- accountId: owner.id, oldState: current, newState: current,
592
- created: null, updated: null, destroyed: followUp,
593
- notCreated: null, notUpdated: null, notDestroyed: null,
594
- }, callId]);
1432
+ state.after.push([
1433
+ "Email/set",
1434
+ {
1435
+ accountId: owner.id,
1436
+ oldState: current,
1437
+ newState: current,
1438
+ created: null,
1439
+ updated: null,
1440
+ destroyed: followUp,
1441
+ notCreated: null,
1442
+ notUpdated: null,
1443
+ notDestroyed: null,
1444
+ },
1445
+ callId,
1446
+ ]);
595
1447
  }
1448
+
596
1449
  return {
597
1450
  accountId: owner.id,
598
1451
  oldState: "1",
599
1452
  newState: "1",
600
- created: Object.keys(created).length ? created : null,
601
- notCreated: Object.keys(notCreated).length ? notCreated : null,
1453
+ created: setResult(created),
1454
+ notCreated: setResult(notCreated),
602
1455
  updated: null,
603
1456
  destroyed: null,
604
1457
  notUpdated: null,
@@ -606,73 +1459,575 @@ async function submissionSet(state: RequestState, args: Args, callId: string) {
606
1459
  };
607
1460
  }
608
1461
 
1462
+ // --------------------------------------------------------- push (RFC 8620 §7.2)
1463
+
1464
+ const MAX_PUSH_SUBSCRIPTIONS = 20;
1465
+
1466
+ type PushSubscriptionRow = typeof jmapPushSubscriptions.$inferSelect;
1467
+
1468
+ /** url and keys are never returned (§7.2.1). */
1469
+ function pushSubscriptionObject(row: PushSubscriptionRow) {
1470
+ return {
1471
+ id: row.id,
1472
+ deviceClientId: row.deviceClientId,
1473
+ verificationCode: row.verifiedAt ? row.verificationCode : null,
1474
+ expires: row.expiresAt.toISOString(),
1475
+ types: row.typesJson,
1476
+ };
1477
+ }
1478
+
1479
+ /** The data types to push; null is all of them. */
1480
+ const pushTypes = z.array(z.string()).nullish();
1481
+
1482
+ /** A PushSubscription create object (RFC 8620 §7.2). */
1483
+ const pushSubscriptionCreate = z.object({
1484
+ deviceClientId: z.string().min(1),
1485
+ url: z
1486
+ .url({ protocol: /^https$/u, error: "url must be an https URL" })
1487
+ .transform((url) => new URL(url).toString()),
1488
+ keys: z.object({ p256dh: z.string(), auth: z.string() }).nullish(),
1489
+ verificationCode: z
1490
+ .never({ error: "verificationCode is set by update" })
1491
+ .optional(),
1492
+ expires: utcDate.nullish(),
1493
+ types: pushTypes,
1494
+ });
1495
+
1496
+ /** Only these change after a subscription is created. */
1497
+ const pushSubscriptionPatch = z.strictObject({
1498
+ verificationCode: z.string().optional(),
1499
+ expires: utcDate.nullish(),
1500
+ types: pushTypes,
1501
+ });
1502
+
1503
+ function ownSubscriptions(state: RequestState) {
1504
+ return and(
1505
+ eq(jmapPushSubscriptions.userId, state.context.user.id),
1506
+ eq(jmapPushSubscriptions.clientId, state.context.clientId)
1507
+ );
1508
+ }
1509
+
1510
+ const pushSubscriptionGetArguments = z.object({
1511
+ ids: idList.nullish(),
1512
+ properties,
1513
+ });
1514
+
1515
+ async function pushSubscriptionGet(
1516
+ state: RequestState,
1517
+ args: z.output<typeof pushSubscriptionGetArguments>
1518
+ ) {
1519
+ const db = createDb(state.context.env.DB);
1520
+ const ids = args.ids ?? null;
1521
+
1522
+ const rows = await db
1523
+ .select()
1524
+ .from(jmapPushSubscriptions)
1525
+ .where(
1526
+ ids
1527
+ ? and(
1528
+ ownSubscriptions(state),
1529
+ inArray(jmapPushSubscriptions.id, ids.length ? ids : [""])
1530
+ )
1531
+ : ownSubscriptions(state)
1532
+ );
1533
+
1534
+ const found = new Set(rows.map((row) => row.id));
1535
+
1536
+ return {
1537
+ list: rows.map((row) => pick(pushSubscriptionObject(row), args.properties)),
1538
+ notFound: ids ? ids.filter((id) => !found.has(id)) : [],
1539
+ };
1540
+ }
1541
+
1542
+ const pushSubscriptionSetArguments = z.object({
1543
+ /** Push subscriptions have no state (§7.2): any given state mismatches. */
1544
+ ifInState: z.string().nullish(),
1545
+ create: setObjects,
1546
+ update: setObjects,
1547
+ destroy: idList.nullish(),
1548
+ });
1549
+
1550
+ async function createPushSubscriptions(
1551
+ state: RequestState,
1552
+ create: JsonObject
1553
+ ) {
1554
+ const db = createDb(state.context.env.DB);
1555
+ const created = new Map<string, JsonObject>();
1556
+ const notCreated = new Map<string, JsonObject>();
1557
+ const entries = Object.entries(create);
1558
+
1559
+ if (!entries.length) return { created, notCreated };
1560
+
1561
+ // The devices with a subscription; a device has one, and a new one replaces it.
1562
+ const devices = new Set(
1563
+ (
1564
+ await db
1565
+ .select({ deviceClientId: jmapPushSubscriptions.deviceClientId })
1566
+ .from(jmapPushSubscriptions)
1567
+ .where(eq(jmapPushSubscriptions.userId, state.context.user.id))
1568
+ ).map((row) => row.deviceClientId)
1569
+ );
1570
+
1571
+ const rows: PushSubscriptionRow[] = [];
1572
+
1573
+ for (const [creationId, input] of entries) {
1574
+ const parsed = pushSubscriptionCreate.safeParse(input);
1575
+
1576
+ if (!parsed.success) {
1577
+ notCreated.set(creationId, invalidProperties(parsed.error.issues));
1578
+ continue;
1579
+ }
1580
+
1581
+ const subscription = parsed.data;
1582
+
1583
+ if (subscription.keys && !state.context.vapid) {
1584
+ notCreated.set(creationId, {
1585
+ type: "invalidProperties",
1586
+ properties: ["keys"],
1587
+ description: "Web Push is not configured on this server",
1588
+ });
1589
+ continue;
1590
+ }
1591
+
1592
+ const others =
1593
+ devices.size - (devices.has(subscription.deviceClientId) ? 1 : 0);
1594
+
1595
+ if (others >= MAX_PUSH_SUBSCRIPTIONS) {
1596
+ notCreated.set(creationId, {
1597
+ type: "overQuota",
1598
+ description: `At most ${MAX_PUSH_SUBSCRIPTIONS} push subscriptions`,
1599
+ });
1600
+ continue;
1601
+ }
1602
+
1603
+ devices.add(subscription.deviceClientId);
1604
+
1605
+ const row: PushSubscriptionRow = {
1606
+ id: crypto.randomUUID(),
1607
+ userId: state.context.user.id,
1608
+ clientId: state.context.clientId,
1609
+ deviceClientId: subscription.deviceClientId,
1610
+ url: subscription.url,
1611
+ p256dh: subscription.keys?.p256dh ?? null,
1612
+ auth: subscription.keys?.auth ?? null,
1613
+ verificationCode: newVerificationCode(),
1614
+ verifiedAt: null,
1615
+ expiresAt: subscriptionExpiry(subscription.expires),
1616
+ typesJson: subscription.types ?? null,
1617
+ createdAt: new Date(),
1618
+ };
1619
+
1620
+ rows.push(row);
1621
+ state.createdIds.set(creationId, row.id);
1622
+ created.set(creationId, {
1623
+ id: row.id,
1624
+ expires: row.expiresAt.toISOString(),
1625
+ });
1626
+ }
1627
+
1628
+ // In order: a later subscription for the same device replaces an earlier one.
1629
+ const [first, ...rest] = rows.flatMap((row) => [
1630
+ db
1631
+ .delete(jmapPushSubscriptions)
1632
+ .where(
1633
+ and(
1634
+ eq(jmapPushSubscriptions.userId, row.userId),
1635
+ eq(jmapPushSubscriptions.deviceClientId, row.deviceClientId)
1636
+ )
1637
+ ),
1638
+ db.insert(jmapPushSubscriptions).values(row),
1639
+ ]);
1640
+
1641
+ if (first) await db.batch([first, ...rest]);
1642
+
1643
+ for (const row of rows) {
1644
+ state.context.defer(
1645
+ sendVerification(row, state.context.vapid).catch((error) => {
1646
+ console.error(
1647
+ "Could not send JMAP push verification",
1648
+ error instanceof Error ? error.message : String(error)
1649
+ );
1650
+ })
1651
+ );
1652
+ }
1653
+
1654
+ return { created, notCreated };
1655
+ }
1656
+
1657
+ async function updatePushSubscriptions(
1658
+ state: RequestState,
1659
+ update: JsonObject
1660
+ ) {
1661
+ const db = createDb(state.context.env.DB);
1662
+ const updated = new Map<string, JsonObject | null>();
1663
+ const notUpdated = new Map<string, JsonObject>();
1664
+ const entries = Object.entries(update);
1665
+
1666
+ if (!entries.length) return { updated, notUpdated };
1667
+
1668
+ const rows = new Map(
1669
+ (
1670
+ await db
1671
+ .select()
1672
+ .from(jmapPushSubscriptions)
1673
+ .where(
1674
+ and(
1675
+ ownSubscriptions(state),
1676
+ inArray(
1677
+ jmapPushSubscriptions.id,
1678
+ entries.map(([id]) => id)
1679
+ )
1680
+ )
1681
+ )
1682
+ ).map((row) => [row.id, row])
1683
+ );
1684
+
1685
+ const changed: Pick<
1686
+ PushSubscriptionRow,
1687
+ "id" | "verifiedAt" | "expiresAt" | "typesJson"
1688
+ >[] = [];
1689
+
1690
+ for (const [id, input] of entries) {
1691
+ const row = rows.get(id);
1692
+
1693
+ if (!row) {
1694
+ notUpdated.set(id, { type: "notFound" });
1695
+ continue;
1696
+ }
1697
+
1698
+ const parsed = pushSubscriptionPatch.safeParse(input);
1699
+
1700
+ if (!parsed.success) {
1701
+ notUpdated.set(id, invalidProperties(parsed.error.issues));
1702
+ continue;
1703
+ }
1704
+
1705
+ const patch = parsed.data;
1706
+
1707
+ if (
1708
+ patch.verificationCode !== undefined &&
1709
+ patch.verificationCode !== row.verificationCode
1710
+ ) {
1711
+ notUpdated.set(id, {
1712
+ type: "invalidProperties",
1713
+ properties: ["verificationCode"],
1714
+ description: "The verification code does not match",
1715
+ });
1716
+ continue;
1717
+ }
1718
+
1719
+ const expiresAt =
1720
+ patch.expires === undefined
1721
+ ? row.expiresAt
1722
+ : subscriptionExpiry(patch.expires);
1723
+
1724
+ changed.push({
1725
+ id,
1726
+ verifiedAt:
1727
+ patch.verificationCode === undefined
1728
+ ? row.verifiedAt
1729
+ : (row.verifiedAt ?? new Date()),
1730
+ expiresAt,
1731
+ typesJson: patch.types === undefined ? row.typesJson : patch.types,
1732
+ });
1733
+
1734
+ // The server may shorten the asked expiry; then it says what it chose.
1735
+ const askedExpiry = patch.expires ? Date.parse(patch.expires) : null;
1736
+
1737
+ updated.set(
1738
+ id,
1739
+ askedExpiry !== null && askedExpiry !== expiresAt.getTime()
1740
+ ? { expires: expiresAt.toISOString() }
1741
+ : null
1742
+ );
1743
+ }
1744
+
1745
+ const [first, ...rest] = changed.map(({ id, ...values }) =>
1746
+ db
1747
+ .update(jmapPushSubscriptions)
1748
+ .set(values)
1749
+ .where(eq(jmapPushSubscriptions.id, id))
1750
+ );
1751
+
1752
+ if (first) await db.batch([first, ...rest]);
1753
+
1754
+ return { updated, notUpdated };
1755
+ }
1756
+
1757
+ async function pushSubscriptionSet(
1758
+ state: RequestState,
1759
+ args: z.output<typeof pushSubscriptionSetArguments>
1760
+ ) {
1761
+ const db = createDb(state.context.env.DB);
1762
+
1763
+ if (args.ifInState != null) throw new MethodError("stateMismatch");
1764
+
1765
+ const { created, notCreated } = await createPushSubscriptions(
1766
+ state,
1767
+ args.create ?? {}
1768
+ );
1769
+
1770
+ const { updated, notUpdated } = await updatePushSubscriptions(
1771
+ state,
1772
+ args.update ?? {}
1773
+ );
1774
+
1775
+ const destroyIds = args.destroy ?? [];
1776
+
1777
+ const removed = destroyIds.length
1778
+ ? await db
1779
+ .delete(jmapPushSubscriptions)
1780
+ .where(
1781
+ and(
1782
+ ownSubscriptions(state),
1783
+ inArray(jmapPushSubscriptions.id, destroyIds)
1784
+ )
1785
+ )
1786
+ .returning({ id: jmapPushSubscriptions.id })
1787
+ : [];
1788
+
1789
+ const destroyed = new Set(removed.map((row) => row.id));
1790
+ const notDestroyed = new Map<string, JsonObject>();
1791
+
1792
+ for (const id of destroyIds) {
1793
+ if (!destroyed.has(id)) notDestroyed.set(id, { type: "notFound" });
1794
+ }
1795
+
1796
+ return {
1797
+ created: setResult(created),
1798
+ updated: setResult(updated),
1799
+ destroyed: destroyed.size ? [...destroyed] : null,
1800
+ notCreated: setResult(notCreated),
1801
+ notUpdated: setResult(notUpdated),
1802
+ notDestroyed: setResult(notDestroyed),
1803
+ };
1804
+ }
1805
+
609
1806
  // ----------------------------------------------------------------- dispatch
610
1807
 
611
- const methods: Record<string, (state: RequestState, args: Args, callId: string) => unknown> = {
612
- "Core/echo": (_state, args) => args,
613
- "Mailbox/get": mailboxGet,
614
- "Mailbox/query": mailboxQuery,
615
- "Mailbox/changes": async (state, args) => {
616
- const owner = account(state, args);
617
- return changes(owner.id, args.sinceState, await mailboxStub(state.context.env, owner.id).jmapState());
618
- },
619
- "Email/query": emailQuery,
620
- "Email/get": emailGet,
621
- "Email/set": emailSet,
622
- "Email/changes": async (state, args) => {
623
- const owner = account(state, args);
624
- return changes(owner.id, args.sinceState, await mailboxStub(state.context.env, owner.id).jmapState());
625
- },
626
- "Thread/get": threadGet,
627
- "Thread/changes": async (state, args) => {
628
- const owner = account(state, args);
629
- return changes(owner.id, args.sinceState, await mailboxStub(state.context.env, owner.id).jmapState());
630
- },
631
- "SearchSnippet/get": (state, args) => {
632
- const owner = account(state, args);
633
- const ids = stringIds(args.emailIds, "emailIds");
634
- return { accountId: owner.id, list: ids.map((emailId) => ({ emailId, subject: null, preview: null })), notFound: [] };
1808
+ type MethodHandler = (
1809
+ state: RequestState,
1810
+ args: JsonObject,
1811
+ callId: string
1812
+ ) => JsonObject | Promise<JsonObject>;
1813
+
1814
+ /**
1815
+ * A method: its arguments' schema, the mail scopes a call needs (each
1816
+ * method needs its own), and what it does with the parsed arguments.
1817
+ */
1818
+ function method<Schema extends z.ZodType>(definition: {
1819
+ arguments: Schema;
1820
+ scopes: (args: z.output<Schema>) => readonly string[];
1821
+ run: (
1822
+ state: RequestState,
1823
+ args: z.output<Schema>,
1824
+ callId: string
1825
+ ) => JsonObject | Promise<JsonObject>;
1826
+ }): MethodHandler {
1827
+ return (state, raw, callId) => {
1828
+ const args = parseArguments(definition.arguments, raw);
1829
+
1830
+ const missing = definition
1831
+ .scopes(args)
1832
+ .filter((scope) => !state.context.scopes.includes(scope));
1833
+
1834
+ if (missing.length) {
1835
+ throw new MethodError(
1836
+ "forbidden",
1837
+ `This token was not given ${missing.join(", ")}`
1838
+ );
1839
+ }
1840
+
1841
+ return definition.run(state, args, callId);
1842
+ };
1843
+ }
1844
+
1845
+ const reading = () => [MAIL_READ_SCOPE];
1846
+
1847
+ /** Foo/changes for the types that share the mailbox's one state. */
1848
+ const mailboxChanges = method({
1849
+ arguments: changesArguments,
1850
+ scopes: reading,
1851
+ run: async (state, args) => {
1852
+ const owner = account(state, args.accountId);
1853
+
1854
+ return changes(
1855
+ owner,
1856
+ args.sinceState,
1857
+ await mailboxStub(state.context.env, owner.id).jmapState()
1858
+ );
635
1859
  },
636
- "Identity/get": identityGet,
637
- "EmailSubmission/set": submissionSet,
1860
+ });
1861
+
1862
+ const methods = new Map<string, MethodHandler>([
1863
+ [
1864
+ "Core/echo",
1865
+ method({
1866
+ arguments: z.record(z.string(), z.json()),
1867
+ scopes: () => [],
1868
+ run: (_state, args) => args,
1869
+ }),
1870
+ ],
1871
+ [
1872
+ "Mailbox/get",
1873
+ method({
1874
+ arguments: mailboxGetArguments,
1875
+ scopes: reading,
1876
+ run: mailboxGet,
1877
+ }),
1878
+ ],
1879
+ [
1880
+ "Mailbox/query",
1881
+ method({
1882
+ arguments: mailboxQueryArguments,
1883
+ scopes: reading,
1884
+ run: mailboxQuery,
1885
+ }),
1886
+ ],
1887
+ ["Mailbox/changes", mailboxChanges],
1888
+ [
1889
+ "Email/query",
1890
+ method({
1891
+ arguments: emailQueryArguments,
1892
+ scopes: reading,
1893
+ run: emailQuery,
1894
+ }),
1895
+ ],
1896
+ [
1897
+ "Email/get",
1898
+ method({ arguments: emailGetArguments, scopes: reading, run: emailGet }),
1899
+ ],
1900
+ [
1901
+ "Email/set",
1902
+ method({
1903
+ arguments: emailSetArguments,
1904
+ scopes: emailSetScopes,
1905
+ run: emailSet,
1906
+ }),
1907
+ ],
1908
+ ["Email/changes", mailboxChanges],
1909
+ [
1910
+ "Thread/get",
1911
+ method({ arguments: threadGetArguments, scopes: reading, run: threadGet }),
1912
+ ],
1913
+ ["Thread/changes", mailboxChanges],
1914
+ [
1915
+ "SearchSnippet/get",
1916
+ method({
1917
+ arguments: z.object({ accountId, emailIds: idList }),
1918
+ scopes: reading,
1919
+ run: (state, args) => ({
1920
+ accountId: account(state, args.accountId).id,
1921
+ list: args.emailIds.map((emailId) => ({
1922
+ emailId,
1923
+ subject: null,
1924
+ preview: null,
1925
+ })),
1926
+ notFound: [],
1927
+ }),
1928
+ }),
1929
+ ],
1930
+ [
1931
+ "Identity/get",
1932
+ method({
1933
+ arguments: identityGetArguments,
1934
+ scopes: reading,
1935
+ run: identityGet,
1936
+ }),
1937
+ ],
1938
+ [
1939
+ "EmailSubmission/set",
1940
+ method({
1941
+ arguments: submissionSetArguments,
1942
+ scopes: () => [MAIL_SEND_SCOPE],
1943
+ run: submissionSet,
1944
+ }),
1945
+ ],
1946
+ [
1947
+ "PushSubscription/get",
1948
+ method({
1949
+ arguments: pushSubscriptionGetArguments,
1950
+ scopes: reading,
1951
+ run: pushSubscriptionGet,
1952
+ }),
1953
+ ],
1954
+ [
1955
+ "PushSubscription/set",
1956
+ method({
1957
+ arguments: pushSubscriptionSetArguments,
1958
+ scopes: reading,
1959
+ run: pushSubscriptionSet,
1960
+ }),
1961
+ ],
1962
+ ]);
1963
+
1964
+ /** RFC 8620 §3.4. */
1965
+ type JmapResponse = {
1966
+ methodResponses: Invocation[];
1967
+ createdIds?: Record<string, string>;
1968
+ sessionState: string;
638
1969
  };
639
1970
 
640
- export async function runJmapRequest(context: JmapContext, body: unknown) {
641
- if (!isRecord(body) || !Array.isArray(body.using) || !Array.isArray(body.methodCalls)) {
642
- throw new JmapError("urn:ietf:params:jmap:error:notRequest", "A JMAP request has using and methodCalls");
643
- }
644
- if (!body.using.includes(CORE)) {
645
- throw new JmapError("urn:ietf:params:jmap:error:unknownCapability", `${CORE} is required`);
1971
+ /** Runs a parsed request's method calls (RFC 8620 §3.3). */
1972
+ export async function runJmapRequest(
1973
+ context: JmapContext,
1974
+ request: JmapRequest
1975
+ ) {
1976
+ if (!request.using.includes(CORE)) {
1977
+ throw new JmapError(
1978
+ "urn:ietf:params:jmap:error:unknownCapability",
1979
+ `${CORE} is required`
1980
+ );
646
1981
  }
647
- if (body.methodCalls.length > 32) {
648
- throw new JmapError("urn:ietf:params:jmap:error:limit", "At most 32 method calls per request");
1982
+
1983
+ if (request.methodCalls.length > MAX_CALLS) {
1984
+ throw new JmapError(
1985
+ "urn:ietf:params:jmap:error:limit",
1986
+ `At most ${MAX_CALLS} method calls per request`
1987
+ );
649
1988
  }
1989
+
650
1990
  const state: RequestState = {
651
1991
  context,
652
1992
  responses: [],
653
- createdIds: isRecord(body.createdIds) ? { ...body.createdIds as Record<string, string> } : {},
1993
+ createdIds: new Map(Object.entries(request.createdIds ?? {})),
654
1994
  drafts: new Map(),
655
1995
  after: [],
656
1996
  };
657
- for (const call of body.methodCalls) {
658
- if (!Array.isArray(call) || typeof call[0] !== "string" || !isRecord(call[1]) || typeof call[2] !== "string") {
659
- throw new JmapError("urn:ietf:params:jmap:error:notRequest", "Each method call is [name, arguments, id]");
660
- }
661
- const [name, rawArgs, callId] = call as Invocation;
662
- const method = methods[name];
1997
+
1998
+ for (const [name, rawArgs, callId] of request.methodCalls) {
1999
+ const handler = methods.get(name);
2000
+
663
2001
  try {
664
- if (!method) throw new MethodError("unknownMethod");
665
- const args = resolveReferences(state, rawArgs);
666
- state.responses.push([name, await method(state, args, callId) as Args, callId]);
667
- state.responses.push(...state.after.splice(0));
2002
+ if (!handler) throw new MethodError("unknownMethod");
2003
+
2004
+ // oxlint-disable-next-line eslint/no-await-in-loop -- a call may reference the results of earlier ones (RFC 8620 §3.7), so calls run in order
2005
+ const result = await handler(
2006
+ state,
2007
+ resolveReferences(state, rawArgs),
2008
+ callId
2009
+ );
2010
+
2011
+ state.responses.push([name, result, callId], ...state.after.splice(0));
668
2012
  } catch (error) {
669
2013
  if (!(error instanceof MethodError)) throw error;
670
- state.responses.push(["error", { type: error.type, description: error.message }, callId]);
2014
+ state.responses.push([
2015
+ "error",
2016
+ { type: error.type, description: error.message },
2017
+ callId,
2018
+ ]);
671
2019
  }
672
2020
  }
673
- return {
2021
+
2022
+ const response: JmapResponse = {
674
2023
  methodResponses: state.responses,
675
- ...(isRecord(body.createdIds) ? { createdIds: state.createdIds } : {}),
676
2024
  sessionState: String(context.accounts.length),
677
2025
  };
2026
+
2027
+ // Only a request that sent createdIds gets them back (§3.4).
2028
+ if (request.createdIds) {
2029
+ response.createdIds = Object.fromEntries(state.createdIds);
2030
+ }
2031
+
2032
+ return response;
678
2033
  }