@open-workspace/email 0.4.2 → 0.5.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 (268) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,538 @@
1
+ /** The mailbox's part of backups: its messages' hashes, its settings and drafts, and restoring them. */
2
+ import {
3
+ and,
4
+ asc,
5
+ eq,
6
+ gt,
7
+ isNotNull,
8
+ isNull,
9
+ getTableColumns,
10
+ or,
11
+ sql,
12
+ } from "drizzle-orm";
13
+
14
+ import type { BackupFile } from "../backups/file-parts";
15
+ import { PART_BYTES } from "../backups/file-parts";
16
+ import * as autoReplies from "./mailbox-auto-reply";
17
+ import * as mailboxDrafts from "./mailbox-drafts";
18
+ import * as mailboxImport from "./mailbox-import";
19
+ import {
20
+ autoReplyLog,
21
+ autoReplySettings,
22
+ conversations,
23
+ drafts,
24
+ emailReadStates,
25
+ emails,
26
+ folders,
27
+ systemFolderOrder,
28
+ mailboxAiConfiguration,
29
+ mailRules,
30
+ senders,
31
+ } from "./schema";
32
+ import type { Email } from "./schema";
33
+ import type {
34
+ DraftInput,
35
+ MailboxBackupSettings,
36
+ MailboxContext,
37
+ } from "./support";
38
+ import { IMPORTED_FOLDERS_KEY, MAX_RULES } from "./support";
39
+
40
+ // A retry can replace the archived MIME, assign a Message-ID, or renew links
41
+ // even when delivery fails again. Read-state and folder changes leave the MIME alone.
42
+ function backupSource(
43
+ email: Pick<
44
+ Email,
45
+ "rawMimeR2Key" | "messageIdHeader" | "transportState" | "attachmentsJson"
46
+ >
47
+ ) {
48
+ return JSON.stringify([
49
+ email.rawMimeR2Key,
50
+ email.messageIdHeader,
51
+ email.transportState,
52
+ email.attachmentsJson.flatMap((file) =>
53
+ file.delivery === "download_link" ? [file.downloadTokenHash] : []
54
+ ),
55
+ ]);
56
+ }
57
+
58
+ /**
59
+ * A page of messages in id order for a backup snapshot: up to `limit`
60
+ * rows with their place, read state and stored hash, within the new-object
61
+ * budget. Keep bodies out of this RPC: even a single page can exceed 32 MiB.
62
+ */
63
+ export function listBackupEmails(
64
+ m: MailboxContext,
65
+ afterId: string | null,
66
+ limit: number,
67
+ newLimit: number
68
+ ) {
69
+ const readers = m.db
70
+ .select({ ids: sql<string>`json_group_array(${emailReadStates.userId})` })
71
+ .from(emailReadStates)
72
+ .where(eq(emailReadStates.emailId, emails.id));
73
+
74
+ const page = m.db
75
+ .select({
76
+ id: emails.id,
77
+ conversationId: emails.conversationId,
78
+ direction: emails.direction,
79
+ envelopeTo: emails.envelopeTo,
80
+ listId: emails.listId,
81
+ listPostAddress: emails.listPostAddress,
82
+ transportState: emails.transportState,
83
+ transportError: emails.transportError,
84
+ deliveryStatusJson: emails.deliveryStatusJson,
85
+ subject: emails.subject,
86
+ timelineAt: emails.timelineAt,
87
+ backupSha256: emails.backupSha256,
88
+ rawMimeR2Key: emails.rawMimeR2Key,
89
+ messageIdHeader: emails.messageIdHeader,
90
+ linked:
91
+ sql<string>`case when instr(${emails.attachmentsJson}, '"download_link"') then ${emails.attachmentsJson} else '[]' end`.mapWith(
92
+ {
93
+ mapFromDriverValue(value: string) {
94
+ const files: Email["attachmentsJson"] = JSON.parse(value);
95
+
96
+ return files.filter((file) => file.delivery === "download_link");
97
+ },
98
+ }
99
+ ),
100
+ mailboxState: conversations.mailboxState,
101
+ folderName: folders.name,
102
+ readers: sql<string>`(${readers})`.mapWith((json: string) => {
103
+ const ids: string[] = JSON.parse(json);
104
+
105
+ return ids;
106
+ }),
107
+ })
108
+ .from(emails)
109
+ .innerJoin(conversations, eq(conversations.id, emails.conversationId))
110
+ .leftJoin(folders, eq(folders.id, conversations.folderId))
111
+ .where(afterId ? gt(emails.id, afterId) : undefined)
112
+ .orderBy(asc(emails.id))
113
+ .limit(limit + 1)
114
+ .all();
115
+
116
+ let more = page.length > limit;
117
+ const rows = [];
118
+ let cost = 0;
119
+
120
+ for (const { linked, rawMimeR2Key, messageIdHeader, ...row } of page.slice(
121
+ 0,
122
+ limit
123
+ )) {
124
+ const backupSha256 = linked.every((file) => file.backupFile)
125
+ ? row.backupSha256
126
+ : null;
127
+
128
+ const weight = backupSha256
129
+ ? 0
130
+ : 1 +
131
+ linked.reduce((n, file) => n + Math.ceil(file.size / PART_BYTES), 0);
132
+
133
+ if (rows.length && cost + weight > newLimit) {
134
+ more = true;
135
+ break;
136
+ }
137
+
138
+ cost += weight;
139
+ rows.push({
140
+ ...row,
141
+ backupSha256,
142
+ pending: backupSha256
143
+ ? null
144
+ : {
145
+ rawMimeR2Key,
146
+ source: backupSource({
147
+ rawMimeR2Key,
148
+ messageIdHeader,
149
+ transportState: row.transportState,
150
+ attachmentsJson: linked,
151
+ }),
152
+ linked,
153
+ },
154
+ attachments: backupSha256
155
+ ? linked.flatMap((file) =>
156
+ file.backupFile
157
+ ? [
158
+ {
159
+ downloadTokenHash: file.downloadTokenHash,
160
+ filename: file.filename,
161
+ contentType: file.contentType,
162
+ file: file.backupFile,
163
+ },
164
+ ]
165
+ : []
166
+ )
167
+ : [],
168
+ });
169
+ }
170
+
171
+ return { rows, more, cost };
172
+ }
173
+
174
+ /** What a backup keeps of the mailbox beside its mail (worker/backups/mail-backup.ts). */
175
+ export function backupSettings(m: MailboxContext) {
176
+ return {
177
+ folders: m.db.select().from(folders).all(),
178
+ systemFolderOrder: m.db.select().from(systemFolderOrder).all(),
179
+ rules: m.db.select().from(mailRules).orderBy(asc(mailRules.position)).all(),
180
+ autoReply: autoReplies.getAutoReply(m),
181
+ autoReplyLog: m.db.select().from(autoReplyLog).all(),
182
+ ai: m.db.select().from(mailboxAiConfiguration).get() ?? null,
183
+ // Blocks and "Not spam"; the counters come back with the mail.
184
+ senders: m.db
185
+ .select({
186
+ address: senders.address,
187
+ domain: senders.domain,
188
+ blockedAt: senders.blockedAt,
189
+ trustedAt: senders.trustedAt,
190
+ })
191
+ .from(senders)
192
+ .where(or(isNotNull(senders.blockedAt), isNotNull(senders.trustedAt)))
193
+ .all(),
194
+ };
195
+ }
196
+
197
+ export type BackupDraftKey = { userId: string; id: string };
198
+
199
+ /** Restoring MIME gives attachments fresh IDs. Equal files keep their order within each delivery type. */
200
+ function portableForwardFiles(files: Email["attachmentsJson"]) {
201
+ const occurrences = new Map<string, number>();
202
+
203
+ return files.map((file) => {
204
+ const key = JSON.stringify([file.filename, file.size, file.delivery]);
205
+ const index = occurrences.get(key) ?? 0;
206
+ occurrences.set(key, index + 1);
207
+
208
+ return { id: file.id, key: `${key}:${index}` };
209
+ });
210
+ }
211
+
212
+ /** Read full draft bodies in small pages. A SQLite row may be up to 2 MiB,
213
+ * and a Durable Object RPC response is limited to 32 MiB. */
214
+ export function listBackupDrafts(
215
+ m: MailboxContext,
216
+ after: BackupDraftKey | null
217
+ ) {
218
+ return m.db
219
+ .select({
220
+ ...getTableColumns(drafts),
221
+ sourceMessageId: emails.messageIdHeader,
222
+ sourceFiles: sql<
223
+ Email["attachmentsJson"] | null
224
+ >`case when ${drafts.forwardedAttachmentIds} is not null then ${emails.attachmentsJson} end`.mapWith(
225
+ emails.attachmentsJson
226
+ ),
227
+ })
228
+ .from(drafts)
229
+ .leftJoin(emails, eq(emails.id, drafts.sourceEmailId))
230
+ .where(
231
+ after
232
+ ? sql`(${drafts.userId}, ${drafts.id}) > (${after.userId}, ${after.id})`
233
+ : undefined
234
+ )
235
+ .orderBy(asc(drafts.userId), asc(drafts.id))
236
+ .limit(8)
237
+ .all()
238
+ .map(({ sourceFiles, forwardedAttachmentIds, ...draft }) => ({
239
+ ...draft,
240
+ forwardedFiles: forwardedAttachmentIds
241
+ ? portableForwardFiles(sourceFiles ?? [])
242
+ .filter((file) => forwardedAttachmentIds.includes(file.id))
243
+ .map((file) => file.key)
244
+ : null,
245
+ }));
246
+ }
247
+
248
+ /**
249
+ * Adds what `settings` holds that the mailbox lacks; nothing here is
250
+ * changed. Folders match by name, rules by id (their folders follow the
251
+ * names), a sender's block or trust only where the sender has neither, and
252
+ * the auto-reply, its log and the AI instructions only if none is set.
253
+ * Reports unapplied settings so the CLI can retry this line.
254
+ */
255
+ export function restoreSettings(
256
+ m: MailboxContext,
257
+ settings: MailboxBackupSettings
258
+ ) {
259
+ let added = 0;
260
+ const skipped = new Set<string>();
261
+
262
+ m.state.storage.transactionSync(() => {
263
+ const folderIds = new Map<string, string>();
264
+ const missingFolders = new Set<string>();
265
+
266
+ // Folders a person placed keep their place; new ones, and those the
267
+ // restore's own message lines just created, take the saved one.
268
+ const imported = new Set(
269
+ m.state.storage.kv.get<string[]>(IMPORTED_FOLDERS_KEY)
270
+ );
271
+
272
+ const before = new Set(
273
+ m.db
274
+ .select({ id: folders.id })
275
+ .from(folders)
276
+ .all()
277
+ .map((row) => row.id)
278
+ .filter((id) => !imported.has(id))
279
+ );
280
+
281
+ for (const folder of settings.folders) {
282
+ // Created at the end: the saved place is set just below.
283
+ const placed = mailboxImport.importFolder(m, folder.name, "end");
284
+
285
+ if ("skipped" in placed) {
286
+ missingFolders.add(folder.id);
287
+ skipped.add(
288
+ mailboxImport.importFolderError(folder.name, placed.skipped)
289
+ );
290
+ continue;
291
+ }
292
+
293
+ folderIds.set(folder.id, placed.id);
294
+
295
+ if (!before.has(placed.id)) {
296
+ m.db
297
+ .update(folders)
298
+ .set({ sortOrder: folder.sortOrder })
299
+ .where(eq(folders.id, placed.id))
300
+ .run();
301
+ added += 1;
302
+ }
303
+ }
304
+
305
+ m.state.storage.kv.delete(IMPORTED_FOLDERS_KEY);
306
+
307
+ for (const row of settings.systemFolderOrder) {
308
+ added += m.db
309
+ .insert(systemFolderOrder)
310
+ .values(row)
311
+ .onConflictDoNothing()
312
+ .returning()
313
+ .all().length;
314
+ }
315
+
316
+ const rules = m.db
317
+ .select({ id: mailRules.id, position: mailRules.position })
318
+ .from(mailRules)
319
+ .all();
320
+
321
+ const ruleIds = new Set(rules.map((rule) => rule.id));
322
+ let position = Math.max(0, ...rules.map((rule) => rule.position));
323
+
324
+ for (const rule of settings.rules) {
325
+ if (ruleIds.has(rule.id)) continue;
326
+
327
+ if (ruleIds.size >= MAX_RULES) {
328
+ skipped.add("rules limit");
329
+ break;
330
+ }
331
+
332
+ // Rules are appended in order. Resume from this rule once its folder fits.
333
+ if (
334
+ rule.actionsJson.some(
335
+ (action) =>
336
+ action.type === "moveToFolder" &&
337
+ missingFolders.has(action.folderId)
338
+ )
339
+ ) {
340
+ break;
341
+ }
342
+
343
+ ruleIds.add(rule.id);
344
+ position += 1;
345
+ m.db
346
+ .insert(mailRules)
347
+ .values({
348
+ ...rule,
349
+ position,
350
+ // A folder deleted before the backup keeps its old id: still "deleted".
351
+ actionsJson: rule.actionsJson.map((action) =>
352
+ action.type === "moveToFolder"
353
+ ? {
354
+ ...action,
355
+ folderId: folderIds.get(action.folderId) ?? action.folderId,
356
+ }
357
+ : action
358
+ ),
359
+ })
360
+ .run();
361
+ added += 1;
362
+ }
363
+
364
+ const autoReply = settings.autoReply
365
+ ? m.db
366
+ .insert(autoReplySettings)
367
+ .values({ ...settings.autoReply, id: 1 })
368
+ .onConflictDoNothing()
369
+ .returning()
370
+ .all()
371
+ : [];
372
+
373
+ if (autoReply.length) {
374
+ added += 1;
375
+
376
+ for (const row of settings.autoReplyLog) {
377
+ m.db.insert(autoReplyLog).values(row).onConflictDoNothing().run();
378
+ }
379
+ }
380
+
381
+ if (settings.ai) {
382
+ added += m.db
383
+ .insert(mailboxAiConfiguration)
384
+ .values(settings.ai)
385
+ .onConflictDoNothing()
386
+ .returning()
387
+ .all().length;
388
+ }
389
+
390
+ for (const sender of settings.senders) {
391
+ added += m.db
392
+ .insert(senders)
393
+ .values(sender)
394
+ .onConflictDoUpdate({
395
+ target: senders.address,
396
+ set: {
397
+ blockedAt: sql`excluded.blocked_at`,
398
+ trustedAt: sql`excluded.trusted_at`,
399
+ },
400
+ setWhere: and(isNull(senders.blockedAt), isNull(senders.trustedAt)),
401
+ })
402
+ .returning()
403
+ .all().length;
404
+ }
405
+ });
406
+
407
+ if (added) {
408
+ m.forgetParticipants();
409
+ void m.announce({ inboxChanged: false });
410
+ }
411
+
412
+ return { changed: added > 0, skipped: [...skipped] };
413
+ }
414
+
415
+ /**
416
+ * Adds a person's draft unless they have one with its id. A reply or
417
+ * forward finds its message by its id, the id the restored copy got
418
+ * (`restoredSource.id`), or its Message-ID (a copy already here); without
419
+ * one it becomes a new message with the same contents.
420
+ */
421
+ export function restoreDraft(
422
+ m: MailboxContext,
423
+ userId: string,
424
+ input: DraftInput,
425
+ restoredSource: {
426
+ id: string | null;
427
+ messageId: string | null;
428
+ forwardedFiles?: string[] | null;
429
+ }
430
+ ) {
431
+ const copy = (messageId: string) =>
432
+ m.db
433
+ .select({
434
+ id: emails.id,
435
+ conversationId: emails.conversationId,
436
+ attachmentsJson: emails.attachmentsJson,
437
+ })
438
+ .from(emails)
439
+ .where(eq(emails.messageIdHeader, messageId))
440
+ .get() ?? null;
441
+
442
+ const source = input.sourceEmailId
443
+ ? (m.getEmail(input.sourceEmailId) ??
444
+ (restoredSource.id ? m.getEmail(restoredSource.id) : null) ??
445
+ (restoredSource.messageId ? copy(restoredSource.messageId) : null))
446
+ : null;
447
+
448
+ const draft: DraftInput = source
449
+ ? {
450
+ ...input,
451
+ sourceEmailId: source.id,
452
+ forwardedAttachmentIds: restoredSource.forwardedFiles
453
+ ? portableForwardFiles(source.attachmentsJson)
454
+ .filter((file) =>
455
+ restoredSource.forwardedFiles?.includes(file.key)
456
+ )
457
+ .map((file) => file.id)
458
+ : input.forwardedAttachmentIds,
459
+ conversationId: source.conversationId,
460
+ }
461
+ : {
462
+ ...input,
463
+ kind: "compose",
464
+ sourceEmailId: null,
465
+ forwardedAttachmentIds: null,
466
+ conversationId: null,
467
+ replyMode: null,
468
+ };
469
+
470
+ const result = mailboxDrafts.writeDraft(
471
+ m,
472
+ userId,
473
+ draft,
474
+ 0,
475
+ mailboxDrafts.getDraft(m, userId, input.id)
476
+ );
477
+
478
+ if (result.status === "saved") {
479
+ mailboxDrafts.announceDrafts(m, true);
480
+ }
481
+
482
+ if (result.status === "conflict" && result.draft?.id !== input.id) {
483
+ return "replyExists";
484
+ }
485
+
486
+ return result.status;
487
+ }
488
+
489
+ /**
490
+ * Forgets every backup hash: the address stopped keeping mail, so its
491
+ * objects may be swept once no kept snapshot names them, and the hashes
492
+ * would then name objects that are gone.
493
+ */
494
+ export function clearBackupHashes(m: MailboxContext) {
495
+ m.db
496
+ .update(emails)
497
+ .set({ backupSha256: null })
498
+ .where(isNotNull(emails.backupSha256))
499
+ .run();
500
+ }
501
+
502
+ export type BackupHash = {
503
+ id: string;
504
+ source: string;
505
+ sha256: string;
506
+ files?: Record<string, BackupFile>;
507
+ };
508
+
509
+ export function setBackupHashes(m: MailboxContext, hashes: BackupHash[]) {
510
+ m.state.storage.transactionSync(() => {
511
+ for (const { id, source, sha256, files } of hashes) {
512
+ const current = m.db
513
+ .select({
514
+ rawMimeR2Key: emails.rawMimeR2Key,
515
+ messageIdHeader: emails.messageIdHeader,
516
+ transportState: emails.transportState,
517
+ attachmentsJson: emails.attachmentsJson,
518
+ })
519
+ .from(emails)
520
+ .where(eq(emails.id, id))
521
+ .get();
522
+
523
+ if (!current || backupSource(current) !== source) continue;
524
+
525
+ const attachments =
526
+ files &&
527
+ current.attachmentsJson.map((file) =>
528
+ files[file.id] ? { ...file, backupFile: files[file.id] } : file
529
+ );
530
+
531
+ m.db
532
+ .update(emails)
533
+ .set({ backupSha256: sha256, attachmentsJson: attachments })
534
+ .where(eq(emails.id, id))
535
+ .run();
536
+ }
537
+ });
538
+ }