@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,55 @@
1
+ import type {
2
+ IMessageRepository,
3
+ IThreadMessageRepository,
4
+ } from "@remit/data-ports";
5
+
6
+ export interface StaleMessageReconcileDeps {
7
+ messageService: Pick<IMessageRepository, "delete">;
8
+ threadMessageService: Pick<
9
+ IThreadMessageRepository,
10
+ "findAllByMessageId" | "deleteMany"
11
+ >;
12
+ }
13
+
14
+ export interface StaleMessageReconcileResult {
15
+ threadMessagesDeleted: number;
16
+ }
17
+
18
+ /**
19
+ * Delete a Message row (and every ThreadMessage copy that points at it) once
20
+ * the caller has confirmed the message no longer exists on the IMAP server.
21
+ *
22
+ * A row outliving an upstream expunge (or a UIDVALIDITY change — #1272) is
23
+ * the EXPECTED terminal outcome for a body that can never be fetched (issue
24
+ * #1270 / epic #1281 invariant 3): expunges are routine, so cleaning up here
25
+ * is normal operation, not an incident. Deleting the row makes the existing
26
+ * missing-row 404 path (`MessageService.get` / `describe`) authoritative
27
+ * again — nothing renders the row, nothing re-arms a sync for it.
28
+ *
29
+ * Exported standalone, not inlined in the body-sync retry path, so #1272's
30
+ * UIDVALIDITY cursor rebuild can call the same reconciliation when it finds
31
+ * rows whose UIDs no longer resolve after a cursor rebuild.
32
+ */
33
+ export const reconcileStaleMessage = async (
34
+ deps: StaleMessageReconcileDeps,
35
+ accountConfigId: string,
36
+ messageId: string,
37
+ ): Promise<StaleMessageReconcileResult> => {
38
+ const threadMessages = await deps.threadMessageService.findAllByMessageId(
39
+ accountConfigId,
40
+ messageId,
41
+ );
42
+
43
+ if (threadMessages.length > 0) {
44
+ await deps.threadMessageService.deleteMany(
45
+ threadMessages.map((row) => ({
46
+ accountConfigId: row.accountConfigId,
47
+ threadMessageId: row.threadMessageId,
48
+ })),
49
+ );
50
+ }
51
+
52
+ await deps.messageService.delete(messageId);
53
+
54
+ return { threadMessagesDeleted: threadMessages.length };
55
+ };
@@ -0,0 +1,44 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ImapFlowConnection } from "../imapflow-connection.js";
3
+
4
+ /**
5
+ * Per-file mailbox isolation for the mailfuzz e2e suite (#508).
6
+ *
7
+ * The e2e files share one Dovecot account. INBOX is the seeded corpus and is
8
+ * treated as read-only: any test that APPENDs or mutates flags does so in its
9
+ * own uniquely-named mailbox instead, so two files can run in parallel without
10
+ * contending on the same message set. This is what lets `test:e2e` drop
11
+ * `--test-concurrency=1`.
12
+ */
13
+
14
+ export const uniqueMailboxName = (prefix: string): string =>
15
+ `${prefix}_${Date.now()}_${randomUUID().slice(0, 8)}`;
16
+
17
+ const seedMessage = (index: number): string =>
18
+ [
19
+ "From: seed@example.com",
20
+ "To: vmail@localhost",
21
+ `Subject: Isolated seed message ${index}`,
22
+ `Date: ${new Date().toUTCString()}`,
23
+ `Message-ID: <seed-${index}-${randomUUID()}@test.example.com>`,
24
+ "",
25
+ `Isolated seed body ${index}`,
26
+ ].join("\r\n");
27
+
28
+ /**
29
+ * Create `mailbox` and APPEND `count` deterministic messages into it. Returns
30
+ * the appended UIDs in insertion order.
31
+ */
32
+ export const seedMailbox = async (
33
+ connection: ImapFlowConnection,
34
+ mailbox: string,
35
+ count: number,
36
+ ): Promise<number[]> => {
37
+ await connection.createMailbox(mailbox);
38
+ const uids: number[] = [];
39
+ for (let index = 0; index < count; index++) {
40
+ const { uid } = await connection.append(mailbox, seedMessage(index));
41
+ uids.push(uid);
42
+ }
43
+ return uids;
44
+ };
@@ -0,0 +1,27 @@
1
+ import { ImapFlowConnection } from "../imapflow-connection.js";
2
+
3
+ export const MAILFUZZ_CONFIG = {
4
+ host: process.env.MAILFUZZ_HOST ?? "localhost",
5
+ port: Number(process.env.MAILFUZZ_PORT ?? 1143),
6
+ user: process.env.MAILFUZZ_USER ?? "vmail",
7
+ credentials: {
8
+ kind: "password" as const,
9
+ password: process.env.MAILFUZZ_PASSWORD ?? "testpass123",
10
+ },
11
+ tls: false,
12
+ };
13
+
14
+ export const createMailfuzzConnection = (): ImapFlowConnection =>
15
+ new ImapFlowConnection(MAILFUZZ_CONFIG);
16
+
17
+ export const withMailfuzzConnection = async (
18
+ fn: (connection: ImapFlowConnection) => Promise<void>,
19
+ ): Promise<void> => {
20
+ const connection = createMailfuzzConnection();
21
+ await connection.connect();
22
+ await fn(connection).finally(() => {
23
+ if (connection.isConnected) {
24
+ return connection.disconnect();
25
+ }
26
+ });
27
+ };
@@ -0,0 +1,461 @@
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
+
29
+ import { Buffer } from "node:buffer";
30
+ import type { BodyPartItem } from "@remit/data-ports";
31
+
32
+ export type MapperInput = Pick<
33
+ BodyPartItem,
34
+ | "partPath"
35
+ | "isMultipart"
36
+ | "mediaType"
37
+ | "mediaSubtype"
38
+ | "contentId"
39
+ | "dispositionFilename"
40
+ | "disposition"
41
+ > & { sizeOctets?: number };
42
+
43
+ /** Tiny xorshift32 PRNG. `next()` returns a float in [0, 1). */
44
+ export interface Rng {
45
+ next(): number;
46
+ int(maxExclusive: number): number;
47
+ pick<T>(items: readonly T[]): T;
48
+ bool(probability: number): boolean;
49
+ }
50
+
51
+ export const createRng = (seed: number): Rng => {
52
+ // xorshift32 needs a non-zero 32-bit state.
53
+ let state = (seed | 0) === 0 ? 0xc0dec0de | 0 : seed | 0;
54
+
55
+ const next = (): number => {
56
+ state ^= state << 13;
57
+ state ^= state >>> 17;
58
+ state ^= state << 5;
59
+ // Map signed-int range to [0, 1).
60
+ return ((state >>> 0) % 0xffffffff) / 0xffffffff;
61
+ };
62
+
63
+ return {
64
+ next,
65
+ int: (maxExclusive: number) => Math.floor(next() * maxExclusive),
66
+ pick: <T>(items: readonly T[]): T =>
67
+ items[Math.floor(next() * items.length)],
68
+ bool: (probability: number) => next() < probability,
69
+ };
70
+ };
71
+
72
+ /* -------------------------------------------------------------------- */
73
+ /* Tree shape */
74
+ /* -------------------------------------------------------------------- */
75
+
76
+ export type MultipartSubtypeName = "mixed" | "alternative" | "related";
77
+
78
+ export type LeafContentType =
79
+ | "text/plain"
80
+ | "text/html"
81
+ | "application/pdf"
82
+ | "image/png"
83
+ | "application/octet-stream";
84
+
85
+ export interface LeafNode {
86
+ kind: "leaf";
87
+ contentType: LeafContentType;
88
+ /** Decoded body bytes the renderer will encode into the EML. */
89
+ bytes: Buffer;
90
+ /** Optional `filename=` attribute on the leaf. */
91
+ filename?: string;
92
+ /** Optional `Content-ID:` header value (without angle brackets). */
93
+ contentId?: string;
94
+ /** "inline" or "attachment" Content-Disposition. */
95
+ disposition?: "inline" | "attachment";
96
+ }
97
+
98
+ export interface MultipartNode {
99
+ kind: "multipart";
100
+ subtype: MultipartSubtypeName;
101
+ children: MimeTreeNode[];
102
+ }
103
+
104
+ export type MimeTreeNode = LeafNode | MultipartNode;
105
+
106
+ const LEAF_CONTENT_TYPES: readonly LeafContentType[] = [
107
+ "text/plain",
108
+ "text/html",
109
+ "application/pdf",
110
+ "image/png",
111
+ "application/octet-stream",
112
+ ];
113
+
114
+ const MULTIPART_SUBTYPES: readonly MultipartSubtypeName[] = [
115
+ "mixed",
116
+ "alternative",
117
+ "related",
118
+ ];
119
+
120
+ export interface GenerateOptions {
121
+ maxDepth?: number;
122
+ /** Probability the root is a multipart (vs. a single flat leaf). */
123
+ rootMultipartProb?: number;
124
+ /** Probability an empty buffer is used for a leaf body. */
125
+ emptyLeafProb?: number;
126
+ }
127
+
128
+ const DEFAULT_OPTS: Required<GenerateOptions> = {
129
+ maxDepth: 4,
130
+ rootMultipartProb: 0.85,
131
+ emptyLeafProb: 0.05,
132
+ };
133
+
134
+ const extensionFor = (contentType: LeafContentType): string => {
135
+ switch (contentType) {
136
+ case "text/plain":
137
+ return "txt";
138
+ case "text/html":
139
+ return "html";
140
+ case "application/pdf":
141
+ return "pdf";
142
+ case "image/png":
143
+ return "png";
144
+ case "application/octet-stream":
145
+ return "bin";
146
+ }
147
+ };
148
+
149
+ const randomBasename = (rng: Rng): string => {
150
+ // Short ASCII basename — keeps the EML readable.
151
+ const letters = "abcdefghijklmnopqrstuvwxyz";
152
+ const len = 3 + rng.int(5);
153
+ let s = "";
154
+ for (let i = 0; i < len; i++) s += letters[rng.int(letters.length)];
155
+ return s;
156
+ };
157
+
158
+ const generateLeafBytes = (
159
+ rng: Rng,
160
+ partPath: string,
161
+ contentType: LeafContentType,
162
+ emptyLeafProb: number,
163
+ ): Buffer => {
164
+ if (rng.bool(emptyLeafProb)) return Buffer.alloc(0);
165
+ return Buffer.from(`leaf-${partPath}-${contentType}`, "utf8");
166
+ };
167
+
168
+ const buildLeaf = (
169
+ rng: Rng,
170
+ partPath: string,
171
+ emptyLeafProb: number,
172
+ ): LeafNode => {
173
+ const contentType = rng.pick(LEAF_CONTENT_TYPES);
174
+ const bytes = generateLeafBytes(rng, partPath, contentType, emptyLeafProb);
175
+
176
+ const leaf: LeafNode = { kind: "leaf", contentType, bytes };
177
+
178
+ const ext = extensionFor(contentType);
179
+ const isTextStar = contentType.startsWith("text/");
180
+
181
+ // Random attachment metadata:
182
+ // - ~25% get a filename (more common on non-text leaves)
183
+ // - ~10% get a contentId (image/inline-style)
184
+ // - text/plain and text/html mostly stay bare (they route via parsed.text/html)
185
+ const wantsFilename = isTextStar ? rng.bool(0.05) : rng.bool(0.45);
186
+ const wantsContentId = rng.bool(0.15);
187
+
188
+ if (wantsFilename) {
189
+ leaf.filename = `${randomBasename(rng)}.${ext}`;
190
+ leaf.disposition = rng.bool(0.5) ? "attachment" : "inline";
191
+ }
192
+ if (wantsContentId) {
193
+ leaf.contentId = `${randomBasename(rng)}@example.org`;
194
+ // inline content-id attachments are conventionally inline.
195
+ if (!leaf.disposition) leaf.disposition = "inline";
196
+ }
197
+
198
+ return leaf;
199
+ };
200
+
201
+ /**
202
+ * Decay child probability with depth: at depth 4 (max), all children are
203
+ * leaves to guarantee termination.
204
+ */
205
+ const childMultipartProb = (depth: number, maxDepth: number): number => {
206
+ if (depth >= maxDepth - 1) return 0;
207
+ // 0.6 → 0.4 → 0.2 → 0 from depth 0 outward.
208
+ const slots = maxDepth - 1;
209
+ const remaining = slots - depth;
210
+ return Math.max(0, (remaining / slots) * 0.6);
211
+ };
212
+
213
+ const buildMultipart = (
214
+ rng: Rng,
215
+ depth: number,
216
+ maxDepth: number,
217
+ emptyLeafProb: number,
218
+ partPath: string,
219
+ ): MultipartNode => {
220
+ const subtype = rng.pick(MULTIPART_SUBTYPES);
221
+ const childCount = 1 + rng.int(5); // [1, 5]
222
+ const childMpProb = childMultipartProb(depth, maxDepth);
223
+
224
+ const children: MimeTreeNode[] = [];
225
+ for (let i = 0; i < childCount; i++) {
226
+ const childPath = partPath === "0" ? String(i + 1) : `${partPath}.${i + 1}`;
227
+ const childIsMultipart = rng.bool(childMpProb);
228
+ if (childIsMultipart) {
229
+ children.push(
230
+ buildMultipart(rng, depth + 1, maxDepth, emptyLeafProb, childPath),
231
+ );
232
+ } else {
233
+ children.push(buildLeaf(rng, childPath, emptyLeafProb));
234
+ }
235
+ }
236
+
237
+ return { kind: "multipart", subtype, children };
238
+ };
239
+
240
+ export const generateMimeTree = (
241
+ rng: Rng,
242
+ opts: GenerateOptions = {},
243
+ ): MimeTreeNode => {
244
+ const o = { ...DEFAULT_OPTS, ...opts };
245
+ const rootIsMultipart = rng.bool(o.rootMultipartProb);
246
+ if (!rootIsMultipart) {
247
+ return buildLeaf(rng, "0", o.emptyLeafProb);
248
+ }
249
+ return buildMultipart(rng, 0, o.maxDepth, o.emptyLeafProb, "0");
250
+ };
251
+
252
+ /* -------------------------------------------------------------------- */
253
+ /* BodyPart projection */
254
+ /* -------------------------------------------------------------------- */
255
+
256
+ const splitContentType = (
257
+ contentType: string,
258
+ ): { mediaType: MapperInput["mediaType"]; mediaSubtype: string } => {
259
+ const [top, sub] = contentType.split("/");
260
+ const map: Record<string, MapperInput["mediaType"]> = {
261
+ text: "TEXT" as MapperInput["mediaType"],
262
+ image: "IMAGE" as MapperInput["mediaType"],
263
+ application: "APPLICATION" as MapperInput["mediaType"],
264
+ multipart: "MULTIPART" as MapperInput["mediaType"],
265
+ };
266
+ const mediaType = map[top];
267
+ if (!mediaType) {
268
+ throw new Error(`mime-tree-generator: unknown top-level type "${top}"`);
269
+ }
270
+ return { mediaType, mediaSubtype: sub };
271
+ };
272
+
273
+ /**
274
+ * Walk the tree the same way `mime-walker.ts` would and emit
275
+ * `MapperInput[]` in declaration order. Root path is "0"; subsequent
276
+ * leaves are "1", "2", "1.1", "1.2", ... — matches `walkMimeStructure`.
277
+ */
278
+ export const treeToBodyParts = (tree: MimeTreeNode): MapperInput[] => {
279
+ const out: MapperInput[] = [];
280
+
281
+ const visit = (node: MimeTreeNode, partPath: string): void => {
282
+ if (node.kind === "leaf") {
283
+ const { mediaType, mediaSubtype } = splitContentType(node.contentType);
284
+ const row: MapperInput = {
285
+ partPath,
286
+ isMultipart: false,
287
+ mediaType,
288
+ mediaSubtype,
289
+ sizeOctets: node.bytes.length,
290
+ ...(node.filename ? { dispositionFilename: node.filename } : {}),
291
+ ...(node.contentId ? { contentId: node.contentId } : {}),
292
+ ...(node.disposition ? { disposition: node.disposition } : {}),
293
+ };
294
+ out.push(row);
295
+ return;
296
+ }
297
+
298
+ out.push({
299
+ partPath,
300
+ isMultipart: true,
301
+ mediaType: "MULTIPART" as MapperInput["mediaType"],
302
+ mediaSubtype: node.subtype,
303
+ });
304
+ for (let i = 0; i < node.children.length; i++) {
305
+ const childPath =
306
+ partPath === "0" ? String(i + 1) : `${partPath}.${i + 1}`;
307
+ visit(node.children[i], childPath);
308
+ }
309
+ };
310
+
311
+ visit(tree, "0");
312
+ return out;
313
+ };
314
+
315
+ /* -------------------------------------------------------------------- */
316
+ /* EML renderer */
317
+ /* -------------------------------------------------------------------- */
318
+
319
+ /**
320
+ * Render a buffer as quoted-printable in a very conservative dialect:
321
+ * ASCII printable stays raw, anything else hex-encoded. Line length
322
+ * limit ignored — fixtures are short enough that no fold is needed for
323
+ * our property test. (mailparser tolerates long QP lines.)
324
+ */
325
+ const encodeQuotedPrintable = (buf: Buffer): string => {
326
+ let out = "";
327
+ for (const b of buf) {
328
+ if (b === 0x09 || b === 0x20 || (b >= 0x21 && b <= 0x7e && b !== 0x3d)) {
329
+ out += String.fromCharCode(b);
330
+ } else if (b === 0x0a) {
331
+ out += "\r\n";
332
+ } else {
333
+ out += `=${b.toString(16).toUpperCase().padStart(2, "0")}`;
334
+ }
335
+ }
336
+ return out;
337
+ };
338
+
339
+ const encodeBase64 = (buf: Buffer): string => {
340
+ const b64 = buf.toString("base64");
341
+ // Wrap at 76 columns per RFC 2045.
342
+ const lines: string[] = [];
343
+ for (let i = 0; i < b64.length; i += 76) lines.push(b64.slice(i, i + 76));
344
+ return lines.join("\r\n");
345
+ };
346
+
347
+ const transferEncodingFor = (
348
+ contentType: LeafContentType,
349
+ ): "7bit" | "base64" | "quoted-printable" => {
350
+ if (contentType === "text/plain") return "quoted-printable";
351
+ if (contentType === "text/html") return "7bit";
352
+ return "base64";
353
+ };
354
+
355
+ const renderLeaf = (leaf: LeafNode): string => {
356
+ const lines: string[] = [];
357
+
358
+ const params: string[] = [];
359
+ if (leaf.contentType.startsWith("text/")) params.push("charset=us-ascii");
360
+ if (leaf.filename) params.push(`name="${leaf.filename}"`);
361
+ const ctypeLine =
362
+ params.length > 0
363
+ ? `Content-Type: ${leaf.contentType}; ${params.join("; ")}`
364
+ : `Content-Type: ${leaf.contentType}`;
365
+ lines.push(ctypeLine);
366
+
367
+ const cte = transferEncodingFor(leaf.contentType);
368
+ lines.push(`Content-Transfer-Encoding: ${cte}`);
369
+
370
+ if (leaf.disposition) {
371
+ const dispLine = leaf.filename
372
+ ? `Content-Disposition: ${leaf.disposition}; filename="${leaf.filename}"`
373
+ : `Content-Disposition: ${leaf.disposition}`;
374
+ lines.push(dispLine);
375
+ }
376
+ if (leaf.contentId) {
377
+ lines.push(`Content-ID: <${leaf.contentId}>`);
378
+ }
379
+
380
+ let body = "";
381
+ if (leaf.bytes.length > 0) {
382
+ if (cte === "base64") body = encodeBase64(leaf.bytes);
383
+ else if (cte === "quoted-printable")
384
+ body = encodeQuotedPrintable(leaf.bytes);
385
+ else body = leaf.bytes.toString("utf8");
386
+ }
387
+
388
+ lines.push("");
389
+ lines.push(body);
390
+ return lines.join("\r\n");
391
+ };
392
+
393
+ /**
394
+ * Deterministic boundary derived from the seed + node path. Each
395
+ * multipart node gets its own unique boundary so nested rendering is
396
+ * unambiguous.
397
+ */
398
+ const boundaryFor = (seed: number, partPath: string): string =>
399
+ `=_b_${seed.toString(16)}_${partPath.replace(/\./g, "_")}_=`;
400
+
401
+ const renderNode = (
402
+ node: MimeTreeNode,
403
+ partPath: string,
404
+ seed: number,
405
+ ): string => {
406
+ if (node.kind === "leaf") return renderLeaf(node);
407
+
408
+ const boundary = boundaryFor(seed, partPath);
409
+ const out: string[] = [];
410
+ out.push(`Content-Type: multipart/${node.subtype}; boundary="${boundary}"`);
411
+ out.push("");
412
+ for (let i = 0; i < node.children.length; i++) {
413
+ const childPath = partPath === "0" ? String(i + 1) : `${partPath}.${i + 1}`;
414
+ out.push(`--${boundary}`);
415
+ out.push(renderNode(node.children[i], childPath, seed));
416
+ }
417
+ out.push(`--${boundary}--`);
418
+ out.push("");
419
+ return out.join("\r\n");
420
+ };
421
+
422
+ export interface RenderOptions {
423
+ seed: number;
424
+ subject?: string;
425
+ from?: string;
426
+ to?: string;
427
+ messageId?: string;
428
+ }
429
+
430
+ export const renderEml = (tree: MimeTreeNode, opts: RenderOptions): string => {
431
+ const headers: string[] = [];
432
+ headers.push(`From: ${opts.from ?? "alice@example.org"}`);
433
+ headers.push(`To: ${opts.to ?? "bob@example.org"}`);
434
+ headers.push(`Subject: ${opts.subject ?? `property-${opts.seed}`}`);
435
+ headers.push("Date: Thu, 28 May 2026 09:00:00 +0000");
436
+ headers.push(
437
+ `Message-Id: <${opts.messageId ?? `property-${opts.seed}@example.org`}>`,
438
+ );
439
+ headers.push("MIME-Version: 1.0");
440
+
441
+ if (tree.kind === "leaf") {
442
+ // Flat single-leaf message: leaf headers merge with the envelope.
443
+ const leafRendered = renderLeaf(tree);
444
+ // Drop the duplicate trailing newlines and merge.
445
+ return `${headers.join("\r\n")}\r\n${leafRendered}\r\n`;
446
+ }
447
+
448
+ const boundary = boundaryFor(opts.seed, "0");
449
+ const out: string[] = [];
450
+ out.push(...headers);
451
+ out.push(`Content-Type: multipart/${tree.subtype}; boundary="${boundary}"`);
452
+ out.push("");
453
+ for (let i = 0; i < tree.children.length; i++) {
454
+ const childPath = String(i + 1);
455
+ out.push(`--${boundary}`);
456
+ out.push(renderNode(tree.children[i], childPath, opts.seed));
457
+ }
458
+ out.push(`--${boundary}--`);
459
+ out.push("");
460
+ return out.join("\r\n");
461
+ };