@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,14 +1,20 @@
1
- import type { Email } from "../mailbox/schema";
2
1
  import {
3
2
  LINKED_ATTACHMENT_TEXT_PREFIX,
4
3
  linkedAttachmentTextToken,
5
4
  } from "../../shared/mail";
5
+ import type { Email } from "../mailbox/schema";
6
6
 
7
7
  const MAX_CONTEXT_CHARACTERS = 24_000;
8
8
 
9
9
  type ContentSource = Pick<
10
10
  Email,
11
- "fromJson" | "toJson" | "ccJson" | "subject" | "timelineAt" | "bodyText" | "preview"
11
+ | "fromJson"
12
+ | "toJson"
13
+ | "ccJson"
14
+ | "subject"
15
+ | "timelineAt"
16
+ | "bodyText"
17
+ | "preview"
12
18
  >;
13
19
 
14
20
  export function escapeHtml(value: string) {
@@ -22,13 +28,18 @@ export function escapeHtml(value: string) {
22
28
 
23
29
  function displayAddress(email: ContentSource) {
24
30
  const from = email.fromJson[0];
31
+
25
32
  if (!from) return "Unknown sender";
33
+
26
34
  return from.name ? `${from.name} <${from.address}>` : from.address;
27
35
  }
28
36
 
29
37
  function clippedBody(email: ContentSource) {
30
- const value = email.bodyText?.trim() || email.preview.trim() || "No text body";
38
+ const value =
39
+ email.bodyText?.trim() || email.preview.trim() || "No text body";
40
+
31
41
  if (value.length <= MAX_CONTEXT_CHARACTERS) return value;
42
+
32
43
  return `${value.slice(0, MAX_CONTEXT_CHARACTERS).trimEnd()}\n[Context truncated]`;
33
44
  }
34
45
 
@@ -51,24 +62,31 @@ export function contextForNewRecipient(email: ContentSource) {
51
62
  }
52
63
 
53
64
  export function forwardedMessageText(email: ContentSource) {
54
- return ["Forwarded message", ...metadataLines(email), "", clippedBody(email)].join("\n");
65
+ return [
66
+ "Forwarded message",
67
+ ...metadataLines(email),
68
+ "",
69
+ clippedBody(email),
70
+ ].join("\n");
55
71
  }
56
72
 
57
73
  export function forwardedMessageHtml(email: ContentSource) {
58
74
  const metadata = metadataLines(email)
59
75
  .map((line) => `<div>${escapeHtml(line)}</div>`)
60
76
  .join("");
77
+
61
78
  return `<section data-forwarded-message><strong>Forwarded message</strong>${metadata}<pre style="white-space:pre-wrap">${escapeHtml(clippedBody(email))}</pre></section>`;
62
79
  }
63
80
 
64
81
  export function appendForwardedMessage(
65
82
  bodyText: string,
66
83
  bodyHtml: string | undefined,
67
- forwarded: ContentSource | null,
84
+ forwarded: ContentSource | null
68
85
  ) {
69
86
  if (!forwarded) return { bodyText, bodyHtml };
70
87
  const text = forwardedMessageText(forwarded);
71
88
  const nextText = `${bodyText.trimEnd()}${bodyText.trimEnd() ? "\n\n" : ""}${text}`;
89
+
72
90
  return {
73
91
  bodyText: nextText,
74
92
  bodyHtml: bodyHtml
@@ -77,42 +95,59 @@ export function appendForwardedMessage(
77
95
  };
78
96
  }
79
97
 
80
- export function textWithQuotedContext(bodyText: string, quotedText: string | null) {
98
+ export function textWithQuotedContext(
99
+ bodyText: string,
100
+ quotedText: string | null
101
+ ) {
81
102
  if (!quotedText) return bodyText;
82
- const quote = quotedText.split("\n").map((line) => `> ${line}`).join("\n");
103
+
104
+ const quote = quotedText
105
+ .split("\n")
106
+ .map((line) => `> ${line}`)
107
+ .join("\n");
108
+
83
109
  return `${bodyText.trimEnd()}${bodyText.trimEnd() ? "\n\n" : ""}${quote}`;
84
110
  }
85
111
 
86
- export function htmlWithQuotedContext(bodyHtml: string, quotedText: string | null) {
112
+ export function htmlWithQuotedContext(
113
+ bodyHtml: string,
114
+ quotedText: string | null
115
+ ) {
87
116
  if (!quotedText) return bodyHtml;
117
+
88
118
  return `${bodyHtml}<blockquote><pre style="white-space:pre-wrap">${escapeHtml(quotedText)}</pre></blockquote>`;
89
119
  }
90
120
 
91
121
  export function externalizeLinkedInlineImages(
92
122
  bodyHtml: string,
93
- attachments: Array<{
123
+ attachments: {
94
124
  disposition: "attachment" | "inline";
95
125
  contentId: string | null;
96
126
  filename: string;
97
127
  downloadUrl: string;
98
- }>,
128
+ }[]
99
129
  ) {
100
130
  let nextHtml = bodyHtml;
131
+
101
132
  for (const attachment of attachments) {
102
133
  if (attachment.disposition !== "inline" || !attachment.contentId) continue;
103
- const escapedContentId = attachment.contentId.replace(
134
+
135
+ const escapedContentId = attachment.contentId.replaceAll(
104
136
  /[.*+?^${}()|[\]\\]/gu,
105
- "\\$&",
137
+ "\\$&"
106
138
  );
139
+
107
140
  const image = new RegExp(
108
141
  `<img(?=[^>]*\\bsrc=(["'])cid:${escapedContentId}\\1)[^>]*>`,
109
- "giu",
142
+ "giu"
110
143
  );
111
- nextHtml = nextHtml.replace(
144
+
145
+ nextHtml = nextHtml.replaceAll(
112
146
  image,
113
- `<a href="${escapeHtml(attachment.downloadUrl)}">${escapeHtml(attachment.filename)}</a>`,
147
+ `<a href="${escapeHtml(attachment.downloadUrl)}">${escapeHtml(attachment.filename)}</a>`
114
148
  );
115
149
  }
150
+
116
151
  return nextHtml;
117
152
  }
118
153
 
@@ -123,16 +158,18 @@ type PositionedLinkedAttachment = {
123
158
  };
124
159
 
125
160
  function escapeRegExp(value: string) {
126
- return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
161
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
127
162
  }
128
163
 
129
164
  const unresolvedLinkedAttachmentText = new RegExp(
130
165
  `\\[\\[${escapeRegExp(LINKED_ATTACHMENT_TEXT_PREFIX)}[^\\]]+\\]\\]`,
131
- "gu",
166
+ "gu"
132
167
  );
168
+
169
+ // oxlint-disable-next-line prefer-regex-literals -- the pattern is built with escaped backslashes in a template
133
170
  const unresolvedLinkedAttachmentHtml = new RegExp(
134
171
  `<span(?=[^>]*\\bdata-linked-attachment=(["'])[^"']*\\1)[^>]*>[\\s\\S]*?<\\/span>`,
135
- "giu",
172
+ "giu"
136
173
  );
137
174
 
138
175
  function linkedAttachmentHtml(filename: string, downloadUrl: string) {
@@ -156,51 +193,59 @@ export function resolveLinkedAttachmentPlaceholders(input: {
156
193
  bodyHtml: string | undefined;
157
194
  attachments: PositionedLinkedAttachment[];
158
195
  }) {
159
- let bodyText = input.bodyText;
160
- let bodyHtml = input.bodyHtml;
196
+ let { bodyText } = input;
197
+ let { bodyHtml } = input;
161
198
  const textPlacedUploadIds = new Set<string>();
162
199
  const htmlPlacedUploadIds = new Set<string>();
163
200
 
164
201
  for (const attachment of input.attachments) {
165
202
  if (!attachment.uploadId) continue;
166
203
  const textToken = linkedAttachmentTextToken(attachment.uploadId);
204
+
167
205
  if (bodyText.includes(textToken)) {
168
206
  bodyText = bodyText.replaceAll(
169
207
  textToken,
170
208
  attachment.downloadUrl
171
209
  ? `${attachment.filename}: ${attachment.downloadUrl}`
172
- : "",
210
+ : ""
173
211
  );
212
+
174
213
  if (attachment.downloadUrl) {
175
214
  textPlacedUploadIds.add(attachment.uploadId);
176
215
  }
177
216
  }
217
+
178
218
  if (!bodyHtml) continue;
179
219
 
180
220
  const marker = escapeRegExp(attachment.uploadId);
221
+
181
222
  const placeholder = new RegExp(
182
223
  `<span(?=[^>]*\\bdata-linked-attachment=(["'])${marker}\\1)[^>]*>[\\s\\S]*?<\\/span>`,
183
- "giu",
224
+ "giu"
184
225
  );
226
+
185
227
  let matched = false;
186
- bodyHtml = bodyHtml.replace(placeholder, () => {
228
+ bodyHtml = bodyHtml.replaceAll(placeholder, () => {
187
229
  matched = true;
230
+
188
231
  return attachment.downloadUrl
189
232
  ? linkedAttachmentHtml(attachment.filename, attachment.downloadUrl)
190
233
  : "";
191
234
  });
235
+
192
236
  if (matched && attachment.downloadUrl) {
193
237
  htmlPlacedUploadIds.add(attachment.uploadId);
194
238
  }
195
239
  }
196
240
 
197
- bodyText = bodyText.replace(unresolvedLinkedAttachmentText, "");
241
+ bodyText = bodyText.replaceAll(unresolvedLinkedAttachmentText, "");
242
+
198
243
  if (bodyHtml) {
199
- bodyHtml = bodyHtml.replace(unresolvedLinkedAttachmentHtml, "");
244
+ bodyHtml = bodyHtml.replaceAll(unresolvedLinkedAttachmentHtml, "");
200
245
  }
201
246
 
202
247
  return {
203
- bodyText: bodyText.replace(/\n{3,}/gu, "\n\n"),
248
+ bodyText: bodyText.replaceAll(/\n{3,}/gu, "\n\n"),
204
249
  bodyHtml,
205
250
  textPlacedUploadIds,
206
251
  htmlPlacedUploadIds,
@@ -6,13 +6,14 @@ import {
6
6
  import { dedupeRecipientFields } from "./recipients";
7
7
 
8
8
  export function emailDestinations(
9
- message: Pick<Email, "toJson" | "ccJson" | "bccJson">,
9
+ message: Pick<Email, "toJson" | "ccJson" | "bccJson">
10
10
  ) {
11
11
  const { to, cc, bcc } = dedupeRecipientFields({
12
12
  to: message.toJson.map((item) => item.address),
13
13
  cc: message.ccJson.map((item) => item.address),
14
14
  bcc: message.bccJson.map((item) => item.address),
15
15
  });
16
+
16
17
  if (to.length) {
17
18
  return {
18
19
  to,
@@ -20,27 +21,36 @@ export function emailDestinations(
20
21
  bcc: bcc.length ? bcc : undefined,
21
22
  };
22
23
  }
24
+
23
25
  if (cc.length) return { cc, bcc: bcc.length ? bcc : undefined };
26
+
24
27
  if (bcc.length) return { bcc };
25
28
  throw new Error("Queued message has no recipients");
26
29
  }
27
30
 
28
31
  export async function prepareOutboundDelivery(env: Env, message: Email) {
29
32
  const storedHtml = message.bodyHtmlR2Key
30
- ? await env.MAIL_STORAGE.get(message.bodyHtmlR2Key).then(
31
- (object) => object?.text(),
33
+ ? await env.MAIL_STORAGE.get(message.bodyHtmlR2Key).then((object) =>
34
+ object?.text()
32
35
  )
33
36
  : undefined;
37
+
34
38
  const html = storedHtml
35
39
  ? htmlWithQuotedContext(storedHtml, message.quotedText)
36
40
  : undefined;
41
+
37
42
  const attachments: EmailAttachment[] = await Promise.all(
38
43
  message.attachmentsJson
39
44
  .filter((attachment) => attachment.delivery === "attached")
40
45
  .map(async (attachment) => {
41
46
  const object = await env.MAIL_STORAGE.get(attachment.r2Key);
42
- if (!object) throw new Error(`Attachment ${attachment.filename} is missing`);
47
+
48
+ if (!object) {
49
+ throw new Error(`Attachment ${attachment.filename} is missing`);
50
+ }
51
+
43
52
  const content = await object.arrayBuffer();
53
+
44
54
  return attachment.disposition === "inline"
45
55
  ? {
46
56
  disposition: "inline" as const,
@@ -55,29 +65,33 @@ export async function prepareOutboundDelivery(env: Env, message: Email) {
55
65
  type: attachment.contentType,
56
66
  content,
57
67
  };
58
- }),
68
+ })
59
69
  );
70
+
60
71
  const from = message.fromJson[0];
72
+
61
73
  if (!from) throw new Error("Outgoing message has no From address");
74
+ // Threading headers, each only when the message has references to carry.
75
+ const headers: Record<string, string> = {};
76
+
77
+ if (message.inReplyToJson.length) {
78
+ headers["In-Reply-To"] = message.inReplyToJson.join(" ");
79
+ }
80
+
81
+ if (message.referencesJson.length) {
82
+ headers.References = message.referencesJson.join(" ");
83
+ }
62
84
 
63
85
  return {
64
86
  from: { name: from.name ?? "", email: from.address },
65
87
  ...emailDestinations(message),
66
88
  replyTo: message.replyToJson[0]?.address,
67
89
  subject: message.subject,
68
- text: textWithQuotedContext(
69
- message.bodyText ?? "",
70
- message.quotedText,
71
- ) || undefined,
90
+ text:
91
+ textWithQuotedContext(message.bodyText ?? "", message.quotedText) ||
92
+ undefined,
72
93
  html,
73
94
  attachments: attachments.length ? attachments : undefined,
74
- headers: {
75
- ...(message.inReplyToJson.length
76
- ? { "In-Reply-To": message.inReplyToJson.join(" ") }
77
- : {}),
78
- ...(message.referencesJson.length
79
- ? { References: message.referencesJson.join(" ") }
80
- : {}),
81
- },
95
+ headers,
82
96
  };
83
97
  }
@@ -1,3 +1,13 @@
1
+ import {
2
+ deferWebhookTask,
3
+ queueWebhookEvent,
4
+ } from "@open-workspace/core/module";
5
+
6
+ import {
7
+ EMAIL_SENT_EVENT,
8
+ EMAIL_WEBHOOK_SOURCE,
9
+ emailWebhookEventId,
10
+ } from "../../shared/webhooks";
1
11
  import { mailboxStub } from "../mailbox";
2
12
  import type { Email } from "../mailbox/schema";
3
13
  import {
@@ -5,14 +15,9 @@ import {
5
15
  messageIdForRequest,
6
16
  outgoingRequestFingerprint,
7
17
  prepareOutgoingEmail,
8
- type OutgoingMessageInput,
9
18
  } from "./outbound";
19
+ import type { OutgoingMessageInput } from "./outbound";
10
20
  import { discardComposerUploads } from "./uploads";
11
- import {
12
- deferWebhookTask,
13
- emailWebhookEventId,
14
- queueWebhookEvent,
15
- } from "@open-workspace/core/worker/webhooks/service.ts";
16
21
 
17
22
  export class OutgoingRequestConflictError extends Error {}
18
23
 
@@ -23,13 +28,16 @@ function deferComposerUploadCleanup(input: {
23
28
  defer: (task: Promise<unknown>) => void;
24
29
  }) {
25
30
  const uploadIds = [...new Set(input.uploadIds)];
31
+
26
32
  if (!uploadIds.length) return;
27
- input.defer(discardComposerUploads({
28
- env: input.env,
29
- mailboxId: input.compose.mailboxId,
30
- userId: input.compose.userId,
31
- uploadIds,
32
- }));
33
+ input.defer(
34
+ discardComposerUploads({
35
+ env: input.env,
36
+ mailboxId: input.compose.mailboxId,
37
+ userId: input.compose.userId,
38
+ uploadIds,
39
+ })
40
+ );
33
41
  }
34
42
 
35
43
  export function deferEmailSentWebhook(input: {
@@ -39,20 +47,22 @@ export function deferEmailSentWebhook(input: {
39
47
  defer: (task: Promise<unknown>) => void;
40
48
  }) {
41
49
  if (input.email.transportState !== "submitted") return;
42
- deferWebhookTask(input.defer, () => queueWebhookEvent(input.env, {
43
- eventId: emailWebhookEventId(
44
- "email.sent",
45
- input.mailboxId,
46
- input.email.id,
47
- ),
48
- eventType: "email.sent",
49
- occurredAt: input.email.timelineAt.getTime(),
50
- source: {
51
- kind: "email",
52
- mailboxId: input.mailboxId,
53
- messageId: input.email.id,
54
- },
55
- }));
50
+ deferWebhookTask(input.defer, () =>
51
+ queueWebhookEvent(input.env, {
52
+ eventId: emailWebhookEventId(
53
+ EMAIL_SENT_EVENT,
54
+ input.mailboxId,
55
+ input.email.id
56
+ ),
57
+ eventType: EMAIL_SENT_EVENT,
58
+ occurredAt: input.email.timelineAt.getTime(),
59
+ source: {
60
+ kind: EMAIL_WEBHOOK_SOURCE,
61
+ mailboxId: input.mailboxId,
62
+ messageId: input.email.id,
63
+ },
64
+ })
65
+ );
56
66
  }
57
67
 
58
68
  export async function submitOutgoing(input: {
@@ -72,17 +82,19 @@ export async function submitOutgoing(input: {
72
82
  const id = await messageIdForRequest(compose.mailboxId, compose.requestId);
73
83
  const requestFingerprint = await outgoingRequestFingerprint(compose);
74
84
  const existing = await stub.getEmail(id);
85
+
75
86
  if (existing) {
76
87
  if (
77
- existing.direction !== "outgoing"
78
- || existing.requestFingerprint !== requestFingerprint
88
+ existing.direction !== "outgoing" ||
89
+ existing.requestFingerprint !== requestFingerprint
79
90
  ) {
80
91
  // The conflicting request was not accepted, so its composer still owns
81
92
  // these immutable uploads and may retry them with a fresh attempt id.
82
93
  throw new OutgoingRequestConflictError(
83
- "Request identifier is already in use with different content",
94
+ "Request identifier is already in use with different content"
84
95
  );
85
96
  }
97
+
86
98
  deferComposerUploadCleanup({
87
99
  ...input,
88
100
  uploadIds: compose.attachments.map((attachment) => attachment.uploadId),
@@ -93,6 +105,7 @@ export async function submitOutgoing(input: {
93
105
  email: existing,
94
106
  defer: input.defer,
95
107
  });
108
+
96
109
  return { email: existing, inserted: false };
97
110
  }
98
111
 
@@ -112,22 +125,26 @@ export async function submitOutgoing(input: {
112
125
  });
113
126
 
114
127
  let submission: Awaited<ReturnType<typeof stub.submitOutgoing>>;
128
+
115
129
  try {
116
130
  submission = await stub.submitOutgoing(prepared.email);
117
131
  } catch (error) {
118
132
  await discardPreparedObjects(input.env, prepared.storageKeys);
119
133
  throw error;
120
134
  }
135
+
121
136
  if (submission.outcome !== "inserted") {
122
137
  await discardPreparedObjects(input.env, prepared.storageKeys);
138
+
123
139
  if (submission.outcome === "conflict") {
124
140
  // Do not clean the losing request's composer uploads. Only prepared
125
141
  // message-scoped copies belong to this failed submission attempt.
126
142
  throw new OutgoingRequestConflictError(
127
- "Request identifier is already in use with different content",
143
+ "Request identifier is already in use with different content"
128
144
  );
129
145
  }
130
146
  }
147
+
131
148
  deferComposerUploadCleanup({
132
149
  ...input,
133
150
  uploadIds: prepared.composerUploadIds,
@@ -138,6 +155,7 @@ export async function submitOutgoing(input: {
138
155
  email: submission.email,
139
156
  defer: input.defer,
140
157
  });
158
+
141
159
  return {
142
160
  email: submission.email,
143
161
  inserted: submission.outcome === "inserted",
@@ -1,9 +1,6 @@
1
1
  import type { ReplyPlan } from "../../shared/mail";
2
2
  import type { Email } from "../mailbox/schema";
3
- import {
4
- normalizedParticipantSet,
5
- sameParticipantSet,
6
- } from "./participants";
3
+ import { normalizedParticipantSet, sameParticipantSet } from "./participants";
7
4
 
8
5
  type ParticipantEmail = Pick<
9
6
  Email,
@@ -27,29 +24,43 @@ export function shouldDetachOutboundReply(input: {
27
24
  }) {
28
25
  if (!input.plan.isGroup) return false;
29
26
 
30
- const actual = normalizedRecipients([...input.to, ...input.cc], input.ownAddress);
27
+ const actual = normalizedRecipients(
28
+ [...input.to, ...input.cc],
29
+ input.ownAddress
30
+ );
31
+
31
32
  if (actual.size > 1) return false;
32
33
 
33
- const listAction = input.plan.actions.find((action) => action.mode === "reply_list");
34
+ const listAction = input.plan.actions.find(
35
+ (action) => action.mode === "reply_list"
36
+ );
37
+
34
38
  const matchesListPost = listAction
35
39
  ? sameParticipantSet(
36
40
  actual,
37
- normalizedRecipients([...listAction.to, ...listAction.cc], input.ownAddress),
41
+ normalizedRecipients(
42
+ [...listAction.to, ...listAction.cc],
43
+ input.ownAddress
44
+ )
38
45
  )
39
46
  : false;
47
+
40
48
  return !matchesListPost;
41
49
  }
42
50
 
43
51
  function previousParticipants(ownAddress: string, history: ParticipantEmail[]) {
44
- const values = history.flatMap((message) => [
45
- ...message.fromJson,
46
- ...message.toJson,
47
- ...message.ccJson,
48
- ...message.bccJson,
49
- ...(message.listPostAddress
50
- ? [{ address: message.listPostAddress, name: null }]
51
- : []),
52
- ]).map((item) => item.address);
52
+ const values = history
53
+ .flatMap((message) => [
54
+ ...message.fromJson,
55
+ ...message.toJson,
56
+ ...message.ccJson,
57
+ ...message.bccJson,
58
+ ...(message.listPostAddress
59
+ ? [{ address: message.listPostAddress, name: null }]
60
+ : []),
61
+ ])
62
+ .map((item) => item.address);
63
+
53
64
  return normalizedRecipients(values, ownAddress);
54
65
  }
55
66
 
@@ -62,9 +73,11 @@ export function hasNewRecipients(input: {
62
73
  }) {
63
74
  if (!input.history.length) return false;
64
75
  const previous = previousParticipants(input.ownAddress, input.history);
76
+
65
77
  const next = normalizedRecipients(
66
78
  [...input.to, ...input.cc, ...input.bcc],
67
- input.ownAddress,
79
+ input.ownAddress
68
80
  );
81
+
69
82
  return [...next].some((recipient) => !previous.has(recipient));
70
83
  }