@remit/mailbox-service 0.0.112 → 0.0.114

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 (270) 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} +16 -72
  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} +38 -64
  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 +129 -0
  78. package/dist/mailbox-queue.js +216 -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 +280 -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} +13 -68
  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 -97
  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 -88
  150. package/src/account-credentials.ts +0 -210
  151. package/src/attribute-mapper.test.ts +0 -104
  152. package/src/attribute-mapper.ts +0 -148
  153. package/src/body-parse.test.ts +0 -55
  154. package/src/body-part-mapper.property.test.ts +0 -354
  155. package/src/body-part-mapper.ts +0 -410
  156. package/src/body-sync-queue.test.ts +0 -64
  157. package/src/body-sync-queue.ts +0 -131
  158. package/src/body-sync-terminal.test.ts +0 -148
  159. package/src/body-sync-terminal.ts +0 -174
  160. package/src/body-sync.test.ts +0 -925
  161. package/src/body-sync.ts +0 -1891
  162. package/src/calendar-parts.ts +0 -41
  163. package/src/classification-backfill.test.ts +0 -285
  164. package/src/classification-backfill.ts +0 -363
  165. package/src/classify-message.test.ts +0 -142
  166. package/src/classify-message.ts +0 -116
  167. package/src/connection-factory.ts +0 -102
  168. package/src/connection-test.ts +0 -208
  169. package/src/credentials.test.ts +0 -181
  170. package/src/external-move.test.ts +0 -262
  171. package/src/external-move.ts +0 -285
  172. package/src/filter-operations.test.ts +0 -319
  173. package/src/filter-operations.ts +0 -377
  174. package/src/filter-update.test.ts +0 -313
  175. package/src/filters/filter-config.test.ts +0 -87
  176. package/src/filters/filter-config.ts +0 -34
  177. package/src/filters/list-id.test.ts +0 -50
  178. package/src/filters/match.test.ts +0 -392
  179. package/src/filters/match.ts +0 -225
  180. package/src/filters/pipeline.test.ts +0 -199
  181. package/src/filters/pipeline.ts +0 -170
  182. package/src/flag-push.test.ts +0 -112
  183. package/src/flag-push.ts +0 -198
  184. package/src/flag-queue.test.ts +0 -197
  185. package/src/flag-queue.ts +0 -509
  186. package/src/folder-operations.test.ts +0 -273
  187. package/src/folder-operations.ts +0 -217
  188. package/src/folder-placement.ts +0 -56
  189. package/src/forwarded-message.test.ts +0 -122
  190. package/src/heuristics/authenticationResults.test.ts +0 -189
  191. package/src/heuristics/authenticationResults.ts +0 -212
  192. package/src/heuristics/classifyByHeaders.test.ts +0 -889
  193. package/src/heuristics/classifyByHeaders.ts +0 -467
  194. package/src/heuristics/classifyPlacement.test.ts +0 -366
  195. package/src/heuristics/classifyPlacement.ts +0 -211
  196. package/src/heuristics/classifyRealMail.test.ts +0 -242
  197. package/src/heuristics/machineSenders.test.ts +0 -101
  198. package/src/heuristics/senderMismatch.test.ts +0 -346
  199. package/src/heuristics/senderMismatch.ts +0 -259
  200. package/src/imapflow-connect-retry.test.ts +0 -97
  201. package/src/imapflow-connection.test.ts +0 -503
  202. package/src/imapflow-connection.ts +0 -1476
  203. package/src/index.ts +0 -397
  204. package/src/list-id-backfill.test.ts +0 -207
  205. package/src/list-id-backfill.ts +0 -274
  206. package/src/mailbox-cursor-rebuild.test.ts +0 -171
  207. package/src/mailbox-cursor-rebuild.ts +0 -146
  208. package/src/mailbox-cursor.test.ts +0 -141
  209. package/src/mailbox-delete-intent.test.ts +0 -119
  210. package/src/mailbox-management.test.ts +0 -243
  211. package/src/mailbox-management.ts +0 -838
  212. package/src/mailbox-presence.test.ts +0 -74
  213. package/src/mailbox-queue.ts +0 -397
  214. package/src/mailbox-rename-intent.test.ts +0 -220
  215. package/src/mailbox-rename-subtree.test.ts +0 -287
  216. package/src/mailbox-sync.test.ts +0 -286
  217. package/src/mailbox-sync.ts +0 -724
  218. package/src/message-move.test.ts +0 -726
  219. package/src/message-move.ts +0 -1518
  220. package/src/message-parser.ts +0 -26
  221. package/src/message-presence.test.ts +0 -50
  222. package/src/message-read.ts +0 -87
  223. package/src/message-save-retry.test.ts +0 -90
  224. package/src/message-sync-flags.test.ts +0 -167
  225. package/src/message-sync.test.ts +0 -762
  226. package/src/message-sync.ts +0 -2133
  227. package/src/mime-walker.test.ts +0 -311
  228. package/src/mime-walker.ts +0 -306
  229. package/src/organize-job.ts +0 -93
  230. package/src/outbox-attachment-content.test.ts +0 -153
  231. package/src/outbox-attachment-content.ts +0 -104
  232. package/src/outbox-attachment-filename.test.ts +0 -132
  233. package/src/outbox-attachment-filename.ts +0 -76
  234. package/src/outbox-attachment.test.ts +0 -626
  235. package/src/outbox-attachment.ts +0 -536
  236. package/src/outbox-failed-recovery.test.ts +0 -299
  237. package/src/outbox-queue.test.ts +0 -315
  238. package/src/outbox-queue.ts +0 -525
  239. package/src/ownership.ts +0 -140
  240. package/src/placement-move-terminal.ts +0 -145
  241. package/src/placement-move.ts +0 -363
  242. package/src/placement-settled.test.ts +0 -147
  243. package/src/placement.test.ts +0 -404
  244. package/src/quarantine.test.ts +0 -133
  245. package/src/quarantine.ts +0 -229
  246. package/src/refusal.ts +0 -29
  247. package/src/snippet.test.ts +0 -213
  248. package/src/snippet.ts +0 -152
  249. package/src/spam-report.test.ts +0 -329
  250. package/src/spam-report.ts +0 -357
  251. package/src/sync-warning.test.ts +0 -213
  252. package/src/sync-warning.ts +0 -56
  253. package/src/sync-watermarks.test.ts +0 -409
  254. package/src/sync-watermarks.ts +0 -319
  255. package/src/system-flag-wire-format.test.ts +0 -77
  256. package/src/test-helpers/fake-imap.ts +0 -690
  257. package/src/test-helpers/folder-roles.ts +0 -66
  258. package/src/test-helpers/mime-tree-generator.ts +0 -461
  259. package/src/test-helpers/test-queue.ts +0 -56
  260. package/src/test-helpers/test-store.ts +0 -299
  261. package/src/text/normalizer.test.ts +0 -223
  262. package/src/text/normalizer.ts +0 -140
  263. package/src/thread-message-rows.ts +0 -77
  264. package/src/thread-root.test.ts +0 -29
  265. package/src/thread-root.ts +0 -51
  266. package/src/types/mailparser-augment.d.ts +0 -23
  267. package/src/types/natural-porter-stemmer.d.ts +0 -50
  268. package/src/types/stopword.d.ts +0 -69
  269. package/src/types.ts +0 -371
  270. 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;