@remit/mailbox-service 0.0.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 (124) hide show
  1. package/README.md +147 -0
  2. package/package.json +65 -0
  3. package/src/account-credentials.ts +128 -0
  4. package/src/adversarial-mime.e2e.test.ts +311 -0
  5. package/src/attribute-mapper.test.ts +78 -0
  6. package/src/attribute-mapper.ts +147 -0
  7. package/src/body-part-mapper.property.test.ts +354 -0
  8. package/src/body-part-mapper.ts +360 -0
  9. package/src/body-sync-queue.test.ts +124 -0
  10. package/src/body-sync-queue.ts +131 -0
  11. package/src/body-sync-terminal.test.ts +265 -0
  12. package/src/body-sync-terminal.ts +172 -0
  13. package/src/body-sync.ts +1202 -0
  14. package/src/connection-factory.ts +102 -0
  15. package/src/connection-test.ts +208 -0
  16. package/src/credentials.test.ts +181 -0
  17. package/src/filters/match.test.ts +181 -0
  18. package/src/filters/match.ts +143 -0
  19. package/src/filters/pipeline.ts +243 -0
  20. package/src/flag-push-terminal.test.ts +156 -0
  21. package/src/flag-push-terminal.ts +106 -0
  22. package/src/flag-push.test.ts +408 -0
  23. package/src/flag-push.ts +198 -0
  24. package/src/flag-queue.ts +500 -0
  25. package/src/heuristics/classifyByHeaders.test.ts +578 -0
  26. package/src/heuristics/classifyByHeaders.ts +369 -0
  27. package/src/heuristics/classifyPlacement.ts +96 -0
  28. package/src/heuristics/socialDomains.ts +23 -0
  29. package/src/heuristics/transactionalDomains.ts +26 -0
  30. package/src/imapflow-connect-retry.test.ts +108 -0
  31. package/src/imapflow-connection.e2e.test.ts +355 -0
  32. package/src/imapflow-connection.integ.test.ts +327 -0
  33. package/src/imapflow-connection.test.ts +161 -0
  34. package/src/imapflow-connection.ts +1374 -0
  35. package/src/index.ts +214 -0
  36. package/src/mailbox-cursor-rebuild.test.ts +171 -0
  37. package/src/mailbox-cursor-rebuild.ts +146 -0
  38. package/src/mailbox-cursor.test.ts +249 -0
  39. package/src/mailbox-cursor.ts +177 -0
  40. package/src/mailbox-management.test.ts +103 -0
  41. package/src/mailbox-management.ts +235 -0
  42. package/src/mailbox-queue.ts +258 -0
  43. package/src/mailbox-sync.test.ts +153 -0
  44. package/src/mailbox-sync.ts +590 -0
  45. package/src/message-move.ts +825 -0
  46. package/src/message-parser.ts +26 -0
  47. package/src/message-sync.ts +1021 -0
  48. package/src/mime-walker.test.ts +311 -0
  49. package/src/mime-walker.ts +305 -0
  50. package/src/outbox-queue.ts +294 -0
  51. package/src/pass-through-unit-of-work.ts +17 -0
  52. package/src/placement-move-terminal.test.ts +179 -0
  53. package/src/placement-move-terminal.ts +104 -0
  54. package/src/placement-move.ts +224 -0
  55. package/src/snippet.test.ts +213 -0
  56. package/src/snippet.ts +152 -0
  57. package/src/stale-message-reconcile.test.ts +82 -0
  58. package/src/stale-message-reconcile.ts +55 -0
  59. package/src/test-helpers/isolated-mailbox.ts +44 -0
  60. package/src/test-helpers/mailfuzz-connection.ts +27 -0
  61. package/src/test-helpers/mime-tree-generator.ts +461 -0
  62. package/src/text/normalizer.test.ts +223 -0
  63. package/src/text/normalizer.ts +140 -0
  64. package/src/types/mailparser-augment.d.ts +15 -0
  65. package/src/types/natural-porter-stemmer.d.ts +50 -0
  66. package/src/types/stopword.d.ts +69 -0
  67. package/src/types.ts +349 -0
  68. package/test/fixtures/mime/01-flat-text-plain.bodyparts.json +8 -0
  69. package/test/fixtures/mime/01-flat-text-plain.eml +10 -0
  70. package/test/fixtures/mime/01-flat-text-plain.expected.json +10 -0
  71. package/test/fixtures/mime/02-flat-text-html.bodyparts.json +8 -0
  72. package/test/fixtures/mime/02-flat-text-html.eml +10 -0
  73. package/test/fixtures/mime/02-flat-text-html.expected.json +10 -0
  74. package/test/fixtures/mime/03-alternative-text-html.bodyparts.json +20 -0
  75. package/test/fixtures/mime/03-alternative-text-html.eml +19 -0
  76. package/test/fixtures/mime/03-alternative-text-html.expected.json +16 -0
  77. package/test/fixtures/mime/04-mixed-html-pdf-attachment.bodyparts.json +22 -0
  78. package/test/fixtures/mime/04-mixed-html-pdf-attachment.eml +20 -0
  79. package/test/fixtures/mime/04-mixed-html-pdf-attachment.expected.json +16 -0
  80. package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.bodyparts.json +22 -0
  81. package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.eml +21 -0
  82. package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.expected.json +16 -0
  83. package/test/fixtures/mime/06-related-html-cid-image.bodyparts.json +23 -0
  84. package/test/fixtures/mime/06-related-html-cid-image.eml +21 -0
  85. package/test/fixtures/mime/06-related-html-cid-image.expected.json +16 -0
  86. package/test/fixtures/mime/07-mixed-alternative-related-attachment.bodyparts.json +55 -0
  87. package/test/fixtures/mime/07-mixed-alternative-related-attachment.eml +47 -0
  88. package/test/fixtures/mime/07-mixed-alternative-related-attachment.expected.json +34 -0
  89. package/test/fixtures/mime/08-two-pdfs-same-filename.bodyparts.json +30 -0
  90. package/test/fixtures/mime/08-two-pdfs-same-filename.eml +26 -0
  91. package/test/fixtures/mime/08-two-pdfs-same-filename.expected.json +22 -0
  92. package/test/fixtures/mime/09-attachment-no-filename.bodyparts.json +21 -0
  93. package/test/fixtures/mime/09-attachment-no-filename.eml +20 -0
  94. package/test/fixtures/mime/09-attachment-no-filename.expected.json +16 -0
  95. package/test/fixtures/mime/10-calendar-invite.bodyparts.json +22 -0
  96. package/test/fixtures/mime/10-calendar-invite.eml +33 -0
  97. package/test/fixtures/mime/10-calendar-invite.expected.json +16 -0
  98. package/test/fixtures/mime/11-quoted-printable-text.bodyparts.json +8 -0
  99. package/test/fixtures/mime/11-quoted-printable-text.eml +10 -0
  100. package/test/fixtures/mime/11-quoted-printable-text.expected.json +10 -0
  101. package/test/fixtures/mime/12-base64-binary.bodyparts.json +22 -0
  102. package/test/fixtures/mime/12-base64-binary.eml +20 -0
  103. package/test/fixtures/mime/12-base64-binary.expected.json +16 -0
  104. package/test/fixtures/mime/13-message-rfc822-forward.bodyparts.json +22 -0
  105. package/test/fixtures/mime/13-message-rfc822-forward.eml +28 -0
  106. package/test/fixtures/mime/13-message-rfc822-forward.expected.json +16 -0
  107. package/test/fixtures/mime/14-deeply-nested-5-levels.bodyparts.json +38 -0
  108. package/test/fixtures/mime/14-deeply-nested-5-levels.eml +34 -0
  109. package/test/fixtures/mime/14-deeply-nested-5-levels.expected.json +10 -0
  110. package/test/fixtures/mime/15-empty-text-part.bodyparts.json +21 -0
  111. package/test/fixtures/mime/15-empty-text-part.eml +18 -0
  112. package/test/fixtures/mime/15-empty-text-part.expected.json +16 -0
  113. package/test/fixtures/mime/16-empty-non-text-part.bodyparts.json +30 -0
  114. package/test/fixtures/mime/16-empty-non-text-part.eml +24 -0
  115. package/test/fixtures/mime/16-empty-non-text-part.expected.json +22 -0
  116. package/test/fixtures/mime-adversarial-e2e/01-octet-stream-pdf.eml +21 -0
  117. package/test/fixtures/mime-adversarial-e2e/02-nested-related-cid-image.eml +31 -0
  118. package/test/fixtures/mime-adversarial-e2e/03-calendar-invite.eml +33 -0
  119. package/test/fixtures/mime-adversarial-e2e/04-forwarded-rfc822-with-attachments.eml +42 -0
  120. package/test/fixtures/mime-adversarial-e2e/05-tnef-winmail.eml +25 -0
  121. package/test/fixtures/mime-adversarial-e2e/06-8bit-non-ascii.eml +15 -0
  122. package/test/fixtures/mime-adversarial-e2e/07-quoted-printable-soft-breaks.eml +17 -0
  123. package/test/fixtures/mime-adversarial-e2e/08-alternative-empty-text.eml +18 -0
  124. package/tsconfig.json +8 -0
