@joelincc/mailroom 0.1.0 → 0.3.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 (80) hide show
  1. package/README.md +54 -8
  2. package/SECURITY.md +1 -1
  3. package/bin/mailroom.mjs +26 -0
  4. package/dist/broadcast/config.js +79 -0
  5. package/dist/broadcast/explain.js +50 -0
  6. package/dist/cli/args.js +29 -0
  7. package/dist/cli/errors.js +37 -0
  8. package/dist/cli/main.js +533 -0
  9. package/dist/compose/clicks.js +29 -0
  10. package/dist/compose/compose.js +275 -0
  11. package/dist/compose/index.js +8 -0
  12. package/dist/compose/markdown.js +1197 -0
  13. package/dist/compose/personalize.js +123 -0
  14. package/dist/compose/preflight.js +251 -0
  15. package/dist/compose/preview.js +41 -0
  16. package/dist/compose/render.js +141 -0
  17. package/dist/compose/template.js +118 -0
  18. package/docs/broadcast.md +199 -0
  19. package/docs/composing.md +156 -0
  20. package/docs/desk-commands.md +52 -0
  21. package/docs/export.md +52 -0
  22. package/docs/lists.md +68 -0
  23. package/docs/security-model.md +6 -4
  24. package/docs/ses.md +116 -0
  25. package/docs/tracking.md +102 -0
  26. package/docs/unsubscribe.md +124 -0
  27. package/docs/welcome.md +72 -0
  28. package/migrations/0004_last_error.sql +2 -0
  29. package/migrations/0005_lists.sql +41 -0
  30. package/migrations/0006_broadcast.sql +154 -0
  31. package/migrations/0007_unsubscribe.sql +12 -0
  32. package/migrations/0008_tracking.sql +5 -0
  33. package/migrations/0009_welcome.sql +17 -0
  34. package/package.json +21 -3
  35. package/src/alert.ts +123 -0
  36. package/src/aws-sigv4.ts +100 -0
  37. package/src/broadcast/audience.ts +96 -0
  38. package/src/broadcast/campaigns.ts +352 -0
  39. package/src/broadcast/config.ts +136 -0
  40. package/src/broadcast/dispatch.ts +779 -0
  41. package/src/broadcast/events.ts +110 -0
  42. package/src/broadcast/explain.ts +73 -0
  43. package/src/broadcast/freeze.ts +93 -0
  44. package/src/broadcast/index.ts +21 -0
  45. package/src/broadcast/postman.ts +229 -0
  46. package/src/broadcast/reconcile.ts +120 -0
  47. package/src/broadcast/routes.ts +181 -0
  48. package/src/broadcast/ses.ts +181 -0
  49. package/src/broadcast/stats.ts +59 -0
  50. package/src/broadcast/status.ts +60 -0
  51. package/src/broadcast/test-send.ts +88 -0
  52. package/src/broadcast/warmup.ts +150 -0
  53. package/src/broadcast/worker.ts +218 -0
  54. package/src/cf-events.ts +4 -3
  55. package/src/cli/args.ts +27 -0
  56. package/src/cli/errors.ts +39 -0
  57. package/src/cli/main.ts +515 -0
  58. package/src/compose/clicks.ts +45 -0
  59. package/src/compose/compose.ts +297 -0
  60. package/src/compose/index.ts +8 -0
  61. package/src/compose/markdown.ts +1173 -0
  62. package/src/compose/personalize.ts +130 -0
  63. package/src/compose/preflight.ts +250 -0
  64. package/src/compose/preview.ts +58 -0
  65. package/src/compose/render.ts +158 -0
  66. package/src/compose/template.ts +197 -0
  67. package/src/core.ts +45 -2
  68. package/src/export.ts +184 -0
  69. package/src/feedback.ts +128 -0
  70. package/src/http.ts +17 -0
  71. package/src/index.ts +146 -32
  72. package/src/list-routes.ts +55 -0
  73. package/src/lists.ts +381 -0
  74. package/src/ses-events.ts +426 -0
  75. package/src/track.ts +409 -0
  76. package/src/unsub-wiring.ts +64 -0
  77. package/src/unsub.ts +499 -0
  78. package/src/webhook.ts +5 -3
  79. package/src/welcome.ts +257 -0
  80. package/wrangler.example.jsonc +16 -2
