@open-workspace/email 0.3.0 → 0.4.1

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 (221) hide show
  1. package/README.md +22 -22
  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_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  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 +77 -28
  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 +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  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 +88 -22
  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 +271 -173
  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 +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  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 +126 -93
  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 +595 -225
  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 +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  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 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -1,10 +1,11 @@
1
+ import { hashToken, randomToken } from "@open-workspace/core/module";
1
2
  import type { z } from "zod";
3
+
2
4
  import {
3
5
  attachmentsRequiringDownloadLinks,
4
6
  composerAttachmentLimitError,
5
7
  isComposerInlineImageContentType,
6
8
  } from "../../shared/mail";
7
- import { hashToken, randomToken } from "@open-workspace/core/worker/lib/crypto.ts";
8
9
  import type { StoredAttachment } from "../mailbox/model";
9
10
  import type { Email, NewEmail } from "../mailbox/schema";
10
11
  import {
@@ -16,10 +17,7 @@ import {
16
17
  resolveLinkedAttachmentPlaceholders,
17
18
  textWithQuotedContext,
18
19
  } from "./outbound-content";
19
- import {
20
- address,
21
- replyThreadHeaders,
22
- } from "./rfc";
20
+ import { address, replyThreadHeaders } from "./rfc";
23
21
  import type { composeSchema } from "./schemas";
24
22
  import {
25
23
  copyStoredAttachmentToMessage,
@@ -34,6 +32,7 @@ export type OutgoingMessageInput = z.infer<typeof composeSchema> & {
34
32
  /** Set by the route from the authenticated session. */
35
33
  userId: string;
36
34
  };
35
+
37
36
  type PreparedAttachment = StoredAttachment & {
38
37
  downloadUrl: string | null;
39
38
  sourceUploadId?: string;
@@ -44,16 +43,12 @@ export class ComposerAttachmentLimitError extends Error {}
44
43
 
45
44
  type OutgoingAttachmentDraft = Pick<
46
45
  OutgoingMessageInput,
47
- | "attachments"
48
- | "bodyHtml"
49
- | "bodyText"
50
- | "mailboxId"
51
- | "subject"
52
- | "userId"
46
+ "attachments" | "bodyHtml" | "bodyText" | "mailboxId" | "subject" | "userId"
53
47
  >;
54
48
 
55
49
  export async function discardPreparedObjects(env: Env, storageKeys: string[]) {
56
50
  if (!storageKeys.length) return;
51
+
57
52
  try {
58
53
  await env.MAIL_STORAGE.delete(storageKeys);
59
54
  } catch (error) {
@@ -62,8 +57,9 @@ export async function discardPreparedObjects(env: Env, storageKeys: string[]) {
62
57
  }
63
58
  }
64
59
 
65
- export async function outgoingRequestFingerprint(compose: OutgoingMessageInput) {
60
+ export function outgoingRequestFingerprint(compose: OutgoingMessageInput) {
66
61
  const { userId: _, ...payload } = compose;
62
+
67
63
  return hashToken(`outgoing-request-v2\0${JSON.stringify(payload)}`);
68
64
  }
69
65
 
@@ -73,7 +69,7 @@ export function withDownloadLinks(
73
69
  bodyText: string,
74
70
  bodyHtml: string | undefined,
75
71
  attachments: PreparedAttachment[],
76
- expiresAt: Date,
72
+ expiresAt: Date
77
73
  ) {
78
74
  const positioned = resolveLinkedAttachmentPlaceholders({
79
75
  bodyText,
@@ -84,10 +80,12 @@ export function withDownloadLinks(
84
80
  downloadUrl: attachment.downloadUrl,
85
81
  })),
86
82
  });
83
+
87
84
  const links = attachments.filter(
88
85
  (attachment): attachment is PreparedAttachment & { downloadUrl: string } =>
89
- attachment.downloadUrl !== null,
86
+ attachment.downloadUrl !== null
90
87
  );
88
+
91
89
  if (!links.length) {
92
90
  return {
93
91
  bodyText: positioned.bodyText,
@@ -96,44 +94,51 @@ export function withDownloadLinks(
96
94
  }
97
95
 
98
96
  const expiry = expiresAt.toISOString().slice(0, 10);
97
+
99
98
  const fallbackTextLinks = links.filter(
100
99
  (attachment) =>
101
- !attachment.sourceUploadId
102
- || !positioned.textPlacedUploadIds.has(attachment.sourceUploadId),
100
+ !attachment.sourceUploadId ||
101
+ !positioned.textPlacedUploadIds.has(attachment.sourceUploadId)
103
102
  );
103
+
104
104
  const textBlock = fallbackTextLinks.length
105
105
  ? [
106
106
  `Attachments (download links expire ${expiry}):`,
107
- ...fallbackTextLinks.map((attachment) =>
108
- `- ${attachment.filename}: ${attachment.downloadUrl}`
107
+ ...fallbackTextLinks.map(
108
+ (attachment) => `- ${attachment.filename}: ${attachment.downloadUrl}`
109
109
  ),
110
110
  ].join("\n")
111
111
  : "";
112
+
112
113
  const nextText = textBlock
113
114
  ? `${positioned.bodyText.trimEnd()}${positioned.bodyText.trimEnd() ? "\n\n" : ""}${textBlock}`
114
115
  : positioned.bodyText;
115
- if (!positioned.bodyHtml) {
116
- return { bodyText: nextText, bodyHtml: positioned.bodyHtml };
116
+
117
+ const positionedHtml = positioned.bodyHtml;
118
+
119
+ if (!positionedHtml) {
120
+ return { bodyText: nextText, bodyHtml: positionedHtml };
117
121
  }
118
122
 
119
123
  const inlineImagePlacements = new Set(
120
124
  links.flatMap((attachment) =>
121
- attachment.disposition === "inline"
122
- && attachment.contentId
123
- && positioned.bodyHtml!.includes(`cid:${attachment.contentId}`)
125
+ attachment.disposition === "inline" &&
126
+ attachment.contentId &&
127
+ positionedHtml.includes(`cid:${attachment.contentId}`)
124
128
  ? [attachment.id]
125
129
  : []
126
- ),
130
+ )
127
131
  );
128
- const nextHtml = externalizeLinkedInlineImages(positioned.bodyHtml, links);
132
+
133
+ const nextHtml = externalizeLinkedInlineImages(positionedHtml, links);
134
+
129
135
  const fallbackHtmlLinks = links.filter(
130
136
  (attachment) =>
131
- (
132
- !attachment.sourceUploadId
133
- || !positioned.htmlPlacedUploadIds.has(attachment.sourceUploadId)
134
- )
135
- && !inlineImagePlacements.has(attachment.id),
137
+ (!attachment.sourceUploadId ||
138
+ !positioned.htmlPlacedUploadIds.has(attachment.sourceUploadId)) &&
139
+ !inlineImagePlacements.has(attachment.id)
136
140
  );
141
+
137
142
  if (!fallbackHtmlLinks.length) {
138
143
  return { bodyText: nextText, bodyHtml: nextHtml };
139
144
  }
@@ -141,19 +146,24 @@ export function withDownloadLinks(
141
146
  const htmlBlock = [
142
147
  `<p>Attachments (download links expire ${escapeHtml(expiry)}):</p>`,
143
148
  "<ul>",
144
- ...fallbackHtmlLinks.map((attachment) =>
145
- `<li><a href="${escapeHtml(attachment.downloadUrl)}">${escapeHtml(attachment.filename)}</a></li>`,
149
+ ...fallbackHtmlLinks.map(
150
+ (attachment) =>
151
+ `<li><a href="${escapeHtml(attachment.downloadUrl)}">${escapeHtml(attachment.filename)}</a></li>`
146
152
  ),
147
153
  "</ul>",
148
154
  ].join("");
155
+
149
156
  return { bodyText: nextText, bodyHtml: `${nextHtml}${htmlBlock}` };
150
157
  }
151
158
 
152
- export async function messageIdForRequest(mailboxId: string, requestId: string) {
159
+ export async function messageIdForRequest(
160
+ mailboxId: string,
161
+ requestId: string
162
+ ) {
153
163
  return `msg_${await hashToken(`${mailboxId}:${requestId}`)}`;
154
164
  }
155
165
 
156
- async function loadPreparedComposerAttachments(input: {
166
+ function loadPreparedComposerAttachments(input: {
157
167
  env: Env;
158
168
  compose: OutgoingAttachmentDraft;
159
169
  storagePrefix: string;
@@ -162,6 +172,7 @@ async function loadPreparedComposerAttachments(input: {
162
172
  const loadUpload = input.finalized
163
173
  ? loadComposerUpload
164
174
  : loadComposerUploadMetadata;
175
+
165
176
  return Promise.all(
166
177
  input.compose.attachments.map(async (file, index) => {
167
178
  try {
@@ -171,14 +182,16 @@ async function loadPreparedComposerAttachments(input: {
171
182
  userId: input.compose.userId,
172
183
  uploadId: file.uploadId,
173
184
  });
185
+
174
186
  if (
175
- file.disposition === "inline"
176
- && !isComposerInlineImageContentType(upload.contentType)
187
+ file.disposition === "inline" &&
188
+ !isComposerInlineImageContentType(upload.contentType)
177
189
  ) {
178
190
  throw new UploadValidationError(
179
- "Inline images must be PNG, JPEG, GIF, or WebP",
191
+ "Inline images must be PNG, JPEG, GIF, or WebP"
180
192
  );
181
193
  }
194
+
182
195
  return {
183
196
  id: `att_${index + 1}`,
184
197
  sourceUploadId: file.uploadId,
@@ -198,9 +211,10 @@ async function loadPreparedComposerAttachments(input: {
198
211
  if (error instanceof UploadValidationError) {
199
212
  throw new ComposerAttachmentLimitError(error.message);
200
213
  }
214
+
201
215
  throw error;
202
216
  }
203
- }),
217
+ })
204
218
  );
205
219
  }
206
220
 
@@ -218,6 +232,7 @@ function planOutgoingAttachments(input: {
218
232
  input.forwarded?.attachmentsJson ?? []
219
233
  ).map((file, index) => {
220
234
  const id = `fwd_att_${index + 1}`;
235
+
221
236
  return {
222
237
  ...file,
223
238
  id,
@@ -233,17 +248,23 @@ function planOutgoingAttachments(input: {
233
248
  downloadUrl: null,
234
249
  };
235
250
  });
251
+
236
252
  const attachments = [...input.uploaded, ...forwardedAttachments];
237
253
  const limitError = composerAttachmentLimitError(attachments);
254
+
238
255
  if (limitError) throw new ComposerAttachmentLimitError(limitError);
256
+
239
257
  const forwardedContent = appendForwardedMessage(
240
258
  input.compose.bodyText,
241
259
  input.compose.bodyHtml,
242
- input.forwarded,
260
+ input.forwarded
243
261
  );
244
- const quotedText = input.includeRelatedContext && input.related
245
- ? contextForNewRecipient(input.related)
246
- : null;
262
+
263
+ const quotedText =
264
+ input.includeRelatedContext && input.related
265
+ ? contextForNewRecipient(input.related)
266
+ : null;
267
+
247
268
  const linkedIds = attachmentsRequiringDownloadLinks({
248
269
  subject: input.compose.subject,
249
270
  bodyText: textWithQuotedContext(forwardedContent.bodyText, quotedText),
@@ -252,6 +273,7 @@ function planOutgoingAttachments(input: {
252
273
  : undefined,
253
274
  attachments,
254
275
  });
276
+
255
277
  return {
256
278
  attachments,
257
279
  forwardedContent,
@@ -273,10 +295,12 @@ export async function preflightOutgoingAttachments(input: {
273
295
  storagePrefix: "preflight",
274
296
  finalized: false,
275
297
  });
298
+
276
299
  const plan = planOutgoingAttachments({
277
300
  ...input,
278
301
  uploaded,
279
302
  });
303
+
280
304
  return {
281
305
  externalizedAttachments: plan.linkedIds.size,
282
306
  linkedUploadIds: uploaded.flatMap((attachment) =>
@@ -312,6 +336,7 @@ export async function prepareOutgoingEmail(input: {
312
336
  storagePrefix,
313
337
  finalized: true,
314
338
  });
339
+
315
340
  const plan = planOutgoingAttachments({
316
341
  compose,
317
342
  uploaded,
@@ -320,15 +345,14 @@ export async function prepareOutgoingEmail(input: {
320
345
  includeRelatedContext: input.includeRelatedContext,
321
346
  storagePrefix,
322
347
  });
323
- const {
324
- forwardedContent,
325
- linkedIds,
326
- quotedText,
327
- } = plan;
348
+
349
+ const { forwardedContent, linkedIds, quotedText } = plan;
350
+
328
351
  const attachments: PreparedAttachment[] = await Promise.all(
329
352
  plan.attachments.map(async (file) => {
330
353
  if (!linkedIds.has(file.id)) return file;
331
354
  const token = `${compose.mailboxId}.${id}.${file.id}.${randomToken()}`;
355
+
332
356
  return {
333
357
  ...file,
334
358
  delivery: "download_link" as const,
@@ -336,23 +360,23 @@ export async function prepareOutgoingEmail(input: {
336
360
  downloadExpiresAt: expiresAt.getTime(),
337
361
  downloadUrl: new URL(
338
362
  `/api/downloads/mail/${encodeURIComponent(token)}`,
339
- input.requestUrl,
363
+ input.requestUrl
340
364
  ).toString(),
341
365
  };
342
- }),
366
+ })
343
367
  );
368
+
344
369
  const content = withDownloadLinks(
345
370
  forwardedContent.bodyText,
346
371
  forwardedContent.bodyHtml,
347
372
  attachments,
348
- expiresAt,
373
+ expiresAt
349
374
  );
375
+
350
376
  // The stored body is the authored content only. Quoted context is persisted
351
377
  // separately and added to the transport payload at delivery time.
352
378
  const storedBodyHtml = content.bodyHtml;
353
- const bodyHtmlR2Key = storedBodyHtml
354
- ? `${storagePrefix}/body.html`
355
- : null;
379
+ const bodyHtmlR2Key = storedBodyHtml ? `${storagePrefix}/body.html` : null;
356
380
 
357
381
  const storageKeys = [
358
382
  ...attachments.flatMap((file) =>
@@ -360,9 +384,11 @@ export async function prepareOutgoingEmail(input: {
360
384
  ),
361
385
  ...(bodyHtmlR2Key ? [bodyHtmlR2Key] : []),
362
386
  ];
387
+
363
388
  const writes = [
364
389
  ...attachments.flatMap((file) => {
365
390
  if (!file.sourceObjectKey) return [];
391
+
366
392
  return [
367
393
  copyStoredAttachmentToMessage({
368
394
  env: input.env,
@@ -373,15 +399,20 @@ export async function prepareOutgoingEmail(input: {
373
399
  ];
374
400
  }),
375
401
  ...(bodyHtmlR2Key && storedBodyHtml
376
- ? [input.env.MAIL_STORAGE.put(bodyHtmlR2Key, storedBodyHtml, {
377
- httpMetadata: { contentType: "text/html; charset=utf-8" },
378
- })]
402
+ ? [
403
+ input.env.MAIL_STORAGE.put(bodyHtmlR2Key, storedBodyHtml, {
404
+ httpMetadata: { contentType: "text/html; charset=utf-8" },
405
+ }),
406
+ ]
379
407
  : []),
380
408
  ];
409
+
381
410
  const writeResults = await Promise.allSettled(writes);
411
+
382
412
  const failedWrite = writeResults.find(
383
- (result): result is PromiseRejectedResult => result.status === "rejected",
413
+ (result): result is PromiseRejectedResult => result.status === "rejected"
384
414
  );
415
+
385
416
  if (failedWrite) {
386
417
  await discardPreparedObjects(input.env, storageKeys);
387
418
  throw failedWrite.reason;
@@ -392,12 +423,14 @@ export async function prepareOutgoingEmail(input: {
392
423
  const cc = compose.cc.map((value) => address(value));
393
424
  const bcc = compose.bcc.map((value) => address(value));
394
425
  const replyTo = compose.replyTo ? [address(compose.replyTo)] : [];
426
+
395
427
  const threadHeaders = related
396
428
  ? replyThreadHeaders(related)
397
429
  : { inReplyTo: [], references: [] };
398
- const continuedList = related?.conversationId === input.conversationId
399
- ? related
400
- : null;
430
+
431
+ const continuedList =
432
+ related?.conversationId === input.conversationId ? related : null;
433
+
401
434
  const email: NewEmail = {
402
435
  id,
403
436
  requestFingerprint: input.requestFingerprint,
@@ -412,20 +445,13 @@ export async function prepareOutgoingEmail(input: {
412
445
  ccJson: cc,
413
446
  bccJson: bcc,
414
447
  subject: compose.subject || "(no subject)",
415
- preview: content.bodyText
416
- .replace(/\s+/gu, " ")
417
- .trim()
418
- .slice(0, 220),
448
+ preview: content.bodyText.replaceAll(/\s+/gu, " ").trim().slice(0, 220),
419
449
  bodyText: content.bodyText,
420
450
  quotedText,
421
451
  bodyHtmlR2Key,
422
452
  attachmentsJson: attachments.map(
423
- ({
424
- downloadUrl: _,
425
- sourceUploadId: __,
426
- sourceObjectKey: ___,
427
- ...file
428
- }) => file,
453
+ ({ downloadUrl: _, sourceUploadId: __, sourceObjectKey: ___, ...file }) =>
454
+ file
429
455
  ),
430
456
  listId: continuedList?.listId ?? null,
431
457
  listPostAddress: continuedList?.listPostAddress ?? null,
@@ -433,6 +459,7 @@ export async function prepareOutgoingEmail(input: {
433
459
  transportState: "unconfirmed",
434
460
  deliveryStatusJson: [],
435
461
  };
462
+
436
463
  return {
437
464
  email,
438
465
  externalizedAttachments: linkedIds.size,
@@ -2,16 +2,16 @@ import {
2
2
  forwardSubject,
3
3
  MAX_MAIL_RECIPIENTS,
4
4
  replySubject,
5
- type ReplyActionMode,
6
5
  } from "../../shared/mail";
6
+ import type { ReplyActionMode } from "../../shared/mail";
7
7
  import { mailboxStub } from "../mailbox";
8
8
  import type { Email } from "../mailbox/schema";
9
- import { hasNewRecipients, shouldDetachOutboundReply } from "./outbound-threading";
10
9
  import {
11
- dedupeRecipientFields,
12
- recipientCount,
13
- type RecipientFields,
14
- } from "./recipients";
10
+ hasNewRecipients,
11
+ shouldDetachOutboundReply,
12
+ } from "./outbound-threading";
13
+ import { dedupeRecipientFields, recipientCount } from "./recipients";
14
+ import type { RecipientFields } from "./recipients";
15
15
  import { buildReplyPlan, canReplyFrom } from "./reply-plan";
16
16
 
17
17
  type OutgoingContextCode = "BAD_REQUEST" | "NOT_FOUND" | "NOT_READY";
@@ -20,7 +20,7 @@ export class OutgoingContextError extends Error {
20
20
  constructor(
21
21
  readonly status: 400 | 404 | 409,
22
22
  readonly code: OutgoingContextCode,
23
- message: string,
23
+ message: string
24
24
  ) {
25
25
  super(message);
26
26
  }
@@ -31,15 +31,18 @@ export async function resolveForwardContext(input: {
31
31
  mailboxId: string;
32
32
  sourceEmailId: string;
33
33
  }) {
34
- const source = await mailboxStub(input.env, input.mailboxId)
35
- .getEmail(input.sourceEmailId);
34
+ const source = await mailboxStub(input.env, input.mailboxId).getEmail(
35
+ input.sourceEmailId
36
+ );
37
+
36
38
  if (!source) {
37
39
  throw new OutgoingContextError(
38
40
  404,
39
41
  "NOT_FOUND",
40
- "Forwarded message was not found",
42
+ "Forwarded message was not found"
41
43
  );
42
44
  }
45
+
43
46
  return {
44
47
  source,
45
48
  subject: forwardSubject(source.subject),
@@ -63,46 +66,53 @@ export async function resolveReplyContext(input: {
63
66
  }> {
64
67
  const stub = mailboxStub(input.env, input.mailboxId);
65
68
  const source = await stub.getEmail(input.sourceEmailId);
69
+
66
70
  if (!source) {
67
71
  throw new OutgoingContextError(
68
72
  404,
69
73
  "NOT_FOUND",
70
- "Reply source was not found",
74
+ "Reply source was not found"
71
75
  );
72
76
  }
77
+
73
78
  if (!canReplyFrom(source)) {
74
79
  throw new OutgoingContextError(
75
80
  409,
76
81
  "NOT_READY",
77
- "Wait until the parent message has a confirmed Message-ID",
82
+ "Wait until the parent message has a confirmed Message-ID"
78
83
  );
79
84
  }
80
85
 
81
86
  const plan = buildReplyPlan(input.ownAddress, source);
87
+
82
88
  const action = plan.actions.find(
83
- (candidate) => candidate.mode === input.mode,
89
+ (candidate) => candidate.mode === input.mode
84
90
  );
91
+
85
92
  if (!action) {
86
93
  throw new OutgoingContextError(
87
94
  400,
88
95
  "BAD_REQUEST",
89
- "Reply mode is not available",
96
+ "Reply mode is not available"
90
97
  );
91
98
  }
99
+
92
100
  const recipients = dedupeRecipientFields({
93
101
  to: action.to,
94
102
  cc: input.cc ?? action.cc,
95
103
  bcc: input.bcc,
96
104
  });
105
+
97
106
  if (recipientCount(recipients) > MAX_MAIL_RECIPIENTS) {
98
107
  throw new OutgoingContextError(
99
108
  400,
100
109
  "BAD_REQUEST",
101
- `An email can have at most ${MAX_MAIL_RECIPIENTS} recipients across To, Cc, and Bcc`,
110
+ `An email can have at most ${MAX_MAIL_RECIPIENTS} recipients across To, Cc, and Bcc`
102
111
  );
103
112
  }
104
113
 
105
114
  const history = await stub.getConversation(source.conversationId);
115
+
106
116
  return {
107
117
  source,
108
118
  recipients,
@@ -1,4 +1,8 @@
1
- import { normalizeEmail, normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
1
+ import {
2
+ normalizeEmail,
3
+ normalizeMailboxAddress,
4
+ } from "@open-workspace/core/module";
5
+
2
6
  import type { MailAddress } from "../mailbox/model";
3
7
 
4
8
  export type ParticipantSource = {
@@ -15,60 +19,64 @@ export type ParticipantSuggestion = {
15
19
 
16
20
  export function normalizedParticipantSet(
17
21
  values: Iterable<string>,
18
- ownAddress: string,
22
+ ownAddress: string
19
23
  ) {
20
24
  const own = normalizeMailboxAddress(ownAddress);
21
25
  const result = new Set<string>();
26
+
22
27
  for (const value of values) {
23
28
  const normalized = normalizeEmail(value);
24
- if (
25
- normalized
26
- && normalizeMailboxAddress(normalized) !== own
27
- ) {
29
+
30
+ if (normalized && normalizeMailboxAddress(normalized) !== own) {
28
31
  result.add(normalized);
29
32
  }
30
33
  }
34
+
31
35
  return result;
32
36
  }
33
37
 
34
38
  export function uniqueParticipantAddresses(
35
39
  values: Iterable<MailAddress>,
36
- ownAddress: string,
40
+ ownAddress: string
37
41
  ) {
38
42
  return [
39
43
  ...normalizedParticipantSet(
40
44
  Array.from(values, (value) => value.address),
41
- ownAddress,
45
+ ownAddress
42
46
  ),
43
47
  ];
44
48
  }
45
49
 
46
50
  export function sameParticipantSet(
47
51
  left: ReadonlySet<string>,
48
- right: ReadonlySet<string>,
52
+ right: ReadonlySet<string>
49
53
  ) {
50
- return left.size === right.size
51
- && [...left].every((value) => right.has(value));
54
+ return (
55
+ left.size === right.size && [...left].every((value) => right.has(value))
56
+ );
52
57
  }
53
58
 
54
59
  export function participantLabels(
55
60
  values: Iterable<MailAddress>,
56
- ownAddress: string,
61
+ ownAddress: string
57
62
  ) {
58
63
  const own = normalizeMailboxAddress(ownAddress);
59
64
  const result = new Map<string, string>();
65
+
60
66
  for (const participant of values) {
61
67
  const normalized = normalizeEmail(participant.address);
68
+
62
69
  if (
63
- !normalized
64
- || normalizeMailboxAddress(normalized) === own
65
- || result.has(normalized)
66
- ) continue;
67
- result.set(
68
- normalized,
69
- participant.name?.trim() || participant.address,
70
- );
70
+ !normalized ||
71
+ normalizeMailboxAddress(normalized) === own ||
72
+ result.has(normalized)
73
+ ) {
74
+ continue;
75
+ }
76
+
77
+ result.set(normalized, participant.name?.trim() || participant.address);
71
78
  }
79
+
72
80
  return [...result.values()];
73
81
  }
74
82
 
@@ -78,7 +86,7 @@ export function suggestParticipants(
78
86
  query: string,
79
87
  limit: number,
80
88
  /** Blocked or reported correspondents are never suggested. */
81
- exclude: (address: string) => boolean = () => false,
89
+ exclude: (address: string) => boolean = () => false
82
90
  ): ParticipantSuggestion[] {
83
91
  const own = normalizeMailboxAddress(ownAddress);
84
92
  const needle = query.trim().toLocaleLowerCase("en-US");
@@ -92,21 +100,28 @@ export function suggestParticipants(
92
100
  ...message.bccJson,
93
101
  ]) {
94
102
  const address = normalizeEmail(participant.address);
103
+
95
104
  if (
96
- !address
97
- || normalizeMailboxAddress(address) === own
98
- || result.has(address)
99
- || exclude(address.toLocaleLowerCase("en-US"))
100
- ) continue;
105
+ !address ||
106
+ normalizeMailboxAddress(address) === own ||
107
+ result.has(address) ||
108
+ exclude(address.toLocaleLowerCase("en-US"))
109
+ ) {
110
+ continue;
111
+ }
112
+
101
113
  const name = participant.name?.trim() || null;
114
+
102
115
  if (
103
- needle
104
- && !address.toLocaleLowerCase("en-US").includes(needle)
105
- && !name?.toLocaleLowerCase("en-US").includes(needle)
116
+ needle &&
117
+ !address.toLocaleLowerCase("en-US").includes(needle) &&
118
+ !name?.toLocaleLowerCase("en-US").includes(needle)
106
119
  ) {
107
120
  continue;
108
121
  }
122
+
109
123
  result.set(address, { address, name });
124
+
110
125
  if (result.size >= limit) return [...result.values()];
111
126
  }
112
127
  }