@@ -0,0 +1,500 @@
1
+ import type {
2
+ IMessageFlagRepository,
3
+ IMessageRepository,
4
+ IThreadMessageRepository,
5
+ } from "@remit/data-ports";
6
+ import { NotFoundError } from "@remit/data-ports/errors";
7
+ import { MessageSystemFlag, type StarColor } from "@remit/domain-enums";
8
+ import type { FlagPushOperationValue, FlagPushService } from "./flag-push.js";
9
+
10
+ /**
11
+ * StarColor type derived from the StarColor const object
12
+ */
13
+ type StarColorValue = (typeof StarColor)[keyof typeof StarColor];
14
+
15
+ /**
16
+ * Logger interface
17
+ */
18
+ export interface FlagQueueLogger {
19
+ info(obj: Record<string, unknown>, msg: string): void;
20
+ error(obj: Record<string, unknown>, msg: string): void;
21
+ }
22
+
23
+ const noopLogger: FlagQueueLogger = {
24
+ info: () => {},
25
+ error: () => {},
26
+ };
27
+
28
+ /**
29
+ * Input for updateFlags API method
30
+ */
31
+ export interface UpdateFlagsInput {
32
+ isRead?: boolean;
33
+ isStarred?: boolean;
34
+ starColor?: StarColorValue;
35
+ }
36
+
37
+ /**
38
+ * Result of updateFlags API method
39
+ */
40
+ export interface UpdateFlagsResult {
41
+ messageId: string;
42
+ isRead: boolean;
43
+ isStarred: boolean;
44
+ }
45
+
46
+ /**
47
+ * Configuration for FlagQueueService
48
+ */
49
+ export interface FlagQueueConfig {
50
+ messageFlagService: IMessageFlagRepository;
51
+ messageService: IMessageRepository;
52
+ threadMessageService: IThreadMessageRepository;
53
+ flagPushService: FlagPushService;
54
+ logger?: FlagQueueLogger;
55
+ }
56
+
57
+ /**
58
+ * Service for marking messages as read/unread/starred, local-first with a
59
+ * durable pending-flag marker (issue #1273, epic #1281).
60
+ *
61
+ * Every flip below follows the SAME sequence: persist the pending marker
62
+ * FIRST via {@link FlagPushService.flip} (the durable record IMAP still owes
63
+ * this push, and best-effort enqueues a wake-up hint), THEN apply locally
64
+ * (MessageFlag + ThreadMessage). The marker write is what makes the user's
65
+ * intent durable — not the enqueue, which may fail freely (see
66
+ * `FlagPushService`'s own doc) — and writing it first means a crash before
67
+ * the local write leaves an unapplied local flip behind an already-durable
68
+ * marker, never a flipped flag with no marker (review finding on #1292;
69
+ * mirrors #1289's `PlacementMoveService.moveMessage` ordering). This class
70
+ * therefore no longer touches
71
+ * `Mailbox.unseenCount` at all: that field is a pure projection, recomputed
72
+ * only from IMAP (`doc/rules/data-flow.md`); the displayed count is adjusted
73
+ * at READ TIME from pending markers (`applyPendingMoveCountPrediction`,
74
+ * `packages/backend/src/derive/pendingMoveCounts.ts`).
75
+ *
76
+ * The service updates BOTH entities locally:
77
+ * - MessageFlag: The canonical flag record
78
+ * - ThreadMessage.isRead / hasStars / star: Denormalized for efficient queries
79
+ */
80
+ export class FlagQueueService {
81
+ private messageFlagService: IMessageFlagRepository;
82
+ private messageService: IMessageRepository;
83
+ private threadMessageService: IThreadMessageRepository;
84
+ private flagPushService: FlagPushService;
85
+ private log: FlagQueueLogger;
86
+
87
+ constructor(config: FlagQueueConfig) {
88
+ const {
89
+ messageFlagService,
90
+ messageService,
91
+ threadMessageService,
92
+ flagPushService,
93
+ } = config;
94
+ this.messageFlagService = messageFlagService;
95
+ this.messageService = messageService;
96
+ this.threadMessageService = threadMessageService;
97
+ this.flagPushService = flagPushService;
98
+ this.log = config.logger ?? noopLogger;
99
+ }
100
+
101
+ /**
102
+ * Update ThreadMessage.isRead for ALL ThreadMessages matching this messageId.
103
+ *
104
+ * A message can exist in multiple mailboxes (e.g., inbox and archive), so we
105
+ * must update all instances to keep the isRead status consistent.
106
+ *
107
+ * The `composites` map carries the CURRENT values of every attribute that
108
+ * participates in a sort key. ElectroDB uses them for the conditional check
109
+ * on the existing row and combines them with `set()` to recompute the new
110
+ * sort keys. Passing the NEW `isRead` value here would make the conditional
111
+ * check fail (existing row still has the old value) and the patch would be
112
+ * misreported as NotFoundError, silently dropping the update.
113
+ *
114
+ * Handles race condition where ThreadMessage may be deleted between find and update.
115
+ */
116
+ private updateThreadMessageIsRead = async (
117
+ accountConfigId: string,
118
+ messageId: string,
119
+ isRead: boolean,
120
+ ): Promise<void> => {
121
+ const threadMessages = await this.threadMessageService.findAllByMessageId(
122
+ accountConfigId,
123
+ messageId,
124
+ );
125
+ if (threadMessages.length === 0) {
126
+ this.log.info(
127
+ { messageId },
128
+ "ThreadMessage not found for messageId - skipping isRead update",
129
+ );
130
+ return;
131
+ }
132
+
133
+ for (const threadMessage of threadMessages) {
134
+ try {
135
+ await this.threadMessageService.update(
136
+ threadMessage.accountConfigId,
137
+ threadMessage.threadMessageId,
138
+ { isRead },
139
+ {
140
+ composites: {
141
+ sentDate: threadMessage.sentDate,
142
+ mailboxId: threadMessage.mailboxId,
143
+ isRead: threadMessage.isRead,
144
+ isDeleted: threadMessage.isDeleted,
145
+ hasStars: threadMessage.hasStars,
146
+ hasAttachment: threadMessage.hasAttachment,
147
+ },
148
+ },
149
+ );
150
+ this.log.info(
151
+ { messageId, threadMessageId: threadMessage.threadMessageId, isRead },
152
+ "Updated ThreadMessage.isRead",
153
+ );
154
+ } catch (err) {
155
+ if (err instanceof NotFoundError) {
156
+ this.log.info(
157
+ { messageId, threadMessageId: threadMessage.threadMessageId },
158
+ "ThreadMessage deleted during update - skipping isRead update",
159
+ );
160
+ continue;
161
+ }
162
+ throw err;
163
+ }
164
+ }
165
+ };
166
+
167
+ /**
168
+ * Update ThreadMessage.hasStars and star color for ALL ThreadMessages matching this messageId.
169
+ *
170
+ * A message can exist in multiple mailboxes (e.g., inbox and archive), so we
171
+ * must update all instances to keep the star status consistent.
172
+ *
173
+ * Handles race condition where ThreadMessage may be deleted between find and update.
174
+ */
175
+ private updateThreadMessageStars = async (
176
+ accountConfigId: string,
177
+ messageId: string,
178
+ updates: { hasStars?: boolean; star?: StarColorValue },
179
+ ): Promise<void> => {
180
+ if (Object.keys(updates).length === 0) return;
181
+
182
+ const threadMessages = await this.threadMessageService.findAllByMessageId(
183
+ accountConfigId,
184
+ messageId,
185
+ );
186
+ if (threadMessages.length === 0) {
187
+ this.log.info(
188
+ { messageId },
189
+ "ThreadMessage not found for messageId - skipping star update",
190
+ );
191
+ return;
192
+ }
193
+
194
+ for (const threadMessage of threadMessages) {
195
+ try {
196
+ await this.threadMessageService.update(
197
+ threadMessage.accountConfigId,
198
+ threadMessage.threadMessageId,
199
+ updates,
200
+ {
201
+ composites: {
202
+ sentDate: threadMessage.sentDate,
203
+ mailboxId: threadMessage.mailboxId,
204
+ isRead: threadMessage.isRead,
205
+ isDeleted: threadMessage.isDeleted,
206
+ hasStars: threadMessage.hasStars,
207
+ hasAttachment: threadMessage.hasAttachment,
208
+ },
209
+ },
210
+ );
211
+ this.log.info(
212
+ {
213
+ messageId,
214
+ threadMessageId: threadMessage.threadMessageId,
215
+ updates,
216
+ },
217
+ "Updated ThreadMessage stars",
218
+ );
219
+ } catch (err) {
220
+ if (err instanceof NotFoundError) {
221
+ this.log.info(
222
+ { messageId, threadMessageId: threadMessage.threadMessageId },
223
+ "ThreadMessage deleted during update - skipping star update",
224
+ );
225
+ continue;
226
+ }
227
+ throw err;
228
+ }
229
+ }
230
+ };
231
+
232
+ /**
233
+ * Flip one flag field: persist the pending marker FIRST, then apply
234
+ * locally. Every caller in this class routes through here so the marker
235
+ * write is never skipped. Returns whether a change actually happened —
236
+ * `false` for a redundant flip (already in the desired state), which
237
+ * every caller uses to skip the (otherwise redundant) ThreadMessage
238
+ * update too.
239
+ *
240
+ * Ordering matters (review finding on #1292): a marker written AFTER the
241
+ * local `MessageFlag` flip means a crash between the two awaits strands a
242
+ * flipped flag with no marker — no hint was ever sent, the pending-only
243
+ * drain never finds it (no marker to find), and message-sync never
244
+ * rewrites `MessageFlag` from IMAP for an existing row, so nothing else
245
+ * reconciles it either. That is a permanent, silent divergence — exactly
246
+ * the defect #1273 exists to kill. Writing the marker first (matching
247
+ * #1289's `PlacementMoveService.moveMessage` ordering) makes that
248
+ * scenario impossible: the marker's existence is the record of how far
249
+ * the sequence got, so a crash after it can strand at worst an
250
+ * un-applied LOCAL write behind an already-durable marker — recoverable
251
+ * (the caller's natural retry re-applies both steps; `put` and
252
+ * `addFlag`/`removeFlag` are both idempotent) — never the reverse.
253
+ *
254
+ * The current-state check (review finding on #1292) matters for a
255
+ * different reason: `markAsRead`/`markAsUnread`/`updateFlags` take the
256
+ * DESIRED boolean from the caller rather than deriving it from current
257
+ * state (unlike `toggleFlagged`, which already reads `hasFlag` first and
258
+ * so can never generate a redundant marker). A redundant "mark as read"
259
+ * on an already-read message would otherwise still write a fresh `add
260
+ * \Seen` marker; the read-time unseenCount prediction
261
+ * (`applyPendingMoveCountPrediction`) would then subtract one for a
262
+ * message IMAP already counts as seen, transiently under-counting the
263
+ * badge until the marker clears. Skipping the marker (and the local
264
+ * write) entirely when the flag already matches removes the false
265
+ * prediction at the source, not just its symptom.
266
+ */
267
+ private flipFlag = async (
268
+ accountId: string,
269
+ accountConfigId: string,
270
+ messageId: string,
271
+ mailboxId: string,
272
+ flagName: string,
273
+ operation: FlagPushOperationValue,
274
+ ): Promise<boolean> => {
275
+ const alreadyInState = await this.messageFlagService.hasFlag(
276
+ messageId,
277
+ flagName,
278
+ );
279
+ if (
280
+ (operation === "add" && alreadyInState) ||
281
+ (operation === "remove" && !alreadyInState)
282
+ ) {
283
+ this.log.info(
284
+ { messageId, flagName, operation },
285
+ "Flag already in the desired state — skipping redundant marker + local write",
286
+ );
287
+ return false;
288
+ }
289
+
290
+ await this.flagPushService.flip({
291
+ accountId,
292
+ accountConfigId,
293
+ messageId,
294
+ mailboxId,
295
+ flagName,
296
+ operation,
297
+ });
298
+
299
+ if (operation === "add") {
300
+ await this.messageFlagService.addFlag(messageId, flagName);
301
+ } else {
302
+ await this.messageFlagService.removeFlag(messageId, flagName);
303
+ }
304
+
305
+ return true;
306
+ };
307
+
308
+ /**
309
+ * Mark a message as read (add \Seen flag).
310
+ * Updates MessageFlag, ThreadMessage.isRead, and persists a pending
311
+ * flag-push marker for IMAP sync.
312
+ *
313
+ * @param accountConfigId - The owning account config (tenant scope)
314
+ * @param messageId - The message to mark as read
315
+ * @param accountId - The account ID for the IMAP sync event
316
+ */
317
+ markAsRead = async (
318
+ accountConfigId: string,
319
+ messageId: string,
320
+ accountId: string,
321
+ ): Promise<void> => {
322
+ const message = await this.messageService.get(messageId);
323
+
324
+ const changed = await this.flipFlag(
325
+ accountId,
326
+ accountConfigId,
327
+ messageId,
328
+ message.mailboxId,
329
+ MessageSystemFlag.Seen,
330
+ "add",
331
+ );
332
+
333
+ if (changed) {
334
+ await this.updateThreadMessageIsRead(accountConfigId, messageId, true);
335
+ }
336
+
337
+ this.log.info(
338
+ { messageId, changed },
339
+ "Marked message as read (local, push pending)",
340
+ );
341
+ };
342
+
343
+ /**
344
+ * Mark a message as unread (remove \Seen flag).
345
+ * Updates MessageFlag, ThreadMessage.isRead, and persists a pending
346
+ * flag-push marker for IMAP sync.
347
+ *
348
+ * @param accountConfigId - The owning account config (tenant scope)
349
+ * @param messageId - The message to mark as unread
350
+ * @param accountId - The account ID for the IMAP sync event
351
+ */
352
+ markAsUnread = async (
353
+ accountConfigId: string,
354
+ messageId: string,
355
+ accountId: string,
356
+ ): Promise<void> => {
357
+ const message = await this.messageService.get(messageId);
358
+
359
+ const changed = await this.flipFlag(
360
+ accountId,
361
+ accountConfigId,
362
+ messageId,
363
+ message.mailboxId,
364
+ MessageSystemFlag.Seen,
365
+ "remove",
366
+ );
367
+
368
+ if (changed) {
369
+ await this.updateThreadMessageIsRead(accountConfigId, messageId, false);
370
+ }
371
+
372
+ this.log.info(
373
+ { messageId, changed },
374
+ "Marked message as unread (local, push pending)",
375
+ );
376
+ };
377
+
378
+ /**
379
+ * Toggle the starred/flagged status of a message.
380
+ * Updates local state and persists a pending flag-push marker for IMAP
381
+ * sync.
382
+ *
383
+ * @param accountConfigId - The owning account config (tenant scope)
384
+ * @param messageId - The message to toggle
385
+ * @param accountId - The account ID for the IMAP sync event
386
+ * @returns true if flag was added, false if removed
387
+ */
388
+ toggleFlagged = async (
389
+ accountConfigId: string,
390
+ messageId: string,
391
+ accountId: string,
392
+ ): Promise<boolean> => {
393
+ const message = await this.messageService.get(messageId);
394
+
395
+ const hasFlag = await this.messageFlagService.hasFlag(
396
+ messageId,
397
+ MessageSystemFlag.Flagged,
398
+ );
399
+ const operation: FlagPushOperationValue = hasFlag ? "remove" : "add";
400
+
401
+ await this.flipFlag(
402
+ accountId,
403
+ accountConfigId,
404
+ messageId,
405
+ message.mailboxId,
406
+ MessageSystemFlag.Flagged,
407
+ operation,
408
+ );
409
+
410
+ this.log.info(
411
+ { messageId, operation },
412
+ "Toggled flagged status (local, push pending)",
413
+ );
414
+
415
+ return operation === "add";
416
+ };
417
+
418
+ /**
419
+ * Update message flags using API-friendly input format.
420
+ * Maps isRead/isStarred to IMAP flags and updates ThreadMessage accordingly.
421
+ *
422
+ * @param accountConfigId - The owning account config (tenant scope)
423
+ * @param messageId - The message to update
424
+ * @param accountId - The account ID for the IMAP sync event
425
+ * @param input - The flag updates to apply
426
+ * @returns The current flag state after updates
427
+ */
428
+ updateFlags = async (
429
+ accountConfigId: string,
430
+ messageId: string,
431
+ accountId: string,
432
+ input: UpdateFlagsInput,
433
+ ): Promise<UpdateFlagsResult> => {
434
+ const message = await this.messageService.get(messageId);
435
+
436
+ // Handle isRead -> \Seen flag
437
+ if (input.isRead !== undefined) {
438
+ const changed = await this.flipFlag(
439
+ accountId,
440
+ accountConfigId,
441
+ messageId,
442
+ message.mailboxId,
443
+ MessageSystemFlag.Seen,
444
+ input.isRead ? "add" : "remove",
445
+ );
446
+ if (changed) {
447
+ await this.updateThreadMessageIsRead(
448
+ accountConfigId,
449
+ messageId,
450
+ input.isRead,
451
+ );
452
+ }
453
+ }
454
+
455
+ // Handle isStarred -> \Flagged flag and ThreadMessage.hasStars/star
456
+ if (input.isStarred !== undefined || input.starColor !== undefined) {
457
+ if (input.isStarred !== undefined) {
458
+ await this.flipFlag(
459
+ accountId,
460
+ accountConfigId,
461
+ messageId,
462
+ message.mailboxId,
463
+ MessageSystemFlag.Flagged,
464
+ input.isStarred ? "add" : "remove",
465
+ );
466
+ }
467
+
468
+ // Update ThreadMessage hasStars and star color for ALL instances
469
+ const starUpdates: { hasStars?: boolean; star?: StarColorValue } = {};
470
+ if (input.isStarred !== undefined) {
471
+ starUpdates.hasStars = input.isStarred;
472
+ }
473
+ if (input.starColor !== undefined) {
474
+ starUpdates.star = input.starColor;
475
+ }
476
+ await this.updateThreadMessageStars(
477
+ accountConfigId,
478
+ messageId,
479
+ starUpdates,
480
+ );
481
+ }
482
+
483
+ // Return current state
484
+ const isRead = await this.messageFlagService.hasFlag(
485
+ messageId,
486
+ MessageSystemFlag.Seen,
487
+ );
488
+ const isStarred = await this.messageFlagService.hasFlag(
489
+ messageId,
490
+ MessageSystemFlag.Flagged,
491
+ );
492
+
493
+ this.log.info(
494
+ { messageId, isRead, isStarred, input },
495
+ "Updated message flags",
496
+ );
497
+
498
+ return { messageId, isRead, isStarred };
499
+ };
500
+ }