@@ -0,0 +1,118 @@
1
+ // 信件樣板:把「正文」包進頁首/頁尾,變成完整信件。
2
+ // 樣板是設定,不是程式:引擎只給一個通用的樣板工廠 createTemplate(),品牌樣板(名稱、頁尾、地址、文案)放私有設定。
3
+ // 表格排版+內嵌 CSS(Outlook 看得到)、深色模式用 class 覆寫(不把底色反白)。
4
+ export const DEFAULT_THEME = {
5
+ font: "-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang TC','Noto Sans TC','Microsoft JhengHei',Helvetica,Arial,sans-serif",
6
+ text: '#222222',
7
+ muted: '#6b6b6b',
8
+ link: '#1a56c4',
9
+ bg: '#f3f3f3',
10
+ card: '#ffffff',
11
+ border: '#dddddd',
12
+ accent: '#333333',
13
+ codeBg: '#f5f5f5',
14
+ width: 600,
15
+ dark: { bg: '#111111', card: '#1c1c1c', text: '#e8e8e8', muted: '#a0a0a0', link: '#8ab4f8', border: '#3a3a3a', codeBg: '#262626' },
16
+ };
17
+ export const DEFAULT_LABELS = {
18
+ viewInBrowser: 'View in browser',
19
+ unsubscribe: 'Unsubscribe',
20
+ sentTo: 'This email was sent to {email}',
21
+ embedCard: 'This content is best viewed on the website →',
22
+ image: (alt) => (alt ? `[Image: ${alt}]` : '[Image]'),
23
+ };
24
+ export function escapeHtml(s) {
25
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/\uE000/g, '&#123;');
26
+ }
27
+ function mergeTheme(t) {
28
+ return { ...DEFAULT_THEME, ...t, dark: { ...DEFAULT_THEME.dark, ...(t?.dark ?? {}) } };
29
+ }
30
+ export function createTemplate(cfg) {
31
+ const theme = mergeTheme(cfg.theme);
32
+ const labels = { ...DEFAULT_LABELS, ...cfg.labels };
33
+ const lang = cfg.lang ?? 'en';
34
+ const w = theme.width;
35
+ const d = theme.dark;
36
+ const footer = cfg.footerLines ?? [];
37
+ const css = `
38
+ body,table,td,a{-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}
39
+ table{border-collapse:collapse;mso-table-lspace:0;mso-table-rspace:0}
40
+ img{border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic}
41
+ a{word-break:break-word}
42
+ @media only screen and (max-width:${w + 20}px){.mr-wrap{width:100%!important}.mr-pad{padding-left:16px!important;padding-right:16px!important}}
43
+ @media (prefers-color-scheme:dark){
44
+ .mr-bg{background:${d.bg}!important}
45
+ .mr-card{background:${d.card}!important}
46
+ .mr-text{color:${d.text}!important}
47
+ .mr-muted{color:${d.muted}!important}
48
+ .mr-link{color:${d.link}!important}
49
+ .mr-bd{border-color:${d.border}!important}
50
+ .mr-code{background:${d.codeBg}!important}
51
+ }`;
52
+ const renderHtml = (p) => {
53
+ const pre = escapeHtml(p.preheader);
54
+ const header = cfg.logoUrl
55
+ ? `<img src="${escapeHtml(cfg.logoUrl)}" alt="${escapeHtml(cfg.brandName)}" height="36" style="display:block;border:0;height:36px;width:auto">`
56
+ : `<span class="mr-text" style="font-size:20px;font-weight:700;color:${theme.accent}">${escapeHtml(cfg.brandName)}</span>`;
57
+ const tagline = cfg.tagline ? `<div class="mr-muted" style="font-size:13px;color:${theme.muted};margin-top:2px">${escapeHtml(cfg.tagline)}</div>` : '';
58
+ const greeting = cfg.greeting ? `{{#name}}<p class="mr-text" style="margin:0 0 18px;font-size:16px;line-height:1.8;color:${theme.text}">${escapeHtml(cfg.greeting)}</p>{{/name}}` : '';
59
+ const footLines = footer
60
+ .map((l) => typeof l === 'string'
61
+ ? `<p class="mr-muted" style="margin:0 0 6px;font-size:12px;line-height:1.7;color:${theme.muted}">${escapeHtml(l)}</p>`
62
+ : `<p style="margin:0 0 6px;font-size:12px;line-height:1.7"><a class="mr-link" href="${escapeHtml(l.href)}" style="color:${theme.link}">${escapeHtml(l.text)}</a></p>`)
63
+ .join('');
64
+ const sentTo = labels.sentTo.replace('{email}', '{{email}}');
65
+ const lead = cfg.unsubscribeLead ? `${escapeHtml(cfg.unsubscribeLead)} ` : '';
66
+ return `<!doctype html>
67
+ <html lang="${escapeHtml(lang)}" xmlns="http://www.w3.org/1999/xhtml">
68
+ <head>
69
+ <meta charset="utf-8">
70
+ <meta name="viewport" content="width=device-width,initial-scale=1">
71
+ <meta name="color-scheme" content="light dark">
72
+ <meta name="supported-color-schemes" content="light dark">
73
+ <title>${escapeHtml(p.subject)}</title>
74
+ <style>${css}</style>
75
+ </head>
76
+ <body class="mr-bg" style="margin:0;padding:0;background:${theme.bg};word-break:break-word">
77
+ <div style="display:none;max-height:0;overflow:hidden;opacity:0;mso-hide:all;font-size:1px;line-height:1px;color:${theme.bg}">${pre}${'&#8204;&nbsp;'.repeat(40)}</div>
78
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="mr-bg" style="background:${theme.bg}"><tr><td align="center" style="padding:20px 10px">
79
+ <!--[if mso]><table role="presentation" width="${w}" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
80
+ <table role="presentation" class="mr-wrap" width="${w}" cellpadding="0" cellspacing="0" border="0" style="width:${w}px;max-width:100%">
81
+ <tr><td class="mr-pad" style="padding:0 4px 12px;font-family:${theme.font}">
82
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="font-family:${theme.font}">${header}${tagline}</td>
83
+ <td align="right" style="font-family:${theme.font};font-size:12px"><a class="mr-link" href="{{web_url}}" style="color:${theme.link}">${escapeHtml(labels.viewInBrowser)}</a></td></tr></table>
84
+ </td></tr>
85
+ <tr><td class="mr-card mr-bd mr-pad" style="background:${theme.card};border:1px solid ${theme.border};padding:28px 32px;font-family:${theme.font};color:${theme.text}">
86
+ ${greeting}${p.bodyHtml}
87
+ </td></tr>
88
+ <tr><td class="mr-pad" style="padding:16px 4px;font-family:${theme.font}">
89
+ ${cfg.footerHtml ?? ''}${footLines}<p class="mr-muted" style="margin:0 0 6px;font-size:12px;line-height:1.7;color:${theme.muted}">${escapeHtml(cfg.postalAddress)}</p>
90
+ {{#email}}<p class="mr-muted" style="margin:0 0 6px;font-size:12px;line-height:1.7;color:${theme.muted}">${escapeHtml(sentTo)}</p>{{/email}}
91
+ <p class="mr-muted" style="margin:0;font-size:12px;line-height:1.7;color:${theme.muted}">${lead}<a class="mr-link" href="{{unsubscribe_url}}" style="color:${theme.link}">${escapeHtml(labels.unsubscribe)}</a></p>
92
+ ${p.pixelUrl ? `<img src="${escapeHtml(p.pixelUrl)}" width="1" height="1" alt="" style="display:block;border:0;width:1px;height:1px">` : ''}
93
+ </td></tr>
94
+ </table>
95
+ <!--[if mso]></td></tr></table><![endif]-->
96
+ </td></tr></table>
97
+ </body>
98
+ </html>`;
99
+ };
100
+ const renderText = (p) => {
101
+ const lines = [];
102
+ lines.push(cfg.brandName + (cfg.tagline ? ` — ${cfg.tagline}` : ''));
103
+ lines.push(`${labels.viewInBrowser}: {{web_url}}`);
104
+ lines.push('');
105
+ if (cfg.greeting)
106
+ lines.push(`{{#name}}${cfg.greeting}{{/name}}`, '');
107
+ lines.push(p.bodyText.trim(), '', '--');
108
+ if (cfg.footerText)
109
+ lines.push(cfg.footerText.trim());
110
+ for (const l of footer)
111
+ lines.push(typeof l === 'string' ? l : `${l.text}: ${l.href}`);
112
+ lines.push(cfg.postalAddress);
113
+ lines.push(`{{#email}}${labels.sentTo.replace('{email}', '{{email}}')}{{/email}}`);
114
+ lines.push(`${cfg.unsubscribeLead ? `${cfg.unsubscribeLead} ` : ''}${labels.unsubscribe}: {{unsubscribe_url}}`);
115
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n{{#email}}{{\/email}}/g, '') + '\n';
116
+ };
117
+ return { theme, labels, postalAddress: cfg.postalAddress, renderHtml, renderText };
118
+ }
@@ -0,0 +1,199 @@
1
+ # Newsletter broadcasting (preview)
2
+
3
+ Sends one newsletter issue to a frozen list, in waves, at a steady pace, with automatic brakes. Code: `src/broadcast/`
4
+ (exported as `@joelincc/mailroom/broadcast`), tables: migration `0006_broadcast.sql`. Status: **preview** — built-in newsletter
5
+ postmans: Amazon SES (see [docs/ses.md](ses.md)) and a fake one for development; another provider plugs in through the
6
+ `Postman` interface.
7
+
8
+ Everything below uses example values (`mail.example.com`, a 2,000-person list). Your real numbers belong in your private config.
9
+
10
+ ## One issue, start to finish
11
+
12
+ ```
13
+ draft ──approve──▶ approved ──schedule──▶ scheduled ──(cron, at time)──▶ sending ⇄ paused ──▶ done
14
+ ▲ │ ▲ │ │
15
+ └── content edited ─┘ └──── unschedule ────┘ cancelled ◀── (draft / approved / scheduled / paused)
16
+ ```
17
+
18
+ 1. **Draft** — `PUT /v1/campaigns/{id}` with subject, sender (must be on `MARKETING_DOMAIN`), HTML, text, the web version
19
+ URL (`webUrl`, required before scheduling), extra headers (only `List-Unsubscribe`, `List-Unsubscribe-Post`, `List-Id`
20
+ and `X-…`) and the audience. Editing a draft,
21
+ an approved or a scheduled issue sends it back to `draft` and clears approval and the pre-send check.
22
+ After `sending` the content is locked.
23
+ 2. **Pre-send check** — run the compose module's `preflight()` (it needs the network to check links), then
24
+ `POST /v1/campaigns/{id}/preflight` with the result. It is tied to a hash of the content; any edit invalidates it.
25
+ 3. **Approve** — `POST /v1/campaigns/{id}/approve { note }`. The note is required ("who said yes, when, where").
26
+ 4. **Schedule** — `POST /v1/campaigns/{id}/schedule { at }`. Refused unless the approval and a passing pre-send check
27
+ match the current content.
28
+ 5. **Start** (cron, once `scheduled_at` has passed) — the issue moves to `sending` and the list is **frozen** into
29
+ `campaign_recipients`: every member who is `subscribed` at that moment. Members on the global suppression list are
30
+ written as `skipped/suppressed`; members outside this issue's audience as `skipped/warmup`. People who subscribe later
31
+ are not part of this issue. People who unsubscribe or get suppressed later are checked again right before their mail
32
+ is handed over, and skipped (`skipped/unsubscribed`, `skipped/suppressed`).
33
+ 6. **Waves and pacing** (cron, every minute) — recipients are released into the `mailroom-broadcast` queue, wave by wave,
34
+ in audience order. Per minute the engine releases the smallest of:
35
+ - provider speed: `perSecond × 60 × rateFactor` (default 0.8), halved for one minute after a throttling reply;
36
+ - what is left today: your own daily cap (`maxPerDay`, local day, default UTC+8) and the provider's 24-hour quota,
37
+ minus mails already handed over;
38
+ - the pace: `ceil(people to send ÷ paceMinutes)` (default 150 → a 2,000-person issue takes about 2½ hours);
39
+ - what is left in the current wave.
40
+ A new wave starts no earlier than `waveGapMinutes` (60) after the previous one started and `waveGateWaitMinutes` (30)
41
+ after its last mail, and only if the previous wave's hard-bounce rate is below `waveGateBounceRate` (2%).
42
+ 7. **Hand-over** (queue consumer, one at a time, spaced to the provider's per-second limit) — each recipient is one ledger
43
+ row in `messages` (`stream='marketing'`, `tier='marketing'`, key `c:{issue}:{contact}`).
44
+ 8. **Reconcile** — when nobody is left to send, the engine checks
45
+ `frozen = sent + skipped (per reason) + failed + uncertain + pending`, that every sent recipient has a `sent` ledger
46
+ row and the ledger has no extra ones, and that provider events show no second mail to anyone. Only then is the issue
47
+ `done`. Any mismatch pauses it (`reconcile_mismatch:…`) for a person to look at. Events that simply have not arrived
48
+ yet (deliveries, late complaints) are listed as `awaiting`, not as a mismatch. Run `POST /v1/campaigns/{id}/reconcile`
49
+ again later (for example after 72 hours) for the final numbers.
50
+
51
+ ## Never twice
52
+
53
+ - One idempotency key per person per issue. A ledger row that is already `sent` only ever answers `duplicate`.
54
+ - The ledger row is created **before** the mail is handed to the provider. Unlike transactional mail, a newsletter row
55
+ stuck in `sending` is never re-claimed: if the Worker died mid-hand-over, or the provider threw (we cannot know whether
56
+ it accepted the mail), that recipient becomes `uncertain`. A provider event for that mail settles it as sent; otherwise
57
+ a person decides with `POST /v1/campaigns/{id}/resolve { contact, as: 'sent' | 'failed', note }`. An issue with
58
+ `uncertain` recipients cannot reach `done`.
59
+ - Queue redelivery, the same person released twice, or a stuck release re-sent after `stuckMinutes` (10): the consumer
60
+ only hands over recipients whose state is `enqueued`, and the ledger key catches the rest.
61
+ - Nothing is handed over while the issue is not `sending` or the sender domain is on hold.
62
+
63
+ ## Brakes
64
+
65
+ | Level | Condition (defaults) | What happens |
66
+ |---|---|---|
67
+ | Wave gate | previous wave's hard bounces ≥ 2% | issue paused before the next wave |
68
+ | Issue brake | ≥ 200 sent in this issue and hard bounces ≥ 4%; or ≥ 3 complaints and ≥ 0.1% (no sent minimum: the 3 complaints are the floor) | issue paused |
69
+ | Provider | provider reports the account as not `HEALTHY`, or answers "account paused" | sending issues paused, scheduled issues do not start, queued mails are not handed over |
70
+ | Queue stalled | work handed to the queue but no result for 30 minutes | issue paused |
71
+ | Domain stop | among newsletter mails sent in the last 30 days (and since the last release): ≥ 200 sent and hard bounces ≥ 4% or complaints ≥ 0.08% | **all** newsletters on the domain stop; scheduled issues do not start |
72
+ | Warm-up gate | see below | the ladder does not move up; after 2 failures in a row it locks |
73
+
74
+ Every brake waits for a person: `POST /v1/campaigns/{id}/resume { note }` (refused while the domain is on hold) and
75
+ `POST /v1/broadcast/release-hold { note }`. After a resume, **only the brake that paused the issue** (bounce rate,
76
+ complaint rate or wave gate) restarts counting from the resume; every other rate keeps counting the whole issue. After a
77
+ release, the domain rate counts only mails sent after the release. An issue that finishes with failed recipients is
78
+ `done` (they were tried `maxAttempts` times) and raises a yellow alert. Newsletter ledger rows are kept at least 400
79
+ days even if `LEDGER_RETENTION_DAYS` is shorter (de-duplication and the domain rate depend on them). Transactional mail (the "must
80
+ deliver" desk) is not affected by any of this: it uses another sender domain and its own providers.
81
+
82
+ Alerts (started, paused, finished, blocked) go to the `alert` hook you pass in; the engine does not send them itself.
83
+
84
+ ## Warm-up ladder
85
+
86
+ ```http
87
+ PUT /v1/warmup/ramp/1 { "waves": [["core"], ["steady", "returning"], ["new"]] }
88
+ PUT /v1/warmup/ramp/2 { "waves": [["core"], ["steady", "returning"], ["new"], ["quiet"]] }
89
+ PUT /v1/warmup/ramp/3 { "waves": [["core"], ["steady", "returning"], ["new"], ["quiet"], ["*"]], "maxCount": 1800 }
90
+ ```
91
+
92
+ An issue with `"audience": { "plan": "ramp" }` is sent to the **current step** (the highest released step; step 1 needs
93
+ no release). Segment names come from `list_members.segment`; `"*"` means everyone not matched earlier (it must be last).
94
+ `maxCount` caps the step; the people beyond it (last waves first) are `skipped/warmup`.
95
+
96
+ After an issue has been `done` for 72 hours:
97
+
98
+ ```http
99
+ POST /v1/warmup/ramp/evaluate { "campaign": "weekly-12", "baselineOpenRate": 0.52 }
100
+ ```
101
+
102
+ `baselineOpenRate` is **the same people's** average open rate before the switch (computed by your analytics, not by the
103
+ engine; comparing with the whole list would make a step that only mails the most engaged readers look better than it
104
+ is). Pass: hard bounces ≤ 2%, complaints ≤ 0.1%, open rate not more than 5 points below the baseline, and the issue
105
+ reconciled cleanly → the next step is released. Fail → the next issue stays on the same step. Two failures in a row lock
106
+ the ladder: scheduled issues on it do not start until `POST /v1/warmup/ramp/unblock { note }`. Each issue is evaluated
107
+ once. Open rate = people with an open event ÷ (sent − hard bounces).
108
+
109
+ ## Status
110
+
111
+ - `GET /v1/campaigns/{id}` — state, approval, pre-send check, recipients by state/reason/wave, rates (no content, no addresses).
112
+ - `GET /v1/campaigns/{id}/audience` — who would receive it if it started now: per wave and segment, and how many are skipped (suppressed, not in this warm-up step). Read-only.
113
+ - `GET /v1/campaigns/{id}/preview` — the issue filled in for a sample reader (and a reader without a name), the pre-send check detail. `POST` does the same and marks this exact content as previewed; **approval over HTTP is refused (`preview_required`) until it has been**, and any edit invalidates it.
114
+ - `POST /v1/campaigns/{id}/test { to: [...], subjectPrefix? }` — real postman, real headers, one mail per address, **only to addresses listed in `TEST_RECIPIENTS`** (at most 10 per call), subject prefixed. Not in the frozen list, not in the ledger, not counted anywhere. The provider's events for a test mail (tag `contact=test`) are recorded but never suppress an address or unsubscribe anyone, so a test mailbox that bounces or marks the mail as spam changes nothing on the list; still, send test mail only to mailboxes you own and have confirmed receive mail. Refused while the domain is on hold. A postman error that leaves the outcome unknown is reported as `unknown_outcome` and never retried.
115
+ - The status answer includes `pauseExplain` for a paused issue: the code, a one-line summary, the numerator and denominator at the time, the threshold, whether the domain hold must be released first, whether a plain resume makes sense, and the suggested next step.
116
+ - `GET /v1/throttle` — today's cap and usage, provider speed and health, domain hold, issues in flight.
117
+
118
+ ## Postmen
119
+
120
+ ```ts
121
+ interface Postman {
122
+ name: string;
123
+ send(mail: PostmanMail): Promise<{ ok: true; providerId: string } | { ok: false; kind: 'temporary' | 'permanent' | 'throttled' | 'account_paused'; error: string }>;
124
+ limits(): Promise<{ perSecond: number; perDay: number; sentLast24h?: number; enforcement: string }>;
125
+ }
126
+ ```
127
+
128
+ Return a failure **only when you are sure the provider did not accept the mail**; throw when you do not know. One postman
129
+ per deployment; switching is a config change and a deploy, never automatic.
130
+
131
+ Provider feedback enters through one function, whatever the provider:
132
+
133
+ ```ts
134
+ await ingestEvent(db, { provider, providerEventId, providerMessageId, type, subtype, at, email, campaign, contact }, { feedback })
135
+ ```
136
+
137
+ `type` is one of `send`, `delivery`, `bounce` (`subtype` `Permanent…` / `Transient` / `Undetermined`; a transient
138
+ bounce may carry `cause: "mailbox"` or `"content"` — only `mailbox` counts toward the transient-bounce streak), `complaint`,
139
+ `reject`, `delay`, `open`, `click`, `unsubscribe`. Re-deliveries of the same `providerEventId` are ignored. Without a
140
+ `feedback` hook, bounces, complaints and deliveries go through `applyFeedback` (see [docs/unsubscribe.md](unsubscribe.md)).
141
+ An `unsubscribe` event that names an issue unsubscribes the person from that issue's list.
142
+
143
+ ### The fake postman
144
+
145
+ `FakePostman` sends nothing. Addresses whose local part is `success`, `bounce`, `complaint`, `ooto` or
146
+ `suppressionlist` (optionally `+tag`) behave like a provider's mailbox simulator and produce the matching events after a
147
+ short delay. `rules` can make any address answer `temporary`, `permanent`, `throttle`, `account_paused`, `delay`,
148
+ `daily_quota`, `soft_bounce` (a mailbox-full transient bounce) or `crash` (throw), optionally only the first `times` calls. In the Worker, set
149
+ `NEWSLETTER_POSTMAN = "fake"`; its events come back through the broadcast queue.
150
+
151
+ ## Worker setup
152
+
153
+ ```jsonc
154
+ "vars": {
155
+ "MARKETING_DOMAIN": "mail.example.com",
156
+ "NEWSLETTER_POSTMAN": "fake",
157
+ "NEWSLETTER_MAX_PER_DAY": 3000,
158
+ "BROADCAST_CONFIG": { "paceMinutes": 150 }
159
+ },
160
+ "queues": {
161
+ "producers": [{ "binding": "BROADCAST", "queue": "mailroom-broadcast" }],
162
+ "consumers": [{ "queue": "mailroom-broadcast", "max_batch_size": 10, "max_concurrency": 1, "max_retries": 10, "dead_letter_queue": "mailroom-broadcast-dlq" }]
163
+ },
164
+ "triggers": { "crons": ["* * * * *"] }
165
+ ```
166
+
167
+ Keep `max_concurrency: 1`: the per-second spacing is applied inside one consumer. Keep a dead-letter queue: send
168
+ messages lost there are re-released after `stuckMinutes`, but provider events (bounces, complaints) are not, and the
169
+ brakes would undercount them. Do not give an HTTP client the same site name as `BROADCAST_CONFIG.site`.
170
+
171
+ Personalisation per recipient goes through `render(campaign, recipient)`. The Worker default fills the compose
172
+ placeholders (`{{name}}`, `{{email}}`, `{{web_url}}`, `{{unsubscribe_url}}`, `{{unsubscribe_mailto}}`, also inside the
173
+ headers) with a signed unsubscribe token per recipient (`UNSUB_TOKEN_SECRET`, `UNSUB_BASE_URL`, optional `UNSUB_MAILTO`;
174
+ see [docs/unsubscribe.md](unsubscribe.md)). Without them every issue pauses with `render_error` instead of sending mail
175
+ without an unsubscribe link. Headers produced by a custom `render` are checked against the same allowlist.
176
+
177
+ ### All settings (`BROADCAST_CONFIG`)
178
+
179
+ | Key | Default | Meaning |
180
+ |---|---|---|
181
+ | `site` | `newsletter` | ledger `site` for newsletter rows |
182
+ | `maxPerDay` | 3000 | your own daily cap (also `NEWSLETTER_MAX_PER_DAY`) |
183
+ | `rateFactor` | 0.8 | share of the provider's speed to use |
184
+ | `paceMinutes` | 150 | spread one issue over this many minutes |
185
+ | `waveGapMinutes` / `waveGateWaitMinutes` / `waveGateBounceRate` | 60 / 30 / 0.02 | wave timing and gate |
186
+ | `brakeMinSent` / `brakeHardBounceRate` / `brakeComplaintCount` / `brakeComplaintRate` | 200 / 0.04 / 3 / 0.001 | issue brake |
187
+ | `domainWindowDays` / `domainMinSent` / `domainBounceRate` / `domainComplaintRate` | 30 / 200 / 0.04 / 0.0008 | domain stop |
188
+ | `domainMinComplaints` | 1 (max 10) | complaints in the window needed (besides the rate) to stop the domain. 1 = no extra floor: with a small sample a single complaint can cross 0.08% (1 of 220 is 0.45%). Decide before the first real send whether to raise it |
189
+ | `waveGateMinSent` | 1 (max 100) | mails the previous wave must have sent before its bounce rate is judged. With 30-person waves one bounce is 3.3%, over the 2% gate |
190
+ | `startGraceMinutes` | 360 (max 2880) | a scheduled issue more than this many minutes past its time (provider unhealthy or unreachable, domain on hold, Worker down) goes back to **`draft`** (approval and preview are cleared) with a yellow alert `start_stale` instead of starting late: look at it again, approve it again, schedule it again. An issue that did start but handed **no mail at all** to the provider for this long is paused (`brake:start_stale`) |
191
+ | `stuckMinutes` / `stallMinutes` | 10 / 30 | re-release / queue-stalled brake |
192
+ | `maxAttempts` / `throttleRetrySeconds` | 3 / 30 | temporary failures / throttling |
193
+ | `utcOffsetHours` | 8 | which local day the daily cap uses |
194
+ | `limitsRefreshMinutes` | 60 | how often provider limits and health are read |
195
+ | `gateWaitHours` / `gateBounceRate` / `gateComplaintRate` / `gateOpenDrop` / `gateMaxFails` | 72 / 0.02 / 0.001 / 0.05 / 2 | warm-up gate |
196
+
197
+ Invalid values fall back to the default; they never switch a check off. The three settings above also have a ceiling (a floor set absurdly high would switch the brake off): a larger value is ignored and the default is used, with a line in the log.
198
+
199
+ When the provider's limits cannot be read (bad key, API down) the engine does **not** start scheduled issues (`start_blocked_provider_unreachable`): they stay `scheduled` until the limits can be read again, or until `startGraceMinutes` passes and they go back to `draft`.
@@ -0,0 +1,156 @@
1
+ # Composing an issue
2
+
3
+ This is the "compose" side of the newsletter desk: it turns one markdown source into an email — HTML and plain text — and
4
+ refuses to let a broken issue be scheduled. It only **produces** content. Click redirects, open pixels and event logging
5
+ are separate parts; this module just emits the placeholders they will fill in.
6
+
7
+ Import from the `./compose` entry point. It has no Cloudflare-specific imports, so it runs in Node, in a Worker and in tests:
8
+
9
+ ```ts
10
+ import { compose, createTemplate, preflight, personalize, buildPreview } from '@joelincc/mailroom/compose';
11
+ ```
12
+
13
+ ## What goes in, what comes out
14
+
15
+ ```ts
16
+ const template = createTemplate({
17
+ brandName: 'Example Weekly',
18
+ greeting: 'Hi {{name}},', // omitted for readers without a name
19
+ footerLines: ['You get this because you subscribed.'],
20
+ postalAddress: '1 Example Street, Sample City 00000',
21
+ });
22
+
23
+ const issue = compose({
24
+ source, // markdown, optional frontmatter (title, description)
25
+ template,
26
+ issue: '2026-01-05', // becomes utm_campaign
27
+ trackBase: 'https://t.example.com', // omit to skip link rewriting and the open pixel
28
+ siteBase: 'https://example.com', // resolves relative links
29
+ assetBase: 'https://cdn.example.com', // resolves relative image URLs
30
+ });
31
+ ```
32
+
33
+ `compose()` returns `subject`, `preheader`, `html`, `text`, `headers` (the two unsubscribe headers), `links`
34
+ (every rewritten link: index, final URL, original URL, text), `images`, `problems` and `htmlBytes`.
35
+ The HTML is stored once per issue — it is never rendered per recipient until send time.
36
+
37
+ ### Markdown that works
38
+
39
+ Headings, paragraphs (a single newline becomes a line break), bold, italic, inline code, links, bare URLs, images, lists (nested, ordered, with their start number), block quotes, tables (with alignment), fenced and indented code, rules.
40
+ Also understood: `<https://…>` autolinks, `<a href="…">text</a>` (only the `href` and the text are kept — every other
41
+ attribute is dropped and the link goes through the normal checks and tracking), and paired `<b>` / `<strong>` / `<i>` / `<em>`.
42
+ HTML character references (`&nbsp;`, `&amp;`, `&#39;` …) are decoded once and escaped once.
43
+
44
+ A bare `http://` / `https://` URL is cut where the site cuts it: it runs to the next whitespace (a full-width space
45
+ or a no-break space counts) or `<`, and ASCII punctuation at the very end (`.` `,` `:` `;` `!` `?` `'` `*` `_` `~` `]`, an
46
+ unbalanced `)`) is not part of it. (One known difference: the rare ASCII characters `"` `{` `}` `|` `^` `\` end the link in
47
+ the email but not on the site; the text after them stays visible.) Everything else belongs to the link, including non-ASCII characters: a Japanese or Chinese path
48
+ (`https://ja.wikipedia.org/wiki/写真`), full-width punctuation, and words glued to the URL without a space
49
+ (`詳見https://example.com/a這篇文章`, `https://example.com/p/1看完再說`) — on the site all of that is link text, so it is link
50
+ text in the email too, and the destination carries the non-ASCII characters as `%XX`, as on the site. Such a link usually
51
+ points to a page that does not exist; the pre-send link check reports it (`link_broken`), and a URL whose last character is
52
+ full-width punctuation (`(https://example.com/a)`, `https://example.com/a。`) gets a `url_glued_text` warning. The fix in
53
+ the article is a space after the URL. The link text of `[text](url)` is never autolinked again (the site does not put a
54
+ link inside a link).
55
+
56
+ In the plain-text version a link is printed as `text (url)`, where `url` is the tracking URL (or the final URL without
57
+ tracking). The text is left out only when it adds nothing: when it is empty, when it is the printed URL itself, or when it
58
+ is a URL contained in the printed URL (an untracked link, which only gains `utm_*`). So a bare URL prints as
59
+ `https://example.com/a (https://t.example.com/c/…)`: the reader sees what the site shows, glued words included, and the
60
+ mail never silently drops text.
61
+
62
+ Block structure follows CommonMark (with GFM tables) for everything the email supports: the parser first decides which lines form which block — fenced or indented code, HTML comment block, paragraph, list item, quote, table, heading (ATX or setext) — and only then parses the inline content of each block. HTML comments are handled **in that same single pass**; there is no separate comment-stripping step that could disagree with the parser about where code is. A line that starts with `<!--` (indented at most three spaces) is a comment block that ends on the line containing `-->` (blank lines in between included); it can interrupt a paragraph, a list item or a quote, exactly as on a CommonMark site, and any text after `-->` on its last line is kept. Inside a paragraph, heading or table cell, inline code and comments are recognised in one left-to-right scan, so whichever starts first wins: `` `<!--` `` is code, `<!-- a ` b -->` is a comment. Inline code never crosses a block boundary, so a multi-line code span that meets a line starting with `<!--` ends there and that line is a comment (CommonMark behaviour). Code fences (``` and ~~~, longer fences, fences in lists and quotes) and indented code keep their `<!--` and `-->` text verbatim. Lazy continuation lines join a quote or list item only when its last block is an open paragraph.
63
+
64
+ Two safety nets run after that. First, a reconciliation: every `<!--` in the source must be accounted for as either a hidden comment or text inside code; if one is left over (a backslash-escaped `\<!--`, a `<!--` in image alt text or a URL), the issue gets a `comment_leaked` error. Second, the final email HTML and plain text are rendered again with code contents masked; if anything outside code still contains `<!--` (for example from `&lt;!--`), that is also a `comment_leaked` error. A bare URL followed directly by a backtick, and an unfinished `<tag` after a comment on the same line, are errors too. Comments containing `--!>` (browsers end a comment there early) are an error (`comment_ambiguous`). Constructs that a website would pass through as raw HTML or hide in other ways are blocked with an error rather than imitated: a line holding a single tag such as `<em>`, `<br>` or `<a href="…">` on its own (an HTML block — inline tags inside a paragraph are fine), `<?…>`, `<!X…>` and `<![CDATA[…]]>` (`unsupported_html`), and link reference definitions `[name]: url` (`unsupported_syntax`), and footnote definitions the site would not show: a definition is kept only when it is a one-line paragraph line starting at column 0 (consecutive definition lines are fine), its label has no spaces and is defined once (labels are case-insensitive), its content is plain text (not a list, quote, heading, code, HTML or another definition), no indented continuation follows it, and a real footnote reference `[^x]` appears in the text (references inside code, comments, URLs, escapes, entities or the definitions themselves do not count, nor does one written right after a bare URL or email address, which the site absorbs into the link); anything else is an error, and so is a footnote reference inside link text. A link inside the text of another link is an error too (the site shows the outer brackets and URL literally; the mail would lose them). A footnote reference that the site absorbs into a preceding bare URL — also when brackets or emphasis wrap the URL, as in `(www.example.com**[^1]***)` or `**https://example.com**[^1]` — is itself an error (`unsupported_syntax`, fix: put a space before the reference), even if the same footnote is referenced properly elsewhere. Every URL in the run of non-space characters before the reference is checked, not only the first; a URL counts as closed only when it is the destination of something that really is a link on the site (`[text](url)`, `![alt](url)`, `<url>`, `<a href>`) — when link text contains another link, the site does not treat the outer brackets as a link, and its `](url)` is a bare URL. A tab in the structure at the start of a line (indentation, after `>`, after a list marker) is an error (`unsupported_syntax`): how a site lays it out depends on every enclosing container, so it cannot be predicted reliably; use spaces. Tabs inside fenced code (Go, Makefiles), also in lists and quotes, are fine and kept as they are; in indented code only the four columns of indentation must be spaces. Like the site's renderer, an ordered list that does not start at 1, or an empty list item, is not recognised right after an indented code block or as the first block of a list item or quote that interrupts a paragraph; that line becomes a paragraph. A table needs a delimiter row containing `|` that is indented less than four spaces; a list item, heading or quote line never becomes a table header. These rules are checked by `tests/compose-fuzz.test.ts`, which generates random combinations of comments, code and blocks and compares the output with a CommonMark reference renderer (a dev dependency): nothing hidden on the site may appear in the email, nothing visible may disappear, and `<!--` / `-->` inside code stay verbatim — unless the issue is blocked with an error. CI runs a small sample; run `MAILROOM_FUZZ_N=24000 npm test` for a long run. A bare URL that has `[`, `*` or a backtick glued to it in the same word (or an HTML entity right before it), `![^x]`, and a footnote reference after nested brackets are errors as well: the site absorbs such runs into one link. Baseline at the time of writing (keep it current when the parser changes): the built-in generator gives zero violations on 4 × 24,000 samples (about 40 % of them blocked with an error). Several additional adversarial generators written during review (nested containers with tabs, footnotes, inline-symbol soup) were run for about 350,000 more samples; all were clean except an inline-symbol generator that glues bare URLs, emphasis, links, footnote references and code without spaces. On 40,000 such samples it used to leave 213 cases (200 where words glued to a bare URL vanished from the plain-text email, 8 where code was split differently from the site, 5 where a footnote hidden on the site was printed in the email, inside runs like `(www.example.com**[^1]***)`); with the bare-URL and footnote rules above it leaves none: the 200 are now handled correctly (178) or blocked (22), and the other 13 are blocked (about 65 % of these samples are blocked in all). The other review generators were re-run for 320,000 samples with the same results as before. One known layout difference: after an HTML block inside a list item, a following under-indented line may be split into code differently from the site (content stays visible).
65
+
66
+ A line that holds only `<div>`, `<div lang="…">` or `</div>` (a language wrapper) is dropped and its content converted normally; a `div` with any other attribute (`hidden`, `style`, `class` …) is an error, so text meant to be hidden can never reach readers. Angle-bracket words that only look like tags (`<Research.example>`, `</p/100110>`) are reported with a hint to rewrite them or put them in backticks.
67
+
68
+ Everything else is **not** passed through: an unknown tag or an unknown block syntax (for example `:::note`) is recorded
69
+ as an `error` problem and the pre-send check fails, so nothing half-converted can be sent. So are an unclosed `<!--` comment
70
+ (`unclosed_comment`, wherever it starts — on a website it hides everything after it) and an unclosed code fence (`unclosed_fence`, which turns the rest of the container into code); the text after them is kept in the output.
71
+ The exception is content that cannot work in an email — `<iframe>`, `<video>`, `<audio>`, `<embed>`, `<object>`, `<canvas>`
72
+ and a ```` ```mermaid ```` fence: it becomes a "view on the website" link card and an `info` problem.
73
+
74
+ To write a literal `{{` in an article, escape it as `\{\{` (a code span or fence containing `{{` is escaped for you).
75
+ An unescaped `{{…}}` that is not one of the placeholders below fails the check.
76
+
77
+ ### Links, tracking and personalisation
78
+
79
+ | Placeholder | Filled by `personalize()` with |
80
+ |---|---|
81
+ | `{{name}}` | the reader's name; wrap a whole element in `{{#name}}…{{/name}}` to drop it when there is no name |
82
+ | `{{email}}` | the address (use `{{#email}}…{{/email}}` the same way) |
83
+ | `{{unsubscribe_url}}` | the unsubscribe page URL (never rewritten) |
84
+ | `{{unsubscribe_mailto}}` | a `mailto:` unsubscribe link (e.g. `mailto:unsub@example.com?subject=<token>`); only used in the `List-Unsubscribe` header, and only when `compose({ unsubscribeMailto: true })`. Then `personalize()` requires `unsubscribe_mailto` in the recipient data and throws if it is missing or not a plain `mailto:` link |
85
+ | `{{web_url}}` | the web version of the issue (never rewritten) |
86
+ | `{{c:N}}` | the signature for link N (inside `https://t.example.com/c/{{c:N}}`) |
87
+ | `{{o}}` | the signature for the open pixel (`https://t.example.com/o/{{o}}.gif`) |
88
+
89
+ Only these are accepted. Two shapes of `List-Unsubscribe` pass the check: `<{{unsubscribe_url}}>` and
90
+ `<{{unsubscribe_url}}>, <{{unsubscribe_mailto}}>`; `List-Unsubscribe-Post: List-Unsubscribe=One-Click` is always required.
91
+ The interface for whoever builds the unsubscribe flow: put the per-recipient URL in `unsubscribe_url` and, if you accept
92
+ unsubscribe-by-mail, the per-recipient mailto in `unsubscribe_mailto`; both must be free of CR/LF.
93
+
94
+ Only the links written in the article body are tracked and get `utm_*`. The links the template adds (the "view in browser"
95
+ link, footer links, the unsubscribe link) are left as they are: no tracking redirect, no `utm_*`.
96
+ Every body link (except placeholders, `mailto:` and `tel:`) (except placeholders, `mailto:` and `tel:`) is rewritten to the tracking URL and its
97
+ destination gets `utm_source=newsletter`, `utm_medium=email`, `utm_campaign=<issue>` appended to the original query string
98
+ (which is otherwise left byte-for-byte as written; an existing `utm_*` is not overwritten). `javascript:` and
99
+ `data:` links are refused. `personalize()` escapes values for HTML, flattens the name to one line (max 60 characters),
100
+ expands everything in a single pass (a name containing `{{email}}` stays literal), and **throws** if `email`,
101
+ `unsubscribe_url` or `web_url` is missing or not `https`, or if any placeholder is left over.
102
+
103
+ ## Pre-send check
104
+
105
+ ```ts
106
+ const check = await preflight(issue, { template, webUrl }); // schedule only if check.ok && check.linksChecked && check.webChecked
107
+ ```
108
+
109
+ Every `error` blocks scheduling. `warn` and `info` are recorded only. The result also carries `linksChecked` and `webChecked`:
110
+ scheduling a real send requires `ok && linksChecked && webChecked` — offline mode (`checkLinks: false`) and a missing `webUrl`
111
+ are errors (`links_unchecked`, `web_url_unchecked`), not warnings. Links and images are taken from the **final HTML**, so
112
+ the template's footer is checked too, not only the article.
113
+
114
+ | Code | Blocks when |
115
+ |---|---|
116
+ | `html_too_large` | HTML (plus an allowance for signatures and personalisation) is 90,000 bytes or more (`maxHtmlBytes`) |
117
+ | `text_missing` | no plain-text version |
118
+ | `unsubscribe_link_missing`, `unsubscribe_text_missing` | the HTML or the text has no unsubscribe link |
119
+ | `unsubscribe_header_missing`, `unsubscribe_post_header_missing` | `List-Unsubscribe` or `List-Unsubscribe-Post` is missing |
120
+ | `address_missing`, `address_todo`, `address_not_in_html`, `address_not_in_text` | the template has no postal address, it is still a TODO marker, or it did not make it into the mail |
121
+ | `todo_marker` | `[[TODO: …]]` / `【待補:…】` is still present anywhere in the mail, including inside an `href` or `src` |
122
+ | `links_unchecked`, `web_url_unchecked` | offline mode, or no web-version URL was given |
123
+ | `image_alt_missing` | an image has no alt text |
124
+ | `subject_missing`, `subject_too_long`, `subject_invalid` | no subject, more than 80 characters (counted as characters, not bytes), or a control character / newline in it |
125
+ | `preheader_missing` | no preview text |
126
+ | `unknown_placeholder`, `unbalanced_section` | any `{{…}}` that is not on the list above, or an unmatched `{{#name}}` |
127
+ | `link_broken`, `image_broken` | HTTP 404 or 410 (only these two; a HEAD that returns 404/410/405/501 is retried once with GET before judging) |
128
+ | `link_invalid`, `link_private_host` | a malformed URL, or one pointing at localhost / a private or reserved address (IPv4, IPv6, IPv4-mapped IPv6, 100.64/10…) |
129
+ | `link_redirect_private`, `link_redirect_bad` | a redirect leads to a private address, a non-http(s) URL, or loops past 5 hops |
130
+ | `unsupported_html`, `unsupported_syntax`, `unsafe_link`, `link_not_absolute`, `image_not_absolute`, `issue_invalid`, `track_base_invalid` | reported by `compose()` itself |
131
+
132
+ Redirects are followed by hand, one hop at a time, and every hop goes through the private-address check again. The check looks at the host as written; it does not resolve DNS, so run `preflight` from a network that cannot reach your internal services if the content is not written by you.
133
+
134
+ Timeouts, network errors and other status codes (403, 429, 5xx…) are recorded as `warn` (`link_unverified`,
135
+ `link_status`) and do not block. Pass your own `fetch` to test, or `checkLinks: false` to run offline.
136
+
137
+ ## Scanner clicks
138
+
139
+ Security scanners click every link in a message right after it is delivered. `detectScannerClicks(clicks, sentAt)` is the rule
140
+ for spotting that (pure function; recording events belongs to the redirect side): when one message gets clicks on **3 or more
141
+ different links within 60 seconds of being sent**, every click of that message inside the window is returned for marking as
142
+ `detail.suspect = 'scanner'`. Mark, don't delete; exclude the marked ones when counting clicks. Window and threshold are
143
+ adjustable (`windowMs`, `minDistinctLinks`). Opens are kept as they are (mail-client preloading cannot be told apart reliably).
144
+
145
+ ## Preview
146
+
147
+ `buildPreview(issue, check)` returns a map of file name → content: `email.html` and `email.txt` (rendered for a sample
148
+ reader), `check.json`, `links.json`, and `index.html` — one page with the check results, the mail at phone and desktop
149
+ width, and the plain text. With `withoutName: true` it also renders the no-name version. Writing the files is up to the caller.
150
+
151
+ ## Templates
152
+
153
+ A template is configuration, not code: `createTemplate()` takes a brand name, optional logo, greeting, footer lines or a
154
+ trusted `footerHtml` / `footerText` block, labels, a theme and the postal address. The layout is table-based with inline CSS
155
+ (Outlook-safe), 600 px wide, with a dark-mode override. Keep brand templates in your own configuration; the engine ships
156
+ none. The compose module is tested against a made-up issue in `tests/fixtures/`.
@@ -0,0 +1,52 @@
1
+ # Newsletter desk commands
2
+
3
+ `bin/mailroom.mjs` (also `@joelincc/mailroom/cli` as `runCli`) is the one set of commands for a whole newsletter issue. It talks to the
4
+ admin endpoints of the deployed Worker (see [broadcast.md](broadcast.md)); it never touches the database itself.
5
+
6
+ ```sh
7
+ export MAILROOM_URL=https://mailroom.example.com # the Worker's admin address
8
+ export MAILROOM_ADMIN_TOKEN=... # the admin token (never put it in a file in the repo)
9
+ node bin/mailroom.mjs campaign status weekly-12
10
+ node bin/mailroom.mjs --config ./my-defaults.mjs campaign create --issue weekly-12 --post my-post --yes
11
+ ```
12
+
13
+ Requires Node 22.18+. Installed from npm it runs the compiled JavaScript in `dist/` (built by `prepack`; Node does not strip types inside `node_modules`); in a source checkout it loads the TypeScript directly. Your own defaults (list, sender, template, test addresses…) live in a module
14
+ whose default export is a `CliDefaults` (`--config <path>` or `MAILROOM_CONFIG`), or call `runCli(argv, { defaults, env })` from your own script.
15
+ Nothing specific to one deployment is built in.
16
+
17
+ ## Rules every command follows
18
+
19
+ - **Dry run unless `--yes`.** A command that changes anything (including test mail and "mark as previewed") only prints what it *would* do until
20
+ you add `--yes`. Read-only commands (`status`, `audience`, `throttle`, `reconcile`) never need it.
21
+ - **Two outputs.** A short summary for people; with `--json` exactly one JSON object on stdout (`{ ok, command, … }`, or `{ ok: false, error }`).
22
+ - **Errors say what to do next.** Exit code 1 = refused or failed (nothing half-done is hidden), 2 = wrong usage.
23
+ - **Nothing is retried silently.** Failed test mail and unknown outcomes are reported, not resent.
24
+
25
+ ## The flow of one issue
26
+
27
+ | Step | Command | Notes |
28
+ |---|---|---|
29
+ | 1 | `campaign create --issue ID (--source file.md \| --post NAME) [--web-url URL] --yes` | Composes the email, runs the pre-send check (it opens the links), saves a **draft**. Same id again updates the draft. Refused if the same web-version URL, source or body already belongs to another non-cancelled issue |
30
+ | 2 | `campaign preview ID --yes [--out DIR]` | Marks this exact content as previewed. `--out` also writes `email.html`, `email.txt`, `email-no-name.html`, `check.json`. Approval is refused until this has been done for the current content |
31
+ | 3 | `campaign test ID (--to a@x,b@x \| --to-defaults) --yes` | Real postman, real headers, subject prefix; only to the Worker's `TEST_RECIPIENTS` |
32
+ | 4 | `campaign approve ID --note "who, when, where" --yes` | Only after the owner has seen the preview and said yes |
33
+ | 5 | `campaign schedule ID --at "2027-03-01 09:00" --yes` | Local time (default `+08:00`, `--tz`); a past time is refused. The dry run prints who would receive it per wave. `unschedule` takes it back. `start ID --yes` = schedule for now |
34
+ | 6 | `campaign status ID` | State, brake light (green / yellow = a rate is at half its brake / red), counts, rates, why it paused and what to do |
35
+ | 7 | `campaign pause ID --reason "…" --yes` | Emergency stop; mail already handed to the provider still goes out |
36
+ | 8 | `campaign resume ID --note "what was checked" [--release-domain] [--force] --yes` (alias `release`) | Shows which brake fired, the numerator and denominator and the suggestion. `--release-domain` is accepted only when this issue paused *because of* the sender-domain hold (it then releases the hold with the same note and resumes). If the hold exists but is not why this issue paused, release it separately with `hold release` (its dry run prints the threshold and the numbers). A pause whose cause must be fixed first (render error, reconciliation mismatch, a run of permanent failures…) needs `--force` |
37
+ | 9 | `campaign reconcile ID` | frozen = sent + skipped + failed + uncertain + pending, ledger rows, and provider events (sends vs sent; delivered + bounced + not-yet-reported vs sends). A mismatch prints the problem list and every number and exits 1. Run again 72 hours after it finished |
38
+ | — | `campaign retry-failed ID --yes` | Only while the issue is sending or paused; a finished issue is closed |
39
+ | — | `campaign resolve ID --contact N --as sent\|failed --note "…" --yes` | For a recipient left "uncertain" |
40
+ | — | `campaign cancel ID --reason "…" --yes` | Not undoable |
41
+ | — | `campaign hold release --note "…" --yes` | Release the sender-domain hold on its own; paused issues stay paused |
42
+ | — | `campaign audience ID`, `campaign throttle` | Read-only |
43
+
44
+ ## Settings you will want to decide before the first real send
45
+
46
+ All in `BROADCAST_CONFIG` (see [broadcast.md](broadcast.md#all-settings-broadcast_config)):
47
+
48
+ - `domainMinComplaints` (default 1): the sender-domain stop needs this many complaints besides the 0.08% rate. With ~220 mails sent a single
49
+ complaint is 0.45%, so with the default one complaint stops every newsletter on the domain. That errs on the safe side; raise it if you would
50
+ rather have a person look first. `campaign resume … --release-domain` is the one-step way out.
51
+ - `waveGateMinSent` (default 1): with small waves one bounce can cross the 2% wave gate.
52
+ - `startGraceMinutes` (default 360): how late a scheduled issue may start before it goes back to `draft` (and must be approved again).
package/docs/export.md ADDED
@@ -0,0 +1,52 @@
1
+ # Analytics export
2
+
3
+ Hand the delivery events, issues, frozen recipient lists and list members to an outside analytics pipeline as paged NDJSON.
4
+ All endpoints need the admin bearer token (a wrong or missing token gets `404`, so the endpoints do not reveal themselves)
5
+ and have their own rate bucket (`_export`: 60 per minute, 1000 per day), separate from the other admin endpoints.
6
+
7
+ | Endpoint | Cursor | Rows |
8
+ |---|---|---|
9
+ | `GET /v1/export/events?cursor=&limit=` | event `id` | every row of `events` (provider feedback plus open/click/unsubscribe), oldest first |
10
+ | `POST /v1/export/events/ack` `{ "through": id }` | | sets `exported_at` on events with `id <= through` |
11
+ | `GET /v1/export/campaigns?cursor=&limit=` | row number | one row per issue (state, timestamps) |
12
+ | `GET /v1/export/recipients?campaign=&cursor=&limit=` | `contact_id` | the frozen list of one issue: who it was for and their segment **at send time** |
13
+ | `GET /v1/export/members?list=&cursor=&limit=` | `contact_id` | everyone on one list now, with address and segment (for the weekly snapshot) |
14
+
15
+ `limit` defaults to 2000, at most 5000. Each response is one JSON object per line. Paging state is in response headers:
16
+ `x-export-count`, `x-export-has-more` (`1`/`0`) and `x-export-next-cursor` (pass it back as `cursor`; empty when done).
17
+
18
+ ## Guarantees
19
+
20
+ - **Reads change nothing.** Pulling the same cursor again returns the same rows (plus anything newer at the end). A consumer that
21
+ fails half way restarts from the last cursor it durably stored: nothing is skipped and nothing is stored twice as long as the
22
+ consumer de-duplicates on `id` / `provider_event_id`.
23
+ - **`ack` is a marker, not a position.** The consumer keeps its own cursor; it calls `ack` only after the pulled rows are safely
24
+ stored. `ack` can be repeated, never marks beyond the current highest id, and can be used later to decide which events are old
25
+ enough to purge.
26
+ - **Order.** D1 commits writes one at a time, so when `id` N+1 is visible N is too; paging by `id` never skips a row.
27
+ - **No addresses in events, campaigns or recipients.** Events carry `contact_id`; join to the members export for the address.
28
+ Only the members export contains addresses, so keep its output as private as the list itself.
29
+
30
+ ## Event shape
31
+
32
+ ```json
33
+ { "id": 812, "provider": "self", "provider_event_id": "…", "message_id": 77, "provider_message_id": "…",
34
+ "campaign_id": "weekly-163", "contact_id": 12, "type": "click", "subtype": null,
35
+ "at": "2027-03-01T01:07:00.000Z", "detail": { "url": "https://…", "linkIndex": 1, "suspect": "scanner" }, "exported_at": null }
36
+ ```
37
+
38
+ `detail` is the stored JSON (or `null`). Anything shaped like an email address is replaced with `[email]` when the event is recorded and again on export (`@channel`-style handles are not addresses and stay). Contract the analytics side relies on:
39
+
40
+ - `detail.suspect = "scanner"` marks a click that a security scanner made (see `docs/composing.md`). Keep these rows, do not count them.
41
+ - **`detail.prefetch = true` must be written explicitly by the tracking service** for opens that mail-privacy prefetching made. The built-in tracker (`docs/tracking.md`) does this; the user-agent string (`detail.ua`) is only a fallback hint and is not reliable. Check a real message end to end before relying on it.
42
+ - Built-in tracker events have `provider = "self"`; `detail.scannerRule` says why a click was marked (`burst`, `head`, `asn`).
43
+ - `detail.linkIndex` / `detail.url` identify the link of a click.
44
+ - Unsubscribes are recorded by the engine itself when someone goes from subscribed to unsubscribed through the unsubscribe page, the one-click endpoint or an unsubscribe mail: `type = "unsubscribe"`, `detail = { via: "link" | "one_click" | "mailto", list, reason? }`. Repeating the request records nothing more. Unsubscribes made through the list API or a member-centre sync record no event, so a per-issue unsubscribe count only counts people who left from a mail of that issue.
45
+
46
+ Known limits of the address scrub: version-like strings such as `pkg@1.2.3` are masked too, and addresses written percent-encoded (`%40`) are not. Revisit when links start carrying recipient parameters.
47
+
48
+ ## Test data
49
+
50
+ `tests/export-fixture.ts` builds two complete issues with the fake postman (bounces, a complaint, opens, prefetch opens, clicks,
51
+ scanner clicks, unsubscribes) using only `@example.com` addresses. Run
52
+ `node --experimental-strip-types tests/export-fixture.ts <dir>` to write the same data as NDJSON files for an outside pipeline's tests.