@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
@@ -1,461 +0,0 @@
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
- };
@@ -1,223 +0,0 @@
1
- import assert from "node:assert";
2
- import { describe, it } from "node:test";
3
- import { createTextNormalizer } from "./normalizer.js";
4
-
5
- describe("TextNormalizer", () => {
6
- const normalizer = createTextNormalizer();
7
-
8
- describe("detectLanguage", () => {
9
- it("detects English text", () => {
10
- const text =
11
- "The quick brown fox jumps over the lazy dog. This is a sample English text.";
12
- assert.strictEqual(normalizer.detectLanguage(text), "en");
13
- });
14
-
15
- it("detects German text", () => {
16
- const text =
17
- "Der schnelle braune Fuchs springt über den faulen Hund. Dies ist ein deutscher Text.";
18
- assert.strictEqual(normalizer.detectLanguage(text), "de");
19
- });
20
-
21
- it("detects French text", () => {
22
- const text =
23
- "Le renard brun rapide saute par-dessus le chien paresseux. Ceci est un texte français.";
24
- assert.strictEqual(normalizer.detectLanguage(text), "fr");
25
- });
26
-
27
- it("detects Spanish text", () => {
28
- const text =
29
- "El rápido zorro marrón salta sobre el perro perezoso. Este es un texto en español.";
30
- assert.strictEqual(normalizer.detectLanguage(text), "es");
31
- });
32
-
33
- it("detects Italian text", () => {
34
- const text =
35
- "La volpe marrone veloce salta sopra il cane pigro. Questo è un testo italiano.";
36
- assert.strictEqual(normalizer.detectLanguage(text), "it");
37
- });
38
-
39
- it("detects Portuguese text", () => {
40
- const text =
41
- "A rápida raposa marrom salta sobre o cão preguiçoso. Este é um texto em português.";
42
- assert.strictEqual(normalizer.detectLanguage(text), "pt");
43
- });
44
-
45
- it("detects Dutch text", () => {
46
- const text =
47
- "De snelle bruine vos springt over de luie hond. Dit is een Nederlandse tekst.";
48
- assert.strictEqual(normalizer.detectLanguage(text), "nl");
49
- });
50
-
51
- it("defaults to English for short text", () => {
52
- const text = "Hello";
53
- assert.strictEqual(normalizer.detectLanguage(text), "en");
54
- });
55
-
56
- it("defaults to English for empty text", () => {
57
- assert.strictEqual(normalizer.detectLanguage(""), "en");
58
- });
59
- });
60
-
61
- describe("tokenize", () => {
62
- it("tokenizes text into words", () => {
63
- const text = "Hello, World! How are you?";
64
- assert.deepStrictEqual(normalizer.tokenize(text), [
65
- "hello",
66
- "world",
67
- "how",
68
- "are",
69
- "you",
70
- ]);
71
- });
72
-
73
- it("handles Unicode characters", () => {
74
- const text = "Réunion demain café";
75
- assert.deepStrictEqual(normalizer.tokenize(text), [
76
- "réunion",
77
- "demain",
78
- "café",
79
- ]);
80
- });
81
-
82
- it("handles German umlauts", () => {
83
- const text = "Besprechung über München";
84
- assert.deepStrictEqual(normalizer.tokenize(text), [
85
- "besprechung",
86
- "über",
87
- "münchen",
88
- ]);
89
- });
90
-
91
- it("normalizes whitespace", () => {
92
- const text = " multiple spaces\n\ttabs ";
93
- assert.deepStrictEqual(normalizer.tokenize(text), [
94
- "multiple",
95
- "spaces",
96
- "tabs",
97
- ]);
98
- });
99
- });
100
-
101
- describe("stem", () => {
102
- it("stems English words", () => {
103
- assert.strictEqual(normalizer.stem("running", "en"), "run");
104
- assert.strictEqual(normalizer.stem("jumps", "en"), "jump");
105
- assert.strictEqual(normalizer.stem("connected", "en"), "connect");
106
- });
107
-
108
- it("stems German words", () => {
109
- // German Porter stemmer has different rules than English
110
- // Just verify it returns a string and doesn't throw
111
- const result1 = normalizer.stem("verbindung", "de");
112
- const result2 = normalizer.stem("laufend", "de");
113
- assert.ok(typeof result1 === "string");
114
- assert.ok(typeof result2 === "string");
115
- // The stemmer should at least return something
116
- assert.ok(result1.length > 0);
117
- assert.ok(result2.length > 0);
118
- });
119
-
120
- it("stems French words", () => {
121
- assert.strictEqual(normalizer.stem("réunion", "fr"), "réunion");
122
- assert.strictEqual(normalizer.stem("connexion", "fr"), "connexion");
123
- });
124
-
125
- it("defaults to English stemmer for unknown language", () => {
126
- assert.strictEqual(normalizer.stem("running"), "run");
127
- });
128
- });
129
-
130
- describe("removeStopwords", () => {
131
- it("removes English stopwords", () => {
132
- const words = ["the", "quick", "brown", "fox", "is", "running"];
133
- const result = normalizer.removeStopwords(words, "en");
134
- assert.ok(!result.includes("the"));
135
- assert.ok(!result.includes("is"));
136
- assert.ok(result.includes("quick"));
137
- assert.ok(result.includes("brown"));
138
- assert.ok(result.includes("fox"));
139
- assert.ok(result.includes("running"));
140
- });
141
-
142
- it("removes German stopwords", () => {
143
- const words = ["der", "schnelle", "fuchs", "ist", "braun"];
144
- const result = normalizer.removeStopwords(words, "de");
145
- assert.ok(!result.includes("der"));
146
- assert.ok(!result.includes("ist"));
147
- assert.ok(result.includes("schnelle"));
148
- assert.ok(result.includes("fuchs"));
149
- });
150
-
151
- it("removes French stopwords", () => {
152
- const words = ["le", "renard", "est", "rapide"];
153
- const result = normalizer.removeStopwords(words, "fr");
154
- assert.ok(!result.includes("le"));
155
- assert.ok(!result.includes("est"));
156
- assert.ok(result.includes("renard"));
157
- assert.ok(result.includes("rapide"));
158
- });
159
-
160
- it("removes Dutch stopwords", () => {
161
- const words = ["de", "snelle", "vos", "is", "bruin"];
162
- const result = normalizer.removeStopwords(words, "nl");
163
- assert.ok(!result.includes("de"));
164
- assert.ok(!result.includes("is"));
165
- assert.ok(result.includes("snelle"));
166
- assert.ok(result.includes("vos"));
167
- });
168
- });
169
-
170
- describe("normalize", () => {
171
- it("normalizes English text with stemming and stopword removal", () => {
172
- const text = "The quick brown fox is running quickly";
173
- const result = normalizer.normalize(text, { language: "en" });
174
- // Should remove "the" and "is", stem "running" and "quickly"
175
- assert.ok(!result.includes("the "));
176
- assert.ok(!result.includes(" is "));
177
- assert.ok(result.includes("quick"));
178
- assert.ok(result.includes("run"));
179
- });
180
-
181
- it("normalizes German text", () => {
182
- const text = "Der schnelle braune Fuchs ist laufend";
183
- const result = normalizer.normalize(text, { language: "de" });
184
- assert.ok(!result.includes("der "));
185
- assert.ok(!result.includes(" ist "));
186
- });
187
-
188
- it("normalizes without stemming when disabled", () => {
189
- const text = "running quickly";
190
- const result = normalizer.normalize(text, {
191
- language: "en",
192
- stem: false,
193
- removeStopwords: false,
194
- });
195
- assert.strictEqual(result, "running quickly");
196
- });
197
-
198
- it("handles Unicode text", () => {
199
- const text = "Réunion à Paris demain";
200
- const result = normalizer.normalize(text, { language: "fr" });
201
- assert.ok(result.includes("réunion"));
202
- assert.ok(result.includes("pari"));
203
- assert.ok(result.includes("demain"));
204
- });
205
-
206
- it("deduplicates consecutive words", () => {
207
- const text = "hello hello world world world";
208
- const result = normalizer.normalize(text, {
209
- language: "en",
210
- stem: false,
211
- removeStopwords: false,
212
- });
213
- assert.strictEqual(result, "hello world");
214
- });
215
-
216
- it("defaults to English when language not specified", () => {
217
- const text = "The quick brown fox";
218
- const result = normalizer.normalize(text);
219
- // "the" should be removed as English stopword
220
- assert.ok(!result.includes("the "));
221
- });
222
- });
223
- });