@remit/mailbox-service 0.0.111 → 0.0.113

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 (298) hide show
  1. package/dist/account-credentials.d.ts +83 -0
  2. package/dist/account-credentials.js +104 -0
  3. package/dist/attribute-mapper.d.ts +36 -0
  4. package/dist/attribute-mapper.js +119 -0
  5. package/dist/body-parse.d.ts +28 -0
  6. package/{src/body-parse.ts → dist/body-parse.js} +18 -26
  7. package/dist/body-part-mapper.d.ts +92 -0
  8. package/dist/body-part-mapper.js +301 -0
  9. package/dist/body-sync-queue.d.ts +59 -0
  10. package/dist/body-sync-queue.js +56 -0
  11. package/dist/body-sync-terminal.d.ts +58 -0
  12. package/dist/body-sync-terminal.js +95 -0
  13. package/dist/body-sync.d.ts +351 -0
  14. package/dist/body-sync.js +1204 -0
  15. package/dist/calendar-parts.d.ts +23 -0
  16. package/dist/calendar-parts.js +18 -0
  17. package/dist/classification-backfill.d.ts +91 -0
  18. package/dist/classification-backfill.js +180 -0
  19. package/dist/classify-message.d.ts +31 -0
  20. package/dist/classify-message.js +89 -0
  21. package/dist/connection-factory.d.ts +54 -0
  22. package/dist/connection-factory.js +54 -0
  23. package/dist/connection-test.d.ts +41 -0
  24. package/dist/connection-test.js +152 -0
  25. package/dist/external-move.d.ts +94 -0
  26. package/dist/external-move.js +173 -0
  27. package/dist/filter-operations.d.ts +42 -0
  28. package/dist/filter-operations.js +211 -0
  29. package/dist/filters/filter-config.d.ts +14 -0
  30. package/dist/filters/filter-config.js +10 -0
  31. package/{src/filters/list-id.ts → dist/filters/list-id.d.ts} +2 -16
  32. package/dist/filters/list-id.js +26 -0
  33. package/dist/filters/match.d.ts +69 -0
  34. package/dist/filters/match.js +165 -0
  35. package/dist/filters/pipeline.d.ts +64 -0
  36. package/dist/filters/pipeline.js +100 -0
  37. package/{src/flag-push-terminal.ts → dist/flag-push-terminal.d.ts} +19 -77
  38. package/dist/flag-push-terminal.js +63 -0
  39. package/dist/flag-push.d.ts +69 -0
  40. package/dist/flag-push.js +111 -0
  41. package/dist/flag-queue.d.ts +175 -0
  42. package/dist/flag-queue.js +291 -0
  43. package/dist/folder-operations.d.ts +39 -0
  44. package/dist/folder-operations.js +112 -0
  45. package/dist/folder-placement.d.ts +13 -0
  46. package/dist/folder-placement.js +23 -0
  47. package/dist/heuristics/authenticationResults.d.ts +10 -0
  48. package/dist/heuristics/authenticationResults.js +187 -0
  49. package/dist/heuristics/classifyByHeaders.d.ts +82 -0
  50. package/dist/heuristics/classifyByHeaders.js +365 -0
  51. package/dist/heuristics/classifyPlacement.d.ts +67 -0
  52. package/dist/heuristics/classifyPlacement.js +153 -0
  53. package/dist/heuristics/machineSenders.d.ts +21 -0
  54. package/{src/heuristics/machineSenders.ts → dist/heuristics/machineSenders.js} +34 -40
  55. package/dist/heuristics/senderMismatch.d.ts +81 -0
  56. package/dist/heuristics/senderMismatch.js +192 -0
  57. package/dist/heuristics/socialDomains.d.ts +14 -0
  58. package/{src/heuristics/socialDomains.ts → dist/heuristics/socialDomains.js} +9 -9
  59. package/dist/heuristics/transactionalDomains.d.ts +18 -0
  60. package/{src/heuristics/transactionalDomains.ts → dist/heuristics/transactionalDomains.js} +8 -8
  61. package/dist/imapflow-connection.d.ts +377 -0
  62. package/dist/imapflow-connection.js +1147 -0
  63. package/dist/index.d.ts +63 -0
  64. package/dist/index.js +65 -0
  65. package/dist/list-id-backfill.d.ts +83 -0
  66. package/dist/list-id-backfill.js +132 -0
  67. package/dist/mailbox-cursor-rebuild.d.ts +74 -0
  68. package/dist/mailbox-cursor-rebuild.js +71 -0
  69. package/{src/mailbox-cursor.ts → dist/mailbox-cursor.d.ts} +20 -98
  70. package/dist/mailbox-cursor.js +102 -0
  71. package/dist/mailbox-intent.d.ts +41 -0
  72. package/{src/mailbox-intent.ts → dist/mailbox-intent.js} +39 -63
  73. package/dist/mailbox-management.d.ts +240 -0
  74. package/dist/mailbox-management.js +576 -0
  75. package/dist/mailbox-presence.d.ts +52 -0
  76. package/{src/mailbox-presence.ts → dist/mailbox-presence.js} +19 -30
  77. package/dist/mailbox-queue.d.ts +126 -0
  78. package/dist/mailbox-queue.js +214 -0
  79. package/dist/mailbox-sync.d.ts +93 -0
  80. package/dist/mailbox-sync.js +490 -0
  81. package/dist/mailbox-upstream.d.ts +38 -0
  82. package/{src/mailbox-upstream.ts → dist/mailbox-upstream.js} +37 -47
  83. package/dist/message-category.d.ts +51 -0
  84. package/{src/message-category.ts → dist/message-category.js} +28 -71
  85. package/dist/message-move.d.ts +285 -0
  86. package/dist/message-move.js +858 -0
  87. package/dist/message-parser.d.ts +14 -0
  88. package/dist/message-parser.js +17 -0
  89. package/{src/message-presence.ts → dist/message-presence.d.ts} +1 -13
  90. package/dist/message-presence.js +29 -0
  91. package/dist/message-read.d.ts +51 -0
  92. package/dist/message-read.js +31 -0
  93. package/dist/message-sync.d.ts +345 -0
  94. package/dist/message-sync.js +1358 -0
  95. package/dist/mime-walker.d.ts +102 -0
  96. package/dist/mime-walker.js +198 -0
  97. package/dist/organize-job.d.ts +20 -0
  98. package/dist/organize-job.js +37 -0
  99. package/dist/outbox-attachment-content.d.ts +37 -0
  100. package/dist/outbox-attachment-content.js +50 -0
  101. package/dist/outbox-attachment-filename.d.ts +19 -0
  102. package/dist/outbox-attachment-filename.js +64 -0
  103. package/dist/outbox-attachment.d.ts +148 -0
  104. package/dist/outbox-attachment.js +273 -0
  105. package/dist/outbox-queue.d.ts +73 -0
  106. package/dist/outbox-queue.js +284 -0
  107. package/{src/outbox-status.ts → dist/outbox-status.d.ts} +1 -6
  108. package/dist/outbox-status.js +18 -0
  109. package/dist/ownership.d.ts +24 -0
  110. package/dist/ownership.js +83 -0
  111. package/dist/placement-move-terminal.d.ts +67 -0
  112. package/dist/placement-move-terminal.js +88 -0
  113. package/dist/placement-move.d.ts +83 -0
  114. package/dist/placement-move.js +216 -0
  115. package/{src/placement-settled.ts → dist/placement-settled.d.ts} +19 -50
  116. package/dist/placement-settled.js +75 -0
  117. package/dist/quarantine.d.ts +95 -0
  118. package/dist/quarantine.js +131 -0
  119. package/dist/refusal.d.ts +31 -0
  120. package/dist/refusal.js +3 -0
  121. package/{src/restore-source-placement.ts → dist/restore-source-placement.d.ts} +29 -101
  122. package/dist/restore-source-placement.js +79 -0
  123. package/dist/search-text-backfill.d.ts +15 -0
  124. package/dist/search-text-backfill.js +33 -0
  125. package/dist/snippet.d.ts +61 -0
  126. package/dist/snippet.js +129 -0
  127. package/dist/spam-report.d.ts +86 -0
  128. package/dist/spam-report.js +241 -0
  129. package/dist/sync-warning.d.ts +21 -0
  130. package/dist/sync-warning.js +26 -0
  131. package/dist/sync-watermarks.d.ts +138 -0
  132. package/dist/sync-watermarks.js +205 -0
  133. package/dist/test-helpers/fake-imap.d.ts +151 -0
  134. package/dist/test-helpers/fake-imap.js +508 -0
  135. package/dist/test-helpers/folder-roles.d.ts +34 -0
  136. package/dist/test-helpers/folder-roles.js +47 -0
  137. package/dist/test-helpers/mime-tree-generator.d.ts +82 -0
  138. package/dist/test-helpers/mime-tree-generator.js +329 -0
  139. package/dist/test-helpers/test-store.d.ts +69 -0
  140. package/dist/test-helpers/test-store.js +193 -0
  141. package/dist/text/normalizer.d.ts +20 -0
  142. package/dist/text/normalizer.js +102 -0
  143. package/dist/thread-message-rows.d.ts +69 -0
  144. package/dist/thread-message-rows.js +40 -0
  145. package/dist/thread-root.d.ts +7 -0
  146. package/dist/thread-root.js +25 -0
  147. package/dist/types.d.ts +343 -0
  148. package/dist/types.js +19 -0
  149. package/package.json +86 -73
  150. package/src/account-credentials.ts +0 -210
  151. package/src/adversarial-mime.e2e.test.ts +0 -307
  152. package/src/attribute-mapper.test.ts +0 -104
  153. package/src/attribute-mapper.ts +0 -148
  154. package/src/body-parse.test.ts +0 -55
  155. package/src/body-part-mapper.property.test.ts +0 -354
  156. package/src/body-part-mapper.ts +0 -360
  157. package/src/body-sync-auto-read-writeonce.test.ts +0 -219
  158. package/src/body-sync-calendar-suggestion.test.ts +0 -433
  159. package/src/body-sync-category-denormalize.test.ts +0 -352
  160. package/src/body-sync-category-override.test.ts +0 -501
  161. package/src/body-sync-category-writeonce.test.ts +0 -234
  162. package/src/body-sync-filter.test.ts +0 -237
  163. package/src/body-sync-message-gone.test.ts +0 -139
  164. package/src/body-sync-placement-flags.test.ts +0 -347
  165. package/src/body-sync-placement-writeonce.test.ts +0 -337
  166. package/src/body-sync-quarantine.test.ts +0 -276
  167. package/src/body-sync-queue.test.ts +0 -124
  168. package/src/body-sync-queue.ts +0 -131
  169. package/src/body-sync-resync.test.ts +0 -605
  170. package/src/body-sync-terminal.test.ts +0 -310
  171. package/src/body-sync-terminal.ts +0 -176
  172. package/src/body-sync-unclassifiable-once.test.ts +0 -260
  173. package/src/body-sync-unsubscribed-auto-read.test.ts +0 -176
  174. package/src/body-sync.ts +0 -1970
  175. package/src/calendar-parts.ts +0 -41
  176. package/src/classification-backfill.test.ts +0 -615
  177. package/src/classification-backfill.ts +0 -363
  178. package/src/classify-message.test.ts +0 -205
  179. package/src/classify-message.ts +0 -116
  180. package/src/connection-factory.ts +0 -102
  181. package/src/connection-test.ts +0 -208
  182. package/src/credentials.test.ts +0 -181
  183. package/src/external-move.test.ts +0 -369
  184. package/src/external-move.ts +0 -272
  185. package/src/filters/anchor-drift.ts +0 -55
  186. package/src/filters/filter-config.test.ts +0 -229
  187. package/src/filters/filter-config.ts +0 -69
  188. package/src/filters/list-id.test.ts +0 -50
  189. package/src/filters/match.test.ts +0 -429
  190. package/src/filters/match.ts +0 -274
  191. package/src/filters/message-embedder.test.ts +0 -39
  192. package/src/filters/message-embedder.ts +0 -33
  193. package/src/filters/pipeline.test.ts +0 -330
  194. package/src/filters/pipeline.ts +0 -284
  195. package/src/flag-push-terminal.test.ts +0 -209
  196. package/src/flag-push.test.ts +0 -408
  197. package/src/flag-push.ts +0 -198
  198. package/src/flag-queue-stars.test.ts +0 -171
  199. package/src/flag-queue.ts +0 -509
  200. package/src/folder-placement.ts +0 -56
  201. package/src/heuristics/authenticationResults.test.ts +0 -189
  202. package/src/heuristics/authenticationResults.ts +0 -212
  203. package/src/heuristics/classifyByHeaders.test.ts +0 -889
  204. package/src/heuristics/classifyByHeaders.ts +0 -467
  205. package/src/heuristics/classifyPlacement.test.ts +0 -366
  206. package/src/heuristics/classifyPlacement.ts +0 -211
  207. package/src/heuristics/classifyRealMail.test.ts +0 -242
  208. package/src/heuristics/machineSenders.test.ts +0 -101
  209. package/src/heuristics/senderMismatch.test.ts +0 -346
  210. package/src/heuristics/senderMismatch.ts +0 -259
  211. package/src/imapflow-connect-retry.test.ts +0 -134
  212. package/src/imapflow-connection.e2e.test.ts +0 -335
  213. package/src/imapflow-connection.integ.test.ts +0 -316
  214. package/src/imapflow-connection.test.ts +0 -469
  215. package/src/imapflow-connection.ts +0 -1475
  216. package/src/index.ts +0 -350
  217. package/src/list-id-backfill.test.ts +0 -573
  218. package/src/list-id-backfill.ts +0 -274
  219. package/src/mailbox-cursor-rebuild.test.ts +0 -171
  220. package/src/mailbox-cursor-rebuild.ts +0 -146
  221. package/src/mailbox-cursor.test.ts +0 -249
  222. package/src/mailbox-delete-intent.test.ts +0 -246
  223. package/src/mailbox-management.test.ts +0 -356
  224. package/src/mailbox-management.ts +0 -839
  225. package/src/mailbox-presence.test.ts +0 -72
  226. package/src/mailbox-queue.ts +0 -415
  227. package/src/mailbox-rename-intent.test.ts +0 -389
  228. package/src/mailbox-rename-subtree.test.ts +0 -664
  229. package/src/mailbox-sync.test.ts +0 -848
  230. package/src/mailbox-sync.ts +0 -724
  231. package/src/message-delete-junk-reconcile.test.ts +0 -117
  232. package/src/message-delete-no-trash.test.ts +0 -245
  233. package/src/message-delete-unsettled-placement.test.ts +0 -396
  234. package/src/message-move-copy.test.ts +0 -562
  235. package/src/message-move-empty-trash.test.ts +0 -326
  236. package/src/message-move-same-mailbox.test.ts +0 -139
  237. package/src/message-move-unsettled-placement.test.ts +0 -378
  238. package/src/message-move.ts +0 -1348
  239. package/src/message-parser.ts +0 -26
  240. package/src/message-presence.test.ts +0 -50
  241. package/src/message-sync-address-spoof.test.ts +0 -293
  242. package/src/message-sync-category.test.ts +0 -142
  243. package/src/message-sync-changedsince.test.ts +0 -840
  244. package/src/message-sync-flags.test.ts +0 -158
  245. package/src/message-sync-junk-harvest.test.ts +0 -244
  246. package/src/message-sync-quarantine.test.ts +0 -416
  247. package/src/message-sync-repoint.test.ts +0 -419
  248. package/src/message-sync.ts +0 -1963
  249. package/src/mime-walker.test.ts +0 -311
  250. package/src/mime-walker.ts +0 -305
  251. package/src/outbox-attachment-content.test.ts +0 -153
  252. package/src/outbox-attachment-content.ts +0 -104
  253. package/src/outbox-attachment-filename.test.ts +0 -132
  254. package/src/outbox-attachment-filename.ts +0 -76
  255. package/src/outbox-attachment.test.ts +0 -738
  256. package/src/outbox-attachment.ts +0 -536
  257. package/src/outbox-failed-recovery.test.ts +0 -370
  258. package/src/outbox-queue-settled-row.test.ts +0 -140
  259. package/src/outbox-queue.test.ts +0 -291
  260. package/src/outbox-queue.ts +0 -508
  261. package/src/pass-through-unit-of-work.ts +0 -17
  262. package/src/placement-move-terminal.test.ts +0 -300
  263. package/src/placement-move-terminal.ts +0 -148
  264. package/src/placement-move-unsettled.test.ts +0 -275
  265. package/src/placement-move.ts +0 -336
  266. package/src/placement-settled.test.ts +0 -147
  267. package/src/placement-transition-race.test.ts +0 -482
  268. package/src/quarantine.test.ts +0 -191
  269. package/src/quarantine.ts +0 -228
  270. package/src/snippet.test.ts +0 -213
  271. package/src/snippet.ts +0 -152
  272. package/src/spam-report.test.ts +0 -801
  273. package/src/spam-report.ts +0 -357
  274. package/src/stale-message-reconcile.test.ts +0 -82
  275. package/src/stale-message-reconcile.ts +0 -55
  276. package/src/sync-watermarks.test.ts +0 -409
  277. package/src/sync-watermarks.ts +0 -319
  278. package/src/system-flag-wire-format.test.ts +0 -77
  279. package/src/test-helpers/folder-roles.ts +0 -66
  280. package/src/test-helpers/isolated-mailbox.ts +0 -44
  281. package/src/test-helpers/mailfuzz-connection.ts +0 -27
  282. package/src/test-helpers/mime-tree-generator.ts +0 -461
  283. package/src/text/normalizer.test.ts +0 -223
  284. package/src/text/normalizer.ts +0 -140
  285. package/src/thread-message-rows.ts +0 -77
  286. package/src/types/mailparser-augment.d.ts +0 -15
  287. package/src/types/natural-porter-stemmer.d.ts +0 -50
  288. package/src/types/stopword.d.ts +0 -69
  289. package/src/types.ts +0 -371
  290. package/test/fixtures/mime-adversarial-e2e/01-octet-stream-pdf.eml +0 -21
  291. package/test/fixtures/mime-adversarial-e2e/02-nested-related-cid-image.eml +0 -31
  292. package/test/fixtures/mime-adversarial-e2e/03-calendar-invite.eml +0 -33
  293. package/test/fixtures/mime-adversarial-e2e/04-forwarded-rfc822-with-attachments.eml +0 -42
  294. package/test/fixtures/mime-adversarial-e2e/05-tnef-winmail.eml +0 -25
  295. package/test/fixtures/mime-adversarial-e2e/06-8bit-non-ascii.eml +0 -15
  296. package/test/fixtures/mime-adversarial-e2e/07-quoted-printable-soft-breaks.eml +0 -17
  297. package/test/fixtures/mime-adversarial-e2e/08-alternative-empty-text.eml +0 -18
  298. package/tsconfig.json +0 -8
@@ -0,0 +1,508 @@
1
+ import { Readable } from "node:stream";
2
+ import { simpleParser } from "mailparser";
3
+ /** An error shaped the way ImapFlow reports a tagged NO from the server. */
4
+ export const imapError = (code, text) => Object.assign(new Error(`Command failed: [${code}] ${text}`), {
5
+ serverResponseCode: code,
6
+ responseText: text,
7
+ });
8
+ const nonexistent = (path) => imapError("NONEXISTENT", `Mailbox doesn't exist: ${path}`);
9
+ export const eml = (headers, body = "body") => Buffer.from([
10
+ ...Object.entries({
11
+ From: "Sender <sender@example.com>",
12
+ To: "me@example.com",
13
+ Subject: "Hello",
14
+ "Content-Type": "text/plain",
15
+ ...headers,
16
+ })
17
+ .filter(([, value]) => value !== "")
18
+ .map(([name, value]) => `${name}: ${value}`),
19
+ "",
20
+ body,
21
+ ].join("\r\n"));
22
+ const toAddresses = (value) => (value?.value ?? [])
23
+ .filter((entry) => entry.address)
24
+ .map((entry) => {
25
+ const [mailbox, host] = (entry.address ?? "").split("@");
26
+ return { name: entry.name || undefined, mailbox, host };
27
+ });
28
+ const single = (value) => Array.isArray(value) ? value[0] : value;
29
+ const messageIdOf = (raw) => /^Message-ID:\s*(.+?)\s*$/im.exec(raw.toString("utf8"))?.[1] ?? "";
30
+ const UID_RANGE = /^(\d+)(?::(\d+|\*))?$/;
31
+ /** Whether `uid` is in an IMAP sequence set such as `3`, `1,4` or `2:*`. */
32
+ const inUidSet = (set, uid, highest) => set.split(",").some((part) => {
33
+ const match = UID_RANGE.exec(part);
34
+ if (!match)
35
+ throw new Error(`the fake server cannot read UID set ${set}`);
36
+ const from = Number(match[1]);
37
+ const to = match[2] === undefined
38
+ ? from
39
+ : match[2] === "*"
40
+ ? Math.max(highest, from)
41
+ : Number(match[2]);
42
+ return uid >= Math.min(from, to) && uid <= Math.max(from, to);
43
+ });
44
+ /**
45
+ * An IMAP server held in memory, behind the same connection port the imapflow
46
+ * adapter implements. It refuses what a server refuses: a folder that does not
47
+ * exist is `NONEXISTENT`, a transfer or APPEND to one is `TRYCREATE`, and a
48
+ * SEARCH it does not model throws rather than matching everything. FETCH rows
49
+ * are derived from the raw bytes the way the adapter derives them. `log`
50
+ * records every command that would reach the wire.
51
+ */
52
+ export class FakeImapServer {
53
+ folders = new Map();
54
+ modseq = 1n;
55
+ nextUidValidity = 1000;
56
+ log = [];
57
+ failNext = {};
58
+ ignoreNext = new Set();
59
+ condstore = true;
60
+ uidplus = true;
61
+ namespacePrefix = "";
62
+ connections = 0;
63
+ onFetchBody = async () => { };
64
+ addFolder(path, options = {}) {
65
+ if (this.folders.has(path))
66
+ throw new Error(`${path} already exists`);
67
+ this.folders.set(path, {
68
+ uidValidity: options.uidValidity ?? 7,
69
+ uidNext: 1,
70
+ attributes: options.attributes ?? [],
71
+ subscribed: true,
72
+ messages: new Map(),
73
+ });
74
+ }
75
+ hasFolder(path) {
76
+ return this.folders.has(path);
77
+ }
78
+ /** Another client deleted the folder. */
79
+ removeFolder(path) {
80
+ if (!this.folders.delete(path))
81
+ throw nonexistent(path);
82
+ }
83
+ isSubscribed(path) {
84
+ return this.folder(path).subscribed;
85
+ }
86
+ folder(path) {
87
+ const folder = this.folders.get(path);
88
+ if (!folder)
89
+ throw nonexistent(path);
90
+ return folder;
91
+ }
92
+ paths() {
93
+ return [...this.folders.keys()];
94
+ }
95
+ deliver(path, raw, options = {}) {
96
+ const folder = this.folder(path);
97
+ const uid = options.uid ?? folder.uidNext;
98
+ if (folder.messages.has(uid))
99
+ throw new Error(`uid ${uid} is taken in ${path}`);
100
+ folder.uidNext = Math.max(folder.uidNext, uid + 1);
101
+ folder.messages.set(uid, {
102
+ raw,
103
+ flags: new Set(options.flags ?? []),
104
+ modseq: this.modseq++,
105
+ internalDate: new Date(1_700_000_000_000 + uid * 1000),
106
+ bodyStructure: options.bodyStructure,
107
+ });
108
+ return uid;
109
+ }
110
+ /** Another client expunged the message. */
111
+ expunge(path, uid) {
112
+ if (!this.folder(path).messages.delete(uid)) {
113
+ throw new Error(`no uid ${uid} in ${path}`);
114
+ }
115
+ }
116
+ /** Another client expunged everything in the folder. */
117
+ empty(path) {
118
+ this.folder(path).messages.clear();
119
+ }
120
+ /** One STORE from another client: every message it touches shares the new mod-sequence. */
121
+ store(path, uids, flags) {
122
+ const modseq = this.modseq++;
123
+ for (const uid of uids) {
124
+ const message = this.folder(path).messages.get(uid);
125
+ if (!message)
126
+ throw new Error(`no uid ${uid} in ${path}`);
127
+ message.flags = new Set(flags);
128
+ message.modseq = modseq;
129
+ }
130
+ }
131
+ /** The server renumbered the folder: a new UIDVALIDITY, UIDs from 1. */
132
+ renumber(path, uidValidity) {
133
+ const folder = this.folder(path);
134
+ const messages = [...folder.messages.values()];
135
+ folder.uidValidity = uidValidity;
136
+ folder.messages = new Map(messages.map((message, i) => [i + 1, message]));
137
+ folder.uidNext = messages.length + 1;
138
+ }
139
+ flagsOf(path, uid) {
140
+ return [...(this.folder(path).messages.get(uid)?.flags ?? [])].sort();
141
+ }
142
+ uids(path, messageIdHeader) {
143
+ return [...this.folder(path).messages]
144
+ .filter(([, message]) => messageIdHeader === undefined ||
145
+ messageIdOf(message.raw) === messageIdHeader)
146
+ .map(([uid]) => uid);
147
+ }
148
+ /** What the server holds in a folder, as another client would read it. */
149
+ messages(path) {
150
+ return [...this.folder(path).messages].map(([uid, message]) => ({
151
+ uid,
152
+ messageIdHeader: messageIdOf(message.raw),
153
+ flags: [...message.flags].sort(),
154
+ raw: message.raw,
155
+ }));
156
+ }
157
+ /** The server changed UIDVALIDITY without renumbering what it serves. */
158
+ setUidValidity(path, uidValidity) {
159
+ this.folder(path).uidValidity = uidValidity;
160
+ }
161
+ uidValidityOf(path) {
162
+ return this.folder(path).uidValidity;
163
+ }
164
+ highestModseq() {
165
+ return this.modseq - 1n;
166
+ }
167
+ bumpModseq() {
168
+ return this.modseq++;
169
+ }
170
+ commands(verb) {
171
+ return this.log.filter((line) => line.startsWith(`${verb} `));
172
+ }
173
+ run(verb, detail) {
174
+ this.log.push(`${verb} ${detail}`);
175
+ const failure = this.failNext[verb];
176
+ if (failure) {
177
+ delete this.failNext[verb];
178
+ throw failure;
179
+ }
180
+ }
181
+ createFolder(path) {
182
+ if (this.folders.has(path))
183
+ return false;
184
+ this.nextUidValidity += 1;
185
+ this.addFolder(path, { uidValidity: this.nextUidValidity });
186
+ return true;
187
+ }
188
+ renameFolder(oldPath, newPath) {
189
+ this.folder(oldPath);
190
+ if (this.folders.has(newPath)) {
191
+ throw imapError("ALREADYEXISTS", `Mailbox already exists: ${newPath}`);
192
+ }
193
+ for (const [path, folder] of [...this.folders]) {
194
+ if (path !== oldPath && !path.startsWith(`${oldPath}/`))
195
+ continue;
196
+ this.folders.delete(path);
197
+ this.folders.set(newPath + path.slice(oldPath.length), folder);
198
+ }
199
+ }
200
+ deleteFolder(path) {
201
+ if (path === "INBOX")
202
+ throw imapError("CANNOT", "Cannot delete INBOX");
203
+ this.folder(path);
204
+ for (const key of [...this.folders.keys()]) {
205
+ if (key === path || key.startsWith(`${path}/`))
206
+ this.folders.delete(key);
207
+ }
208
+ }
209
+ connection() {
210
+ this.connections += 1;
211
+ return new FakeImapConnection(this);
212
+ }
213
+ }
214
+ export class FakeImapConnection {
215
+ server;
216
+ state = "authenticated";
217
+ isConnected = true;
218
+ selected = null;
219
+ constructor(server) {
220
+ this.server = server;
221
+ }
222
+ open() {
223
+ if (this.selected === null)
224
+ throw new Error("No mailbox selected");
225
+ return this.server.folder(this.selected);
226
+ }
227
+ uidList = (uids) => uids.join(",");
228
+ connect = async () => { };
229
+ disconnect = async () => { };
230
+ getNamespaces = async () => {
231
+ this.server.run("NAMESPACE", "");
232
+ return {
233
+ personal: [{ prefix: this.server.namespacePrefix, delimiter: "/" }],
234
+ other: [],
235
+ shared: [],
236
+ };
237
+ };
238
+ listMailboxes = async () => {
239
+ this.server.run("LIST", "");
240
+ return this.server.paths().map((fullPath) => {
241
+ const separator = fullPath.lastIndexOf("/");
242
+ return {
243
+ fullPath,
244
+ name: separator === -1 ? fullPath : fullPath.slice(separator + 1),
245
+ delimiter: "/",
246
+ attributes: this.server.folder(fullPath).attributes,
247
+ parentPath: separator === -1 ? null : fullPath.slice(0, separator),
248
+ };
249
+ });
250
+ };
251
+ openBox = async (path, readOnly = false) => {
252
+ this.server.run(readOnly ? "EXAMINE" : "SELECT", path);
253
+ const folder = this.server.folder(path);
254
+ this.selected = path;
255
+ return {
256
+ name: path,
257
+ readOnly,
258
+ uidvalidity: folder.uidValidity,
259
+ uidnext: folder.uidNext,
260
+ flags: [],
261
+ permFlags: [],
262
+ persistentUIDs: true,
263
+ messages: { total: folder.messages.size, new: 0 },
264
+ newKeywords: false,
265
+ };
266
+ };
267
+ closeBox = async () => {
268
+ this.server.run("CLOSE", `${this.selected}`);
269
+ this.selected = null;
270
+ };
271
+ search = async (criteria) => {
272
+ this.server.run("SEARCH", `${this.selected} ${JSON.stringify(criteria)}`);
273
+ const folder = this.open();
274
+ const all = [...folder.messages.keys()];
275
+ const [first] = criteria;
276
+ if (criteria.length === 1 && first === "ALL")
277
+ return all;
278
+ if (criteria.length === 1 &&
279
+ Array.isArray(first) &&
280
+ first.length === 2 &&
281
+ first[0] === "UID") {
282
+ const highest = Math.max(0, ...all);
283
+ return all.filter((uid) => inUidSet(String(first[1]), uid, highest));
284
+ }
285
+ if (criteria.length === 1 &&
286
+ Array.isArray(first) &&
287
+ first.length === 3 &&
288
+ first[0] === "HEADER" &&
289
+ String(first[1]).toLowerCase() === "message-id") {
290
+ return all.filter((uid) => messageIdOf(folder.messages.get(uid)?.raw ?? Buffer.alloc(0)) ===
291
+ first[2]);
292
+ }
293
+ throw new Error(`the fake server does not answer SEARCH ${JSON.stringify(criteria)}`);
294
+ };
295
+ toImapMessage = async (uid, stored) => {
296
+ const parsed = await simpleParser(stored.raw);
297
+ const header = (name) => {
298
+ const value = parsed.headers.get(name);
299
+ return typeof value === "string" ? value : "";
300
+ };
301
+ const contentType = single(parsed.headers.get("content-type"));
302
+ const headerStructure = {
303
+ type: contentType?.value ?? "text/plain",
304
+ parameters: contentType?.params,
305
+ encoding: header("content-transfer-encoding") || "7bit",
306
+ size: stored.raw.length,
307
+ };
308
+ const references = parsed.references;
309
+ return {
310
+ uid,
311
+ seq: uid,
312
+ flags: [...stored.flags],
313
+ internalDate: stored.internalDate,
314
+ size: stored.raw.length,
315
+ envelope: {
316
+ date: parsed.date?.toISOString() ?? "",
317
+ subject: parsed.subject ?? "",
318
+ from: toAddresses(single(parsed.from)),
319
+ sender: toAddresses(single(parsed.from)),
320
+ replyTo: toAddresses(single(parsed.replyTo)),
321
+ to: toAddresses(single(parsed.to)),
322
+ cc: toAddresses(single(parsed.cc)),
323
+ bcc: [],
324
+ inReplyTo: header("in-reply-to"),
325
+ messageId: header("message-id"),
326
+ },
327
+ references: references === undefined
328
+ ? undefined
329
+ : Array.isArray(references)
330
+ ? references
331
+ : [references],
332
+ ...(stored.bodyStructure === null
333
+ ? {}
334
+ : { bodyStructure: stored.bodyStructure ?? headerStructure }),
335
+ ...(this.server.condstore ? { modseq: stored.modseq.toString() } : {}),
336
+ };
337
+ };
338
+ fetchRows = async (uids) => {
339
+ const folder = this.open();
340
+ const rows = [];
341
+ for (const uid of uids) {
342
+ const stored = folder.messages.get(uid);
343
+ if (stored)
344
+ rows.push(await this.toImapMessage(uid, stored));
345
+ }
346
+ return rows;
347
+ };
348
+ fetchMessages = async (uids) => {
349
+ this.server.run("FETCH", `${this.selected} ${this.uidList(uids)}`);
350
+ return this.fetchRows(uids);
351
+ };
352
+ supportsCondstore = () => this.server.condstore;
353
+ fetchMessagesChangedSince = async (sinceModseq) => {
354
+ this.server.run("FETCH", `${this.selected} 1:* CHANGEDSINCE ${sinceModseq}`);
355
+ if (!this.server.condstore) {
356
+ throw new Error("CHANGEDSINCE requires CONDSTORE");
357
+ }
358
+ const folder = this.open();
359
+ const rows = [];
360
+ for (const [uid, stored] of folder.messages) {
361
+ if (stored.modseq > sinceModseq) {
362
+ rows.push(await this.toImapMessage(uid, stored));
363
+ }
364
+ }
365
+ return rows;
366
+ };
367
+ fetchEnvelopeSnapshots = async (uids) => {
368
+ this.server.run("FETCH", `${this.selected} ${this.uidList(uids)} ENVELOPE`);
369
+ const rows = await this.fetchRows(uids);
370
+ return rows.map((row) => ({
371
+ uid: row.uid,
372
+ messageId: row.envelope?.messageId ?? "",
373
+ internalDate: row.internalDate,
374
+ }));
375
+ };
376
+ fetchMessageBody = async (uid) => {
377
+ this.server.run("BODY", `${this.selected} ${uid}`);
378
+ await this.server.onFetchBody(uid);
379
+ return this.open().messages.get(uid)?.raw ?? null;
380
+ };
381
+ async *fetchMessageBodies(uids) {
382
+ this.server.run("BODY", `${this.selected} ${this.uidList(uids)}`);
383
+ const folder = this.open();
384
+ for (const uid of uids) {
385
+ const stored = folder.messages.get(uid);
386
+ if (stored)
387
+ yield { uid, source: Readable.from([stored.raw]) };
388
+ }
389
+ }
390
+ touch = (detail, uids, change) => {
391
+ this.server.run("STORE", `${this.selected} ${this.uidList(uids)} ${detail}`);
392
+ const folder = this.open();
393
+ const modseq = this.server.bumpModseq();
394
+ for (const uid of uids) {
395
+ const stored = folder.messages.get(uid);
396
+ if (!stored)
397
+ continue;
398
+ change(stored.flags);
399
+ stored.modseq = modseq;
400
+ }
401
+ };
402
+ addFlags = async (uids, flags) => this.touch(`+${flags.join(" ")}`, uids, (set) => {
403
+ for (const flag of flags)
404
+ set.add(flag);
405
+ });
406
+ removeFlags = async (uids, flags) => this.touch(`-${flags.join(" ")}`, uids, (set) => {
407
+ for (const flag of flags)
408
+ set.delete(flag);
409
+ });
410
+ setFlags = async (uids, flags) => this.touch(flags.join(" "), uids, (set) => {
411
+ set.clear();
412
+ for (const flag of flags)
413
+ set.add(flag);
414
+ });
415
+ createMailbox = async (path) => {
416
+ const resolved = this.server.namespacePrefix + path;
417
+ this.server.run("CREATE", resolved);
418
+ return { path: resolved, created: this.server.createFolder(resolved) };
419
+ };
420
+ deleteMailbox = async (path) => {
421
+ this.server.run("DELETE", path);
422
+ this.server.deleteFolder(path);
423
+ return { path };
424
+ };
425
+ renameMailbox = async (oldPath, requested) => {
426
+ const newPath = this.server.namespacePrefix + requested;
427
+ this.server.run("RENAME", `${oldPath} ${newPath}`);
428
+ this.server.renameFolder(oldPath, newPath);
429
+ return { path: oldPath, newPath };
430
+ };
431
+ subscribeMailbox = async (path) => {
432
+ this.server.run("SUBSCRIBE", path);
433
+ this.server.folder(path).subscribed = true;
434
+ };
435
+ unsubscribeMailbox = async (path) => {
436
+ this.server.run("UNSUBSCRIBE", path);
437
+ this.server.folder(path).subscribed = false;
438
+ };
439
+ transfer = (verb, uids, destination) => {
440
+ this.server.run(verb, `${this.selected} ${this.uidList(uids)} ${destination}`);
441
+ if (!this.server.hasFolder(destination)) {
442
+ throw imapError("TRYCREATE", `Mailbox doesn't exist: ${destination}`);
443
+ }
444
+ const target = this.server.folder(destination);
445
+ const uidMap = new Map();
446
+ if (this.server.ignoreNext.delete(verb)) {
447
+ return { destination, uidValidity: target.uidValidity, uidMap };
448
+ }
449
+ const source = this.open();
450
+ for (const uid of uids) {
451
+ const stored = source.messages.get(uid);
452
+ if (!stored)
453
+ continue;
454
+ const next = target.uidNext++;
455
+ target.messages.set(next, {
456
+ ...stored,
457
+ flags: new Set(stored.flags),
458
+ modseq: this.server.bumpModseq(),
459
+ });
460
+ if (verb === "MOVE")
461
+ source.messages.delete(uid);
462
+ if (this.server.uidplus)
463
+ uidMap.set(uid, next);
464
+ }
465
+ return { destination, uidValidity: target.uidValidity, uidMap };
466
+ };
467
+ moveMessages = async (uids, destination) => this.transfer("MOVE", uids, destination);
468
+ copyMessages = async (uids, destination) => this.transfer("COPY", uids, destination);
469
+ deleteMessages = async (uids) => {
470
+ this.server.run("EXPUNGE", `${this.selected} ${this.uidList(uids)}`);
471
+ const folder = this.open();
472
+ let deleted = 0;
473
+ for (const uid of uids) {
474
+ if (folder.messages.delete(uid))
475
+ deleted++;
476
+ }
477
+ return deleted;
478
+ };
479
+ getMailboxStatus = async (path) => {
480
+ this.server.run("STATUS", path);
481
+ const folder = this.server.folder(path);
482
+ const messages = [...folder.messages.values()];
483
+ return {
484
+ messages: messages.length,
485
+ recent: 0,
486
+ unseen: messages.filter((message) => !message.flags.has("\\Seen")).length,
487
+ uidNext: folder.uidNext,
488
+ uidValidity: folder.uidValidity,
489
+ highestModseq: this.server.condstore
490
+ ? this.server.highestModseq().toString()
491
+ : "0",
492
+ deletedCount: messages.filter((message) => message.flags.has("\\Deleted"))
493
+ .length,
494
+ };
495
+ };
496
+ append = async (mailbox, message, flags = []) => {
497
+ this.server.run("APPEND", mailbox);
498
+ if (!this.server.hasFolder(mailbox)) {
499
+ throw imapError("TRYCREATE", `Mailbox doesn't exist: ${mailbox}`);
500
+ }
501
+ const uid = this.server.deliver(mailbox, Buffer.isBuffer(message) ? message : Buffer.from(message), { flags });
502
+ return {
503
+ destination: mailbox,
504
+ uidValidity: this.server.folder(mailbox).uidValidity,
505
+ uid,
506
+ };
507
+ };
508
+ }
@@ -0,0 +1,34 @@
1
+ import type { IMailboxSpecialUseRepository } from "@remit/data-ports";
2
+ import type { JunkRoleMailboxes, RoleResolution } from "@remit/data-ports/folder-role";
3
+ type RoleMailbox = {
4
+ mailboxId: string;
5
+ fullPath: string;
6
+ };
7
+ /**
8
+ * The evidence-carrying answer behind `findTrashMailbox`, so a stub that names
9
+ * a Trash folder answers both reads consistently. A named folder stands in as
10
+ * server-flagged: the suites using this are testing something other than how
11
+ * the role was decided.
12
+ */
13
+ export declare const trashRole: (trash: RoleMailbox | null) => RoleResolution<RoleMailbox>;
14
+ /**
15
+ * A folder-role map for an account that has appointed nothing and whose server
16
+ * flags nothing — every mailbox is an ordinary folder. The stand-in for the
17
+ * many suites that construct `MessageSyncService` for a reason unrelated to
18
+ * which folder holds which role.
19
+ */
20
+ export declare const noFolderRoles: IMailboxSpecialUseRepository;
21
+ /** A folder-role map naming the mailboxes that hold Junk and Trash. */
22
+ export declare const folderRoles: (roles: {
23
+ junkMailboxId?: string;
24
+ trashMailboxId?: string;
25
+ }) => IMailboxSpecialUseRepository;
26
+ /** An account whose config resolves no Junk and no Trash anywhere. */
27
+ export declare const NO_JUNK_ROLES: JunkRoleMailboxes;
28
+ /** The same account, as the resolved map `saveMessage` is handed. */
29
+ export declare const NO_FOLDER_ROLES: {
30
+ junkMailboxId: null;
31
+ trashMailboxId: null;
32
+ configJunkRoles: JunkRoleMailboxes;
33
+ };
34
+ export {};
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The evidence-carrying answer behind `findTrashMailbox`, so a stub that names
3
+ * a Trash folder answers both reads consistently. A named folder stands in as
4
+ * server-flagged: the suites using this are testing something other than how
5
+ * the role was decided.
6
+ */
7
+ export const trashRole = (trash) => trash ? { kind: "flagged", mailbox: trash } : { kind: "none" };
8
+ /**
9
+ * A folder-role map for an account that has appointed nothing and whose server
10
+ * flags nothing — every mailbox is an ordinary folder. The stand-in for the
11
+ * many suites that construct `MessageSyncService` for a reason unrelated to
12
+ * which folder holds which role.
13
+ */
14
+ export const noFolderRoles = {
15
+ findJunkMailbox: async () => null,
16
+ findTrashMailbox: async () => null,
17
+ resolveTrashRole: async () => trashRole(null),
18
+ resolveJunkRolesForConfig: async () => NO_JUNK_ROLES,
19
+ };
20
+ /** A folder-role map naming the mailboxes that hold Junk and Trash. */
21
+ export const folderRoles = (roles) => {
22
+ const trash = roles.trashMailboxId
23
+ ? { mailboxId: roles.trashMailboxId, fullPath: roles.trashMailboxId }
24
+ : null;
25
+ return {
26
+ findJunkMailbox: async () => roles.junkMailboxId
27
+ ? { mailboxId: roles.junkMailboxId, fullPath: roles.junkMailboxId }
28
+ : null,
29
+ findTrashMailbox: async () => trash,
30
+ resolveTrashRole: async () => trashRole(trash),
31
+ resolveJunkRolesForConfig: async () => ({
32
+ junkMailboxIds: roles.junkMailboxId ? [roles.junkMailboxId] : [],
33
+ trashMailboxIds: roles.trashMailboxId ? [roles.trashMailboxId] : [],
34
+ }),
35
+ };
36
+ };
37
+ /** An account whose config resolves no Junk and no Trash anywhere. */
38
+ export const NO_JUNK_ROLES = {
39
+ junkMailboxIds: [],
40
+ trashMailboxIds: [],
41
+ };
42
+ /** The same account, as the resolved map `saveMessage` is handed. */
43
+ export const NO_FOLDER_ROLES = {
44
+ junkMailboxId: null,
45
+ trashMailboxId: null,
46
+ configJunkRoles: NO_JUNK_ROLES,
47
+ };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Deterministic random MIME tree generator for the body-part mapper
3
+ * property test (issue #395 PR C).
4
+ *
5
+ * Three pieces:
6
+ *
7
+ * 1. `createRng(seed)` — small xorshift32 PRNG. Same seed → same sequence
8
+ * so failing CI runs reproduce locally via `MAPPER_PROPERTY_SEED`.
9
+ *
10
+ * 2. `generateMimeTree(rng, opts)` — synthesise a random tree:
11
+ * - root is either a leaf or a `multipart/<mixed|alternative|related>`
12
+ * - multiparts have N ∈ [1, 5] children
13
+ * - each child is leaf or multipart, depth capped at `maxDepth` (4)
14
+ * - leaves draw uniformly from a fixed set of media types
15
+ * - some leaves get a `dispositionFilename`, some a `contentId`,
16
+ * some both, most neither
17
+ * - leaves are mostly non-empty; a small fraction get zero bytes to
18
+ * exercise the empty-leaf short-circuit in the mapper
19
+ *
20
+ * 3. `renderEml(tree)` + `treeToBodyParts(tree)` — produce a paired
21
+ * `.eml` string and the `MapperInput[]` rows the mime-walker would
22
+ * emit for that tree. Both walk the same tree, so partPath, content
23
+ * type, filename and contentId stay aligned by construction.
24
+ *
25
+ * No external deps. Built on Node primitives only (`node:buffer`,
26
+ * `node:string_decoder` via `Buffer.from(..., 'base64')`).
27
+ */
28
+ import { Buffer } from "node:buffer";
29
+ import type { BodyPartItem } from "@remit/data-ports";
30
+ export type MapperInput = Pick<BodyPartItem, "partPath" | "isMultipart" | "mediaType" | "mediaSubtype" | "contentId" | "dispositionFilename" | "disposition"> & {
31
+ sizeOctets?: number;
32
+ };
33
+ /** Tiny xorshift32 PRNG. `next()` returns a float in [0, 1). */
34
+ export interface Rng {
35
+ next(): number;
36
+ int(maxExclusive: number): number;
37
+ pick<T>(items: readonly T[]): T;
38
+ bool(probability: number): boolean;
39
+ }
40
+ export declare const createRng: (seed: number) => Rng;
41
+ export type MultipartSubtypeName = "mixed" | "alternative" | "related";
42
+ export type LeafContentType = "text/plain" | "text/html" | "application/pdf" | "image/png" | "application/octet-stream";
43
+ export interface LeafNode {
44
+ kind: "leaf";
45
+ contentType: LeafContentType;
46
+ /** Decoded body bytes the renderer will encode into the EML. */
47
+ bytes: Buffer;
48
+ /** Optional `filename=` attribute on the leaf. */
49
+ filename?: string;
50
+ /** Optional `Content-ID:` header value (without angle brackets). */
51
+ contentId?: string;
52
+ /** "inline" or "attachment" Content-Disposition. */
53
+ disposition?: "inline" | "attachment";
54
+ }
55
+ export interface MultipartNode {
56
+ kind: "multipart";
57
+ subtype: MultipartSubtypeName;
58
+ children: MimeTreeNode[];
59
+ }
60
+ export type MimeTreeNode = LeafNode | MultipartNode;
61
+ export interface GenerateOptions {
62
+ maxDepth?: number;
63
+ /** Probability the root is a multipart (vs. a single flat leaf). */
64
+ rootMultipartProb?: number;
65
+ /** Probability an empty buffer is used for a leaf body. */
66
+ emptyLeafProb?: number;
67
+ }
68
+ export declare const generateMimeTree: (rng: Rng, opts?: GenerateOptions) => MimeTreeNode;
69
+ /**
70
+ * Walk the tree the same way `mime-walker.ts` would and emit
71
+ * `MapperInput[]` in declaration order. Root path is "0"; subsequent
72
+ * leaves are "1", "2", "1.1", "1.2", ... — matches `walkMimeStructure`.
73
+ */
74
+ export declare const treeToBodyParts: (tree: MimeTreeNode) => MapperInput[];
75
+ export interface RenderOptions {
76
+ seed: number;
77
+ subject?: string;
78
+ from?: string;
79
+ to?: string;
80
+ messageId?: string;
81
+ }
82
+ export declare const renderEml: (tree: MimeTreeNode, opts: RenderOptions) => string;